Skip to content

Constraints

Column Constraints

ColumnConstraint

Bases: ABC

Abstract base class for column-level constraints.

Applied to individual columns to define validation rules.

Source code in src/yads/constraints.py
44
45
46
47
48
class ColumnConstraint(ABC):
    """Abstract base class for column-level constraints.

    Applied to individual columns to define validation rules.
    """

NotNullConstraint dataclass

Bases: ColumnConstraint

Constraint requiring that column values cannot be NULL.

Source code in src/yads/constraints.py
51
52
53
54
55
56
@dataclass(frozen=True)
class NotNullConstraint(ColumnConstraint):
    """Constraint requiring that column values cannot be NULL."""

    def __str__(self) -> str:
        return "NotNullConstraint()"

PrimaryKeyConstraint dataclass

Bases: ColumnConstraint

Constraint designating a column as the primary key.

Source code in src/yads/constraints.py
59
60
61
62
63
64
@dataclass(frozen=True)
class PrimaryKeyConstraint(ColumnConstraint):
    """Constraint designating a column as the primary key."""

    def __str__(self) -> str:
        return "PrimaryKeyConstraint()"

DefaultConstraint dataclass

Bases: ColumnConstraint

Constraint providing a default value for a column.

Specifies the value to use when no explicit value is provided during insert operations. The default value should be compatible with the column's data type.

Parameters:

Name Type Description Default
value Any

The default value to use.

required
Source code in src/yads/constraints.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@dataclass(frozen=True)
class DefaultConstraint(ColumnConstraint):
    """Constraint providing a default value for a column.

    Specifies the value to use when no explicit value is provided during insert
    operations. The default value should be compatible with the column's data type.

    Args:
        value: The default value to use.
    """

    value: Any

    def __str__(self) -> str:
        return f"DefaultConstraint(value={self.value!r})"

ForeignKeyConstraint dataclass

Bases: ColumnConstraint

Column-level foreign key constraint.

Parameters:

Name Type Description Default
references ForeignKeyReference

The ForeignKeyReference specifying the target table and columns.

required
name str | None

Optional name for the constraint.

None
Example
# Simple foreign key to users table
ForeignKeyConstraint(
    references=ForeignKeyReference(table="users")
)

# Named foreign key with specific column
ForeignKeyConstraint(
    name="fk_order_customer",
    references=ForeignKeyReference(table="customers", columns=["id"])
)
Source code in src/yads/constraints.py
 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
@dataclass(frozen=True)
class ForeignKeyConstraint(ColumnConstraint):
    """Column-level foreign key constraint.

    Args:
        references: The `ForeignKeyReference` specifying the target table and columns.
        name: Optional name for the constraint.

    Example:
        ```python
        # Simple foreign key to users table
        ForeignKeyConstraint(
            references=ForeignKeyReference(table="users")
        )

        # Named foreign key with specific column
        ForeignKeyConstraint(
            name="fk_order_customer",
            references=ForeignKeyReference(table="customers", columns=["id"])
        )
        ```
    """

    references: ForeignKeyReference
    name: str | None = None

    def __str__(self) -> str:
        parts: list[str] = []
        if self.name:
            parts.append(f"name={self.name!r}")
        parts.append(f"references={self.references}")

        pretty_parts = ", ".join(parts)
        return f"ForeignKeyConstraint({pretty_parts})"

IdentityConstraint dataclass

Bases: ColumnConstraint

Constraint for auto-incrementing identity columns.

Parameters:

Name Type Description Default
always bool

If True, values are always generated (GENERATED ALWAYS). If False, allows manual value insertion (GENERATED BY DEFAULT).

True
start int | None

Starting value for the sequence. If None, uses database default.

None
increment int | None

Increment step for each new value. If None, uses database default.

None

Raises:

Type Description
InvalidConstraintError

If increment is zero.

Source code in src/yads/constraints.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
@dataclass(frozen=True)
class IdentityConstraint(ColumnConstraint):
    """Constraint for auto-incrementing identity columns.

    Args:
        always: If True, values are always generated (GENERATED ALWAYS).
               If False, allows manual value insertion (GENERATED BY DEFAULT).
        start: Starting value for the sequence. If None, uses database default.
        increment: Increment step for each new value. If None, uses database default.

    Raises:
        InvalidConstraintError: If increment is zero.
    """

    always: bool = True
    start: int | None = None
    increment: int | None = None

    def __post_init__(self):
        if self.increment == 0:
            raise InvalidConstraintError(
                f"Identity 'increment' must be a non-zero integer, not {self.increment}."
            )

Table Constraints

TableConstraint dataclass

Bases: ABC

Abstract base class for table-level constraints.

Source code in src/yads/constraints.py
146
147
148
149
150
151
152
153
@dataclass(frozen=True)
class TableConstraint(ABC):
    """Abstract base class for table-level constraints."""

    @cached_property
    @abstractmethod
    def constrained_columns(self) -> list[str]:
        """Return the list of column names involved in this constraint."""

constrained_columns abstractmethod cached property

Return the list of column names involved in this constraint.

PrimaryKeyTableConstraint dataclass

Bases: TableConstraint

Table-level primary key constraint.

Parameters:

Name Type Description Default
columns list[str]

List of column names that form the composite primary key.

required
name str | None

Optional name for the constraint.

None

Raises:

Type Description
InvalidConstraintError

If columns list is empty.

Example
# Composite primary key
PrimaryKeyTableConstraint(
    columns=["order_id", "line_number"],
    name="pk_order_lines"
)

# Simple composite key without name
PrimaryKeyTableConstraint(columns=["year", "month", "category"])
Source code in src/yads/constraints.py
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
@dataclass(frozen=True)
class PrimaryKeyTableConstraint(TableConstraint):
    """Table-level primary key constraint.

    Args:
        columns: List of column names that form the composite primary key.
        name: Optional name for the constraint.

    Raises:
        InvalidConstraintError: If columns list is empty.

    Example:
        ```python
        # Composite primary key
        PrimaryKeyTableConstraint(
            columns=["order_id", "line_number"],
            name="pk_order_lines"
        )

        # Simple composite key without name
        PrimaryKeyTableConstraint(columns=["year", "month", "category"])
        ```
    """

    columns: list[str]
    name: str | None = None

    def __post_init__(self):
        if not self.columns:
            raise InvalidConstraintError(
                "PrimaryKeyTableConstraint 'columns' cannot be empty."
            )

    @cached_property
    def constrained_columns(self) -> list[str]:
        return self.columns

    def __str__(self) -> str:
        parts: list[str] = []
        if self.name:
            parts.append(f"name={self.name!r}")

        formatted_columns = ",\n".join(f"{col!r}" for col in self.columns)
        indented_columns = textwrap.indent(formatted_columns, "  ")
        parts.append(f"columns=[\n{indented_columns}\n]")

        pretty_parts = ",\n".join(parts)
        indented_parts = textwrap.indent(pretty_parts, "  ")
        return f"PrimaryKeyTableConstraint(\n{indented_parts}\n)"

ForeignKeyTableConstraint dataclass

Bases: TableConstraint

Table-level foreign key constraint for composite relationships.

Defines a foreign key across multiple columns. The number of columns must match the number of referenced columns.

Parameters:

Name Type Description Default
columns list[str]

List of column names in this table that form the foreign key.

required
references ForeignKeyReference

The ForeignKeyReference specifying the target table and columns.

required
name str | None

Optional name for the constraint.

None

Raises:

Type Description
InvalidConstraintError

If columns list is empty or if the number of columns doesn't match the referenced columns.

Example
# Composite foreign key
ForeignKeyTableConstraint(
    columns=["customer_id", "customer_region"],
    references=ForeignKeyReference(
        table="customers",
        columns=["id", "region"]
    ),
    name="fk_order_customer"
)
Source code in src/yads/constraints.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@dataclass(frozen=True)
class ForeignKeyTableConstraint(TableConstraint):
    """Table-level foreign key constraint for composite relationships.

    Defines a foreign key across multiple columns. The number of columns must
    match the number of referenced columns.

    Args:
        columns: List of column names in this table that form the foreign key.
        references: The ForeignKeyReference specifying the target table and columns.
        name: Optional name for the constraint.

    Raises:
        InvalidConstraintError: If columns list is empty or if the number of
                              columns doesn't match the referenced columns.

    Example:
        ```python
        # Composite foreign key
        ForeignKeyTableConstraint(
            columns=["customer_id", "customer_region"],
            references=ForeignKeyReference(
                table="customers",
                columns=["id", "region"]
            ),
            name="fk_order_customer"
        )
        ```
    """

    columns: list[str]
    references: ForeignKeyReference
    name: str | None = None

    def __post_init__(self):
        if not self.columns:
            raise InvalidConstraintError(
                "ForeignKeyTableConstraint 'columns' cannot be empty."
            )
        if self.references.columns and len(self.columns) != len(self.references.columns):
            raise InvalidConstraintError(
                f"The number of columns in the foreign key ({len(self.columns)}) must match the number of "
                f"referenced columns ({len(self.references.columns)})."
            )

    @cached_property
    def constrained_columns(self) -> list[str]:
        return self.columns

    def __str__(self) -> str:
        parts: list[str] = []
        if self.name:
            parts.append(f"name={self.name!r}")

        formatted_columns = ",\n".join(f"{col!r}" for col in self.columns)
        indented_columns = textwrap.indent(formatted_columns, "  ")
        parts.append(f"columns=[\n{indented_columns}\n]")
        parts.append(f"references={self.references}")

        pretty_parts = ",\n".join(parts)
        indented_parts = textwrap.indent(pretty_parts, "  ")
        return f"ForeignKeyTableConstraint(\n{indented_parts}\n)"

ForeignKeyReference dataclass

Reference specification for foreign key constraints.

Defines the target table and optional columns referenced by a foreign key.

Parameters:

Name Type Description Default
table str

Name of the referenced table.

required
columns list[str] | None

List of column names in the referenced table.

None

Raises:

Type Description
InvalidConstraintError

If columns is an empty list.

Source code in src/yads/constraints.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@dataclass(frozen=True)
class ForeignKeyReference:
    """Reference specification for foreign key constraints.

    Defines the target table and optional columns referenced by a foreign key.

    Args:
        table: Name of the referenced table.
        columns: List of column names in the referenced table.

    Raises:
        InvalidConstraintError: If columns is an empty list.
    """

    table: str
    columns: list[str] | None = None

    def __post_init__(self):
        if self.columns == []:
            raise InvalidConstraintError(
                "ForeignKeyReference 'columns' cannot be an empty list."
            )

    def __str__(self) -> str:
        if self.columns:
            return f"{self.table}({', '.join(self.columns)})"
        return self.table