Pyzzel 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyzzel/core/column.py ADDED
@@ -0,0 +1,222 @@
1
+ """Column descriptors and their SQL specifications."""
2
+
3
+ import re
4
+ from typing import NamedTuple
5
+
6
+ from pyzzel.core.types import ColumnType, Integer
7
+ from pyzzel.errors import ModelDefinitionError, QueryError
8
+ from pyzzel.sql.builder import ColumnSpec, check_default_expression, quote_ident
9
+ from pyzzel.sql.conditions import Comparison, InList, NullCheck, OrderBy, Pattern
10
+
11
+
12
+ _FOREIGN_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}\.[A-Za-z_][A-Za-z0-9_]{0,62}$")
13
+ _ON_DELETE = {"NO ACTION", "RESTRICT", "CASCADE", "SET NULL"}
14
+
15
+
16
+ class Labeled(NamedTuple):
17
+ column: "Column"
18
+ alias: str
19
+
20
+
21
+ class Column:
22
+ """A typed model field with change tracking."""
23
+
24
+ def __init__(
25
+ self,
26
+ type,
27
+ *,
28
+ primary_key=False,
29
+ nullable=True,
30
+ unique=False,
31
+ default=None,
32
+ server_default=None,
33
+ foreign_key=None,
34
+ on_delete="NO ACTION",
35
+ index=None,
36
+ ):
37
+ """Create a column; server_default is trusted text written by the developer, never user input."""
38
+ if isinstance(type, ColumnType):
39
+ pass
40
+ else:
41
+ try:
42
+ is_column_type = issubclass(type, ColumnType)
43
+ except TypeError:
44
+ is_column_type = False
45
+ if is_column_type:
46
+ type = type()
47
+ else:
48
+ raise TypeError("Column type must be a ColumnType class or instance")
49
+ if default is not None and isinstance(default, (list, dict, set, bytearray)):
50
+ raise ModelDefinitionError("Mutable defaults are not supported; use a function such as default=list")
51
+ if primary_key and default is not None:
52
+ raise ModelDefinitionError("A primary key column cannot have a Python default")
53
+ if server_default is not None:
54
+ try:
55
+ check_default_expression(server_default)
56
+ except ValueError as error:
57
+ raise ModelDefinitionError(str(error)) from error
58
+ if foreign_key is not None and (
59
+ not isinstance(foreign_key, str) or _FOREIGN_KEY.fullmatch(foreign_key) is None
60
+ ):
61
+ raise ModelDefinitionError("foreign_key must be a 'table.column' identifier")
62
+ if primary_key and foreign_key is not None:
63
+ raise ModelDefinitionError("A primary key column cannot have a foreign_key")
64
+ if not isinstance(on_delete, str) or on_delete.upper() not in _ON_DELETE:
65
+ raise ModelDefinitionError("on_delete must be NO ACTION, RESTRICT, CASCADE, or SET NULL")
66
+ on_delete = on_delete.upper()
67
+ if foreign_key is None and on_delete != "NO ACTION":
68
+ raise ModelDefinitionError("on_delete requires foreign_key")
69
+ if foreign_key is not None and on_delete == "SET NULL" and not nullable:
70
+ raise ModelDefinitionError("SET NULL requires nullable=True")
71
+ if index is not None and not isinstance(index, bool):
72
+ raise ModelDefinitionError("index must be True, False, or None")
73
+ self.type = type
74
+ self.primary_key = primary_key
75
+ self.nullable = nullable
76
+ self.unique = unique
77
+ self.default = default
78
+ self.server_default = server_default
79
+ self.foreign_key = foreign_key
80
+ self.on_delete = on_delete
81
+ self.index = False if primary_key or unique else (
82
+ index if index is not None else foreign_key is not None
83
+ )
84
+ self.name = None
85
+ self.table = None
86
+
87
+ def __set_name__(self, owner, name):
88
+ self.name = name
89
+
90
+ def __get__(self, obj, owner=None):
91
+ if obj is None:
92
+ return self
93
+ return obj.__dict__.get(self.name)
94
+
95
+ def __set__(self, obj, value):
96
+ old = obj.__dict__.get(self.name)
97
+ if value is old or (
98
+ not isinstance(value, Column)
99
+ and not isinstance(old, Column)
100
+ and value == old
101
+ ):
102
+ return
103
+ changed = obj.__dict__.get("_changed")
104
+ if changed is None:
105
+ changed = {}
106
+ obj.__dict__["_changed"] = changed
107
+ changed.setdefault(self.name, old)
108
+ original = changed[self.name]
109
+ if value is original or (
110
+ not isinstance(value, Column) and not isinstance(original, Column)
111
+ and value == original
112
+ ):
113
+ del changed[self.name]
114
+ obj.__dict__[self.name] = value
115
+
116
+ def __hash__(self):
117
+ return id(self)
118
+
119
+ def _clone(self):
120
+ """Copy this column's definition for an inheriting model."""
121
+ clone = Column(
122
+ self.type,
123
+ primary_key=self.primary_key,
124
+ nullable=self.nullable,
125
+ unique=self.unique,
126
+ default=self.default,
127
+ server_default=self.server_default,
128
+ foreign_key=self.foreign_key,
129
+ on_delete=self.on_delete,
130
+ index=self.index,
131
+ )
132
+ clone.name = self.name
133
+ clone.table = self.table
134
+ return clone
135
+
136
+ def label(self, alias):
137
+ """Name this selected value in a result row."""
138
+ try:
139
+ quote_ident(alias)
140
+ except ValueError as error:
141
+ raise QueryError(f"Invalid column label: {error}") from error
142
+ return Labeled(self, alias)
143
+
144
+ def _compare(self, operator, other):
145
+ if isinstance(other, Column):
146
+ raise TypeError("Comparing two columns is not supported yet")
147
+ return Comparison(self.name, operator, self.to_db(other), self.table)
148
+
149
+ def to_db(self, value):
150
+ return None if value is None else self.type.to_db(value)
151
+
152
+ def __eq__(self, other):
153
+ return self._compare("=", other)
154
+
155
+ def __ne__(self, other):
156
+ return self._compare("<>", other)
157
+
158
+ def __lt__(self, other):
159
+ return self._compare("<", other)
160
+
161
+ def __le__(self, other):
162
+ return self._compare("<=", other)
163
+
164
+ def __gt__(self, other):
165
+ return self._compare(">", other)
166
+
167
+ def __ge__(self, other):
168
+ return self._compare(">=", other)
169
+
170
+ def in_(self, values):
171
+ """Values are sent as one array parameter, so the number of values is not limited."""
172
+ if not isinstance(values, (list, tuple, set, frozenset)):
173
+ raise TypeError("in_() needs a list, tuple, set, or frozenset")
174
+ if isinstance(values, (set, frozenset)):
175
+ values = list(values)
176
+ return InList(self.name, [self.to_db(value) for value in values], self.table)
177
+
178
+ def like(self, pattern):
179
+ return Pattern(self.name, "LIKE", pattern, self.table)
180
+
181
+ def ilike(self, pattern):
182
+ return Pattern(self.name, "ILIKE", pattern, self.table)
183
+
184
+ def is_null(self):
185
+ return NullCheck(self.name, table=self.table)
186
+
187
+ def is_not_null(self):
188
+ return NullCheck(self.name, negated=True, table=self.table)
189
+
190
+ def asc(self):
191
+ return OrderBy(self.name, "ASC", self.table)
192
+
193
+ def desc(self):
194
+ return OrderBy(self.name, "DESC", self.table)
195
+
196
+ def _to_spec(self) -> ColumnSpec:
197
+ """Return the SQL builder specification for this column."""
198
+ return ColumnSpec(
199
+ self.name,
200
+ self.type.sql_type,
201
+ primary_key=self.primary_key,
202
+ identity=self.primary_key,
203
+ nullable=self.nullable,
204
+ unique=self.unique,
205
+ default=self.server_default,
206
+ foreign_key=tuple(self.foreign_key.split(".")) if self.foreign_key else None,
207
+ on_delete=self.on_delete if self.foreign_key else None,
208
+ )
209
+
210
+
211
+ class _VersionColumn(Column):
212
+ """Hidden, Pyzzel-managed model version field."""
213
+
214
+ def __init__(self):
215
+ super().__init__(Integer, nullable=False)
216
+
217
+ def __set__(self, obj, value):
218
+ raise AttributeError("version is managed by Pyzzel")
219
+
220
+ def _to_spec(self) -> ColumnSpec:
221
+ """Return the SQL specification for the hidden version field."""
222
+ return ColumnSpec("version", "INTEGER", nullable=False, default="1")
pyzzel/core/query.py ADDED
@@ -0,0 +1,365 @@
1
+ """Immutable model queries and result conversion."""
2
+
3
+ from collections import namedtuple
4
+
5
+ from pyzzel.core.column import Column, Labeled
6
+ from pyzzel.errors import QueryError, TooManyRowsError
7
+ from pyzzel.sql import (
8
+ ColumnRef, Condition, Join, OrderBy, and_, count as build_count,
9
+ select as build_select,
10
+ )
11
+
12
+
13
+ _row_types = {}
14
+ _UNSET = object()
15
+
16
+
17
+ def _validate_condition_columns(models, conditions, main_model=None):
18
+ if not isinstance(models, (tuple, list)):
19
+ models = (models,)
20
+ by_table = {model.__tablename__: model for model in models}
21
+ main_table = main_model.__tablename__ if main_model is not None else models[0].__tablename__
22
+ for condition in conditions:
23
+ for table, name in condition.columns():
24
+ table = table or main_table
25
+ model = by_table.get(table)
26
+ if model is None:
27
+ from pyzzel import Base
28
+
29
+ joined_model = Base._registry.get(table)
30
+ label = joined_model.__name__ if joined_model is not None else table
31
+ raise QueryError(
32
+ f"Unknown column {table}.{name} in this query; Join {label} first"
33
+ )
34
+ if name not in model._all_columns:
35
+ raise QueryError(f"Unknown column {table}.{name} for {model.__name__}")
36
+
37
+
38
+ def _row_type(names):
39
+ row_type = _row_types.get(names)
40
+ if row_type is None:
41
+ row_type = namedtuple("Row", names)
42
+ _row_types[names] = row_type
43
+ return row_type
44
+
45
+
46
+ class Query:
47
+ """Immutable query for one model."""
48
+
49
+ __slots__ = (
50
+ "model", "selected", "condition", "ordering", "_limit", "_offset",
51
+ "_unlimited", "relations", "models", "joins", "_distinct",
52
+ )
53
+
54
+ def __init__(
55
+ self, model, selected=(), condition=None, ordering=(), limit=None,
56
+ offset=None, unlimited=False, relations=(), models=None, joins=(), distinct=False,
57
+ ):
58
+ object.__setattr__(self, "model", model)
59
+ object.__setattr__(self, "selected", tuple(selected))
60
+ object.__setattr__(self, "condition", condition)
61
+ object.__setattr__(self, "ordering", tuple(ordering))
62
+ object.__setattr__(self, "_limit", limit)
63
+ object.__setattr__(self, "_offset", offset)
64
+ object.__setattr__(self, "_unlimited", unlimited)
65
+ object.__setattr__(self, "relations", tuple(relations))
66
+ object.__setattr__(self, "models", tuple(models or (model,)))
67
+ object.__setattr__(self, "joins", tuple(joins))
68
+ object.__setattr__(self, "_distinct", distinct)
69
+
70
+ def __setattr__(self, name, value):
71
+ raise AttributeError("Query objects are immutable")
72
+
73
+ def _new(
74
+ self, *, condition=_UNSET, ordering=_UNSET, limit=_UNSET, offset=_UNSET,
75
+ unlimited=_UNSET, relations=_UNSET, models=_UNSET, joins=_UNSET,
76
+ distinct=_UNSET,
77
+ ):
78
+ return Query(
79
+ self.model,
80
+ self.selected,
81
+ self.condition if condition is _UNSET else condition,
82
+ self.ordering if ordering is _UNSET else ordering,
83
+ self._limit if limit is _UNSET else limit,
84
+ self._offset if offset is _UNSET else offset,
85
+ self._unlimited if unlimited is _UNSET else unlimited,
86
+ self.relations if relations is _UNSET else relations,
87
+ self.models if models is _UNSET else models,
88
+ self.joins if joins is _UNSET else joins,
89
+ self._distinct if distinct is _UNSET else distinct,
90
+ )
91
+
92
+ def with_(self, **relations):
93
+ """Return a query that loads explicitly named one-level relations."""
94
+ from pyzzel import Base
95
+
96
+ if self.joins:
97
+ raise QueryError("with_() cannot be combined with joins")
98
+
99
+ selected_names = set()
100
+ for item in self.selected:
101
+ if isinstance(item, Labeled):
102
+ selected_names.update((item.column.name, item.alias))
103
+ else:
104
+ selected_names.add(item.name)
105
+ if not selected_names:
106
+ selected_names = set(self.model._columns)
107
+ additions = []
108
+ existing_names = {name for name, *_ in self.relations}
109
+ for name, column in relations.items():
110
+ if not isinstance(column, Column) or column.foreign_key is None:
111
+ raise QueryError(f"Relation {name!r} must be a foreign-key Column")
112
+ if name in selected_names or name in existing_names:
113
+ raise QueryError(f"Relation name {name!r} conflicts with a selected column or relation")
114
+ owner = Base._registry.get(column.table)
115
+ if owner is None or owner._all_columns.get(column.name) is not column:
116
+ raise QueryError(f"Could not find exactly one model owning column {column.name!r}")
117
+ parent_table, parent_name = column.foreign_key.split(".")
118
+ parent = Base._registry.get(parent_table)
119
+ if parent is None:
120
+ raise QueryError(f"Foreign-key parent table {parent_table!r} is not registered")
121
+ if parent_name not in parent._columns:
122
+ raise QueryError(f"Foreign-key column {parent_table}.{parent_name} is not registered")
123
+ if self.model is owner and self.model is parent:
124
+ raise QueryError("self-referencing relations are not supported by with_ yet")
125
+ if self.model is owner:
126
+ direction = "many"
127
+ key_column = column
128
+ elif self.model is parent:
129
+ direction = "one"
130
+ key_column = parent._columns[parent_name]
131
+ else:
132
+ raise QueryError(f"{column.name} does not link {self.model.__name__} to another model")
133
+ if key_column.name not in selected_names:
134
+ raise QueryError(f"Add {key_column.name!r} to select() to load relation {name!r}")
135
+ additions.append((name, column, owner, parent, direction, parent._columns[parent_name]))
136
+ existing_names.add(name)
137
+ return self._new(relations=self.relations + tuple(additions))
138
+
139
+ def join(self, model, on=None):
140
+ return self._join(model, "INNER", on)
141
+
142
+ def left_join(self, model, on=None):
143
+ return self._join(model, "LEFT", on)
144
+
145
+ def _join(self, model, kind, on):
146
+ from pyzzel import Base
147
+
148
+ if not isinstance(model, type) or not issubclass(model, Base):
149
+ raise QueryError("join() needs a registered model class")
150
+ if Base._registry.get(getattr(model, "__tablename__", None)) is not model:
151
+ raise QueryError("join() needs a registered model class")
152
+ if model in self.models:
153
+ raise QueryError(f"Model {model.__name__} is already in this query (self-joins are not supported)")
154
+ if self.relations:
155
+ raise QueryError("joins cannot be combined with with_()")
156
+
157
+ existing_tables = {item.__tablename__ for item in self.models}
158
+ candidates = []
159
+ for column in model._columns.values():
160
+ if column.foreign_key:
161
+ parent_table, parent_column = column.foreign_key.split(".")
162
+ if parent_table in existing_tables:
163
+ candidates.append((column, model.__tablename__, column.name, parent_table, parent_column))
164
+ for existing in self.models:
165
+ for column in existing._columns.values():
166
+ if column.foreign_key:
167
+ parent_table, parent_column = column.foreign_key.split(".")
168
+ if parent_table == model.__tablename__:
169
+ candidates.append((column, existing.__tablename__, column.name,
170
+ parent_table, parent_column))
171
+
172
+ if on is not None:
173
+ candidate = next((item for item in candidates if item[0] is on), None)
174
+ if not isinstance(on, Column) or on.foreign_key is None or candidate is None:
175
+ raise QueryError("on= must be a foreign-key column linking the joined model to this query")
176
+ candidates = [candidate]
177
+ elif not candidates:
178
+ existing_names = ", ".join(item.__name__ for item in self.models)
179
+ raise QueryError(f"no foreign key links {existing_names} and {model.__name__}")
180
+ elif len(candidates) > 1:
181
+ raise QueryError(f"Several foreign keys link this query and {model.__name__}; pass on=<foreign key column>")
182
+
183
+ _, left_table, left_column, right_table, right_column = candidates[0]
184
+ join = Join(kind, model.__tablename__, left_table, left_column, right_table, right_column)
185
+ return self._new(models=self.models + (model,), joins=self.joins + (join,))
186
+
187
+ def distinct(self):
188
+ return self._new(distinct=True)
189
+
190
+ def where(self, *conditions):
191
+ if not conditions or any(not isinstance(condition, Condition) for condition in conditions):
192
+ raise TypeError("where() needs conditions such as User.age > 18")
193
+ combined = and_(*conditions)
194
+ if self.condition is not None:
195
+ combined = self.condition & combined
196
+ return self._new(condition=combined)
197
+
198
+ def order_by(self, *items):
199
+ additions = []
200
+ for item in items:
201
+ if isinstance(item, Column):
202
+ name = item.name
203
+ order_item = OrderBy(name, "ASC", item.table)
204
+ elif isinstance(item, OrderBy):
205
+ name = item.column
206
+ order_item = item
207
+ else:
208
+ raise TypeError("order_by() needs Columns or OrderBy values")
209
+ additions.append(order_item)
210
+ return self._new(ordering=self.ordering + tuple(additions))
211
+
212
+ def limit(self, value):
213
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
214
+ raise QueryError("limit() needs an int greater than or equal to 0")
215
+ return self._new(limit=value)
216
+
217
+ def offset(self, value):
218
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
219
+ raise QueryError("offset() needs an int greater than or equal to 0")
220
+ return self._new(offset=value)
221
+
222
+ def _validated_parts(self):
223
+ from pyzzel import Base
224
+
225
+ by_table = {model.__tablename__: model for model in self.models}
226
+ entries = []
227
+ if self.selected:
228
+ for selected in self.selected:
229
+ if isinstance(selected, Labeled):
230
+ column, alias = selected
231
+ else:
232
+ column, alias = selected, None
233
+ if not isinstance(column, Column):
234
+ raise QueryError("select() accepts Columns or labeled Columns")
235
+ table = column.table
236
+ model = by_table.get(table)
237
+ if model is None:
238
+ owner = Base._registry.get(table)
239
+ label = owner.__name__ if owner is not None else str(table)
240
+ raise QueryError(
241
+ f"Unknown column {table}.{column.name} in this query; Join {label} first"
242
+ )
243
+ if model._all_columns.get(column.name) is not column:
244
+ raise QueryError(f"Column {table}.{column.name} does not belong to {model.__name__}")
245
+ entries.append((column, alias))
246
+ else:
247
+ entries = [(column, None) for column in self.model._columns.values()]
248
+
249
+ names = tuple(alias or column.name for column, alias in entries)
250
+ if len(set(names)) != len(names):
251
+ raise QueryError("A selected result field appears more than once; use .label(\"...\")")
252
+
253
+ if self.condition is not None:
254
+ _validate_condition_columns(self.models, (self.condition,), self.model)
255
+ for item in self.ordering:
256
+ table = item.table or self.model.__tablename__
257
+ target = by_table.get(table)
258
+ if target is None or item.column not in target._all_columns:
259
+ from pyzzel import Base
260
+
261
+ joined = Base._registry.get(table)
262
+ label = joined.__name__ if joined is not None else table
263
+ raise QueryError(
264
+ f"Unknown column {table}.{item.column} in this query; Join {label} first"
265
+ )
266
+ refs = [ColumnRef(column.table, column.name, alias) for column, alias in entries]
267
+ return refs, names, entries
268
+
269
+ def to_sql(self):
270
+ """Build the full query statement, including any joins."""
271
+ refs, _, _ = self._validated_parts()
272
+ return build_select(
273
+ self.model.__tablename__,
274
+ refs,
275
+ where=self.condition,
276
+ order_by=self.ordering,
277
+ limit=self._limit,
278
+ offset=self._offset,
279
+ joins=self.joins,
280
+ distinct=self._distinct,
281
+ )
282
+
283
+ def all(self):
284
+ ".all() adds LIMIT max_rows + 1 at run time only to detect an overflow."
285
+ statement = self.to_sql()
286
+ max_rows = self.model.max_rows
287
+ guarded = self._limit is None and not self._unlimited and max_rows is not None
288
+ if guarded:
289
+ refs, _, _ = self._validated_parts()
290
+ statement = build_select(
291
+ self.model.__tablename__,
292
+ refs,
293
+ where=self.condition,
294
+ order_by=self.ordering,
295
+ limit=max_rows + 1,
296
+ offset=self._offset,
297
+ joins=self.joins,
298
+ distinct=self._distinct,
299
+ )
300
+ rows = self.model.execute(statement.sql, statement.params)
301
+ if guarded and len(rows) > max_rows:
302
+ raise TooManyRowsError(
303
+ f"Query returned more than {max_rows} rows. Add limit(), page with offset(), or call unlimited()."
304
+ )
305
+ _, names, entries = self._validated_parts()
306
+ if not self.relations:
307
+ row_type = _row_type(names)
308
+ return [row_type(*row) for row in rows]
309
+
310
+ related_by_name = {}
311
+ for name, fk_column, owner, parent, direction, parent_column in self.relations:
312
+ if direction == "one":
313
+ key_index = next(index for index, (column, _) in enumerate(entries)
314
+ if column is parent_column)
315
+ keys = list(dict.fromkeys(row[key_index] for row in rows if row[key_index] is not None))
316
+ grouped = {}
317
+ if keys:
318
+ children = owner.select().where(fk_column.in_(keys)).order_by(
319
+ owner._all_columns[owner._pk_name]
320
+ ).all()
321
+ for child in children:
322
+ grouped.setdefault(getattr(child, fk_column.name), []).append(child)
323
+ related_by_name[name] = [
324
+ grouped.get(row[key_index], []) if row[key_index] is not None else []
325
+ for row in rows
326
+ ]
327
+ else:
328
+ key_index = next(index for index, (column, _) in enumerate(entries)
329
+ if column is fk_column)
330
+ keys = list(dict.fromkeys(row[key_index] for row in rows if row[key_index] is not None))
331
+ matched = {}
332
+ if keys:
333
+ parents = parent.select().where(parent_column.in_(keys)).all()
334
+ matched = {getattr(row, parent_column.name): row for row in parents}
335
+ related_by_name[name] = [
336
+ matched.get(row[key_index]) if row[key_index] is not None else None
337
+ for row in rows
338
+ ]
339
+ row_type = _row_type((*names, *(relation[0] for relation in self.relations)))
340
+ return [
341
+ row_type(*row, *(related_by_name[relation[0]][index] for relation in self.relations))
342
+ for index, row in enumerate(rows)
343
+ ]
344
+
345
+ def unlimited(self):
346
+ """Return a query without the automatic row guard."""
347
+ return self._new(unlimited=True)
348
+
349
+ def first(self):
350
+ rows = self.limit(1).all()
351
+ return rows[0] if rows else None
352
+
353
+ def count(self):
354
+ if self._distinct:
355
+ raise QueryError("count() with distinct() is not supported yet")
356
+ self._validated_parts()
357
+ statement = build_count(self.model.__tablename__, self.condition, joins=self.joins)
358
+ rows = self.model.execute(statement.sql, statement.params)
359
+ return rows[0][0]
360
+
361
+ def __iter__(self):
362
+ return iter(self.all())
363
+
364
+ def __repr__(self):
365
+ return f"Query({self.to_sql().sql!r})"
pyzzel/core/types.py ADDED
@@ -0,0 +1,95 @@
1
+ """Column types supported by Pyzzel models."""
2
+
3
+
4
+ class ColumnType:
5
+ """Small common interface for PostgreSQL column types."""
6
+
7
+ sql_type = None
8
+
9
+ def to_db(self, value):
10
+ return value
11
+
12
+
13
+ class SmallInteger(ColumnType):
14
+ sql_type = "SMALLINT"
15
+
16
+
17
+ class Integer(ColumnType):
18
+ """PostgreSQL integer column type."""
19
+
20
+ sql_type = "INTEGER"
21
+
22
+
23
+ class BigInteger(ColumnType):
24
+ sql_type = "BIGINT"
25
+
26
+
27
+ class Float(ColumnType):
28
+ sql_type = "DOUBLE PRECISION"
29
+
30
+
31
+ class Numeric(ColumnType):
32
+ def __init__(self, precision=None, scale=None):
33
+ if precision is not None and (type(precision) is not int or precision <= 0):
34
+ raise ValueError("Numeric precision must be a positive integer")
35
+ if scale is not None and (type(scale) is not int or scale < 0):
36
+ raise ValueError("Numeric scale must be a non-negative integer")
37
+ if scale is not None and precision is None:
38
+ raise ValueError("Numeric scale requires precision")
39
+ if precision is not None and scale is not None and scale > precision:
40
+ raise ValueError("Numeric scale cannot exceed precision")
41
+ if precision is None:
42
+ self.sql_type = "NUMERIC"
43
+ elif scale is None:
44
+ self.sql_type = f"NUMERIC({precision})"
45
+ else:
46
+ self.sql_type = f"NUMERIC({precision},{scale})"
47
+
48
+
49
+ class Boolean(ColumnType):
50
+ """PostgreSQL boolean column type."""
51
+
52
+ sql_type = "BOOLEAN"
53
+
54
+
55
+ class Date(ColumnType):
56
+ sql_type = "DATE"
57
+
58
+
59
+ class Time(ColumnType):
60
+ sql_type = "TIME"
61
+
62
+
63
+ class DateTime(ColumnType):
64
+ """PostgreSQL timestamp column type."""
65
+
66
+ sql_type = "TIMESTAMPTZ"
67
+
68
+ def __init__(self, timezone=True):
69
+ self.sql_type = "TIMESTAMPTZ" if timezone else "TIMESTAMP"
70
+
71
+
72
+ class UUID(ColumnType):
73
+ sql_type = "UUID"
74
+
75
+
76
+ class JSON(ColumnType):
77
+ sql_type = "JSONB"
78
+
79
+ def to_db(self, value):
80
+ from psycopg.types.json import Jsonb
81
+
82
+ return Jsonb(value)
83
+
84
+
85
+ class LargeBinary(ColumnType):
86
+ sql_type = "BYTEA"
87
+
88
+
89
+ class String(ColumnType):
90
+ """PostgreSQL text or bounded varchar column type."""
91
+
92
+ def __init__(self, length=None):
93
+ if length is not None and (type(length) is not int or length <= 0):
94
+ raise ValueError("String length must be a positive integer")
95
+ self.sql_type = "TEXT" if length is None else f"VARCHAR({length})"