python-corekit 0.6.2__py3-none-any.whl → 0.6.4__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.
@@ -16,7 +16,7 @@ from corekit.connections.sql.operations import (
16
16
  Update,
17
17
  )
18
18
  from corekit.connections.sql.query import Query
19
- from corekit.connections.sql.table import NamedTable, TableExportItem
19
+ from corekit.connections.sql.table import NamedTable, TableExportItem, TTable
20
20
 
21
21
  __all__ = [
22
22
  "Conditional",
@@ -35,5 +35,6 @@ __all__ = [
35
35
  "Select",
36
36
  "SQLConnection",
37
37
  "TableExportItem",
38
+ "TTable",
38
39
  "Update",
39
40
  ]
@@ -26,7 +26,7 @@ from corekit.config import get_settings
26
26
  from corekit.connections import Connectable
27
27
  from corekit.connections.sql.operations import DqlOperation, Operation, Select
28
28
  from corekit.connections.sql.query import Query
29
- from corekit.connections.sql.table import NamedTable
29
+ from corekit.connections.sql.table import TTable
30
30
 
31
31
  __all__ = ["PaginatedResult", "SQLConnection"]
32
32
 
@@ -261,7 +261,7 @@ class SQLConnection(Connectable):
261
261
  self.session.merge(item)
262
262
  self.session.commit()
263
263
 
264
- def delete(self, table: type[NamedTable], identifier: str) -> None:
264
+ def delete(self, table: type[TTable], identifier: str) -> None:
265
265
  """
266
266
  Delete a row by id.
267
267
  """
@@ -308,19 +308,19 @@ class SQLConnection(Connectable):
308
308
  result = self.select(statement)
309
309
  return None if result is None else result.first()
310
310
 
311
- def fetch_all(self, table: type[NamedTable]) -> Iterator[NamedTable]:
311
+ def fetch_all(self, table: type[TTable]) -> Iterator[TTable]:
312
312
  """
313
313
  Every row in a table.
314
314
  """
315
315
  return self._exec(select(table))
316
316
 
317
- def fetch_one_by_id(self, table: type[NamedTable], identifier: str) -> NamedTable | None:
317
+ def fetch_one_by_id(self, table: type[TTable], identifier: str) -> TTable | None:
318
318
  """
319
319
  A single row by id.
320
320
  """
321
321
  return self.first(select(table).where(table.id == identifier))
322
322
 
323
- def fetch_one_by_condition(self, table: type[NamedTable], key: Any, value: Any) -> NamedTable | None:
323
+ def fetch_one_by_condition(self, table: type[TTable], key: Any, value: Any) -> TTable | None:
324
324
  """
325
325
  The first row where a column equals a value.
326
326
 
@@ -330,13 +330,13 @@ class SQLConnection(Connectable):
330
330
  column = getattr(table, key) if isinstance(key, str) else key
331
331
  return self.first(select(table).where(column == value))
332
332
 
333
- def exists(self, table: type[NamedTable], identifier: str) -> bool:
333
+ def exists(self, table: type[TTable], identifier: str) -> bool:
334
334
  """
335
335
  Whether a row with this id exists.
336
336
  """
337
337
  return self.fetch_one_by_id(table, identifier) is not None
338
338
 
339
- def fetch_or_create_one(self, table: type[NamedTable], identifier: str) -> NamedTable:
339
+ def fetch_or_create_one(self, table: type[TTable], identifier: str) -> TTable:
340
340
  """
341
341
  Fetch a row by id, inserting a default one if it is missing.
342
342
  """
@@ -346,13 +346,13 @@ class SQLConnection(Connectable):
346
346
  self.insert(item)
347
347
  return item
348
348
 
349
- def fetch_many_by_query(self, query: Query) -> list[NamedTable]:
349
+ def fetch_many_by_query(self, query: Query[TTable]) -> list[TTable]:
350
350
  """
351
351
  Every row matching a Query.
352
352
  """
353
353
  return list(self._exec(query.build()))
354
354
 
355
- def delete_many_by_query(self, query: Query) -> int:
355
+ def delete_many_by_query(self, query: Query[TTable]) -> int:
356
356
  """
357
357
  Delete every row matching a Query.
358
358
 
@@ -366,7 +366,7 @@ class SQLConnection(Connectable):
366
366
  self.session.commit()
367
367
  return len(items)
368
368
 
369
- def execute(self, operation: Operation) -> Any:
369
+ def execute(self, operation: Operation[Any]) -> Any:
370
370
  """
371
371
  Run an operation, committing if it writes.
372
372
 
@@ -380,19 +380,19 @@ class SQLConnection(Connectable):
380
380
  self.session.commit()
381
381
  return result
382
382
 
383
- def fetch(self, operation: DqlOperation) -> list[NamedTable]:
383
+ def fetch(self, operation: DqlOperation[TTable]) -> list[TTable]:
384
384
  """
385
385
  Every row an operation selects.
386
386
  """
387
387
  return list(self.execute(operation))
388
388
 
389
- def fetch_one_by_query(self, query: Query) -> NamedTable | None:
389
+ def fetch_one_by_query(self, query: Query[TTable]) -> TTable | None:
390
390
  """
391
391
  The first row matching a Query.
392
392
  """
393
393
  return self.first(query.build())
394
394
 
395
- def count(self, table: type[NamedTable]) -> int:
395
+ def count(self, table: type[TTable]) -> int:
396
396
  """
397
397
  The number of rows in a table.
398
398
  """
@@ -401,13 +401,13 @@ class SQLConnection(Connectable):
401
401
 
402
402
  def paginate(
403
403
  self,
404
- table: type[NamedTable],
404
+ table: type[TTable],
405
405
  offset: int = 0,
406
406
  limit: int = 50,
407
407
  *,
408
408
  order_by: Any = None,
409
409
  desc: bool = False,
410
- ) -> PaginatedResult:
410
+ ) -> PaginatedResult[TTable]:
411
411
  """
412
412
  A page of rows, together with the total row count.
413
413
 
@@ -3,17 +3,17 @@ Statement primitives: the shapes a database operation can take.
3
3
  """
4
4
 
5
5
  from abc import ABC, abstractmethod
6
- from typing import Any, ClassVar
6
+ from typing import Any, ClassVar, Generic, Self
7
7
 
8
8
  from pydantic import BaseModel, Field
9
9
 
10
- from corekit.connections.sql.table import NamedTable
10
+ from corekit.connections.sql.table import TTable
11
11
  from corekit.data.expressions import Expression
12
12
 
13
13
  __all__ = ["Conditional", "DdlOperation", "DmlOperation", "DqlOperation", "Operation"]
14
14
 
15
15
 
16
- class Operation(BaseModel, ABC):
16
+ class Operation(BaseModel, ABC, Generic[TTable]):
17
17
  """
18
18
  A statement waiting to be executed.
19
19
 
@@ -28,7 +28,7 @@ class Operation(BaseModel, ABC):
28
28
  #: Conditional writes (update, delete) and insert both set this; reads do not.
29
29
  writes: ClassVar[bool] = False
30
30
 
31
- table: type[NamedTable]
31
+ table: type[TTable]
32
32
 
33
33
  @abstractmethod
34
34
  def build(self) -> Any:
@@ -40,7 +40,7 @@ class Operation(BaseModel, ABC):
40
40
  return f"{type(self).__name__}({self.table.__name__})"
41
41
 
42
42
 
43
- class Conditional(Operation, ABC):
43
+ class Conditional(Operation[TTable], ABC, Generic[TTable]):
44
44
  """
45
45
  An operation narrowed by conditions, e.g. everything but an insert.
46
46
 
@@ -51,7 +51,7 @@ class Conditional(Operation, ABC):
51
51
 
52
52
  conditions: list[Any] = Field(default_factory=list)
53
53
 
54
- def where(self, condition: Any) -> "Conditional":
54
+ def where(self, condition: Any) -> Self:
55
55
  """
56
56
  Narrow this operation. Repeated calls combine with AND.
57
57
  """
@@ -75,13 +75,13 @@ class Conditional(Operation, ABC):
75
75
  return statement
76
76
 
77
77
 
78
- class DqlOperation(Conditional, ABC):
78
+ class DqlOperation(Conditional[TTable], ABC, Generic[TTable]):
79
79
  """
80
80
  A read. Returns rows and changes nothing.
81
81
  """
82
82
 
83
83
 
84
- class DmlOperation(Conditional, ABC):
84
+ class DmlOperation(Conditional[TTable], ABC, Generic[TTable]):
85
85
  """
86
86
  A conditional write against rows: update or delete.
87
87
 
@@ -92,7 +92,7 @@ class DmlOperation(Conditional, ABC):
92
92
  writes: ClassVar[bool] = True
93
93
 
94
94
 
95
- class DdlOperation(Operation, ABC):
95
+ class DdlOperation(Operation[TTable], ABC, Generic[TTable]):
96
96
  """
97
97
  A change to the schema itself.
98
98
 
@@ -2,7 +2,7 @@
2
2
  The statements an application runs: select, insert, update and delete.
3
3
  """
4
4
 
5
- from typing import Any, ClassVar
5
+ from typing import Any, ClassVar, Generic, Self
6
6
 
7
7
  from pydantic import Field
8
8
  from sqlmodel import delete as _delete
@@ -12,11 +12,12 @@ from sqlmodel import select as _select
12
12
  from sqlmodel import update as _update
13
13
 
14
14
  from corekit.connections.sql.operations.base import DmlOperation, DqlOperation, Operation
15
+ from corekit.connections.sql.table import TTable
15
16
 
16
17
  __all__ = ["Delete", "Insert", "Select", "Update"]
17
18
 
18
19
 
19
- class Select(DqlOperation):
20
+ class Select(DqlOperation[TTable], Generic[TTable]):
20
21
  """
21
22
  Read rows, optionally ordered, offset and capped.
22
23
 
@@ -37,7 +38,7 @@ class Select(DqlOperation):
37
38
  offset_count: int = 0
38
39
  for_update_lock: bool = False
39
40
 
40
- def order_by(self, field: Any, desc: bool = False) -> "Select":
41
+ def order_by(self, field: Any, desc: bool = False) -> Self:
41
42
  """
42
43
  Order results by a field.
43
44
  """
@@ -45,7 +46,7 @@ class Select(DqlOperation):
45
46
  self.order_by_desc = desc
46
47
  return self
47
48
 
48
- def limit(self, limit: int) -> "Select":
49
+ def limit(self, limit: int) -> Self:
49
50
  """
50
51
  Cap the number of rows returned.
51
52
 
@@ -54,14 +55,14 @@ class Select(DqlOperation):
54
55
  self.limit_count = limit
55
56
  return self
56
57
 
57
- def offset(self, offset: int) -> "Select":
58
+ def offset(self, offset: int) -> Self:
58
59
  """
59
60
  Skip the first ``offset`` rows.
60
61
  """
61
62
  self.offset_count = offset
62
63
  return self
63
64
 
64
- def for_update(self) -> "Select":
65
+ def for_update(self) -> Self:
65
66
  """
66
67
  Lock the matching rows until the transaction ends.
67
68
  """
@@ -92,7 +93,7 @@ class Select(DqlOperation):
92
93
  return statement
93
94
 
94
95
 
95
- class Delete(DmlOperation):
96
+ class Delete(DmlOperation[TTable], Generic[TTable]):
96
97
  """
97
98
  Delete every row matching the conditions, in one statement.
98
99
 
@@ -114,7 +115,7 @@ class Delete(DmlOperation):
114
115
  return self._apply_conditions(_delete(self.table))
115
116
 
116
117
 
117
- class Update(DmlOperation):
118
+ class Update(DmlOperation[TTable], Generic[TTable]):
118
119
  """
119
120
  Set columns on every row matching the conditions, in one statement.
120
121
 
@@ -125,7 +126,7 @@ class Update(DmlOperation):
125
126
 
126
127
  values: dict[str, Any] = Field(default_factory=dict)
127
128
 
128
- def set(self, **values: Any) -> "Update":
129
+ def set(self, **values: Any) -> Self:
129
130
  """
130
131
  Columns to write, as keyword arguments.
131
132
  """
@@ -146,7 +147,7 @@ class Update(DmlOperation):
146
147
  return self._apply_conditions(_update(self.table)).values(**self.values)
147
148
 
148
149
 
149
- class Insert(Operation):
150
+ class Insert(Operation[TTable], Generic[TTable]):
150
151
  """
151
152
  Add rows. A write, so ``SQLConnection.execute`` commits it.
152
153
 
@@ -163,7 +164,7 @@ class Insert(Operation):
163
164
 
164
165
  rows: list[dict[str, Any]] = Field(default_factory=list)
165
166
 
166
- def add(self, **values: Any) -> "Insert":
167
+ def add(self, **values: Any) -> Self:
167
168
  """
168
169
  Append one row.
169
170
  """
@@ -3,14 +3,14 @@ Base table type.
3
3
  """
4
4
 
5
5
  import logging
6
- from typing import Any, ClassVar
6
+ from typing import Any, ClassVar, Self, TypeVar
7
7
 
8
8
  from pydantic import BaseModel
9
9
  from sqlmodel import SQLModel
10
10
 
11
11
  from corekit.registry import SmartRegistry
12
12
 
13
- __all__ = ["NamedTable", "TableExportItem"]
13
+ __all__ = ["NamedTable", "TableExportItem", "TTable"]
14
14
 
15
15
 
16
16
  class TableExportItem(BaseModel):
@@ -85,7 +85,7 @@ class NamedTable(SQLModel):
85
85
  return name or cls.__name__
86
86
 
87
87
  @classmethod
88
- def create_default(cls, identifier: str, **kwargs: Any) -> "NamedTable":
88
+ def create_default(cls, identifier: str, **kwargs: Any) -> Self:
89
89
  """
90
90
  Build an instance carrying only its identifier and any supplied fields.
91
91
  """
@@ -98,3 +98,6 @@ class NamedTable(SQLModel):
98
98
  This row as a portable record, tagged with its database table name.
99
99
  """
100
100
  return TableExportItem(table_name=self.table_name, data=self.model_dump())
101
+
102
+
103
+ TTable = TypeVar("TTable", bound=NamedTable)
corekit/data/__init__.py CHANGED
@@ -27,6 +27,9 @@ from corekit.data.expressions import (
27
27
  Dialect,
28
28
  Equals,
29
29
  Expression,
30
+ ExpressionField,
31
+ ExpressionKey,
32
+ ExpressionType,
30
33
  FieldExpression,
31
34
  GreaterThan,
32
35
  GreaterThanOrEquals,
@@ -67,6 +70,9 @@ __all__ = [
67
70
  "DatasetStats",
68
71
  "Equals",
69
72
  "Expression",
73
+ "ExpressionField",
74
+ "ExpressionKey",
75
+ "ExpressionType",
70
76
  "Field",
71
77
  "FieldDescription",
72
78
  "FieldExpression",
@@ -0,0 +1,97 @@
1
+ """
2
+ Composable arithmetic expression trees.
3
+
4
+ Build with ``Field`` / ``Literal`` and operator overloads, evaluate against a
5
+ context, and round-trip with ``to_dict`` / ``from_dict``::
6
+
7
+ from corekit.data.arithmetic import Field
8
+
9
+ total = ((Field("pad_cost") * Field("pad_qty")) + (Field("labor_rate") * Field("hours"))).round()
10
+ """
11
+
12
+ from typing import Annotated, Any
13
+
14
+ from pydantic import GetCoreSchemaHandler
15
+ from pydantic_core import core_schema
16
+
17
+ from corekit.data.arithmetic.expression import (
18
+ Abs,
19
+ Add,
20
+ ArithmeticExpression,
21
+ Ceil,
22
+ Divide,
23
+ Field,
24
+ Floor,
25
+ Literal,
26
+ Max,
27
+ Min,
28
+ Modulo,
29
+ Multiply,
30
+ Negate,
31
+ Percent,
32
+ PercentOf,
33
+ Power,
34
+ Round,
35
+ Subtract,
36
+ UnknownArithmeticFieldError,
37
+ coerce,
38
+ )
39
+ from corekit.data.arithmetic.keys import ArithmeticKey, ArithmeticType
40
+ from corekit.data.arithmetic.operator import ArithmeticOperator
41
+
42
+
43
+ class _ArithmeticExpressionPydanticAnnotation:
44
+ """
45
+ Pydantic marker so ``ArithmeticExpression`` nests in BaseModels.
46
+ """
47
+
48
+ @classmethod
49
+ def __get_pydantic_core_schema__(
50
+ cls,
51
+ _source_type: Any,
52
+ _handler: GetCoreSchemaHandler,
53
+ ) -> core_schema.CoreSchema:
54
+ def validate(value: Any) -> ArithmeticExpression:
55
+ if isinstance(value, ArithmeticExpression):
56
+ return value
57
+ if isinstance(value, dict):
58
+ return ArithmeticExpression.from_dict(value)
59
+ raise TypeError(f"Expected ArithmeticExpression or dict, got {type(value)!r}")
60
+
61
+ return core_schema.no_info_plain_validator_function(
62
+ validate,
63
+ serialization=core_schema.plain_serializer_function_ser_schema(
64
+ lambda value: value.to_dict(),
65
+ when_used="always",
66
+ ),
67
+ )
68
+
69
+
70
+ ArithmeticExpressionField = Annotated[ArithmeticExpression, _ArithmeticExpressionPydanticAnnotation]
71
+
72
+ __all__ = [
73
+ "Abs",
74
+ "Add",
75
+ "ArithmeticExpression",
76
+ "ArithmeticExpressionField",
77
+ "ArithmeticKey",
78
+ "ArithmeticOperator",
79
+ "ArithmeticType",
80
+ "Ceil",
81
+ "Divide",
82
+ "Field",
83
+ "Floor",
84
+ "Literal",
85
+ "Max",
86
+ "Min",
87
+ "Modulo",
88
+ "Multiply",
89
+ "Negate",
90
+ "Percent",
91
+ "PercentOf",
92
+ "Power",
93
+ "Round",
94
+ "Subtract",
95
+ "UnknownArithmeticFieldError",
96
+ "coerce",
97
+ ]