sqlphilosophy 0.3.3__tar.gz → 0.3.5__tar.gz

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.
Files changed (37) hide show
  1. {sqlphilosophy-0.3.3/src/sqlphilosophy.egg-info → sqlphilosophy-0.3.5}/PKG-INFO +29 -5
  2. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/README.md +26 -2
  3. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/pyproject.toml +3 -3
  4. sqlphilosophy-0.3.5/src/sqlphilosophy/VERSION +1 -0
  5. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/aio/protocols.py +7 -0
  6. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/aio/query.py +37 -1
  7. sqlphilosophy-0.3.5/src/sqlphilosophy/aio/registry.py +47 -0
  8. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/strict.py +17 -4
  9. sqlphilosophy-0.3.5/src/sqlphilosophy/sync/composite.py +73 -0
  10. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/sync/protocols.py +7 -0
  11. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/sync/query.py +33 -1
  12. sqlphilosophy-0.3.5/src/sqlphilosophy/sync/registry.py +46 -0
  13. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/types.py +1 -1
  14. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5/src/sqlphilosophy.egg-info}/PKG-INFO +29 -5
  15. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy.egg-info/SOURCES.txt +3 -0
  16. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy.egg-info/requires.txt +2 -2
  17. sqlphilosophy-0.3.3/src/sqlphilosophy/VERSION +0 -1
  18. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/LICENSE +0 -0
  19. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/MANIFEST.in +0 -0
  20. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/setup.cfg +0 -0
  21. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/__init__.py +0 -0
  22. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/_repository_shared.py +0 -0
  23. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/aio/__init__.py +0 -0
  24. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/aio/repository.py +0 -0
  25. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/audit/__init__.py +0 -0
  26. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/audit/context.py +0 -0
  27. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/audit/fields.py +0 -0
  28. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/audit/listener.py +0 -0
  29. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/audit/model.py +0 -0
  30. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/py.typed +0 -0
  31. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/sorting.py +0 -0
  32. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/sql.py +0 -0
  33. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/sync/__init__.py +0 -0
  34. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/sync/repository.py +0 -0
  35. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy/trusted_sql.py +0 -0
  36. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy.egg-info/dependency_links.txt +0 -0
  37. {sqlphilosophy-0.3.3 → sqlphilosophy-0.3.5}/src/sqlphilosophy.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlphilosophy
3
- Version: 0.3.3
3
+ Version: 0.3.5
4
4
  Summary: Portable SQLAlchemy repository kit: sync and async CRUD, statement builders, sort/pagination, and SQL helpers.
5
5
  Author-email: Josh Martin <denverprogrammer@gmail.com>
6
6
  License-Expression: MIT
@@ -20,7 +20,7 @@ Classifier: Typing :: Typed
20
20
  Requires-Python: <4.0,>=3.12
21
21
  Description-Content-Type: text/markdown
22
22
  License-File: LICENSE
23
- Requires-Dist: servicephilosophy>=0.1.0
23
+ Requires-Dist: servicephilosophy<0.2,>=0.1.2
24
24
  Requires-Dist: sqlalchemy<3,>=2.0
25
25
  Provides-Extra: async
26
26
  Requires-Dist: greenlet>=3.0; extra == "async"
@@ -30,7 +30,7 @@ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
30
30
  Requires-Dist: pytest-cov>=6; extra == "dev"
31
31
  Requires-Dist: aiosqlite>=0.20; extra == "dev"
32
32
  Requires-Dist: greenlet>=3.0; extra == "dev"
33
- Requires-Dist: build>=1.2; extra == "dev"
33
+ Requires-Dist: build<2,>=1.6.1; extra == "dev"
34
34
  Requires-Dist: twine>=5; extra == "dev"
35
35
  Requires-Dist: ruff>=0.15; extra == "dev"
36
36
  Requires-Dist: mypy>=1.11; extra == "dev"
@@ -183,10 +183,34 @@ See [RELEASING.md](./RELEASING.md) for GitHub + PyPI trusted publishing. See [CH
183
183
 
184
184
  MIT — see [LICENSE](./LICENSE).
185
185
 
186
- ## Expression lookups and scope overrides (0.3.1)
186
+ ## Expression lookups and scope overrides (0.3+)
187
187
 
188
188
  Both repository bases provide `find_entity(criteria=..., lock=False)`, `find_row(criteria=..., columns=..., lock=False)` and `count_scoped(criteria=...)`. Criteria must not be empty; projected lookups also require columns. Entity lookups return a mapped object, projected lookups return RowMapping, and absence returns None. These methods never commit.
189
189
 
190
190
  Override `apply_scope(statement)` for additional predicates on these helpers. It runs after projection initialization, because `select_columns`/`select_entity` reset the builder's SELECT. This hook does not implicitly scope existing CRUD helpers or arbitrary builder calls: keep ownership checks in named application repository methods. Existing `first`, `get_by_id`, `count` and statement APIs remain available and unchanged.
191
191
 
192
- The 0.3.1 artifact is a local candidate until separately published. Dependent candidate packages use a vendored wheel during validation; publish sqlPhilosophy first before replacing their local sources with registry-only dependencies.
192
+ Published 0.3.3 provides these lookup APIs. The 0.3.4 source prepares compatible
193
+ strict-decoder, documentation and build-metadata fixes. Use a named application
194
+ repository method to own each model-specific projection, ordering and policy;
195
+ compose its query with `statement()` or these lookup helpers instead of
196
+ scattering `select()` calls through controllers/services. Core SQL helpers remain
197
+ available for explicit SQL boundaries; a repository does not supply authorization.
198
+
199
+ The supported dependency range remains SQLAlchemy 2.x. DeliveryPlus native's
200
+ 2.0.49 constraint and RuleAtlas's separate 2.1.5 minimum are host decisions;
201
+ upgrading this package does not silently change either host lock. Coordinated
202
+ candidate verification exercises both SQLAlchemy versions before release.
203
+
204
+ ### Explicit composite-key resources
205
+
206
+
207
+ `sqlphilosophy.sync.composite.CompositeRepository` is an opt-in repository for mapped composite primary keys. It validates complete ordered identities and preserves caller-owned transactions, scoped reads, locks and writable allowlists. Existing `BaseRepository` and asynchronous scalar APIs are unchanged. ApiPhilosophy resource adapters select this repository only through an explicit host `composite_repository(model)` resolver.
208
+
209
+
210
+ Repository-owned projections may compose same-session selections with
211
+ `first.union_all(second).as_subquery("combined")` and use the returned `.c` columns
212
+ in another repository statement. The UNION builder snapshots both scoped arms; it
213
+ does not add scopes or change either arm. Apply each repository's visibility scope
214
+ before composition. Column counts must agree and conflicting explicit bound
215
+ parameters are rejected. `as_subquery()` preserves bound values. Sync and async
216
+ builders support the same API; execute the outer projection through its builder.
@@ -143,10 +143,34 @@ See [RELEASING.md](./RELEASING.md) for GitHub + PyPI trusted publishing. See [CH
143
143
 
144
144
  MIT — see [LICENSE](./LICENSE).
145
145
 
146
- ## Expression lookups and scope overrides (0.3.1)
146
+ ## Expression lookups and scope overrides (0.3+)
147
147
 
148
148
  Both repository bases provide `find_entity(criteria=..., lock=False)`, `find_row(criteria=..., columns=..., lock=False)` and `count_scoped(criteria=...)`. Criteria must not be empty; projected lookups also require columns. Entity lookups return a mapped object, projected lookups return RowMapping, and absence returns None. These methods never commit.
149
149
 
150
150
  Override `apply_scope(statement)` for additional predicates on these helpers. It runs after projection initialization, because `select_columns`/`select_entity` reset the builder's SELECT. This hook does not implicitly scope existing CRUD helpers or arbitrary builder calls: keep ownership checks in named application repository methods. Existing `first`, `get_by_id`, `count` and statement APIs remain available and unchanged.
151
151
 
152
- The 0.3.1 artifact is a local candidate until separately published. Dependent candidate packages use a vendored wheel during validation; publish sqlPhilosophy first before replacing their local sources with registry-only dependencies.
152
+ Published 0.3.3 provides these lookup APIs. The 0.3.4 source prepares compatible
153
+ strict-decoder, documentation and build-metadata fixes. Use a named application
154
+ repository method to own each model-specific projection, ordering and policy;
155
+ compose its query with `statement()` or these lookup helpers instead of
156
+ scattering `select()` calls through controllers/services. Core SQL helpers remain
157
+ available for explicit SQL boundaries; a repository does not supply authorization.
158
+
159
+ The supported dependency range remains SQLAlchemy 2.x. DeliveryPlus native's
160
+ 2.0.49 constraint and RuleAtlas's separate 2.1.5 minimum are host decisions;
161
+ upgrading this package does not silently change either host lock. Coordinated
162
+ candidate verification exercises both SQLAlchemy versions before release.
163
+
164
+ ### Explicit composite-key resources
165
+
166
+
167
+ `sqlphilosophy.sync.composite.CompositeRepository` is an opt-in repository for mapped composite primary keys. It validates complete ordered identities and preserves caller-owned transactions, scoped reads, locks and writable allowlists. Existing `BaseRepository` and asynchronous scalar APIs are unchanged. ApiPhilosophy resource adapters select this repository only through an explicit host `composite_repository(model)` resolver.
168
+
169
+
170
+ Repository-owned projections may compose same-session selections with
171
+ `first.union_all(second).as_subquery("combined")` and use the returned `.c` columns
172
+ in another repository statement. The UNION builder snapshots both scoped arms; it
173
+ does not add scopes or change either arm. Apply each repository's visibility scope
174
+ before composition. Column counts must agree and conflicting explicit bound
175
+ parameters are rejected. `as_subquery()` preserves bound values. Sync and async
176
+ builders support the same API; execute the outer projection through its builder.
@@ -1,5 +1,5 @@
1
1
  [build-system]
2
- requires = ["setuptools>=69", "wheel"]
2
+ requires = ["setuptools>=84.2.1,<85", "wheel>=0.46,<1"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
@@ -24,7 +24,7 @@ classifiers = [
24
24
  ]
25
25
  dynamic = ["version"]
26
26
  dependencies = [
27
- "servicephilosophy>=0.1.0",
27
+ "servicephilosophy>=0.1.2,<0.2",
28
28
  "sqlalchemy>=2.0,<3",
29
29
  ]
30
30
 
@@ -38,7 +38,7 @@ dev = [
38
38
  "pytest-cov>=6",
39
39
  "aiosqlite>=0.20",
40
40
  "greenlet>=3.0",
41
- "build>=1.2",
41
+ "build>=1.6.1,<2",
42
42
  "twine>=5",
43
43
  "ruff>=0.15",
44
44
  "mypy>=1.11",
@@ -0,0 +1 @@
1
+ 0.3.5
@@ -49,6 +49,13 @@ class AsyncBaseRepositoryProtocol[T: DeclarativeBase, U: AsyncRepositoryFactory]
49
49
  model: type[T]
50
50
  _session: AsyncSession
51
51
 
52
+ @property
53
+ def session(self) -> AsyncSession: ...
54
+
55
+ def apply_scope(self, statement: AsyncStatementQueryBuilder[T]) -> AsyncStatementQueryBuilder[T]: ...
56
+
57
+ async def find_entity(self, *, criteria: Sequence[SqlFilter], lock: bool = False) -> T | None: ...
58
+
52
59
  async def get(self, obj_id: PrimaryKey, load_relations: Any = None) -> T: ...
53
60
 
54
61
  async def get_by_id(self, obj_id: PrimaryKey, load_relations: Any = None) -> T | None: ...
@@ -6,10 +6,11 @@ from abc import ABC, abstractmethod
6
6
  from collections.abc import Mapping
7
7
  from typing import Any, cast
8
8
 
9
- from sqlalchemy import func, select
9
+ from sqlalchemy import func, select, union_all
10
10
  from sqlalchemy.ext.asyncio import AsyncSession
11
11
  from sqlalchemy.orm import DeclarativeBase
12
12
  from sqlalchemy.sql import Select
13
+ from sqlalchemy.sql.selectable import Subquery
13
14
 
14
15
  from sqlphilosophy.sorting import ListQuery, OrderByMap, SortConfig
15
16
  from sqlphilosophy.sql import count_composed_select, row_mapping, row_mapping_opt, rows_mapping
@@ -115,6 +116,16 @@ class AsyncStatementQueryBuilder[T: DeclarativeBase](ABC):
115
116
  def as_cte(self, name: str) -> SqlClause:
116
117
  raise NotImplementedError
117
118
 
119
+ def as_subquery(self, name: str | None = None) -> Subquery:
120
+ """Snapshot this composed selection for another repository-owned builder."""
121
+ raise NotImplementedError
122
+
123
+ def union_all[Other: DeclarativeBase](
124
+ self, *others: AsyncStatementQueryBuilder[Other]
125
+ ) -> AsyncStatementQueryBuilder[T]:
126
+ """Compose same-session, equally shaped selections without changing either arm."""
127
+ raise NotImplementedError
128
+
118
129
  @abstractmethod
119
130
  def order_by(self, *clauses: SqlClause) -> AsyncStatementQueryBuilder[T]:
120
131
  raise NotImplementedError
@@ -328,6 +339,31 @@ class AsyncSqlAlchemyStatementBuilder[T: DeclarativeBase](AsyncStatementQueryBui
328
339
  def as_cte(self, name: str) -> SqlClause:
329
340
  return self._stmt.cte(name)
330
341
 
342
+ def as_subquery(self, name: str | None = None) -> Subquery:
343
+ return self._stmt.params(**self._params).subquery(name)
344
+
345
+ def union_all[Other: DeclarativeBase](
346
+ self, *others: AsyncStatementQueryBuilder[Other]
347
+ ) -> AsyncSqlAlchemyStatementBuilder[T]:
348
+ if not others:
349
+ raise ValueError("Union composition requires another selection")
350
+ statements = [self._stmt]
351
+ params = dict(self._params)
352
+ for other in others:
353
+ if not isinstance(other, AsyncSqlAlchemyStatementBuilder) or other._session is not self._session:
354
+ raise ValueError("Union composition requires builders sharing the same session")
355
+ if len(other._stmt.selected_columns) != len(self._stmt.selected_columns):
356
+ raise ValueError("Union selections require the same number of columns")
357
+ if any(key in params and params[key] != value for key, value in other._params.items()):
358
+ raise ValueError("Union selections have conflicting bound parameters")
359
+ params.update(other._params)
360
+ statements.append(other._stmt)
361
+ rows = union_all(*statements).subquery()
362
+ composed = self._copy()
363
+ composed._stmt = select(rows)
364
+ composed._params = params
365
+ return composed
366
+
331
367
  def order_by(self, *clauses: SqlClause) -> AsyncSqlAlchemyStatementBuilder[T]:
332
368
  self._stmt = self._stmt.order_by(*clauses)
333
369
  return self
@@ -0,0 +1,47 @@
1
+ """Explicit model-to-repository construction; factories own session-scoped caching."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import cast
5
+
6
+ from sqlalchemy.ext.asyncio import AsyncSession
7
+ from sqlalchemy.orm import DeclarativeBase
8
+
9
+ from sqlphilosophy.aio.protocols import AsyncRepositoryFactory
10
+ from sqlphilosophy.aio.repository import AsyncBaseRepository
11
+
12
+
13
+ class AsyncRepositoryRegistry[Factory: AsyncRepositoryFactory]:
14
+ """Resolve exact model registrations, falling back to the generic CRUD repository.
15
+
16
+ Builders receive the caller's session and factory. The registry never opens a
17
+ transaction, caches a repository, or infers registrations from subclasses.
18
+ """
19
+
20
+ def __init__(self) -> None:
21
+ self._builders: dict[type[DeclarativeBase], object] = {}
22
+
23
+ def register[Model: DeclarativeBase](
24
+ self,
25
+ model: type[Model],
26
+ builder: Callable[[AsyncSession, Factory], AsyncBaseRepository[Model, Factory]],
27
+ ) -> None:
28
+ if model in self._builders:
29
+ raise ValueError("A model already has a repository registration")
30
+ if not callable(builder):
31
+ raise TypeError("Repository builders must be callable")
32
+ self._builders[model] = builder
33
+
34
+ def repository[Model: DeclarativeBase](
35
+ self, model: type[Model], session: AsyncSession, factory: Factory
36
+ ) -> AsyncBaseRepository[Model, Factory]:
37
+ registered = self._builders.get(model)
38
+ if registered is None:
39
+ return AsyncBaseRepository(model, session, factory)
40
+ # register() couples this exact model key to the builder's result type.
41
+ builder = cast(Callable[[AsyncSession, Factory], AsyncBaseRepository[Model, Factory]], registered)
42
+ repository = builder(session, factory)
43
+ if not isinstance(repository, AsyncBaseRepository):
44
+ raise TypeError("Repository builders must return a AsyncBaseRepository")
45
+ if repository.model is not model or repository.session is not session or repository.factory is not factory:
46
+ raise ValueError("Repository construction changed its model, session or factory")
47
+ return repository
@@ -6,7 +6,7 @@ from collections.abc import Callable, Mapping
6
6
  from datetime import date, datetime
7
7
  from enum import Enum
8
8
  from math import isfinite
9
- from typing import TypeGuard
9
+ from typing import TypeGuard, cast
10
10
  from uuid import UUID
11
11
 
12
12
  from sqlphilosophy.types import JSONValue
@@ -99,9 +99,21 @@ def strict_row_enum[EnumT: Enum](row: Row, key: str, enum_type: type[EnumT]) ->
99
99
  raise _type_error(key, enum_type.__name__, value)
100
100
 
101
101
 
102
+ def _plain_list(value: object) -> list[object] | None:
103
+ if type(value) is not list:
104
+ return None
105
+ # Exact built-in type proof preserves identity without inspecting __class__.
106
+ return cast(list[object], value)
107
+
108
+
109
+ def _is_str_list(value: object) -> TypeGuard[list[str]]:
110
+ items = _plain_list(value)
111
+ return items is not None and all(type(item) is str for item in items)
112
+
113
+
102
114
  def strict_row_str_list(row: Row, key: str) -> list[str]:
103
115
  value = _required(row, key)
104
- if type(value) is not list or not all(type(item) is str for item in value):
116
+ if not _is_str_list(value):
105
117
  raise _type_error(key, "list[str]", value)
106
118
  return value
107
119
 
@@ -111,8 +123,9 @@ def is_strict_json_value(value: object) -> TypeGuard[JSONValue]:
111
123
  return True
112
124
  if type(value) is float:
113
125
  return isfinite(value)
114
- if type(value) is list:
115
- return all(is_strict_json_value(item) for item in value)
126
+ items = _plain_list(value)
127
+ if items is not None:
128
+ return all(is_strict_json_value(item) for item in items)
116
129
  if type(value) is dict:
117
130
  return all(type(key) is str and is_strict_json_value(item) for key, item in value.items())
118
131
  return False
@@ -0,0 +1,73 @@
1
+ """Explicit composite-key CRUD using a caller-owned session and repository scope."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from servicephilosophy import ServiceRepository
6
+ from sqlalchemy import delete, inspect, update
7
+ from sqlalchemy.orm import DeclarativeBase, Session
8
+
9
+ from sqlphilosophy.sync.protocols import RepositoryFactory
10
+ from sqlphilosophy.sync.query import SqlAlchemyStatementBuilder, StatementQueryBuilder
11
+ from sqlphilosophy.types import PrimaryKey, RowMapping, SqlFilter, cursor_rowcount
12
+
13
+ type CompositeKey = tuple[PrimaryKey, ...]
14
+
15
+
16
+ class CompositeRepository[T: DeclarativeBase](ServiceRepository[RepositoryFactory]):
17
+ """A separate opt-in contract; scalar-key repositories retain their API."""
18
+
19
+ def __init__(self, model: type[T], session: Session, factory: RepositoryFactory | None = None) -> None:
20
+ super().__init__(factory)
21
+ self.model, self._session = model, session
22
+ self.columns = tuple(inspect(model).primary_key)
23
+ if len(self.columns) < 2:
24
+ raise ValueError("Composite repositories require multiple primary-key columns")
25
+
26
+ @property
27
+ def session(self) -> Session:
28
+ return self._session
29
+
30
+ def criteria(self, identity: CompositeKey) -> tuple[SqlFilter, ...]:
31
+ if not isinstance(identity, tuple) or len(identity) != len(self.columns):
32
+ raise ValueError("Composite identity must supply every primary-key component")
33
+ for column, value in zip(self.columns, identity, strict=True):
34
+ if type(value) is not column.type.python_type:
35
+ raise ValueError("Composite identity component has the wrong type")
36
+ return tuple(column == value for column, value in zip(self.columns, identity, strict=True))
37
+
38
+ def statement(self) -> StatementQueryBuilder[T]:
39
+ factory = self.maybe_factory
40
+ if factory is not None:
41
+ return factory.create_statement(self.model)
42
+ return SqlAlchemyStatementBuilder(self.session, self.model)
43
+
44
+ def apply_scope(self, statement: StatementQueryBuilder[T]) -> StatementQueryBuilder[T]:
45
+ return statement
46
+
47
+ def find_entity(self, *, criteria: Sequence[SqlFilter], lock: bool = False) -> T | None:
48
+ if not criteria:
49
+ raise ValueError("Composite lookups require explicit criteria")
50
+ statement = self.apply_scope(self.statement()).where(*criteria)
51
+ if lock:
52
+ statement = statement.with_for_update()
53
+ return statement.scalars().first()
54
+
55
+ def add(self, row: T) -> T:
56
+ self.session.add(row)
57
+ self.session.flush()
58
+ return row
59
+
60
+ def update_partial(self, identity: CompositeKey, fields: RowMapping, writable: frozenset[str]) -> int:
61
+ primary = {inspect(self.model).get_property_by_column(column).key for column in self.columns}
62
+ columns = set(inspect(self.model).column_attrs.keys())
63
+ if not writable or not writable <= columns or writable & primary or not fields.keys() <= writable:
64
+ raise ValueError("Composite updates require a mapped non-identity writable allowlist")
65
+ criteria = self.criteria(identity)
66
+ if not fields:
67
+ return 0
68
+ result = self.session.execute(update(self.model).where(*criteria).values(**fields))
69
+ return cursor_rowcount(result)
70
+
71
+ def remove(self, identity: CompositeKey) -> bool:
72
+ result = self.session.execute(delete(self.model).where(*self.criteria(identity)))
73
+ return cursor_rowcount(result) > 0
@@ -48,6 +48,13 @@ class BaseRepositoryProtocol[T: DeclarativeBase, U: RepositoryFactory](
48
48
  model: type[T]
49
49
  _session: Session
50
50
 
51
+ @property
52
+ def session(self) -> Session: ...
53
+
54
+ def apply_scope(self, statement: StatementQueryBuilder[T]) -> StatementQueryBuilder[T]: ...
55
+
56
+ def find_entity(self, *, criteria: Sequence[SqlFilter], lock: bool = False) -> T | None: ...
57
+
51
58
  def get(self, obj_id: PrimaryKey, load_relations: Any = None) -> T: ...
52
59
 
53
60
  def get_by_id(self, obj_id: PrimaryKey, load_relations: Any = None) -> T | None: ...
@@ -10,9 +10,10 @@ from abc import ABC, abstractmethod
10
10
  from collections.abc import Mapping
11
11
  from typing import Any, cast
12
12
 
13
- from sqlalchemy import func, select
13
+ from sqlalchemy import func, select, union_all
14
14
  from sqlalchemy.orm import DeclarativeBase, Session
15
15
  from sqlalchemy.sql import Select
16
+ from sqlalchemy.sql.selectable import Subquery
16
17
 
17
18
  from sqlphilosophy.sorting import ListQuery, OrderByMap, SortConfig
18
19
  from sqlphilosophy.sql import count_composed_select, row_mapping, row_mapping_opt, rows_mapping
@@ -118,6 +119,14 @@ class StatementQueryBuilder[T: DeclarativeBase](ABC):
118
119
  def as_cte(self, name: str) -> SqlClause:
119
120
  raise NotImplementedError
120
121
 
122
+ def as_subquery(self, name: str | None = None) -> Subquery:
123
+ """Snapshot this composed selection for another repository-owned builder."""
124
+ raise NotImplementedError
125
+
126
+ def union_all[Other: DeclarativeBase](self, *others: StatementQueryBuilder[Other]) -> StatementQueryBuilder[T]:
127
+ """Compose same-session, equally shaped selections without changing either arm."""
128
+ raise NotImplementedError
129
+
121
130
  @abstractmethod
122
131
  def order_by(self, *clauses: SqlClause) -> StatementQueryBuilder[T]:
123
132
  raise NotImplementedError
@@ -316,6 +325,29 @@ class SqlAlchemyStatementBuilder[T: DeclarativeBase](StatementQueryBuilder[T]):
316
325
  def as_cte(self, name: str) -> SqlClause:
317
326
  return self._stmt.cte(name)
318
327
 
328
+ def as_subquery(self, name: str | None = None) -> Subquery:
329
+ return self._stmt.params(**self._params).subquery(name)
330
+
331
+ def union_all[Other: DeclarativeBase](self, *others: StatementQueryBuilder[Other]) -> SqlAlchemyStatementBuilder[T]:
332
+ if not others:
333
+ raise ValueError("Union composition requires another selection")
334
+ statements = [self._stmt]
335
+ params = dict(self._params)
336
+ for other in others:
337
+ if not isinstance(other, SqlAlchemyStatementBuilder) or other._session is not self._session:
338
+ raise ValueError("Union composition requires builders sharing the same session")
339
+ if len(other._stmt.selected_columns) != len(self._stmt.selected_columns):
340
+ raise ValueError("Union selections require the same number of columns")
341
+ if any(key in params and params[key] != value for key, value in other._params.items()):
342
+ raise ValueError("Union selections have conflicting bound parameters")
343
+ params.update(other._params)
344
+ statements.append(other._stmt)
345
+ rows = union_all(*statements).subquery()
346
+ composed = self._copy()
347
+ composed._stmt = select(rows)
348
+ composed._params = params
349
+ return composed
350
+
319
351
  def order_by(self, *clauses: SqlClause) -> SqlAlchemyStatementBuilder[T]:
320
352
  self._stmt = self._stmt.order_by(*clauses)
321
353
  return self
@@ -0,0 +1,46 @@
1
+ """Explicit model-to-repository construction; factories own session-scoped caching."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import cast
5
+
6
+ from sqlalchemy.orm import DeclarativeBase, Session
7
+
8
+ from sqlphilosophy.sync.protocols import RepositoryFactory
9
+ from sqlphilosophy.sync.repository import BaseRepository
10
+
11
+
12
+ class RepositoryRegistry[Factory: RepositoryFactory]:
13
+ """Resolve exact model registrations, falling back to the generic CRUD repository.
14
+
15
+ Builders receive the caller's session and factory. The registry never opens a
16
+ transaction, caches a repository, or infers registrations from subclasses.
17
+ """
18
+
19
+ def __init__(self) -> None:
20
+ self._builders: dict[type[DeclarativeBase], object] = {}
21
+
22
+ def register[Model: DeclarativeBase](
23
+ self,
24
+ model: type[Model],
25
+ builder: Callable[[Session, Factory], BaseRepository[Model, Factory]],
26
+ ) -> None:
27
+ if model in self._builders:
28
+ raise ValueError("A model already has a repository registration")
29
+ if not callable(builder):
30
+ raise TypeError("Repository builders must be callable")
31
+ self._builders[model] = builder
32
+
33
+ def repository[Model: DeclarativeBase](
34
+ self, model: type[Model], session: Session, factory: Factory
35
+ ) -> BaseRepository[Model, Factory]:
36
+ registered = self._builders.get(model)
37
+ if registered is None:
38
+ return BaseRepository(model, session, factory)
39
+ # register() couples this exact model key to the builder's result type.
40
+ builder = cast(Callable[[Session, Factory], BaseRepository[Model, Factory]], registered)
41
+ repository = builder(session, factory)
42
+ if not isinstance(repository, BaseRepository):
43
+ raise TypeError("Repository builders must return a BaseRepository")
44
+ if repository.model is not model or repository.session is not session or repository.factory is not factory:
45
+ raise ValueError("Repository construction changed its model, session or factory")
46
+ return repository
@@ -65,4 +65,4 @@ type OrmModel = type[DeclarativeBase]
65
65
 
66
66
  def cursor_rowcount(result: Result[Any]) -> int:
67
67
  """Return affected row count from a DML ``execute`` result."""
68
- return int(cast(CursorResult[Any], result).rowcount or 0)
68
+ return int(cast("CursorResult[Any]", result).rowcount or 0)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlphilosophy
3
- Version: 0.3.3
3
+ Version: 0.3.5
4
4
  Summary: Portable SQLAlchemy repository kit: sync and async CRUD, statement builders, sort/pagination, and SQL helpers.
5
5
  Author-email: Josh Martin <denverprogrammer@gmail.com>
6
6
  License-Expression: MIT
@@ -20,7 +20,7 @@ Classifier: Typing :: Typed
20
20
  Requires-Python: <4.0,>=3.12
21
21
  Description-Content-Type: text/markdown
22
22
  License-File: LICENSE
23
- Requires-Dist: servicephilosophy>=0.1.0
23
+ Requires-Dist: servicephilosophy<0.2,>=0.1.2
24
24
  Requires-Dist: sqlalchemy<3,>=2.0
25
25
  Provides-Extra: async
26
26
  Requires-Dist: greenlet>=3.0; extra == "async"
@@ -30,7 +30,7 @@ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
30
30
  Requires-Dist: pytest-cov>=6; extra == "dev"
31
31
  Requires-Dist: aiosqlite>=0.20; extra == "dev"
32
32
  Requires-Dist: greenlet>=3.0; extra == "dev"
33
- Requires-Dist: build>=1.2; extra == "dev"
33
+ Requires-Dist: build<2,>=1.6.1; extra == "dev"
34
34
  Requires-Dist: twine>=5; extra == "dev"
35
35
  Requires-Dist: ruff>=0.15; extra == "dev"
36
36
  Requires-Dist: mypy>=1.11; extra == "dev"
@@ -183,10 +183,34 @@ See [RELEASING.md](./RELEASING.md) for GitHub + PyPI trusted publishing. See [CH
183
183
 
184
184
  MIT — see [LICENSE](./LICENSE).
185
185
 
186
- ## Expression lookups and scope overrides (0.3.1)
186
+ ## Expression lookups and scope overrides (0.3+)
187
187
 
188
188
  Both repository bases provide `find_entity(criteria=..., lock=False)`, `find_row(criteria=..., columns=..., lock=False)` and `count_scoped(criteria=...)`. Criteria must not be empty; projected lookups also require columns. Entity lookups return a mapped object, projected lookups return RowMapping, and absence returns None. These methods never commit.
189
189
 
190
190
  Override `apply_scope(statement)` for additional predicates on these helpers. It runs after projection initialization, because `select_columns`/`select_entity` reset the builder's SELECT. This hook does not implicitly scope existing CRUD helpers or arbitrary builder calls: keep ownership checks in named application repository methods. Existing `first`, `get_by_id`, `count` and statement APIs remain available and unchanged.
191
191
 
192
- The 0.3.1 artifact is a local candidate until separately published. Dependent candidate packages use a vendored wheel during validation; publish sqlPhilosophy first before replacing their local sources with registry-only dependencies.
192
+ Published 0.3.3 provides these lookup APIs. The 0.3.4 source prepares compatible
193
+ strict-decoder, documentation and build-metadata fixes. Use a named application
194
+ repository method to own each model-specific projection, ordering and policy;
195
+ compose its query with `statement()` or these lookup helpers instead of
196
+ scattering `select()` calls through controllers/services. Core SQL helpers remain
197
+ available for explicit SQL boundaries; a repository does not supply authorization.
198
+
199
+ The supported dependency range remains SQLAlchemy 2.x. DeliveryPlus native's
200
+ 2.0.49 constraint and RuleAtlas's separate 2.1.5 minimum are host decisions;
201
+ upgrading this package does not silently change either host lock. Coordinated
202
+ candidate verification exercises both SQLAlchemy versions before release.
203
+
204
+ ### Explicit composite-key resources
205
+
206
+
207
+ `sqlphilosophy.sync.composite.CompositeRepository` is an opt-in repository for mapped composite primary keys. It validates complete ordered identities and preserves caller-owned transactions, scoped reads, locks and writable allowlists. Existing `BaseRepository` and asynchronous scalar APIs are unchanged. ApiPhilosophy resource adapters select this repository only through an explicit host `composite_repository(model)` resolver.
208
+
209
+
210
+ Repository-owned projections may compose same-session selections with
211
+ `first.union_all(second).as_subquery("combined")` and use the returned `.c` columns
212
+ in another repository statement. The UNION builder snapshots both scoped arms; it
213
+ does not add scopes or change either arm. Apply each repository's visibility scope
214
+ before composition. Column counts must agree and conflicting explicit bound
215
+ parameters are rejected. `as_subquery()` preserves bound values. Sync and async
216
+ builders support the same API; execute the outer projection through its builder.
@@ -19,6 +19,7 @@ src/sqlphilosophy.egg-info/top_level.txt
19
19
  src/sqlphilosophy/aio/__init__.py
20
20
  src/sqlphilosophy/aio/protocols.py
21
21
  src/sqlphilosophy/aio/query.py
22
+ src/sqlphilosophy/aio/registry.py
22
23
  src/sqlphilosophy/aio/repository.py
23
24
  src/sqlphilosophy/audit/__init__.py
24
25
  src/sqlphilosophy/audit/context.py
@@ -26,6 +27,8 @@ src/sqlphilosophy/audit/fields.py
26
27
  src/sqlphilosophy/audit/listener.py
27
28
  src/sqlphilosophy/audit/model.py
28
29
  src/sqlphilosophy/sync/__init__.py
30
+ src/sqlphilosophy/sync/composite.py
29
31
  src/sqlphilosophy/sync/protocols.py
30
32
  src/sqlphilosophy/sync/query.py
33
+ src/sqlphilosophy/sync/registry.py
31
34
  src/sqlphilosophy/sync/repository.py
@@ -1,4 +1,4 @@
1
- servicephilosophy>=0.1.0
1
+ servicephilosophy<0.2,>=0.1.2
2
2
  sqlalchemy<3,>=2.0
3
3
 
4
4
  [async]
@@ -10,7 +10,7 @@ pytest-asyncio>=0.24
10
10
  pytest-cov>=6
11
11
  aiosqlite>=0.20
12
12
  greenlet>=3.0
13
- build>=1.2
13
+ build<2,>=1.6.1
14
14
  twine>=5
15
15
  ruff>=0.15
16
16
  mypy>=1.11
@@ -1 +0,0 @@
1
- 0.3.3
File without changes
File without changes
File without changes