Skip to content

model_fields

BigInteger

Bases: Integer, int

BigInteger field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
class BigInteger(Integer, int):
    """
    BigInteger field factory that construct Field classes and populated their values.
    """

    _type = int
    _sample = 0

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return unsigned_on_mysql(
            sqlalchemy.BigInteger(), mysql.BIGINT, kwargs.get("unsigned", False)
        )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
600
601
602
603
604
605
606
607
608
609
610
611
612
613
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return unsigned_on_mysql(
        sqlalchemy.BigInteger(), mysql.BIGINT, kwargs.get("unsigned", False)
    )

Boolean

Bases: ModelFieldFactory, int

Boolean field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class Boolean(ModelFieldFactory, int):
    """
    Boolean field factory that construct Field classes and populated their values.
    """

    _type = bool
    _sample = True

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Boolean()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
415
416
417
418
419
420
421
422
423
424
425
426
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Boolean()

Date

Bases: ModelFieldFactory, date

Date field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
class Date(ModelFieldFactory, datetime.date):
    """
    Date field factory that construct Field classes and populated their values.
    """

    _type = datetime.date
    _sample = "date"

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Date()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
472
473
474
475
476
477
478
479
480
481
482
483
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Date()

DateTime

Bases: ModelFieldFactory, datetime

DateTime field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
class DateTime(ModelFieldFactory, datetime.datetime):
    """
    DateTime field factory that construct Field classes and populated their values.
    """

    _type = datetime.datetime
    _sample = "datetime"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, timezone: bool = False, **kwargs: Any
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.DateTime(timezone=kwargs.get("timezone", False))

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
450
451
452
453
454
455
456
457
458
459
460
461
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.DateTime(timezone=kwargs.get("timezone", False))

Decimal

Bases: ModelFieldFactory, Decimal

Decimal field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
class Decimal(ModelFieldFactory, decimal.Decimal):
    """
    Decimal field factory that construct Field classes and populated their values.
    """

    _type = decimal.Decimal
    _sample = 0.0

    def __new__(  # type: ignore # noqa CFQ002
        cls,
        *,
        minimum: Optional[float] = None,
        maximum: Optional[float] = None,
        multiple_of: Optional[int] = None,
        precision: Optional[int] = None,
        scale: Optional[int] = None,
        max_digits: Optional[int] = None,
        decimal_places: Optional[int] = None,
        **kwargs: Any,
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        kwargs["ge"] = kwargs["minimum"]
        kwargs["le"] = kwargs["maximum"]

        if kwargs.get("max_digits"):
            kwargs["precision"] = kwargs["max_digits"]
        elif kwargs.get("precision"):
            kwargs["max_digits"] = kwargs["precision"]

        if kwargs.get("decimal_places"):
            kwargs["scale"] = kwargs["decimal_places"]
        elif kwargs.get("scale"):
            kwargs["decimal_places"] = kwargs["scale"]

        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        precision = kwargs.get("precision")
        scale = kwargs.get("scale")
        return sqlalchemy.DECIMAL(precision=precision, scale=scale)

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """
        precision = kwargs.get("precision")
        scale = kwargs.get("scale")
        if precision is None or precision < 0 or scale is None or scale < 0:
            raise ModelDefinitionError(
                "Parameters scale and precision are required for field Decimal"
            )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
683
684
685
686
687
688
689
690
691
692
693
694
695
696
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    precision = kwargs.get("precision")
    scale = kwargs.get("scale")
    return sqlalchemy.DECIMAL(precision=precision, scale=scale)

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
698
699
700
701
702
703
704
705
706
707
708
709
710
@classmethod
def validate(cls, **kwargs: Any) -> None:
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """
    precision = kwargs.get("precision")
    scale = kwargs.get("scale")
    if precision is None or precision < 0 or scale is None or scale < 0:
        raise ModelDefinitionError(
            "Parameters scale and precision are required for field Decimal"
        )

Enum

Bases: ModelFieldFactory

Enum field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
class Enum(ModelFieldFactory):
    """
    Enum field factory that construct Field classes and populated their values.
    """

    _type = E
    _sample = None

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, enum_class: type[E], store_values: bool = False, **kwargs: Any
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        enum_class = kwargs.get("enum_class")
        if enum_class is None or not isinstance(enum_class, EnumMeta):
            raise ModelDefinitionError("Enum Field choices must be EnumType")
        if kwargs.get("store_values") and kwargs.get("values_callable"):
            raise ModelDefinitionError(
                "Enum Field accepts store_values or values_callable, not both"
            )

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return the column type of the enum.

        SQLAlchemy Enum options, such as ``values_callable``, are forwarded
        so callers can store enum values instead of enum names.

        With ``store_values=True`` the column stores member values: an ``int``
        enum gets an ``INTEGER`` column (see ``IntegerEnum``), any other enum
        a ``sqlalchemy.Enum`` of its values as strings.
        """
        enum_cls = kwargs.get("enum_class")
        if kwargs.get("store_values") and issubclass(enum_cls, int):
            return IntegerEnum(enum_cls)
        enum_kwargs = {
            key: value
            for key, value in kwargs.items()
            if key in _SQLALCHEMY_ENUM_KWARGS
        }
        if kwargs.get("store_values"):
            enum_kwargs["values_callable"] = lambda enum: [
                str(member.value) for member in enum
            ]
        return sqlalchemy.Enum(enum_cls, **enum_kwargs)

get_column_type(**kwargs) classmethod

Return the column type of the enum.

SQLAlchemy Enum options, such as values_callable, are forwarded so callers can store enum values instead of enum names.

With store_values=True the column stores member values: an int enum gets an INTEGER column (see IntegerEnum), any other enum a sqlalchemy.Enum of its values as strings.

Source code in ormar/fields/model_fields.py
Python
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return the column type of the enum.

    SQLAlchemy Enum options, such as ``values_callable``, are forwarded
    so callers can store enum values instead of enum names.

    With ``store_values=True`` the column stores member values: an ``int``
    enum gets an ``INTEGER`` column (see ``IntegerEnum``), any other enum
    a ``sqlalchemy.Enum`` of its values as strings.
    """
    enum_cls = kwargs.get("enum_class")
    if kwargs.get("store_values") and issubclass(enum_cls, int):
        return IntegerEnum(enum_cls)
    enum_kwargs = {
        key: value
        for key, value in kwargs.items()
        if key in _SQLALCHEMY_ENUM_KWARGS
    }
    if kwargs.get("store_values"):
        enum_kwargs["values_callable"] = lambda enum: [
            str(member.value) for member in enum
        ]
    return sqlalchemy.Enum(enum_cls, **enum_kwargs)

Float

Bases: ModelFieldFactory, float

Float field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
class Float(ModelFieldFactory, float):
    """
    Float field factory that construct Field classes and populated their values.
    """

    _type = float
    _sample = 0.0

    def __new__(  # type: ignore
        cls,
        *,
        minimum: Optional[float] = None,
        maximum: Optional[float] = None,
        multiple_of: Optional[int] = None,
        **kwargs: Any,
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        kwargs["ge"] = kwargs["minimum"]
        kwargs["le"] = kwargs["maximum"]
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Float()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
393
394
395
396
397
398
399
400
401
402
403
404
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Float()

Integer

Bases: ModelFieldFactory, int

Integer field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
class Integer(ModelFieldFactory, int):
    """
    Integer field factory that construct Field classes and populated their values.
    """

    _bases = (IntegerField,)
    _type = int
    _sample = 0

    def __new__(  # type: ignore
        cls,
        *,
        minimum: Optional[int] = None,
        maximum: Optional[int] = None,
        multiple_of: Optional[int] = None,
        unsigned: bool = False,
        **kwargs: Any,
    ) -> Self:
        if unsigned and minimum is None:
            minimum = 0
        autoincrement = kwargs.pop("autoincrement", None)
        autoincrement_explicit = autoincrement is not None
        autoincrement = (
            autoincrement
            if autoincrement is not None
            else kwargs.get("primary_key", False)
        )
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        kwargs["ge"] = kwargs["minimum"]
        kwargs["le"] = kwargs["maximum"]
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return unsigned_on_mysql(
            sqlalchemy.Integer(), mysql.INTEGER, kwargs.get("unsigned", False)
        )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
316
317
318
319
320
321
322
323
324
325
326
327
328
329
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return unsigned_on_mysql(
        sqlalchemy.Integer(), mysql.INTEGER, kwargs.get("unsigned", False)
    )

IntegerEnum

Bases: TypeDecorator, SchemaEventTarget

Integer column of an int enum: stores the member's value and loads it back as the member, with a CHECK constraint limiting the column to the enum's values::

Text Only
1
country INTEGER CHECK (country IN (1, 2))
Source code in ormar/fields/model_fields.py
Python
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
class IntegerEnum(sqlalchemy.types.TypeDecorator, SchemaEventTarget):
    """
    Integer column of an ``int`` enum: stores the member's value and loads it
    back as the member, with a CHECK constraint limiting the column to the
    enum's values::

        country INTEGER CHECK (country IN (1, 2))
    """

    impl = sqlalchemy.Integer
    cache_ok = True

    def __init__(self, enum_class: type[E]) -> None:
        super().__init__()
        self.enum_class = enum_class

    def _set_parent(self, parent: Any, **kwargs: Any) -> None:
        sqlalchemy.event.listen(parent, "after_parent_attach", self._add_check)

    def _add_check(self, column: sqlalchemy.Column, table: sqlalchemy.Table) -> None:
        values = [int(member) for member in self.enum_class]
        table.append_constraint(sqlalchemy.CheckConstraint(column.in_(values)))

    def process_bind_param(self, value: Any, dialect: Any) -> Optional[int]:
        return None if value is None else int(value)

    def process_result_value(self, value: Any, dialect: Any) -> Any:
        return None if value is None else self.enum_class(value)

IntegerField

Bases: BaseField

Field of an integer column. An unsigned one gets a check on databases without unsigned integers::

Text Only
1
CHECK (id >= 0)  -- PostgreSQL, SQLite; MySQL uses INTEGER UNSIGNED
Source code in ormar/fields/model_fields.py
Python
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
class IntegerField(BaseField):
    """
    Field of an integer column. An unsigned one gets a check on databases
    without unsigned integers::

        CHECK (id >= 0)  -- PostgreSQL, SQLite; MySQL uses INTEGER UNSIGNED
    """

    unsigned: bool = False

    def construct_table_constraints(self) -> list:
        """
        :return: the ``>= 0`` check of an unsigned column, empty otherwise
        :rtype: list
        """
        if not self.unsigned:
            return []
        check = sqlalchemy.CheckConstraint(sqlalchemy.column(self.get_alias()) >= 0)
        return [check.ddl_if(callable_=creates_unsigned_check)]

construct_table_constraints()

Returns:

Type Description
list

the >= 0 check of an unsigned column, empty otherwise

Source code in ormar/fields/model_fields.py
Python
266
267
268
269
270
271
272
273
274
def construct_table_constraints(self) -> list:
    """
    :return: the ``>= 0`` check of an unsigned column, empty otherwise
    :rtype: list
    """
    if not self.unsigned:
        return []
    check = sqlalchemy.CheckConstraint(sqlalchemy.column(self.get_alias()) >= 0)
    return [check.ddl_if(callable_=creates_unsigned_check)]

JSON

Bases: ModelFieldFactory, Json

JSON field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
class JSON(ModelFieldFactory, pydantic.Json):
    """
    JSON field factory that construct Field classes and populated their values.
    """

    _type = pydantic.Json
    _sample = '{"json": "json"}'

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.JSON(none_as_null=kwargs.get("sql_nullable", False))

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
529
530
531
532
533
534
535
536
537
538
539
540
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.JSON(none_as_null=kwargs.get("sql_nullable", False))

LargeBinary

Bases: ModelFieldFactory, bytes

LargeBinary field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
class LargeBinary(ModelFieldFactory, bytes):
    """
    LargeBinary field factory that construct Field classes
    and populated their values.
    """

    _type = bytes
    _sample = "bytes"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, max_length: int, represent_as_base64_str: bool = False, **kwargs: Any
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.LargeBinary(length=kwargs.get("max_length"))

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """
        max_length = kwargs.get("max_length", None)
        if max_length <= 0:
            raise ModelDefinitionError(
                "Parameter max_length is required for field LargeBinary"
            )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
565
566
567
568
569
570
571
572
573
574
575
576
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.LargeBinary(length=kwargs.get("max_length"))

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
578
579
580
581
582
583
584
585
586
587
588
589
@classmethod
def validate(cls, **kwargs: Any) -> None:
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """
    max_length = kwargs.get("max_length", None)
    if max_length <= 0:
        raise ModelDefinitionError(
            "Parameter max_length is required for field LargeBinary"
        )

ModelFieldFactory

Default field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class ModelFieldFactory:
    """
    Default field factory that construct Field classes and populated their values.
    """

    _bases: Any = (BaseField,)
    _type: Any = None
    _sample: Any = None

    def __new__(cls, *args: Any, **kwargs: Any) -> Self:  # type: ignore
        cls.validate(**kwargs)

        default = kwargs.pop("default", None)
        server_default = kwargs.pop("server_default", None)
        nullable = kwargs.pop("nullable", None)
        sql_nullable = kwargs.pop("sql_nullable", None)

        primary_key = kwargs.pop("primary_key", False)
        autoincrement_explicit = kwargs.pop(
            "autoincrement_explicit", "autoincrement" in kwargs
        )
        autoincrement = kwargs.pop("autoincrement", False)

        encrypt_secret = kwargs.pop("encrypt_secret", None)
        encrypt_backend = kwargs.pop("encrypt_backend", EncryptBackends.NONE)
        encrypt_custom_backend = kwargs.pop("encrypt_custom_backend", None)

        overwrite_pydantic_type = kwargs.pop("overwrite_pydantic_type", None)

        nullable = is_field_nullable(
            nullable, default, server_default
        ) or is_auto_primary_key(primary_key, autoincrement)
        sql_nullable = (
            False
            if primary_key
            else (nullable if sql_nullable is None else sql_nullable)
        )

        enum_class = kwargs.pop("enum_class", None)
        field_type = cls._type if enum_class is None else enum_class

        namespace = dict(
            __type__=field_type,
            __pydantic_type__=(
                overwrite_pydantic_type
                if overwrite_pydantic_type is not None
                else field_type
            ),
            __sample__=cls._sample,
            alias=kwargs.pop("name", None),
            name=None,
            primary_key=primary_key,
            default=default,
            server_default=server_default,
            nullable=nullable,
            annotation=field_type,
            sql_nullable=sql_nullable,
            index=kwargs.pop("index", False),
            unique=kwargs.pop("unique", False),
            autoincrement=autoincrement,
            autoincrement_explicit=autoincrement_explicit,
            column_type=cls.get_column_type(
                **kwargs, sql_nullable=sql_nullable, enum_class=enum_class
            ),
            encrypt_secret=encrypt_secret,
            encrypt_backend=encrypt_backend,
            encrypt_custom_backend=encrypt_custom_backend,
            **kwargs,
        )
        Field = type(cls.__name__, cls._bases, {})
        return Field(**namespace)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:  # pragma no cover
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return None

    @classmethod
    def validate(cls, **kwargs: Any) -> None:  # pragma no cover
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
133
134
135
136
137
138
139
140
141
142
143
144
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:  # pragma no cover
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return None

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
146
147
148
149
150
151
152
@classmethod
def validate(cls, **kwargs: Any) -> None:  # pragma no cover
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """

SmallInteger

Bases: Integer, int

SmallInteger field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
class SmallInteger(Integer, int):
    """
    SmallInteger field factory that construct Field classes and populated their values.
    """

    _type = int
    _sample = 0

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return unsigned_on_mysql(
            sqlalchemy.SmallInteger(), mysql.SMALLINT, kwargs.get("unsigned", False)
        )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
624
625
626
627
628
629
630
631
632
633
634
635
636
637
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return unsigned_on_mysql(
        sqlalchemy.SmallInteger(), mysql.SMALLINT, kwargs.get("unsigned", False)
    )

String

Bases: ModelFieldFactory, str

String field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class String(ModelFieldFactory, str):
    """
    String field factory that construct Field classes and populated their values.
    """

    _type = str
    _sample = "string"

    def __new__(  # type: ignore # noqa CFQ002
        cls,
        *,
        max_length: int,
        min_length: Optional[int] = None,
        regex: Optional[str] = None,
        **kwargs: Any,
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.String(length=kwargs.get("max_length"))

    @classmethod
    def validate(cls, **kwargs: Any) -> None:
        """
        Used to validate if all required parameters on a given field type are set.
        :param kwargs: all params passed during construction
        :type kwargs: Any
        """
        max_length = kwargs.get("max_length", -1)
        if max_length <= 0:
            raise ModelDefinitionError(
                "Parameter max_length is required for field String"
            )

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
181
182
183
184
185
186
187
188
189
190
191
192
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.String(length=kwargs.get("max_length"))

validate(**kwargs) classmethod

Used to validate if all required parameters on a given field type are set.

Parameters:

Name Type Description Default
kwargs Any

all params passed during construction

{}
Source code in ormar/fields/model_fields.py
Python
194
195
196
197
198
199
200
201
202
203
204
205
@classmethod
def validate(cls, **kwargs: Any) -> None:
    """
    Used to validate if all required parameters on a given field type are set.
    :param kwargs: all params passed during construction
    :type kwargs: Any
    """
    max_length = kwargs.get("max_length", -1)
    if max_length <= 0:
        raise ModelDefinitionError(
            "Parameter max_length is required for field String"
        )

Text

Bases: ModelFieldFactory, str

Text field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
class Text(ModelFieldFactory, str):
    """
    Text field factory that construct Field classes and populated their values.
    """

    _type = str
    _sample = "text"

    def __new__(cls, **kwargs: Any) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Text()

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
351
352
353
354
355
356
357
358
359
360
361
362
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Text()

Time

Bases: ModelFieldFactory, time

Time field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
class Time(ModelFieldFactory, datetime.time):
    """
    Time field factory that construct Field classes and populated their values.
    """

    _type = datetime.time
    _sample = "time"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, timezone: bool = False, **kwargs: Any
    ) -> Self:  # type: ignore
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }
        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        return sqlalchemy.Time(timezone=kwargs.get("timezone", False))

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
507
508
509
510
511
512
513
514
515
516
517
518
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    return sqlalchemy.Time(timezone=kwargs.get("timezone", False))

UUID

Bases: ModelFieldFactory, UUID

UUID field factory that construct Field classes and populated their values.

Source code in ormar/fields/model_fields.py
Python
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
class UUID(ModelFieldFactory, uuid.UUID):
    """
    UUID field factory that construct Field classes and populated their values.
    """

    _type = uuid.UUID
    _sample = "uuid"

    def __new__(  # type: ignore # noqa CFQ002
        cls, *, uuid_format: str = "hex", **kwargs: Any
    ) -> Self:
        kwargs = {
            **kwargs,
            **{
                k: v
                for k, v in locals().items()
                if k not in ["cls", "__class__", "kwargs"]
            },
        }

        return super().__new__(cls, **kwargs)

    @classmethod
    def get_column_type(cls, **kwargs: Any) -> Any:
        """
        Return proper type of db column for given field type.
        Accepts required and optional parameters that each column type accepts.

        :param kwargs: key, value pairs of sqlalchemy options
        :type kwargs: Any
        :return: initialized column with proper options
        :rtype: sqlalchemy Column
        """
        uuid_format = kwargs.get("uuid_format", "hex")
        return sqlalchemy_uuid.UUID(uuid_format=uuid_format)

get_column_type(**kwargs) classmethod

Return proper type of db column for given field type. Accepts required and optional parameters that each column type accepts.

Parameters:

Name Type Description Default
kwargs Any

key, value pairs of sqlalchemy options

{}

Returns:

Type Description
sqlalchemy Column

initialized column with proper options

Source code in ormar/fields/model_fields.py
Python
735
736
737
738
739
740
741
742
743
744
745
746
747
@classmethod
def get_column_type(cls, **kwargs: Any) -> Any:
    """
    Return proper type of db column for given field type.
    Accepts required and optional parameters that each column type accepts.

    :param kwargs: key, value pairs of sqlalchemy options
    :type kwargs: Any
    :return: initialized column with proper options
    :rtype: sqlalchemy Column
    """
    uuid_format = kwargs.get("uuid_format", "hex")
    return sqlalchemy_uuid.UUID(uuid_format=uuid_format)

creates_unsigned_check(ddl, target, bind, **kwargs)

Return whether the >= 0 check of an unsigned column is created: on MySQL and MariaDB the column is UNSIGNED and needs no check.

Parameters:

Name Type Description Default
ddl Any

DDL element being created

required
target Any

table of the constraint

required
bind Any

connection the DDL runs on

required
kwargs Any

dialect and other details of the DDL run

{}

Returns:

Type Description
bool

True on databases without unsigned integers

Source code in ormar/fields/model_fields.py
Python
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def creates_unsigned_check(ddl: Any, target: Any, bind: Any, **kwargs: Any) -> bool:
    """
    Return whether the ``>= 0`` check of an unsigned column is created: on
    MySQL and MariaDB the column is ``UNSIGNED`` and needs no check.

    :param ddl: DDL element being created
    :type ddl: Any
    :param target: table of the constraint
    :type target: Any
    :param bind: connection the DDL runs on
    :type bind: Any
    :param kwargs: ``dialect`` and other details of the DDL run
    :type kwargs: Any
    :return: True on databases without unsigned integers
    :rtype: bool
    """
    return kwargs["dialect"].name not in UNSIGNED_INTEGER_DIALECTS

is_auto_primary_key(primary_key, autoincrement)

Checks if field is an autoincrement pk -> if yes it's optional.

Parameters:

Name Type Description Default
primary_key bool

flag if field is a pk field

required
autoincrement bool

flag if field should be autoincrement

required

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/model_fields.py
Python
47
48
49
50
51
52
53
54
55
56
57
58
def is_auto_primary_key(primary_key: bool, autoincrement: bool) -> bool:
    """
    Checks if field is an autoincrement pk -> if yes it's optional.

    :param primary_key: flag if field is a pk field
    :type primary_key: bool
    :param autoincrement: flag if field should be autoincrement
    :type autoincrement: bool
    :return: result of the check
    :rtype: bool
    """
    return primary_key and autoincrement

is_field_nullable(nullable, default, server_default)

Checks if the given field should be nullable/ optional based on parameters given.

Parameters:

Name Type Description Default
nullable Optional[bool]

flag explicit setting a column as nullable

required
default Any

value or function to be called as default in python

required
server_default Any

function to be called as default by sql server

required

Returns:

Type Description
bool

result of the check

Source code in ormar/fields/model_fields.py
Python
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def is_field_nullable(
    nullable: Optional[bool],
    default: Any,
    server_default: Any,
) -> bool:
    """
    Checks if the given field should be nullable/ optional based on parameters given.

    :param nullable: flag explicit setting a column as nullable
    :type nullable: Optional[bool]
    :param default: value or function to be called as default in python
    :type default: Any
    :param server_default: function to be called as default by sql server
    :type server_default: Any
    :return: result of the check
    :rtype: bool
    """
    if nullable is None:
        return default is not None or server_default is not None
    return nullable

unsigned_on_mysql(column_type, mysql_type, unsigned)

Return the integer column type, made UNSIGNED on MySQL and MariaDB when unsigned is set. Other databases have no unsigned integers and keep the plain type::

Text Only
1
2
unsigned_on_mysql(sqlalchemy.Integer(), mysql.INTEGER, True)
# MySQL: INTEGER UNSIGNED, PostgreSQL / SQLite: INTEGER

Parameters:

Name Type Description Default
column_type Any

integer column type

required
mysql_type Any

MySQL integer type of the same size

required
unsigned bool

whether the column is unsigned

required

Returns:

Type Description
Any

column type

Source code in ormar/fields/model_fields.py
Python
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def unsigned_on_mysql(column_type: Any, mysql_type: Any, unsigned: bool) -> Any:
    """
    Return the integer column type, made ``UNSIGNED`` on MySQL and MariaDB when
    ``unsigned`` is set. Other databases have no unsigned integers and keep the
    plain type::

        unsigned_on_mysql(sqlalchemy.Integer(), mysql.INTEGER, True)
        # MySQL: INTEGER UNSIGNED, PostgreSQL / SQLite: INTEGER

    :param column_type: integer column type
    :type column_type: Any
    :param mysql_type: MySQL integer type of the same size
    :type mysql_type: Any
    :param unsigned: whether the column is unsigned
    :type unsigned: bool
    :return: column type
    :rtype: Any
    """
    if not unsigned:
        return column_type
    return column_type.with_variant(
        mysql_type(unsigned=True), *UNSIGNED_INTEGER_DIALECTS
    )