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/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ __version__ = "0.0.1"
2
+
3
+ from .core import (
4
+ Base,
5
+ BigInteger,
6
+ Boolean,
7
+ Column,
8
+ ColumnType,
9
+ Date,
10
+ DateTime,
11
+ Float,
12
+ Integer,
13
+ JSON,
14
+ LargeBinary,
15
+ Numeric,
16
+ SmallInteger,
17
+ String,
18
+ Time,
19
+ UUID,
20
+ )
21
+ from .pool import connect, disconnect
22
+ from .sql.conditions import and_, or_
23
+
24
+ __all__ = [
25
+ "__version__",
26
+ "Base",
27
+ "Column",
28
+ "Integer",
29
+ "String",
30
+ "Boolean",
31
+ "DateTime",
32
+ "ColumnType",
33
+ "SmallInteger",
34
+ "BigInteger",
35
+ "Float",
36
+ "Numeric",
37
+ "Date",
38
+ "Time",
39
+ "UUID",
40
+ "JSON",
41
+ "LargeBinary",
42
+ "connect",
43
+ "disconnect",
44
+ "and_",
45
+ "or_",
46
+ ]
@@ -0,0 +1,26 @@
1
+ """Models, columns, and Base."""
2
+
3
+ from .base import Base
4
+ from .column import Column
5
+ from .types import (
6
+ BigInteger,
7
+ Boolean,
8
+ ColumnType,
9
+ Date,
10
+ DateTime,
11
+ Float,
12
+ Integer,
13
+ JSON,
14
+ LargeBinary,
15
+ Numeric,
16
+ SmallInteger,
17
+ String,
18
+ Time,
19
+ UUID,
20
+ )
21
+
22
+ __all__ = [
23
+ "Base", "Column", "ColumnType", "SmallInteger", "Integer", "BigInteger",
24
+ "Float", "Numeric", "String", "Boolean", "Date", "Time", "DateTime",
25
+ "UUID", "JSON", "LargeBinary",
26
+ ]
pyzzel/core/base.py ADDED
@@ -0,0 +1,465 @@
1
+ """Base class for Pyzzel models."""
2
+
3
+ from pyzzel.core.column import Column, Labeled, _VersionColumn
4
+ from pyzzel.core.query import Query, _validate_condition_columns
5
+ from pyzzel.core.types import BigInteger, Integer, SmallInteger
6
+ from pyzzel.errors import ModelDefinitionError, NotFound, PyzzelError, QueryError, VersionConflict
7
+ from pyzzel import pool
8
+ from pyzzel.pool import connection
9
+ from pyzzel.sql import create_table as build_create_table, create_index as build_create_index
10
+ from pyzzel.sql import delete as build_delete
11
+ from pyzzel.sql import insert as build_insert
12
+ from pyzzel.sql import insert_many as build_insert_many
13
+ from pyzzel.sql import (
14
+ delete_where as build_delete_where,
15
+ select_by_pk,
16
+ update as build_update,
17
+ update_where as build_update_where,
18
+ )
19
+ from pyzzel.sql.builder import ColumnSpec, quote_ident
20
+ from pyzzel.sql.conditions import Condition, and_
21
+
22
+
23
+ _RESERVED = {
24
+ "get",
25
+ "save",
26
+ "create",
27
+ "delete",
28
+ "select",
29
+ "where",
30
+ "transaction",
31
+ "execute",
32
+ "create_tables",
33
+ "update",
34
+ "with_",
35
+ "version",
36
+ "max_rows",
37
+ }
38
+
39
+
40
+ def _classify_zero_rows(conn, table, pk_column, pk_value):
41
+ """Raise the appropriate model error after checking existence on this connection."""
42
+ statement = select_by_pk(table, [pk_column], pk_column, pk_value)
43
+ cursor = conn.execute(statement.sql, statement.params)
44
+ if cursor.fetchone() is None:
45
+ raise NotFound(table, pk_value)
46
+ raise VersionConflict(table, pk_value)
47
+
48
+
49
+ class Base:
50
+ """Base class for model definitions and in-memory row data."""
51
+
52
+ __abstract__ = True
53
+ max_rows: int | None = 10_000
54
+ _registry: dict[str, type] = {}
55
+
56
+ def __init_subclass__(cls, **kwargs):
57
+ super().__init_subclass__(**kwargs)
58
+ if cls.__dict__.get("__abstract__", False):
59
+ return
60
+
61
+ if "__tablename__" not in cls.__dict__ or not isinstance(cls.__dict__["__tablename__"], str):
62
+ raise ModelDefinitionError("Concrete models must define a string __tablename__")
63
+ try:
64
+ quote_ident(cls.__dict__["__tablename__"])
65
+ except ValueError as error:
66
+ raise ModelDefinitionError(f"Invalid table name: {error}") from error
67
+
68
+ if any(parent is not Base and issubclass(parent, Base) and not parent.__dict__.get("__abstract__", False)
69
+ for parent in cls.__mro__[1:]):
70
+ raise ModelDefinitionError("Subclassing a concrete model is not supported")
71
+
72
+ columns = {}
73
+ for parent in reversed(cls.__mro__):
74
+ if not issubclass(parent, Base):
75
+ continue
76
+ for name, value in parent.__dict__.items():
77
+ if isinstance(value, Column):
78
+ columns[name] = value
79
+
80
+ table_name = cls.__dict__["__tablename__"]
81
+ for name, column in tuple(columns.items()):
82
+ if name not in cls.__dict__:
83
+ column = column._clone()
84
+ setattr(cls, name, column)
85
+ columns[name] = column
86
+ column.table = table_name
87
+
88
+ primary_keys = [column for column in columns.values() if column.primary_key]
89
+ if len(primary_keys) != 1:
90
+ raise ModelDefinitionError("A model must define exactly one primary key column")
91
+ pk_name = next(name for name, column in columns.items() if column.primary_key)
92
+ if not isinstance(primary_keys[0].type, (SmallInteger, Integer, BigInteger)):
93
+ raise ModelDefinitionError(
94
+ "The primary key must be an integer type (SmallInteger, Integer or BigInteger)."
95
+ )
96
+
97
+ reserved = _RESERVED | {
98
+ name for name in Base.__dict__ if not name.startswith("_")
99
+ }
100
+ for name in columns:
101
+ try:
102
+ quote_ident(name)
103
+ except ValueError as error:
104
+ raise ModelDefinitionError(f"Invalid column name {name!r}: {error}") from error
105
+ if name.startswith("_"):
106
+ raise ModelDefinitionError("Column names must not start with '_'")
107
+ if name in reserved:
108
+ raise ModelDefinitionError(f"Column name {name!r} is reserved")
109
+
110
+ if table_name in Base._registry:
111
+ raise ModelDefinitionError(f"Table name {table_name!r} is already registered")
112
+
113
+ version = _VersionColumn()
114
+ version.name = "version"
115
+ version.table = table_name
116
+ setattr(cls, "version", version)
117
+ cls._columns = columns
118
+ cls._all_columns = {**columns, "version": version}
119
+ cls._pk_name = pk_name
120
+ cls._defaults = tuple(
121
+ (name, column.default)
122
+ for name, column in columns.items()
123
+ if column.default is not None
124
+ )
125
+ Base._registry[table_name] = cls
126
+
127
+ def __init__(self, **kwargs):
128
+ unknown = [name for name in kwargs if name not in self._columns]
129
+ if unknown:
130
+ names = ", ".join(repr(name) for name in unknown)
131
+ raise TypeError(f"Unknown model column(s): {names}")
132
+ self.__dict__.update(kwargs)
133
+ for name, default in self._defaults:
134
+ if name not in kwargs:
135
+ self.__dict__[name] = default() if callable(default) else default
136
+
137
+ @classmethod
138
+ def _from_row(cls, row):
139
+ """Construct a model from ordered row values without change tracking."""
140
+ instance = cls.__new__(cls)
141
+ instance._apply_row(row)
142
+ return instance
143
+
144
+ def _apply_row(self, row):
145
+ """Copy an ordered database row directly onto this model instance."""
146
+ if len(row) != len(self._all_columns):
147
+ raise ValueError("Row length does not match model columns")
148
+ for name, value in zip(self._all_columns, row):
149
+ self.__dict__[name] = value
150
+
151
+ def _changes(self) -> dict:
152
+ """Return current values for fields changed since loading or cleaning."""
153
+ changed = self.__dict__.get("_changed", {})
154
+ return {
155
+ name: self.__dict__.get(name)
156
+ for name in self._columns
157
+ if name in changed
158
+ }
159
+
160
+ def _mark_clean(self):
161
+ """Clear tracked field changes."""
162
+ self.__dict__.pop("_changed", None)
163
+
164
+ @classmethod
165
+ def _column_specs(cls) -> list[ColumnSpec]:
166
+ """Return SQL column specifications in model order."""
167
+ return [column._to_spec() for column in cls._all_columns.values()]
168
+
169
+ @classmethod
170
+ def _index_statements(cls) -> list[str]:
171
+ """Return index DDL for columns configured with an index."""
172
+ return [
173
+ build_create_index(cls.__tablename__, column.name)
174
+ for column in cls._columns.values()
175
+ if column.index
176
+ ]
177
+
178
+ @classmethod
179
+ def _ordered_models(cls) -> list[type]:
180
+ """Validate foreign keys and return registered models in dependency order."""
181
+ registry = Base._registry
182
+ dependencies = {table: [] for table in registry}
183
+ for table, model in registry.items():
184
+ for column in model._columns.values():
185
+ if column.foreign_key is None:
186
+ continue
187
+ parent_table, parent_name = column.foreign_key.split(".")
188
+ parent = registry.get(parent_table)
189
+ if parent is None:
190
+ raise ModelDefinitionError(
191
+ f"Foreign key {table}.{column.name} references unregistered table {parent_table!r}"
192
+ )
193
+ target = parent._columns.get(parent_name)
194
+ if target is None:
195
+ raise ModelDefinitionError(
196
+ f"Foreign key {table}.{column.name} references missing column {parent_table}.{parent_name}"
197
+ )
198
+ if not target.primary_key and not target.unique:
199
+ raise ModelDefinitionError(
200
+ f"Foreign key {table}.{column.name} references {parent_table}.{parent_name}, which is not primary key or unique"
201
+ )
202
+ if parent_table != table and parent_table not in dependencies[table]:
203
+ dependencies[table].append(parent_table)
204
+
205
+ remaining = {table: set(parents) for table, parents in dependencies.items()}
206
+ ordered = []
207
+ ordered_names = set()
208
+ while len(ordered_names) < len(registry):
209
+ ready = next(
210
+ (table for table in registry if table not in ordered_names
211
+ and remaining[table] <= ordered_names),
212
+ None,
213
+ )
214
+ if ready is None:
215
+ cycle_tables = [table for table in registry if table not in ordered_names]
216
+ raise ModelDefinitionError(
217
+ "Circular foreign key references between tables: "
218
+ + ", ".join(cycle_tables)
219
+ )
220
+ ordered.append(registry[ready])
221
+ ordered_names.add(ready)
222
+ return ordered
223
+
224
+ def __repr__(self):
225
+ values = ", ".join(f"{name}={getattr(self, name)!r}" for name in self._columns)
226
+ return f"{type(self).__name__}({values})"
227
+
228
+ @classmethod
229
+ def _run(cls, fn):
230
+ """Run a function on one autocommit pooled connection."""
231
+ with connection() as conn:
232
+ return fn(conn)
233
+
234
+ @classmethod
235
+ def _run_tx(cls, fn):
236
+ """Run a function atomically, reusing an active transaction when possible."""
237
+ if pool.in_transaction():
238
+ return cls._run(fn)
239
+ with pool.transaction():
240
+ return cls._run(fn)
241
+
242
+ @classmethod
243
+ def execute(cls, sql, params=None) -> list[tuple]:
244
+ """Execute raw SQL and return fetched rows when the statement has results."""
245
+ def run(conn):
246
+ cursor = conn.execute(sql, params)
247
+ return cursor.fetchall() if cursor.description is not None else []
248
+
249
+ return cls._run(run)
250
+
251
+ @classmethod
252
+ def create_tables(cls) -> None:
253
+ """Create all registered model tables in a single transaction."""
254
+ models = Base._ordered_models()
255
+
256
+ def run(conn):
257
+ for model in models:
258
+ conn.execute(build_create_table(model.__tablename__, model._column_specs()))
259
+ for model in models:
260
+ for statement in model._index_statements():
261
+ conn.execute(statement)
262
+
263
+ cls._run_tx(run)
264
+
265
+ @classmethod
266
+ def transaction(cls):
267
+ """Return a context manager for one shared database transaction."""
268
+ return pool.transaction()
269
+
270
+ @classmethod
271
+ def create(cls, **values):
272
+ """Create and persist a new instance of this model."""
273
+ return cls(**values).save()
274
+
275
+ @classmethod
276
+ def create_many(cls, rows) -> list:
277
+ """Create rows atomically and return their generated primary keys."""
278
+ rows = list(rows)
279
+ if not rows:
280
+ return []
281
+ if any(not isinstance(row, dict) for row in rows):
282
+ raise TypeError("create_many() rows must be dictionaries")
283
+ rows = [dict(row) for row in rows]
284
+ for row in rows:
285
+ for name, default in cls._defaults:
286
+ if name not in row:
287
+ row[name] = default() if callable(default) else default
288
+ keys = tuple(rows[0])
289
+ for row in rows:
290
+ if set(row) != set(keys):
291
+ raise QueryError("All rows must have the same columns.")
292
+ for name in keys:
293
+ if name not in cls._columns:
294
+ raise QueryError(f"Unknown column {name!r} for {cls.__name__}")
295
+ if name == cls._pk_name or name == "version":
296
+ raise QueryError(f"Column {name!r} cannot be set by create_many()")
297
+ def run(conn):
298
+ ids = []
299
+ if not keys:
300
+ statement = build_insert(
301
+ cls.__tablename__, {}, returning=[cls._pk_name]
302
+ )
303
+ for _ in rows:
304
+ result = conn.execute(statement.sql, statement.params)
305
+ ids.append(result.fetchone()[0])
306
+ return ids
307
+
308
+ chunk_size = min(1000, 65535 // len(keys))
309
+ for offset in range(0, len(rows), chunk_size):
310
+ chunk = rows[offset : offset + chunk_size]
311
+ params = [
312
+ tuple(cls._all_columns[name].to_db(row[name]) for name in keys)
313
+ for row in chunk
314
+ ]
315
+ statement = build_insert_many(
316
+ cls.__tablename__, keys, params, returning=[cls._pk_name]
317
+ )
318
+ result = conn.execute(statement.sql, statement.params)
319
+ ids.extend(row[0] for row in result.fetchall())
320
+ return ids
321
+
322
+ return cls._run_tx(run)
323
+
324
+ @classmethod
325
+ def _write_condition(cls, method, conditions):
326
+ if not conditions:
327
+ raise QueryError(
328
+ f"{method}() needs at least one condition. To change every row use User.<pk>.is_not_null()."
329
+ )
330
+ if any(not isinstance(condition, Condition) for condition in conditions):
331
+ raise TypeError(f"{method}() arguments must be conditions")
332
+ _validate_condition_columns(cls, conditions)
333
+ return and_(*conditions)
334
+
335
+ @classmethod
336
+ def _write_values(cls, method, values):
337
+ if not values:
338
+ raise QueryError(f"{method}() needs at least one value.")
339
+ for name in values:
340
+ if name not in cls._columns:
341
+ raise QueryError(f"Unknown column {name!r} for {cls.__name__}")
342
+ if name == cls._pk_name or name == "version":
343
+ raise QueryError(f"Column {name!r} cannot be changed by {method}()")
344
+
345
+ @classmethod
346
+ def update_where(cls, *conditions, **values) -> int:
347
+ """Update matching rows and bump each row's version."""
348
+ where = cls._write_condition("update_where", conditions)
349
+ cls._write_values("update_where", values)
350
+ statement = build_update_where(
351
+ cls.__tablename__,
352
+ {name: cls._all_columns[name].to_db(value) for name, value in values.items()},
353
+ where,
354
+ "version",
355
+ )
356
+ return cls._run(
357
+ lambda conn: conn.execute(statement.sql, statement.params).rowcount
358
+ )
359
+
360
+ @classmethod
361
+ def delete_where(cls, *conditions) -> int:
362
+ """Delete rows matching one or more conditions."""
363
+ where = cls._write_condition("delete_where", conditions)
364
+ statement = build_delete_where(cls.__tablename__, where)
365
+ return cls._run(
366
+ lambda conn: conn.execute(statement.sql, statement.params).rowcount
367
+ )
368
+
369
+ @classmethod
370
+ def get(cls, *args):
371
+ """Load a row by primary key or conditions, returning None when absent."""
372
+ if args and all(isinstance(arg, Condition) for arg in args):
373
+ row = cls.select(*cls._all_columns.values()).where(*args).first()
374
+ return cls._from_row(row) if row is not None else None
375
+ if len(args) != 1 or isinstance(args[0], Condition):
376
+ raise TypeError("get() needs one primary key value or one or more conditions")
377
+ pk_value = args[0]
378
+ statement = select_by_pk(
379
+ cls.__tablename__, list(cls._all_columns), cls._pk_name, pk_value
380
+ )
381
+ rows = cls.execute(statement.sql, statement.params)
382
+ return cls._from_row(rows[0]) if rows else None
383
+
384
+ @classmethod
385
+ def select(cls, *columns) -> Query:
386
+ for column in columns:
387
+ if isinstance(column, Labeled):
388
+ if not isinstance(column.column, Column):
389
+ raise TypeError("select() accepts Columns or labeled Columns")
390
+ elif not isinstance(column, Column):
391
+ raise TypeError("select() arguments must be Columns")
392
+ return Query(cls, tuple(columns))
393
+
394
+ def save(self):
395
+ """Insert a new model or persist its tracked changes."""
396
+ cls = type(self)
397
+ version = self.version
398
+ pk_name = cls._pk_name
399
+ if version is None:
400
+ if getattr(self, pk_name) is not None:
401
+ raise TypeError(
402
+ "The primary key is generated by the database; do not set it on a new object."
403
+ )
404
+ values = {
405
+ name: cls._all_columns[name].to_db(self.__dict__[name])
406
+ for name in cls._columns
407
+ if name != pk_name and name in self.__dict__
408
+ }
409
+ statement = build_insert(
410
+ cls.__tablename__, values, returning=list(cls._all_columns)
411
+ )
412
+ rows = cls.execute(statement.sql, statement.params)
413
+ self._apply_row(rows[0])
414
+ self._mark_clean()
415
+ return self
416
+
417
+ changes = {
418
+ name: cls._all_columns[name].to_db(value)
419
+ for name, value in self._changes().items()
420
+ }
421
+ if not changes:
422
+ return self
423
+ if pk_name in changes:
424
+ raise PyzzelError("The primary key cannot be changed.")
425
+ pk_value = getattr(self, pk_name)
426
+ statement = build_update(
427
+ cls.__tablename__,
428
+ changes,
429
+ pk_name,
430
+ pk_value,
431
+ "version",
432
+ version,
433
+ returning=list(cls._all_columns),
434
+ )
435
+
436
+ def run(conn):
437
+ cursor = conn.execute(statement.sql, statement.params)
438
+ row = cursor.fetchone()
439
+ if row is None:
440
+ _classify_zero_rows(conn, cls.__tablename__, pk_name, pk_value)
441
+ return row
442
+
443
+ row = cls._run(run)
444
+ self._apply_row(row)
445
+ self._mark_clean()
446
+ return self
447
+
448
+ def delete(self) -> None:
449
+ """Delete this saved model using its primary key and version."""
450
+ cls = type(self)
451
+ version = self.version
452
+ if version is None:
453
+ raise PyzzelError("This object has not been saved.")
454
+ pk_name = cls._pk_name
455
+ pk_value = getattr(self, pk_name)
456
+ statement = build_delete(
457
+ cls.__tablename__, pk_name, pk_value, "version", version
458
+ )
459
+
460
+ def run(conn):
461
+ cursor = conn.execute(statement.sql, statement.params)
462
+ if cursor.rowcount == 0:
463
+ _classify_zero_rows(conn, cls.__tablename__, pk_name, pk_value)
464
+
465
+ cls._run(run)