cerbos-sqlalchemy 0.3.2__tar.gz → 0.6.0__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 (30) hide show
  1. cerbos_sqlalchemy-0.6.0/PKG-INFO +805 -0
  2. cerbos_sqlalchemy-0.6.0/README.md +786 -0
  3. {cerbos-sqlalchemy-0.3.2 → cerbos_sqlalchemy-0.6.0}/pyproject.toml +38 -11
  4. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/__init__.py +23 -0
  5. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/_null_conventions.py +222 -0
  6. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/_nullness.py +31 -0
  7. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/_operators.py +1404 -0
  8. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/_plan.py +296 -0
  9. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/_regex.py +580 -0
  10. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/_translator.py +1101 -0
  11. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/collection_storage.py +681 -0
  12. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/errors.py +16 -0
  13. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/inference.py +385 -0
  14. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/py.typed +0 -0
  15. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/query.py +379 -0
  16. cerbos_sqlalchemy-0.6.0/src/cerbos_sqlalchemy/relations.py +321 -0
  17. cerbos_sqlalchemy-0.6.0/tests/conftest.py +202 -0
  18. cerbos_sqlalchemy-0.6.0/tests/corpus.py +760 -0
  19. cerbos_sqlalchemy-0.6.0/tests/test_adversarial_conformance.py +451 -0
  20. cerbos_sqlalchemy-0.6.0/tests/test_inference.py +303 -0
  21. cerbos_sqlalchemy-0.6.0/tests/test_query.py +1302 -0
  22. cerbos_sqlalchemy-0.6.0/tests/test_relations.py +85 -0
  23. cerbos_sqlalchemy-0.6.0/tests/test_translator.py +601 -0
  24. cerbos_sqlalchemy-0.6.0/tests/typing/check_types.py +66 -0
  25. cerbos-sqlalchemy-0.3.2/PKG-INFO +0 -149
  26. cerbos-sqlalchemy-0.3.2/README.md +0 -132
  27. cerbos-sqlalchemy-0.3.2/src/cerbos_sqlalchemy/__init__.py +0 -7
  28. cerbos-sqlalchemy-0.3.2/src/cerbos_sqlalchemy/query.py +0 -152
  29. cerbos-sqlalchemy-0.3.2/tests/conftest.py +0 -175
  30. cerbos-sqlalchemy-0.3.2/tests/test_query.py +0 -372
@@ -0,0 +1,805 @@
1
+ Metadata-Version: 2.1
2
+ Name: cerbos-sqlalchemy
3
+ Version: 0.6.0
4
+ Summary: SQLAlchemy adapter for generating queries with Cerbos: an open core, language-agnostic, scalable authorization solution
5
+ Author-Email: Cerbos Developers <sdk+sqlalchemy@cerbos.dev>
6
+ License: Apache-2.0
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Topic :: Security
10
+ Classifier: Topic :: Software Development :: Libraries
11
+ Project-URL: Homepage, https://cerbos.dev
12
+ Project-URL: Repository, https://github.com/cerbos/query-plan-adapters/tree/main/sqlalchemy
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: sqlalchemy>=1.4
15
+ Requires-Dist: cerbos>=0.16.1
16
+ Provides-Extra: testcontainers
17
+ Requires-Dist: testcontainers>=4.13.3; extra == "testcontainers"
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Cerbos + SQLAlchemy Adapter
21
+
22
+ Converts a [Cerbos](https://cerbos.dev) query plan ([PlanResources API](https://docs.cerbos.dev/cerbos/latest/api/index.html#resources-query-plan))
23
+ into a [SQLAlchemy](https://docs.sqlalchemy.org/) `Select`, for use with the
24
+ [Cerbos Python SDK](https://github.com/cerbos/cerbos-sdk-python).
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install cerbos-sqlalchemy
30
+ ```
31
+
32
+ - Python >= 3.10
33
+ - SQLAlchemy >= 1.4 (1.4 and 2.x are both tested)
34
+ - Cerbos Python SDK (`cerbos`) >= 0.10.4; Cerbos PDP > v0.16
35
+ - Either SDK client: the HTTP `CerbosClient` or the gRPC client (see [Transports](#transports))
36
+
37
+ ## Quick start
38
+
39
+ ```python
40
+ from cerbos.sdk.client import CerbosClient
41
+ from cerbos.sdk.model import Principal, ResourceDesc
42
+ from sqlalchemy import Column, ForeignKey, Integer, String, create_engine
43
+ from sqlalchemy.orm import Session, declarative_base, relationship
44
+
45
+ from cerbos_sqlalchemy import get_query
46
+
47
+ Base = declarative_base()
48
+
49
+
50
+ class LeaveRequest(Base):
51
+ __tablename__ = "leave_request"
52
+
53
+ id = Column(Integer, primary_key=True)
54
+ department = Column(String(225))
55
+ geography = Column(String(225))
56
+ priority = Column(Integer)
57
+ owner_id = Column(ForeignKey("employee.id"))
58
+
59
+ owner = relationship("Employee")
60
+ approvers = relationship("Employee", secondary="leave_request_approver")
61
+
62
+
63
+ with CerbosClient(host="http://localhost:3592") as c:
64
+ principal = Principal(
65
+ "john",
66
+ roles={"employee"},
67
+ attr={"department": "marketing", "geography": "GB"},
68
+ )
69
+ plan = c.plan_resources("view", principal, ResourceDesc("leave_request"))
70
+
71
+ # ALWAYS_ALLOWED -> select(LeaveRequest)
72
+ # ALWAYS_DENIED -> select(LeaveRequest).where(False)
73
+ # CONDITIONAL -> select(LeaveRequest).where(<translated condition>)
74
+ query = get_query(plan, LeaveRequest)
75
+
76
+ # Compose with your own predicates; a denied plan stays denied.
77
+ query = query.where(LeaveRequest.priority < 5).limit(20)
78
+
79
+ with Session(create_engine("sqlite:///app.db")) as session:
80
+ rows = session.execute(query).scalars().all()
81
+ ```
82
+
83
+ With nothing but the model, every attribute is read from its mapping:
84
+ `R.attr.department` is the `department` column, `R.attr.owner.name` follows the `owner`
85
+ relationship, and `R.attr.approvers.exists(a, a.name == "x")` ranges over the `approvers`
86
+ relationship with `a.name` read from `Employee`. Pass an `attr_map` only for what the mapping
87
+ cannot say; see [Mapping attributes](#mapping-attributes).
88
+
89
+ `get_query` returns a `Select` for all three plan kinds, so you don't need to branch on the kind.
90
+ If you want to skip the round trip on a denial, check
91
+ `plan.filter.kind == PlanResourcesFilterKind.ALWAYS_DENIED` (from `cerbos.sdk.model`) first. Any
92
+ shape the adapter cannot translate raises instead of returning a broader query.
93
+
94
+ To debug, print the SQL: `print(query.compile(compile_kwargs={"literal_binds": True}))`.
95
+
96
+ ## Mapping attributes
97
+
98
+ ### By default: the model's own mapping
99
+
100
+ For an ORM model, an attribute `attr_map` leaves out is read from the model:
101
+
102
+ - `request.resource.attr.a.b.c` follows `a` and `b` as relationships and reads `c` as a column, or
103
+ as a relationship (a collection, or a to-one read whole). Each segment matches a mapped attribute
104
+ by its own name or its snake_case (`createdAt` reads `created_at`). A name matching two different
105
+ attributes is refused.
106
+ - A relationship is read as [`related()`](#collections-in-a-related-table) reads it: its own
107
+ `primaryjoin` and `secondaryjoin`, subtype discriminator, and to-one hops proved by a unique key.
108
+ - A lambda variable takes the element of the collection it ranges over, and its fields resolve on
109
+ the related model: in `R.attr.tags.exists(t, t.name == "x")`, `t.name` is `Tag.name`.
110
+ - `request.resource.id` reads the `id` column.
111
+
112
+ An attribute that resolves nowhere raises `KeyError`, as an unmapped one always has. A Core `Table`
113
+ has no mapping to read, so every attribute must be in `attr_map`.
114
+
115
+ **The contract inference relies on:** the value your application sends for `R.attr.x` is the value
116
+ of the column or relationship named `x`. When it is not (the attribute is computed, renamed, or
117
+ comes from another table without a relationship), map it.
118
+
119
+ ### Overrides: `attr_map`
120
+
121
+ `attr_map` maps a Cerbos attribute reference to a column, and wins over inference. Use it for an
122
+ attribute named differently from its column, a list of scalars (`related(Model.tags, Tag.name)`),
123
+ a relation the mapping does not hold, or a lambda field named differently. Values can be an ORM
124
+ attribute (`LeaveRequest.department`), a Core column (`LeaveRequest.__table__.c.department`), a
125
+ `relationship()` attribute, [`related(...)`](#collections-in-a-related-table), a hand-written
126
+ [`Relation`](#a-hand-written-relation), or any SQLAlchemy column expression.
127
+
128
+ The other options cover what no mapping can say: the [NULL convention](#null-attribute-representation)
129
+ your application sends, [collection storage](#collection-storage) in one column, and
130
+ [operator overrides](#operator-overrides).
131
+
132
+ ### Model styles
133
+
134
+ `table` accepts a Core `Table`, a legacy `declarative_base()` model, or a SQLAlchemy 2.0
135
+ `DeclarativeBase` subclass. An ORM model returns `Select[Tuple[Model]]`; a Core `Table` returns
136
+ `Select[Any]`.
137
+
138
+ ### Columns from more than one table
139
+
140
+ If `attr_map` references columns from other tables, pass `table_mapping` (4th positional
141
+ argument) — a list of `(table, join_condition)` pairs:
142
+
143
+ ```python
144
+ query = get_query(
145
+ plan,
146
+ Table1,
147
+ {
148
+ "request.resource.attr.foo": Table1.foo,
149
+ "request.resource.attr.bar": Table2.bar,
150
+ "request.resource.attr.bosh": Table3.bosh,
151
+ },
152
+ [
153
+ (Table2, Table1.table2_id == Table2.id),
154
+ (Table3, Table1.table3_id == Table3.id),
155
+ ],
156
+ )
157
+ ```
158
+
159
+ Tables may be models or Core `Table`s. A column expression that carries its own correlation (a
160
+ scalar subquery) needs no `table_mapping` entry.
161
+
162
+ If your models use `relationship()`, consider `query.with_only_columns(...)` to avoid implicit joins.
163
+
164
+ ### Collections and relations
165
+
166
+ - **A collection stored in one column** (JSON or PostgreSQL array) — declare it in
167
+ [`collection_columns`](#collection-storage) to get `size()` and constant indexing.
168
+ - **A collection in a related table** — read from its `relationship()` with no configuration, or
169
+ named with [`related()`](#collections-in-a-related-table). Read
170
+ [Mapping hazards](#mapping-hazards).
171
+ - **A collection the PDP already knows** (usually a principal attribute) — translated with no
172
+ configuration; see [Collection macros over known values](#collection-macros-over-known-values).
173
+
174
+ ## Options
175
+
176
+ | Option | Default | Use it when |
177
+ | --- | --- | --- |
178
+ | `table_mapping` | `None` | `attr_map` spans more than one table |
179
+ | `operator_override_fns` | `None` | you need a dialect-specific operator. `relation_overrides()` is merged in for you whenever a collection is mapped |
180
+ | `null_attribute_representation` | `"omitted"` | your app sends explicit nulls for NULL columns (`"explicit"`) |
181
+ | `attribute_null_representation` | `None` | the NULL convention differs per attribute |
182
+ | `collection_columns` | `None` | a policy calls `size()`, indexes, or tests literal membership in a JSON / PostgreSQL array column |
183
+
184
+ ### NULL attribute representation
185
+
186
+ The planner emits the same `eq(x, null)` node however your application represents a NULL column in
187
+ the attributes it sends to `check()`, so you have to tell the adapter which convention you use.
188
+
189
+ | attributes you send for a NULL column | `check()` on that row | `IS NULL` filter |
190
+ | --- | --- | --- |
191
+ | `{"x": None}` — explicit null | allow | selects it — aligned |
192
+ | `{}` — attribute omitted | **deny** (CEL missing-attribute error) | selects it — **over-grants** |
193
+
194
+ The default is `"omitted"`, the convention that fails closed when the guess is wrong. If you send
195
+ NULL columns as explicit nulls, pass `"explicit"`, which translates `== null` to `IS NULL`:
196
+
197
+ ```python
198
+ get_query(plan, Resource, attr_map, null_attribute_representation="explicit")
199
+ ```
200
+
201
+ Under `"omitted"`, `x == null` and `x != null` answer exactly what CEL does: a NULL column is a
202
+ missing-attribute error, and a present one is never null. The adapter renders them as
203
+ `CASE WHEN x IS NOT NULL THEN FALSE END` (`TRUE` for `!=`), which is UNKNOWN for a NULL column and
204
+ stays UNKNOWN under any enclosing `not`, so the row is denied under both polarities. This needs `x`
205
+ mapped to a SQL expression (a column, or a correlated scalar subquery for a to-one relation) and no
206
+ override for that operator; otherwise the comparison raises. Every other null operand raises (a null
207
+ element of an `in` list, a null inside `hasIntersection`, ordering against null), and the refusal
208
+ fires before `operator_override_fns`. See [#302](https://github.com/cerbos/query-plan-adapters/issues/302)
209
+ and [#551](https://github.com/cerbos/query-plan-adapters/issues/551).
210
+
211
+ #### Declare the convention per attribute
212
+
213
+ One policy suite can mix both conventions (the same column mapped under two attribute names). Declare
214
+ it per attribute; the call-level option covers everything undeclared:
215
+
216
+ ```python
217
+ get_query(
218
+ plan,
219
+ Resource,
220
+ attr_map,
221
+ attribute_null_representation={
222
+ "request.resource.attr.owner": "explicit",
223
+ # department is omitted when NULL, so leave it undeclared
224
+ },
225
+ )
226
+ ```
227
+
228
+ Declaring `"explicit"` asserts that the column can be NULL **and** that a NULL reaches `check()` as
229
+ an explicit null. The equality family (`eq`, `ne`, `in`) over that attribute then renders so it is
230
+ never SQL UNKNOWN: CEL's `null != "x"` is TRUE, so the NULL row comes back. Ordering and string
231
+ operators are unchanged (CEL raises on a null receiver, which denies like UNKNOWN does). An
232
+ undeclared attribute follows the call-level option; if that is `"omitted"` and the caller in fact
233
+ sends an explicit null, `!=` against a constant under-grants the NULL rows, which fails closed.
234
+
235
+ **Declare both sides of a field-to-field comparison, or neither** — mixing conventions in one
236
+ comparison throws. See [#308](https://github.com/cerbos/query-plan-adapters/issues/308) and
237
+ [ADR 0004](../docs/adr/0004-the-null-convention-is-a-property-of-the-attribute.md).
238
+
239
+ > [!WARNING]
240
+ > **On Cerbos 0.56.0 and earlier, do not guard with `has()`: write `R.attr.x != null`.** An
241
+ > attribute the plan request omits is unknown to those planners, which assume the data layer
242
+ > supplies it, so they fold `has(R.attr.x)` to true: alone it plans as `ALWAYS_ALLOWED`, and
243
+ > `has(R.attr.x) && R.attr.y > 0` plans as `R.attr.y > 0`, which never excludes a row missing `x`.
244
+ > From 0.57.0 the planner keeps `has(R.attr.x)` in the plan, and the adapter translates it from
245
+ > `x`'s null convention or refuses it: under `omitted` a row has `x` when its value is not null, and
246
+ > under `explicit` every row has it. The planner still drops a `has(R.attr.x)` that only guards an
247
+ > access to `x`, as in `has(R.attr.x) && R.attr.x == "a"`, because that access already denies a row
248
+ > without `x`.
249
+
250
+ ### Collection storage
251
+
252
+ `size(R.attr.tags)` and `R.attr.tags[0]` need to know how the collection is stored. Declare it per
253
+ attribute:
254
+
255
+ ```python
256
+ from cerbos_sqlalchemy import CollectionColumn, get_query
257
+
258
+ get_query(
259
+ plan,
260
+ Resource,
261
+ attr_map,
262
+ collection_columns={
263
+ # PostgreSQL JSON/JSONB, a MySQL JSON column, or a SQLite JSON text column
264
+ "request.resource.attr.tags": CollectionColumn(Resource.tags, "json"),
265
+ # PostgreSQL array of text, varchar, boolean, integer or smallint
266
+ "request.resource.attr.labels": CollectionColumn(Resource.labels, "pgArray"),
267
+ },
268
+ )
269
+ ```
270
+
271
+ The storage names match the drizzle adapter's. The declaration is read in exactly three places. In
272
+ the first two it takes precedence over `attr_map` and any override:
273
+
274
+ - **`size()`** counts elements. Empty is `0`; an SQL NULL column or a non-array JSON value is
275
+ UNKNOWN, so `size(x) == 0` selects empty rows, never missing ones, and `size(x) >= 0` excludes them.
276
+ - **`x[i] == literal`** / **`x[i] != literal`** — string, number, boolean or `null` literal, constant
277
+ non-negative index, either operand order, under logical operators. JSON types are kept (`"1"` is not
278
+ `1`; `true` is not `1` even on SQLite); numbers compare as doubles. An absent element is UNKNOWN,
279
+ so it stays excluded under negation. A null *element* is a value: `[null][0] == null` is true.
280
+ PostgreSQL arrays are read through `to_jsonb`, so a non-1 lower bound still reads the element CEL does.
281
+
282
+ The third applies only to an attribute `attr_map` does **not** map, so a declaration added for
283
+ `size()` and indexing never changes how an existing relation answers membership:
284
+
285
+ - **`literal in x`** / **`hasIntersection(x, [literals])`**, either operand order, for string,
286
+ number, boolean and `null` literals. Each literal matches only an element of its own JSON type, as
287
+ CEL's heterogeneous equality does: `"2" in [2]` is false, and `hasIntersection(x, ["2", 3])`
288
+ matches on the `3` alone. An SQL NULL column or a non-array JSON value is UNKNOWN, so a negated
289
+ membership still excludes it. A column, an expression, or a list/map literal as the element raises.
290
+
291
+ Everything else over a declared element raises: a negative, fractional or dynamic index, ordering, a
292
+ projection like `x[0].name`, and comparison with a list or map literal. Elsewhere the attribute
293
+ still resolves through `attr_map`. The column must hold exactly the list you send to Cerbos, null
294
+ elements included.
295
+
296
+ The SQL is picked per dialect at compile time. SQLite (JSON1), PostgreSQL and MySQL 8.0.17+
297
+ (`"json"` only) are supported; any other dialect raises `CompileError`.
298
+
299
+ ### Operator overrides
300
+
301
+ `operator_override_fns` replaces the handler for an operator — for a more idiomatic SQL form, or to
302
+ translate a collection held in a related table:
303
+
304
+ ```python
305
+ from sqlalchemy.sql.expression import any_
306
+
307
+ query = get_query(
308
+ plan,
309
+ Table1,
310
+ attr_map={"request.resource.attr.foo": Table1.foo},
311
+ operator_override_fns={
312
+ "in": lambda c, v: c == any_(v), # PostgreSQL: = ANY instead of IN
313
+ },
314
+ )
315
+ ```
316
+
317
+ The type is `dict[str, Callable[[GenericColumn, Any], GenericExpression]]`, where `GenericColumn` is
318
+ `Column | InstrumentedAttribute` and `GenericExpression` is `BinaryExpression | ColumnOperators`.
319
+
320
+ - An entry whose value is `None` uses the default handler, including inside nested expressions.
321
+ - Without `operator_override_fns`, every `attr_map` entry is validated. With an explicit mapping
322
+ (even `{}` or only `None` entries), only attributes reached outside active overrides are
323
+ validated; an override owns the operands it translates.
324
+ - `matches()` never reaches the store's regex engine (none is RE2): the pattern is lowered to
325
+ exact string predicates, or refused (["Regular expressions"](#regular-expressions)). Override it
326
+ only if your database's engine is equivalent.
327
+ - An override's intermediate value reaching a default handler raises.
328
+
329
+ For a collection in a related table, use
330
+ [`relation_overrides()`](#collections-in-a-related-table) rather than writing the macros yourself.
331
+
332
+ ### Collection macros over known values
333
+
334
+ `exists`/`all` over a collection the PDP resolves at plan time — usually a principal attribute — is
335
+ translated with no override:
336
+
337
+ ```yaml
338
+ condition:
339
+ match:
340
+ expr: P.attr.teams.exists(t, R.attr.team == t)
341
+ ```
342
+
343
+ The planner unrolls this into an `or`/`and` chain at 10 elements or fewer, and sends a literal list
344
+ above that (cerbos/cerbos#2570, cerbos/cerbos#2817). The adapter applies the same fold with no cap,
345
+ so the SQL is equivalent either side of the threshold. A bare `t` becomes the element, `t.name`
346
+ drills into it, and each body goes through the normal pipeline (overrides and NULL handling apply).
347
+ An empty list: `exists` matches nothing, `all` matches everything. `exists_one` counts the bodies
348
+ that hold, `size(list.filter(t, ...))` counts them as a number, and `x in list.map(t, ...)` is an
349
+ `==` against each mapped body; CEL raises if any body raises, so each of these is UNKNOWN where
350
+ any body is. `except` over a literal list is still refused.
351
+
352
+ A list the plan builds from attributes (`[R.attr.a, R.attr.b].exists(s, s == "x")`) folds the same
353
+ way, with each element substituted into the body. Building the list evaluates every element, so an
354
+ element that raises in CEL (a missing attribute, or an expression over one) makes the whole macro
355
+ raise even beside a match: the folded filter is UNKNOWN for that row. `in` over a built list is an
356
+ `==` per element under the same guard, `x in (cond ? A : B)` is taken per branch, and `x in A + B`
357
+ is `x in A || x in B`.
358
+
359
+ `exists_one`, `filter`, `map` and `except` over a literal list raise, as does a `t.path` the element
360
+ doesn't carry, a map or list element, and a two-variable comprehension (`exists(i, v, ...)`), whose
361
+ index or map key has no SQL lowering. Macros over a related table (`R.attr.tags.exists(...)`) need
362
+ [`relation_overrides()`](#collections-in-a-related-table).
363
+
364
+ ### Collections in a related table
365
+
366
+ A collection whose `relationship()` carries its name needs no mapping. To name one explicitly, map
367
+ the attribute to the `relationship()` or to `related(...)`. The adapter reads the join and the
368
+ cardinality from the mapping:
369
+
370
+ ```python
371
+ from cerbos_sqlalchemy import get_query, related
372
+
373
+ attr_map = {
374
+ # One-to-many or many-to-many: a collection.
375
+ "request.resource.attr.tags": Resource.tags,
376
+ # The lambda variable in `R.attr.tags.exists(t, t.name == "public")`.
377
+ "t": Resource.tags,
378
+ "t.name": Tag.name,
379
+ # A list of strings (`"public" in R.attr.tagNames`): the relationship, then the member column.
380
+ "request.resource.attr.tagNames": related(Resource.tags, Tag.name),
381
+ # A scalar through to-one hops, NULL when a hop is absent.
382
+ "request.resource.attr.owner.name": related(Resource.owner, Owner.name),
383
+ # A collection reached through a to-one hop, guarded by `require_hops`.
384
+ "request.resource.attr.mainCategory.subCategories": related(
385
+ Resource.main_category, Category.sub_categories
386
+ ),
387
+ }
388
+
389
+ query = get_query(plan, Resource, attr_map)
390
+ ```
391
+
392
+ `related(*path)` takes relationship attributes, each starting where the last
393
+ ends, optionally followed by one column of the last target. A bare relationship attribute is
394
+ `related()` of it. What `related()` reads, and what it refuses with `UnsupportedPlanError`:
395
+
396
+ - The join is the relationship's own `primaryjoin` and `secondaryjoin`, plus the target's
397
+ joined-inheritance condition and single-table discriminator, so a filtered association or a
398
+ subtype target selects the rows `Model.rel.any()` would.
399
+ - A to-one hop (`uselist=False`) must equate a unique key of its target (primary key, unique
400
+ constraint, unique index or `unique=True` column) in its `primaryjoin`. Otherwise the database
401
+ does not hold it to one row and `related()` refuses it. A to-one over a `secondary` table is
402
+ refused.
403
+ - Only the last hop may be to-many: CEL cannot dot through a list.
404
+ - A self-referential relationship is refused: map it with a hand-written `Relation` over an
405
+ `aliased()` target.
406
+ - Subqueries correlate against every enclosing table but their own, so a nested collection
407
+ (`c.subCategories` inside `categories`) needs no `correlate`.
408
+ - Default scopes the mapping does not carry (`with_loader_criteria`, a soft-delete column the
409
+ relationship does not filter) are still yours: see [Mapping hazards](#mapping-hazards).
410
+
411
+ Mapping any collection merges `relation_overrides()` beneath `operator_override_fns`, so your own
412
+ overrides still win.
413
+
414
+ #### A hand-written `Relation`
415
+
416
+ When no `relationship()` fits, map the collection to a `Relation` you write:
417
+
418
+ ```python
419
+ from cerbos_sqlalchemy import Relation
420
+
421
+ attr_map["request.resource.attr.tagNames"] = Relation(
422
+ [Tag.resource_id == Resource.id],
423
+ correlate=[Resource],
424
+ member=Tag.name,
425
+ )
426
+ ```
427
+
428
+ `Relation(correlation, correlate=(), *, member=None, hop_correlation=())`:
429
+
430
+ - `correlation` joins an element row to the row that owns the collection, through every hop.
431
+ - `correlate` lists the entities the subqueries correlate against: the queried table, plus every
432
+ enclosing lambda's table for a nested collection (`c.subCategories` inside `categories`).
433
+ SQLAlchemy auto-correlates only with the immediately enclosing `SELECT`.
434
+ - `member` is the element column `in` and `hasIntersection` compare.
435
+ - `hop_correlation` names the predicates that cross a to-one parent; see
436
+ [`require_hops`](#require_hops-the-one-hazard-with-a-library-helper).
437
+
438
+ `relation_overrides()` translates `exists`, `all`, `exists_one`, `size()`, `in`,
439
+ `hasIntersection`, `size(filter(...))`, `x in filter(...)`, `x in map(...)` and
440
+ `hasIntersection(map(...), [...])` over a `Relation`. Each is three-valued: an element whose body is
441
+ SQL NULL is a CEL error, which `exists` absorbs only beside a true element and `all` only beside a
442
+ false one, so `!tags.exists(t, t.name == "x")` excludes a row with a nameless tag, as the PDP does.
443
+ A plain `EXISTS (... WHERE body)` reads that tag as false and its negation selects the row. `in`,
444
+ `size()` and `hasIntersection` over anything that is not a `Relation` fall back to the default
445
+ handler. The dict is new on each call, so merge your own overrides into it.
446
+
447
+ The conformance harness runs exactly these overrides, so the corpus proves them.
448
+
449
+
450
+ ### Regular expressions
451
+
452
+ CEL's `matches()` is RE2, and no store's regex dialect is: MySQL's ICU engine lets `$` match before a
453
+ trailing newline, PostgreSQL's differs in classes and flags, and SQLite has none. So the pattern is
454
+ never handed to the store. The adapter parses it and lowers it only when what it matches can be said
455
+ with exact string predicates:
456
+
457
+ - a finite set of literals, under anchors or not: `^(ab|b)$` is `IN ('ab', 'b')`, `^h` and `\d` are
458
+ `startsWith`/`contains` over each literal, `(?i)` folds ASCII case (and `k`/`s` to KELVIN SIGN and
459
+ LONG S, as RE2 does);
460
+ - every character drawn from a set of at most 64, with a minimum count: `^[ab]+$`, `^\s*$`,
461
+ `^[[:alpha:]]+$`;
462
+ - a prefix and a suffix around one run of non-newline characters: `^a.*b$`, `^.{8,}$`.
463
+
464
+ A pattern RE2 rejects (a backreference, a lookahead, `a**`, a count above 1000) is an evaluation
465
+ error in CEL, so it is UNKNOWN for every row and denies under both polarities. Anything else (a
466
+ negated class, an anchor inside the pattern, a repetition over an unbounded group) raises
467
+ `UnsupportedPlanError`. A missing receiver, or one that is not a string, is UNKNOWN.
468
+
469
+ ### Transports
470
+
471
+ `get_query` accepts the HTTP client's `PlanResourcesResponse` or the gRPC client's protobuf one.
472
+ They behave identically except for a constant zero divisor (`x / -0.0`): only gRPC keeps the sign of
473
+ the zero, so only gRPC translates it; over HTTP, whose JSON renders `-0.0` as `-0` and decodes it to
474
+ the integer `0`, it raises `UnsupportedPlanError`.
475
+
476
+ ### Async
477
+
478
+ `get_query` does no I/O. Execute the `Select` however you already do, including `AsyncSession` or
479
+ `AsyncConnection`:
480
+
481
+ ```python
482
+ async with AsyncSession(async_engine) as session:
483
+ rows = (await session.execute(get_query(plan, Resource, attr_map))).scalars()
484
+ ```
485
+
486
+ Plan with the SDK's async client, or run the sync one off the event loop.
487
+
488
+ ## Correctness requirements
489
+
490
+ ### Database collation requirements
491
+
492
+ CEL string and hierarchy comparisons are byte-exact, and CEL orders strings by code point. The
493
+ adapter does not trust the column's collation for that:
494
+
495
+ - **MySQL:** every comparison, membership test and `LIKE` over a `String` column or a string
496
+ literal runs under `COLLATE utf8mb4_0900_bin`, which is byte-exact and NO PAD, so the default
497
+ `utf8mb4_0900_ai_ci` (on the column or on the connection) cannot make `One` match `one`. String
498
+ columns must use the `utf8mb4` character set, and a comparison over a column whose own collation
499
+ differs cannot use that column's index.
500
+ - **PostgreSQL:** equality is exact under any deterministic collation and is left alone. Every
501
+ ordering (`<`, `<=`, `>`, `>=`) over a string runs under `COLLATE "C"`, since a linguistic
502
+ collation such as `en_US.UTF-8` sorts `"One"` after `"a"`
503
+ ([#489](https://github.com/cerbos/query-plan-adapters/issues/489)). Avoid nondeterministic ICU
504
+ collations and `citext`.
505
+
506
+ The conformance MySQL leg runs under the server default, and the PostgreSQL leg under ICU's
507
+ `en-US`, so the corpus proves both on every run.
508
+
509
+ On SQLite a column collation does not help: SQLite's `LIKE` ignores it and folds ASCII case unless
510
+ the connection sets `PRAGMA case_sensitive_like = ON`. Without the pragma, `contains`, `startsWith`,
511
+ `endsWith` and hierarchy-prefix predicates **over-grant** (`R.attr.name.startsWith("o")` matches
512
+ `One`). The adapter does not own the connection, so set the pragma on every one it opens, as the
513
+ conformance harness does:
514
+
515
+ ```python
516
+ from sqlalchemy import create_engine, event
517
+
518
+ engine = create_engine("sqlite:///app.db")
519
+
520
+
521
+ @event.listens_for(engine, "connect")
522
+ def _case_sensitive_like(dbapi_connection, _connection_record):
523
+ cursor = dbapi_connection.cursor()
524
+ cursor.execute("PRAGMA case_sensitive_like = ON")
525
+ cursor.close()
526
+ ```
527
+
528
+ For an async engine, listen on `async_engine.sync_engine`.
529
+
530
+ ### Timestamps
531
+
532
+ Timestamp literals must be strict RFC 3339, within CEL's year 0001–9999 range, and exactly
533
+ representable at microsecond precision (discarded fractional digits must be zero); the mapped column
534
+ and database must preserve microseconds. A temporal attribute read outside `timestamp()` raises:
535
+ CEL sees the RFC 3339 string the application sent, which a stored timestamp no longer spells, and
536
+ has no overload comparing that string with a timestamp. Compare instants with `timestamp()` on both
537
+ operands.
538
+
539
+ `timestamp(R.attr.x) + duration("86400s")` (or `-`) compared with a timestamp literal is rewritten
540
+ to compare the column with the literal shifted the other way, guarded so a row whose sum leaves
541
+ CEL's range stays denied. Durations must be exact at microsecond precision. `timeSince()` raises:
542
+ the planner leaves it unevaluated, and the plan carries no instant to measure from.
543
+
544
+ ## Supported operators
545
+
546
+ | Shape | Default | Otherwise |
547
+ | --- | --- | --- |
548
+ | Comparisons, logical operators, value-first and field-to-field forms, ternaries | translated | — |
549
+ | `contains`, `startsWith`, `endsWith` | escaped `LIKE` | — |
550
+ | `+`, `-`, `*`, `/` by a constant | translated | — |
551
+ | `/` by a column | refused, unless the numerator is that column or a constant zero (a zero divisor then gives NaN, which has no sign) | an override |
552
+ | `%` | refused: CEL defines it only over integers, and attribute numbers are doubles | an override |
553
+ | `string()` over a text or boolean column | translated (a boolean through a `CASE` that spells `'true'`/`'false'`) | — |
554
+ | `string()` over a numeric column | refused: CEL prints Go's shortest `%g` form (`1e+06`, `-0`) | an override matching your database |
555
+ | `int()`, `double()` | refused | an override matching your database |
556
+ | `size()` over a string column | `LENGTH` (`CHAR_LENGTH` on MySQL, whose `LENGTH` counts bytes) | — |
557
+ | `upperAscii()` | a `REPLACE` per ASCII letter (`UPPER` also folds non-ASCII letters on PostgreSQL and MySQL); compared with a string literal, only the literal's own letters, which keeps SQLite before 3.46 inside its parser stack | — |
558
+ | `m["key"]` over a map attribute | read as `m.key` when `attr_map` maps that path | — |
559
+ | `{"k": v, ...}[R.attr.x] == literal`, `!=` (a map literal read at an attribute key) | the keys whose value answers it, UNKNOWN for a key outside the map | — |
560
+ | `timestamp(x) ± duration(...)` against a timestamp literal | the literal shifted instead | — |
561
+ | `timeSince()` | refused: the plan carries no evaluation instant | — |
562
+ | `size()` over a JSON or PostgreSQL array column | refused until declared | `collection_columns` |
563
+ | `x[i] == literal`, `x[i] != literal` over a JSON or PostgreSQL array column | refused until declared | `collection_columns` |
564
+ | `literal in x`, `hasIntersection(x, [literals])` over a JSON or PostgreSQL array column | refused until declared | `collection_columns`, for an attribute `attr_map` does not map |
565
+ | `exists`, `all` over a literal list (a principal attribute) or a list built from attributes | folded | — |
566
+ | `in` over a list built from attributes, a ternary of lists, or a concatenation `A + B` | translated per element, branch or operand | — |
567
+ | `exists`, `all`, `exists_one`, `filter`, `map`, `in`, `hasIntersection`, `size()` over a related table | — | `relation_overrides()` over a `Relation` |
568
+ | `index` over any other storage | refused | an `index` override |
569
+ | `exists_one` over a literal list, `size(filter(...))` and `in` over `map(...)` of one | folded, UNKNOWN where any body raises | — |
570
+ | `matches()` whose pattern is a finite set of literals under anchors, every character from a set, or a prefix and suffix around `.*` | translated as exact string predicates | — |
571
+ | `matches()` with any other pattern | refused | an override, only if your engine matches RE2 |
572
+ | `==`, `!=` between a string, number or boolean column and a list or map literal | false (true for `!=`) where the column is present | — |
573
+ | Timestamps, hierarchies | translated | — |
574
+
575
+ Numeric `size()` and string operations keep CEL's type errors rather than allowing SQL coercion.
576
+ Constant NaN ordering is false and its negation true (Cerbos 0.55; under 0.54 it was an evaluation
577
+ error and stayed denied under negation). A bare boolean column is accepted as a whole condition.
578
+
579
+ ## Conformance contract
580
+
581
+ The adapter is replayed against the shared [conformance corpus](../conformance/README.md): every
582
+ recorded plan from Cerbos PDP 0.57.0 and 0.56.0 is served by a stub PDP and fetched through the SDK's
583
+ HTTP `CerbosClient`, so it arrives as your application receives it, then translated with one mapping,
584
+ executed on SQLite (through a `Connection` and through an `AsyncSession`), PostgreSQL and MySQL
585
+ (`utf8mb4_0900_bin`), and the returned ids are compared with the decisions the PDP recorded. The
586
+ collections are stored as JSON on every store; the cases that read a collection declared in
587
+ `collection_columns` run once more on PostgreSQL with them stored as arrays (`pgArray`). The results
588
+ are the same on every store. For the current PDP, 0.57.0, where the total is every golden case
589
+ recorded in that tier:
590
+
591
+ | Tier | Passed / total |
592
+ | --- | --- |
593
+ | core | 32 / 32 |
594
+ | extended | 91 / 110 |
595
+ | adversarial | 413 / 550 |
596
+
597
+ Every case that does not pass is either refused with `UnsupportedPlanError` (81 cases) or is
598
+ skipped because its golden file records a planner divergence, which no adapter can pass and the
599
+ harness does not compare. Under 0.57.0 those are three extended cases and four adversarial cases:
600
+ `arithmetic/add/int-literal-plus-constant` and
601
+ `arithmetic/add/int-literal-negated` (the planner drops the int type of the literal in
602
+ `R.attr.x + 1`, while `check()` has no double + int overload and denies every row, so write `1.0`),
603
+ three
604
+ `composition/*` cases whose DENY condition reads `aNumber`, which j2 lacks: the plan's `not(...)` of
605
+ it denies j2, while `check()` receives `aNumber` as absent and treats the erroring DENY as not
606
+ matching ([#530](https://github.com/cerbos/query-plan-adapters/issues/530)), and
607
+ `type-mismatch/in/number-field-in-scalar-principal` and `type-mismatch/in/string-field-in-dyn-string`
608
+ (the planner rewrites `in` over a scalar container to `==`, which `check()` has no overload for;
609
+ [#596](https://github.com/cerbos/query-plan-adapters/issues/596)). On 0.56.0, `null/has/missing-attribute` and `null/has/composed-with-comparison` are skipped too:
610
+ that planner folds `has()` on an omitted attribute to true, while `check()` denies the row; 0.57.0
611
+ keeps `has()` in the plan.
612
+ [`conformance-ledger.json`](conformance-ledger.json) lists each refused case with the mechanism that
613
+ rules it out.
614
+
615
+ ### Refusals
616
+
617
+ A plan shape the adapter cannot express raises `cerbos_sqlalchemy.UnsupportedPlanError`, never a
618
+ best-effort filter. It subclasses `ValueError`, which these refusals raised before it existed; the
619
+ refusal for a relation-mapped attribute that no operator override consumes is also a `TypeError`, as
620
+ it was before. Invalid configuration (an unknown null representation, an unmapped attribute, a missing
621
+ `table_mapping`) keeps raising `ValueError`, `KeyError` or `TypeError`. An operator override that
622
+ cannot translate what it was handed should raise `UnsupportedPlanError` too.
623
+
624
+ ## Mapping hazards
625
+
626
+ The conformance contract proves the *plan* side. The other half is the *mapping*: **the rows a
627
+ subquery reads must be the rows the application put into the resource attributes.** The shared
628
+ corpus catalogues six ways that breaks, and every adapter records a position on each.
629
+
630
+ **A `Relation` is only the predicates you give it.** A collection-valued attribute reaches its rows
631
+ through the correlation you write, so every hazard below but the last is yours. Which ones apply
632
+ depends on how you write it:
633
+
634
+ - Through a mapped **`relationship()`** (`Model.rel.any(...)`, `Model.rel.has(...)`,
635
+ `select(...).join(Model.rel)`), SQLAlchemy applies the `primaryjoin` and, for a
636
+ single-table-inheritance target, the
637
+ [discriminator](https://docs.sqlalchemy.org/en/20/orm/queryguide/inheritance.html#single-inheritance-mappings).
638
+ - Through a `relationship()` attribute or **`related()`**, the adapter applies the same
639
+ `primaryjoin`, `secondaryjoin` and discriminator, and refuses a to-one no unique key holds to
640
+ one row. The conformance harness maps this way.
641
+ - Through a hand-written **`Relation`**, or a correlated `select()` over columns, none of that
642
+ applies.
643
+
644
+ Check both against the SQLAlchemy version you run.
645
+
646
+ | Hazard | Position | Mechanism to check |
647
+ |---|---|---|
648
+ | Filtered association | **Caller-owned** | `relationship(primaryjoin=…)` and `relationship(secondaryjoin=…)`. `.any()`/`.has()` apply them; a hand-written `select()` over the target's columns does not, and must repeat the predicate in its own `where()` |
649
+ | Default scope on the target model | **Caller-owned** | A soft-delete column (`deleted_at IS NULL`), a tenant column, a `published` flag, or a `with_loader_criteria` on the session. SQLAlchemy applies none of them to a subquery you build yourself |
650
+ | Subtype discrimination | **Caller-owned** | `polymorphic_identity` on a single-table-inheritance subclass. `select(Subclass)` carries the discriminator; `select(literal(1)).where(subclass_table.c.x == …)` over the shared table does not, and sees sibling subtypes |
651
+ | To-one relation used as a collection | **Caller-owned** | A `relationship(uselist=False)` whose foreign key has no unique constraint. Nothing makes the database enforce the single row the application saw — add the constraint |
652
+ | Composite association key | **Caller-owned** | A multi-column foreign key. An override is arbitrary SQLAlchemy, so a composite key *is* expressible — and nothing stops you writing half of it. Conjoin every column pair |
653
+ | Absent to-one parent | **Reproduced by `Relation(hop_correlation=…)`**, and proved by the corpus (`relation/all/to-one-chain`, `relation/bare-attribute/negated-one-hop-boolean` and siblings) | `hop_correlation`, which `relation_overrides()` passes to `cerbos_sqlalchemy.require_hops` — see below. Set it on every `Relation` that reaches a COLLECTION through an intermediate to-one hop. A SCALAR read through a to-one hop needs nothing: map it to a correlated scalar subquery and an absent hop is SQL NULL, excluded under both polarities. `attr_map` accepts any column expression for this, and it needs no `table_mapping` ([#375](https://github.com/cerbos/query-plan-adapters/issues/375)) |
654
+
655
+ ### `require_hops`: the one hazard with a library helper
656
+
657
+ Every intermediate segment of `a.b.c` is a to-one parent (CEL cannot dot through a list). When it is
658
+ absent, the application sends no attribute and CEL denies — but a subquery rooted at the resource
659
+ row can't tell an absent parent from a childless one, so `all` reads TRUE, `!exists` reads TRUE and
660
+ the count reads 0, each admitting denied rows ([#309](https://github.com/cerbos/query-plan-adapters/issues/309)).
661
+
662
+ ```python
663
+ # `mainCategory.subCategories`: the collection is reached THROUGH the category hop.
664
+ attr_map["request.resource.attr.mainCategory.subCategories"] = Relation(
665
+ [SubCategory.category_id == Category.id, Category.resource_id == Resource.id],
666
+ correlate=[Resource],
667
+ hop_correlation=[Category.resource_id == Resource.id],
668
+ )
669
+ ```
670
+
671
+ `relation_overrides()` routes every answer over a `Relation` through
672
+ `require_hops(expression, hop_correlation, correlate=())`, which wraps it in a `CASE` with **no
673
+ `ELSE`**: a missing hop yields NULL, which stays excluded under both polarities. With an empty
674
+ `hop_correlation` (a direct relation) it returns the expression unchanged, so `!tags.exists(...)`
675
+ over zero tags is still TRUE.
676
+
677
+ An override of your own over a chain must route **every** operator through it, not only the
678
+ macros: a bare `EXISTS` is FALSE for an absent parent and its negation TRUE, which is how
679
+ membership, `hasIntersection` ([#315](https://github.com/cerbos/query-plan-adapters/issues/315)) and
680
+ `!(size(chain) > 0)` ([#316](https://github.com/cerbos/query-plan-adapters/issues/316)) over-granted.
681
+ It must also keep a NULL body NULL, as `relation_overrides()` does; nothing checks either.
682
+
683
+ ## Behaviour changes
684
+
685
+ - Added: `attr_map` is optional for an ORM model. An attribute it leaves out, lambda variables
686
+ included, is read from the model's columns and relationships by name; see
687
+ [By default: the model's own mapping](#by-default-the-models-own-mapping). It used to raise
688
+ `KeyError`. A widening.
689
+ - Added: an `attr_map` value may be a `relationship()` attribute or `related(...)`, which read the
690
+ join, cardinality and to-one hop guards from the mapping, and mapping a collection merges
691
+ `relation_overrides()` in. A relationship attribute used to be refused with
692
+ `UnsupportedPlanError`. A widening.
693
+ - **Breaking:** `has()` over an attribute mapped to a correlated scalar subquery raises
694
+ `UnsupportedPlanError` unless an override answers `has`. The subquery is NULL for a missing parent
695
+ as well as a missing value, so `!has(parent.x)` selected parentless rows the PDP denies.
696
+ - Added ([#527](https://github.com/cerbos/query-plan-adapters/issues/527)): `Relation` and
697
+ `relation_overrides()`, the conformance harness's three-valued relation macros, now shipped. This
698
+ README used to show a hand-written `exists` override that put the body in `.where(body)`, which
699
+ reads a NULL body as false, so `!tags.exists(...)` selected rows the PDP denies. Replace overrides
700
+ copied from it with `relation_overrides()`. A widening.
701
+ - Fixed: a string, number or temporal column read where CEL needs a boolean (`not R.attr.aString`, `R.attr.aString && R.attr.aBool`) renders as `NULL`, CEL's type error, which `AND` and `OR` absorb as `&&` and `||` absorb it. PostgreSQL rejected the query, and SQLite and MySQL over-granted by reading the text as a number.
702
+ - **Breaking:** `null_attribute_representation` defaults to `"omitted"`, where it defaulted to
703
+ `"explicit"`. A caller that sends explicit nulls and set nothing now gets `x == null` matching no
704
+ row where it rendered `IS NULL`, and a refusal for the other null operands; pass
705
+ `null_attribute_representation="explicit"` to keep the old output
706
+ ([#499](https://github.com/cerbos/query-plan-adapters/issues/499),
707
+ [ADR 0011](../docs/adr/0011-denial-fails-closed-in-the-result.md)).
708
+ - [#500](https://github.com/cerbos/query-plan-adapters/issues/500), found by running the corpus on
709
+ PostgreSQL and MySQL:
710
+ - `+`, `-` and `*` read an integer or `Numeric` column as a double, as CEL reads every attribute
711
+ number. PostgreSQL used to multiply in exact `numeric`, so `R.attr.aNumber * 0.1 == 0.3` was true
712
+ for `3` (CEL: `0.30000000000000004`) — an over-grant.
713
+ - `size()` of a string counts characters on MySQL (`CHAR_LENGTH`), where `LENGTH` counted bytes.
714
+ - An ordering comparison between mismatched types inside a ternary no longer fails on PostgreSQL
715
+ with `CASE types text and boolean cannot be matched`.
716
+ - **Widening:** `collection_columns` storage `"json"` renders on MySQL 8.0.17+, where it used to
717
+ raise `CompileError`.
718
+ - [#545](https://github.com/cerbos/query-plan-adapters/issues/545): an ordering between a boolean
719
+ column and a boolean literal (`R.attr.aBool < true`) now translates, binding the literal as a
720
+ typed parameter, where SQLAlchemy used to raise `ArgumentError` at translation. CEL orders bools
721
+ `false < true`, as SQL's boolean does. A widening.
722
+ - **Breaking:** shapes that used to return a wrong filter now raise `UnsupportedPlanError`:
723
+ - `string()` over a numeric column. CEL prints an attribute double in Go's shortest `%g` form
724
+ (`1e+06`, `2`, `-0`), where `CAST` prints `1000000` or `2.0`, and SQL cannot keep the sign of a
725
+ zero, so `string(R.attr.aDouble) == "1e+06"` under-granted.
726
+ - `/` by a column, unless the numerator is that column or a constant zero. A zero divisor makes
727
+ CEL's quotient an infinity carrying the zero's sign, which SQL cannot read (`-0.0 = 0.0`, and
728
+ SQLite stores `-0.0` as `0.0`); the column used to be assumed `+0.0`, which over-granted.
729
+ - `%` over a column. CEL defines `%` only over integers and attribute numbers are doubles, so it is
730
+ a no-such-overload error; SQL's remainder made `!(R.attr.aNumber % 2 == 1)` true for most rows.
731
+ - A scalar column compared with a list or map literal (`R.attr.aString == ["same"]`), which used to
732
+ bind the list as a parameter and fail, or be coerced, at execution.
733
+ - Translation refusals now raise `cerbos_sqlalchemy.UnsupportedPlanError`, a `ValueError` subclass
734
+ (also a `TypeError` where the refusal raised one before), so existing handlers keep catching them.
735
+ Not breaking.
736
+ - **Breaking** ([#509](https://github.com/cerbos/query-plan-adapters/issues/509)): a collection macro
737
+ nested over the collection an enclosing macro iterates, whose body reads the enclosing element
738
+ (`tags.exists(t, tags.exists(u, u.name != t.name))`), now raises. `attr_map` binds a lambda
739
+ variable's fields by name and an override never sees the scope, so both subqueries range over the
740
+ one unaliased table and the body would compare each element with itself — under negation, an
741
+ over-grant — for any caller that mapped the inner variable.
742
+ - A literal list member the column's type cannot equal is dropped from `in` (`R.attr.aNumber in
743
+ ["5", 2]` compares `2` alone), as `==` already answered it, where it used to be bound into
744
+ `IN (...)` and converted by the store (`'5' = 5` is TRUE on SQLite) — an over-grant, since CEL's
745
+ `5 in ["5"]` is false. A list left with no comparable member is false for a present value.
746
+ - **Widening:** literal membership (`in`, `hasIntersection`) over a declared collection that
747
+ `attr_map` does not map now translates, where it used to raise `Attribute does not exist in the
748
+ attribute column map`. An attribute `attr_map` maps resolves membership exactly as before.
749
+ - **Breaking** ([#227](https://github.com/cerbos/query-plan-adapters/issues/227)): `size()` over a JSON
750
+ or array column not declared in `collection_columns` now raises; it used to return `LENGTH()` of the
751
+ column's text. `index` over undeclared storage raises a message naming the missing declaration
752
+ instead of `Unrecognised operator: index`.
753
+ - [#418](https://github.com/cerbos/query-plan-adapters/issues/418): `string()` over a boolean column now
754
+ translates (to a `CASE` spelling `'true'`/`'false'`, with NULL kept UNKNOWN) where it used to raise.
755
+ `CAST` would render `'1'` on SQLite and MySQL.
756
+ - **Breaking** ([#414](https://github.com/cerbos/query-plan-adapters/issues/414)): numeric `size()` and
757
+ string operations preserve CEL type errors instead of SQL coercion; NaN ordering is false and its
758
+ negation true (Cerbos 0.55); membership preserves the declared NULL convention inside lambda bodies
759
+ and against stored collections; bare temporal-attribute comparisons raise (use `timestamp()`).
760
+ - [#388](https://github.com/cerbos/query-plan-adapters/issues/388): a bare boolean column is accepted as
761
+ the whole condition (e.g. `R.attr.aBool`), where it used to be refused at the root. A widening.
762
+ - A numeric literal outside the int64 range (`R.attr.aDouble < -1e19`) is bound as a float; SQLite
763
+ used to raise `OverflowError` at execution. PostgreSQL is unchanged. A widening.
764
+ - [#387](https://github.com/cerbos/query-plan-adapters/issues/387):
765
+ - `hasIntersection` is order-insensitive like `eq`/`ne`/`in`, so a value-first spelling reaches an
766
+ override with the column first. A widening.
767
+ - **Breaking:** an override's intermediate value reaching a default handler raises; it used to
768
+ compare to a bare `False` and filter out every row.
769
+ - **Breaking:** the non-boolean check that refuses `filter()`/`map()` at the root also runs on every
770
+ `and`/`or`/`not` operand, raising the adapter's message instead of SQLAlchemy's WHERE-role error.
771
+
772
+ ## Example application
773
+
774
+ [`example/`](example/) installs the built wheel and runs the shared
775
+ [demo domain](../demo/README.md) against a live PDP, including pagination and the adapter's `Select`
776
+ composed with an application-owned `.where()` across all three plan kinds:
777
+
778
+ ```bash
779
+ # from the repository root
780
+ demo/scripts/run-example.sh sqlalchemy
781
+ ```
782
+
783
+ ## Development
784
+
785
+ | Suite | Checks | Needs |
786
+ | --- | --- | --- |
787
+ | `tests/test_translator.py` | caller options over recorded corpus plans: null representation, overrides, collection storage, transports, model styles | nothing — plans from `conformance/golden/` |
788
+ | `tests/test_query.py`, `tests/test_relations.py` | plans the planner cannot produce; options no policy can reach | nothing |
789
+ | `tests/test_adversarial_conformance.py` | returned rows match the recorded decisions, or the ledger's refusal is raised: every case on SQLite (sync and async), PostgreSQL and MySQL, and the cases that read a `collection_columns` declaration once more on PostgreSQL with the collections stored as native arrays. Every leg runs twice: with the attributes inferred from the models' mapping, and with every attribute written out in `attr_map` (hand-written `Relation`s and subqueries), and a fuzz replay reports the second as `<store>-declared`. CI runs it under SQLAlchemy 1.4 and 2.x | SQLite, and Docker for PostgreSQL and MySQL, pinned in [`POSTGRES_IMAGE`](POSTGRES_IMAGE) and [`MYSQL_IMAGE`](MYSQL_IMAGE) |
790
+
791
+ ```bash
792
+ pdm install -G :all
793
+ pdm run test # all three
794
+ pdm run format # isort + ruff format
795
+ pdm run lint # ruff check --fix
796
+ ```
797
+
798
+ Without PDM installed, run the same commands through the [pyprojectx](https://pyprojectx.github.io/)
799
+ wrapper, `./pw` (`pw.bat` on Windows), which installs PDM, ruff and isort into `.pyprojectx/` on
800
+ first use: `./pw install`, `./pw test`, `./pw format`, `./pw lint`, or `./pw pdm <command>`. CI runs
801
+ `format` and `lint` on the SQLAlchemy 2.x leg and fails if they leave a diff.
802
+
803
+ CI links Ubuntu 24.04's SQLite (3.45), usually older than the one a developer's Python bundles, and
804
+ before 3.46 a deeply nested expression overflows SQLite's parser stack. `scripts/test-ci-sqlite.sh`
805
+ runs every suite that needs no Docker store against that SQLite, from `pdm.lock`, in a container.