@dads-framework/postgres-access 0.2.0 → 0.3.0

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 (135) hide show
  1. package/BENCHMARK.md +94 -8
  2. package/README.md +165 -102
  3. package/dist/compile-access-policy.d.ts +2 -1
  4. package/dist/compile-access-policy.d.ts.map +1 -1
  5. package/dist/compile-access-policy.js +9 -2
  6. package/dist/compile-access-policy.js.map +1 -1
  7. package/dist/drizzle-executor.d.ts +2 -2
  8. package/dist/drizzle-executor.d.ts.map +1 -1
  9. package/dist/drizzle-executor.js.map +1 -1
  10. package/dist/drizzle-structural.d.ts +23 -0
  11. package/dist/drizzle-structural.d.ts.map +1 -0
  12. package/dist/drizzle-structural.js +22 -0
  13. package/dist/drizzle-structural.js.map +1 -0
  14. package/dist/drizzle.d.ts +4 -0
  15. package/dist/drizzle.d.ts.map +1 -0
  16. package/dist/drizzle.js +4 -0
  17. package/dist/drizzle.js.map +1 -0
  18. package/dist/index.d.ts +5 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +3 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/lookup-primary-pool.d.ts +2 -3
  23. package/dist/lookup-primary-pool.d.ts.map +1 -1
  24. package/dist/lookup-primary-pool.js +2 -1
  25. package/dist/lookup-primary-pool.js.map +1 -1
  26. package/dist/lower-permissions.d.ts.map +1 -1
  27. package/dist/lower-permissions.js +37 -12
  28. package/dist/lower-permissions.js.map +1 -1
  29. package/dist/policy/column-relations.d.ts +34 -0
  30. package/dist/policy/column-relations.d.ts.map +1 -0
  31. package/dist/policy/column-relations.js +127 -0
  32. package/dist/policy/column-relations.js.map +1 -0
  33. package/dist/policy/compile-filter.d.ts +41 -0
  34. package/dist/policy/compile-filter.d.ts.map +1 -0
  35. package/dist/policy/compile-filter.js +127 -0
  36. package/dist/policy/compile-filter.js.map +1 -0
  37. package/dist/policy/compile-forward-policy.d.ts +20 -0
  38. package/dist/policy/compile-forward-policy.d.ts.map +1 -0
  39. package/dist/policy/compile-forward-policy.js +129 -0
  40. package/dist/policy/compile-forward-policy.js.map +1 -0
  41. package/dist/policy/compile-linear-batch.d.ts +1 -0
  42. package/dist/policy/compile-linear-batch.d.ts.map +1 -1
  43. package/dist/policy/compile-linear-batch.js +3 -6
  44. package/dist/policy/compile-linear-batch.js.map +1 -1
  45. package/dist/policy/compile-linear-check.d.ts.map +1 -1
  46. package/dist/policy/compile-linear-check.js +53 -9
  47. package/dist/policy/compile-linear-check.js.map +1 -1
  48. package/dist/policy/compile-postgres-policy.d.ts +9 -4
  49. package/dist/policy/compile-postgres-policy.d.ts.map +1 -1
  50. package/dist/policy/compile-postgres-policy.js +91 -118
  51. package/dist/policy/compile-postgres-policy.js.map +1 -1
  52. package/dist/policy/compile-recursive-policy.d.ts +53 -0
  53. package/dist/policy/compile-recursive-policy.d.ts.map +1 -0
  54. package/dist/policy/compile-recursive-policy.js +231 -0
  55. package/dist/policy/compile-recursive-policy.js.map +1 -0
  56. package/dist/policy/compile-recursive-subjects.d.ts +27 -0
  57. package/dist/policy/compile-recursive-subjects.d.ts.map +1 -0
  58. package/dist/policy/compile-recursive-subjects.js +180 -0
  59. package/dist/policy/compile-recursive-subjects.js.map +1 -0
  60. package/dist/policy/compile-reverse-policy.d.ts +12 -2
  61. package/dist/policy/compile-reverse-policy.d.ts.map +1 -1
  62. package/dist/policy/compile-reverse-policy.js +168 -39
  63. package/dist/policy/compile-reverse-policy.js.map +1 -1
  64. package/dist/policy/compile-shared-point-check.d.ts.map +1 -1
  65. package/dist/policy/compile-shared-point-check.js +165 -13
  66. package/dist/policy/compile-shared-point-check.js.map +1 -1
  67. package/dist/policy/compile-subject-lookup.d.ts +8 -0
  68. package/dist/policy/compile-subject-lookup.d.ts.map +1 -0
  69. package/dist/policy/compile-subject-lookup.js +254 -0
  70. package/dist/policy/compile-subject-lookup.js.map +1 -0
  71. package/dist/policy/permission-cycles.d.ts +27 -0
  72. package/dist/policy/permission-cycles.d.ts.map +1 -0
  73. package/dist/policy/permission-cycles.js +181 -0
  74. package/dist/policy/permission-cycles.js.map +1 -0
  75. package/dist/policy/policy-model.d.ts +24 -0
  76. package/dist/policy/policy-model.d.ts.map +1 -1
  77. package/dist/policy/policy-sql.d.ts +39 -5
  78. package/dist/policy/policy-sql.d.ts.map +1 -1
  79. package/dist/policy/policy-sql.js +189 -15
  80. package/dist/policy/policy-sql.js.map +1 -1
  81. package/dist/policy/resolve-filter.d.ts +25 -0
  82. package/dist/policy/resolve-filter.d.ts.map +1 -0
  83. package/dist/policy/resolve-filter.js +156 -0
  84. package/dist/policy/resolve-filter.js.map +1 -0
  85. package/dist/policy/tarjan-scc.d.ts +3 -0
  86. package/dist/policy/tarjan-scc.d.ts.map +1 -0
  87. package/dist/policy/tarjan-scc.js +58 -0
  88. package/dist/policy/tarjan-scc.js.map +1 -0
  89. package/dist/postgres-access.tsbuildinfo +1 -1
  90. package/dist/postgres-authorization.d.ts +17 -17
  91. package/dist/postgres-authorization.d.ts.map +1 -1
  92. package/dist/postgres-authorization.js +67 -29
  93. package/dist/postgres-authorization.js.map +1 -1
  94. package/dist/postgres-options.d.ts +25 -0
  95. package/dist/postgres-options.d.ts.map +1 -0
  96. package/dist/postgres-options.js +36 -0
  97. package/dist/postgres-options.js.map +1 -0
  98. package/dist/postgres-response.d.ts +5 -0
  99. package/dist/postgres-response.d.ts.map +1 -1
  100. package/dist/postgres-response.js +42 -0
  101. package/dist/postgres-response.js.map +1 -1
  102. package/dist/postgres-tuples.d.ts.map +1 -1
  103. package/dist/postgres-tuples.js +64 -7
  104. package/dist/postgres-tuples.js.map +1 -1
  105. package/dist/postgres-types.d.ts +11 -0
  106. package/dist/postgres-types.d.ts.map +1 -1
  107. package/dist/protected-authorization-scope.d.ts +6 -8
  108. package/dist/protected-authorization-scope.d.ts.map +1 -1
  109. package/dist/protected-authorization-scope.js +13 -8
  110. package/dist/protected-authorization-scope.js.map +1 -1
  111. package/dist/relationship-schema.d.ts +9 -0
  112. package/dist/relationship-schema.d.ts.map +1 -1
  113. package/dist/relationship-schema.js +24 -2
  114. package/dist/relationship-schema.js.map +1 -1
  115. package/dist/testing.d.ts +20 -0
  116. package/dist/testing.d.ts.map +1 -0
  117. package/dist/testing.js +88 -0
  118. package/dist/testing.js.map +1 -0
  119. package/dist/transactional-access-changes.d.ts +3 -3
  120. package/dist/transactional-access-changes.d.ts.map +1 -1
  121. package/dist/transactional-access-changes.js +5 -3
  122. package/dist/transactional-access-changes.js.map +1 -1
  123. package/dist/with-protected-drizzle-transaction.d.ts +18 -0
  124. package/dist/with-protected-drizzle-transaction.d.ts.map +1 -0
  125. package/dist/with-protected-drizzle-transaction.js +52 -0
  126. package/dist/with-protected-drizzle-transaction.js.map +1 -0
  127. package/dist/with-protected-pg-transaction.d.ts +29 -0
  128. package/dist/with-protected-pg-transaction.d.ts.map +1 -0
  129. package/dist/with-protected-pg-transaction.js +110 -0
  130. package/dist/with-protected-pg-transaction.js.map +1 -0
  131. package/dist/with-protected-postgres-transaction.d.ts +6 -21
  132. package/dist/with-protected-postgres-transaction.d.ts.map +1 -1
  133. package/dist/with-protected-postgres-transaction.js +4 -45
  134. package/dist/with-protected-postgres-transaction.js.map +1 -1
  135. package/package.json +26 -4
package/BENCHMARK.md CHANGED
@@ -1,8 +1,96 @@
1
- # Experimental authorization benchmark
1
+ # PostgreSQL authorization benchmark
2
+
3
+ Measure the operation your application depends on. Point checks, paginated
4
+ 10M-row filtered lists (`resolveFilter` / `compileFilter`), column-backed
5
+ foreign-key relations (`columnRelations`), and concurrent mixed reads + writes
6
+ all have distinct cost profiles.
7
+
8
+ ## 10k → 100,000,000-row PostgreSQL scaling ladder & 10,000-hop test (1 vCPU, 2 GB RAM)
9
+
10
+ Measured inside a single hard-capped **1 vCPU, 2 GB RAM** PostgreSQL 16.16
11
+ Linux container (`shared_buffers=512MB`, `effective_cache_size=1536MB`,
12
+ `work_mem=8MB`, `max_parallel_workers_per_gather=0`) across five orders of
13
+ magnitude (**10,000 to 100,000,000 documents**, up to **22 GB** total table +
14
+ index size—11× larger than container RAM).
15
+
16
+ ### 10k → 100,000,000-row scaling curve (1 vCPU, 2 GB RAM)
17
+
18
+ | Documents | App table size | Extra auth storage | Point check: `org_id` (p50) | Point check: `owner_id` (p50) | Outsider deny (p50) | `LIMIT 50`: Org Member (p50) | `LIMIT 50`: Broad Admin, 10% (p50) | Seq scans | 8-worker sustained checks/s (0 errors) |
19
+ | ----------: | -------------: | -----------------: | --------------------------: | ----------------------------: | ------------------: | ---------------------------: | ---------------------------------: | --------: | -------------------------------------: |
20
+ | 10,000 | 2.2 MB | 144 kB | **0.44 ms** | **0.45 ms** | **0.44 ms** | **0.44 ms** | **0.36 ms** | **0** | **2,657 /s** |
21
+ | 100,000 | 21 MB | 536 kB | **0.40 ms** | **0.39 ms** | **0.40 ms** | **0.38 ms** | **0.47 ms** | **0** | **2,672 /s** |
22
+ | 1,000,000 | 220 MB | 4.1 MB | **0.41 ms** | **0.43 ms** | **0.40 ms** | **0.37 ms** | **1.65 ms** | **0** | **2,559 /s** |
23
+ | 10,000,000 | 2.2 GB | 43 MB | **0.40 ms** | **0.40 ms** | **0.39 ms** | **0.53 ms** | **2.04 ms** | **0** | **2,615 /s** |
24
+ | 100,000,000 | **22 GB** | **44 MB** | **0.50 ms** | **0.52 ms** | **0.49 ms** | **1.19 ms** | **2.19 ms** | **0** | **2,505 /s** |
25
+
26
+ ### 10,000-hop nested group chain (1 vCPU, 2 GB RAM)
27
+
28
+ | Nested group hops | Allow check (p50 / p95) | Outsider deny (p50 / p95) | Reverse lookup (p50 / p95) | Mid-chain revoke verified |
29
+ | ----------------: | ----------------------: | ------------------------: | -------------------------: | :------------------------ |
30
+ | 32 | **0.31 / 0.37 ms** | **0.18 / 0.21 ms** | **0.41 / 0.47 ms** | Yes |
31
+ | 128 | **1.46 / 1.55 ms** | **0.31 / 0.36 ms** | **0.45 / 0.51 ms** | Yes |
32
+ | 1,024 | **1.64 / 1.74 ms** | **0.28 / 0.29 ms** | **1.50 / 1.65 ms** | Yes |
33
+ | 10,000 | **15.76 / 16.06 ms** | **0.34 / 0.40 ms** | **14.34 / 14.50 ms** | Yes |
34
+
35
+ ### Hard-capped 1 vCPU, 2 GB RAM logged-table baseline (10M rows)
36
+
37
+ Measured on a single `postgres:16-alpine` (PostgreSQL 16.16) Docker container
38
+ hard-capped to **1 vCPU and 2 GiB RAM** (`NanoCpus=1000000000`,
39
+ `Memory=2147483648`, `shared_buffers=512MB`, `effective_cache_size=1536MB`,
40
+ `work_mem=8MB`, `max_parallel_workers_per_gather=0`) with **10,000,000
41
+ documents**, **10,000 organizations**, 100,000 direct viewer grants, 10,000
42
+ explicit bans, a **depth-100 recursive folder chain**, and a broad admin
43
+ holding 1,000 orgs (**1,000,000 visible documents = 10% of the table**).
44
+
45
+ - Auth table (`dad_authorization_relationship`): **111,027 rows = 30 MB** (vs **2.73 GB** tuples-only — **91× smaller**)
46
+ - Sustained 1-vCPU point checks (5 s, 0 errors): **2,479 checks/sec** (8 workers, 1.00 ms p50, 2.84 ms p95; **2,492 checks/sec** at 16 workers)
47
+ - Sustained 1-vCPU mixed reads + live `UPDATE owner_id` flips (8 workers, 5 s, 0 errors): **2,280 ops/sec** (1.11 ms p50, 3.12 ms p95, **340 live flips/sec**)
48
+
49
+ | Operation (1 vCPU, 2 GB RAM, 10M rows) | p50 (ms) | p95 (ms) | p99 (ms) | Query plan (`EXPLAIN ANALYZE`) |
50
+ | :--------------------------------------------------- | -------: | -------: | -------: | :------------------------------------------------------ |
51
+ | Point check: column-backed `owner_id` (allow) | **0.48** | 0.60 | 0.63 | Index scan on PK |
52
+ | Point check: column-backed `org_id` (allow) | **0.45** | 0.51 | 0.52 | Index scan on PK + tuple PK |
53
+ | Point check: outsider (deny) | **0.44** | 0.54 | 0.58 | Index scan on PK |
54
+ | Point check: depth-100 recursive `folders.parent_id` | **0.57** | 0.74 | 0.87 | Recursive PK index walk |
55
+ | `LIMIT 50` list: outsider (0 / 10M docs) | **0.51** | 0.58 | 0.59 | Branch-pruned `FALSE` |
56
+ | `LIMIT 50` list: `org_member` (1,000 / 10M docs) | **0.59** | 0.62 | 0.63 | `Index Only Scan` (`Heap Fetches: 0`, 0.119 ms PG exec) |
57
+ | `LIMIT 50` list: `super_sparse` (20 direct / 10M) | **0.57** | 0.62 | 0.63 | `Index Scan` on PK |
58
+ | `LIMIT 50` list: `owner_user` (20 owned / 10M) | **0.58** | 0.87 | 1.04 | `Index Scan` on PK (0.107 ms PG exec) |
59
+ | `LIMIT 50` list: `broad_admin` (1M / 10M docs) | **2.04** | 2.53 | 2.63 | `Index Scan` + `Incremental Sort` (0.506 ms, 115 hits) |
60
+
61
+ ### Scaling to 3 vCPUs (Tuples-only vs `columnRelations`)
62
+
63
+ Same 10,000,000-row fixture on a 3-vCPU / 5.8 GiB Docker Postgres 16 container
64
+ comparing tuples-only vs `columnRelations`:
65
+
66
+ ### Storage & throughput comparison (10M documents)
67
+
68
+ | Metric | Tuples-only (`dad_authorization_relationship`) | With `columnRelations` (`org_id`, `owner_id`, `parent_id`) | Delta |
69
+ | :------------------------------------------ | ---------------------------------------------: | ---------------------------------------------------------: | -----------------: |
70
+ | `dad_authorization_relationship` rows | 10,111,000 | **111,027** | **91× fewer rows** |
71
+ | `dad_authorization_relationship` total size | 2.73 GB | **30 MB** | **91× smaller** |
72
+ | 16-worker concurrent point checks (5 s) | 6,432 RPS (0 errors) | **8,274 RPS** (0 errors, 1.75 ms p50) | **+29% faster** |
73
+ | 16-worker mixed reads + live writes (5 s) | 4,603 ops/s (0 errors) | **6,802 ops/s** (0 errors, 835 live `UPDATE` flips/s) | **+48% faster** |
74
+
75
+ ### Single-operation latency on 10,000,000 rows (`columnRelations` enabled)
76
+
77
+ | Operation | p50 (ms) | p95 (ms) | p99 (ms) | Query plan (`EXPLAIN ANALYZE`) |
78
+ | :--------------------------------------------------- | -------: | -------: | -------: | :--------------------------------------------- |
79
+ | Point check: column-backed `owner_id` (allow) | **0.57** | 0.67 | 0.68 | Index scan on PK |
80
+ | Point check: column-backed `org_id` (allow) | **0.53** | 0.58 | 0.59 | Index scan on PK + tuple PK |
81
+ | Point check: outsider (deny) | **0.50** | 0.58 | 0.58 | Index scan on PK |
82
+ | Point check: depth-100 recursive `folders.parent_id` | **0.62** | 0.83 | 0.85 | Recursive PK index walk |
83
+ | `LIMIT 50` list: outsider (0 / 10M docs) | **0.39** | 0.44 | 0.44 | Branch-pruned `FALSE` |
84
+ | `LIMIT 50` list: `org_member` (1,000 / 10M docs) | **0.62** | 0.72 | 0.72 | `Index Only Scan` (`Heap Fetches: 0`, 0.12 ms) |
85
+ | `LIMIT 50` list: `super_sparse` (20 direct / 10M) | **0.63** | 0.76 | 0.76 | `Index Scan` on PK |
86
+ | `LIMIT 50` list: `owner_user` (20 owned / 10M) | **0.77** | 0.98 | 0.98 | `Index Scan` on PK (0.09 ms) |
87
+ | `LIMIT 50` list: `broad_admin` (1M / 10M docs) | **1.88** | 2.09 | 2.09 | `Index Only Scan` (0.53 ms, 115 buffer hits) |
88
+
89
+ Every single 10M-row list query executed with **zero sequential scans**.
90
+
91
+ ---
2
92
 
3
- Measure the operation your application depends on. Point checks, fresh
4
- resource discovery, revision-validated lookup reuse, and protected
5
- transactions have different costs.
93
+ ## Matched point checks against SpiceDB
6
94
 
7
95
  These are Linux development VM measurements with both engines accessed
8
96
  locally. The SpiceDB comparison used the fully consistent in-memory
@@ -11,8 +99,6 @@ They do not set a production latency target or compare persistent
11
99
  SpiceDB deployments. The benchmarks do not include HTTP, application
12
100
  writes, or serializable transaction overhead.
13
101
 
14
- ## Matched point checks against SpiceDB
15
-
16
102
  ```sh
17
103
  CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access -- src/point-check-comparison.benchmark.test.ts
18
104
  ```
@@ -21,7 +107,7 @@ The harness uses the same 5,000-leaf graph for each depth and engine. Both
21
107
  use the public Node authorization adapters over local TCP, with the opt-in prepared-check path against PostgreSQL 16.16 and fully consistent gRPC
22
108
  against the SpiceDB 1.57.0 in-memory testing datastore. It includes transport,
23
109
  encoding, SQL compilation, and decoding in the timed calls. The Linux VM
24
- has 32 vCPUs on an i9-13900KF and runs Node 24.20.0.
110
+ runs Node 24.20.0.
25
111
 
26
112
  Each engine takes three rounds of 1,280 checks per depth and worker count,
27
113
  after 30 warmups per worker. Engine order alternates and each worker checks
@@ -159,7 +245,7 @@ current code and benchmark commands can produce different timings.
159
245
 
160
246
  ### Original forward and reverse baseline
161
247
 
162
- This early baseline was measured on 2026-11-19 Mountain Time. Both backends ran in containers on the same Linux development VM with a 32-vCPU Intel Core i9-13900KF and 25 GiB RAM. Postgres used the `postgres:16-alpine` image. SpiceDB v1.57.0 used its in-memory datastore and fully consistent reads. Node was v24.20.0.
248
+ This early baseline was measured on 2026-11-19. Both backends ran in containers on the same Linux development VM. Postgres used the `postgres:16-alpine` image. SpiceDB v1.57.0 used its in-memory datastore and fully consistent reads. Node was v24.20.0.
163
249
 
164
250
  The fixture grants one actor access through a chain of parent relationships. A single check targets one leaf. A lookup returns every leaf the actor can see. The benchmark validates each answer and takes 15 sequential samples after one warm-up call. Timings include application-side query compilation, transport, and reading the response. They exclude schema installation and seeding. This run used a 4.9-second PostgreSQL statement deadline and a 5-second client deadline.
165
251
 
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # `@dads-framework/postgres-access`
2
2
 
3
3
  Check permissions, list the resources a user can access, and commit relationship
4
- changes alongside business data in the application's Postgres database.
4
+ changes alongside business data in the application's Postgres database. Works
5
+ directly with a plain `pg.Pool` (zero ORM required) or with Drizzle via
6
+ `@dads-framework/postgres-access/drizzle`.
5
7
 
6
8
  ## Trusted experimental
7
9
 
@@ -16,41 +18,58 @@ during which a committed revoke would still be waiting for delivery.
16
18
 
17
19
  Its access decisions and visible resource lists have been checked against
18
20
  SpiceDB. The [live transaction tests](./src/protected-transaction.integration.test.ts)
21
+ and [plain pg transaction tests](./src/plain-pg-transaction.integration.test.ts)
19
22
  cover revocation and rollback. The [graph tests](./src/recursive-subject-set.integration.test.ts)
20
23
  also exercise nested memberships up to 10,000 links.
21
24
 
22
- Start with one protected operation and test a grant, a denial and a
25
+ Start with one protected operation and test a grant, a denial, and a
23
26
  revocation with your own policy. Measure checks and lists while permissions
24
27
  are changing. Sustained production performance under that mix is still open.
25
28
  See the [benchmark results](./BENCHMARK.md) for measured workloads.
26
29
 
27
30
  ## Protected writes
28
31
 
29
- Use `withProtectedPostgresTransaction({ database, authorization }, work)`
30
- when a decision protects a write. The helper opens a serializable Drizzle
31
- transaction and passes `{ tx, authorization }` to the callback. Check access
32
- again inside the callback, even if the route already authorized the request.
33
- Use these same handles for the application writes and relationship changes. Await all work before leaving the callback.
34
- The authorization handle expires on return or error.
35
-
36
- To join an existing transaction, pass `{ transaction: tx, authorization }`.
37
- The helper verifies that it is already serializable and uses the same
38
- transaction. The caller still owns commit and rollback. Propagate failures so
39
- the outer transaction can roll back. The helper does not create a savepoint.
40
-
41
- A PostgreSQL serialization failure surfaces as `PostgresSerializationConflict`
42
- with code `POSTGRES_CONFLICT` and `retryable: true`. A caller that owns the
43
- outer commit can use `readPostgresSerializationConflict(error)` to classify
44
- a failure raised there. Retry the entire application transaction if retrying
45
- is appropriate. The helper invokes the callback at most once per call.
32
+ ### Plain `pg.Pool` (Drizzle-free)
33
+
34
+ Use `withProtectedPgTransaction({ pool, authorization }, work)` when a decision
35
+ protects a write on a standard node-postgres pool. The helper checks out a
36
+ client, starts `BEGIN ISOLATION LEVEL SERIALIZABLE`, and passes
37
+ `{ client, authorization }` bound to that client. Check access again inside the
38
+ callback (for example via `createAccessClient(authorization)`), run application
39
+ SQL on `client`, and await all work before returning. The authorization handle
40
+ expires as soon as the callback finishes or throws.
41
+
42
+ ### Drizzle (`@dads-framework/postgres-access/drizzle`)
43
+
44
+ If your app uses Drizzle, import `withProtectedDrizzleTransaction` (and
45
+ `transactionExecutor`) from `@dads-framework/postgres-access/drizzle`. Pass
46
+ `{ database, authorization }` to open a serializable Drizzle transaction, or
47
+ `{ transaction: tx, authorization }` to join an existing serializable
48
+ transaction. Core `withProtectedPostgresTransaction` and
49
+ `withProtectedPgTransaction` both target plain `pg.Pool` with zero Drizzle
50
+ dependency. When joining an outer transaction, the caller still owns commit and
51
+ rollback; propagate failures so the outer transaction rolls back (the helper
52
+ does not create a savepoint).
53
+
54
+ ### Serialization conflicts and ordering
55
+
56
+ A PostgreSQL serialization failure (`40001`) surfaces as
57
+ `PostgresSerializationConflict` with code `POSTGRES_CONFLICT` and
58
+ `retryable: true`. A caller that owns an outer commit can use
59
+ `readPostgresSerializationConflict(error)` to classify a failure raised there.
60
+ Pass `retries` (and optional `retryBaseDelayMs`, default `15`) to
61
+ `withProtectedPgTransaction({ pool, authorization, retries: 3 }, work)` to
62
+ automatically retry idempotent callbacks with jittered exponential backoff on
63
+ `40001` conflicts. By default `retries` is `0`, invoking the callback at most
64
+ once per call.
46
65
 
47
66
  Serializable isolation makes the commit consistent with a serial ordering of
48
67
  transactions. A revoke committed before the permission check's transaction
49
68
  snapshot is visible to that check. An overlapping revoke may serialize after
50
69
  the protected write. If an operation requires revocation to take precedence
51
70
  over an overlapping write, coordinate both operations through an application
52
- lock or equivalent ordering mechanism. For reads and explicit tuple changes
53
- in an existing transaction, use `inTransaction` or `inDrizzleTransaction`.
71
+ lock or equivalent ordering mechanism. For reads and explicit tuple changes in
72
+ an existing transaction, use `inTransaction` or `inDrizzleTransaction`.
54
73
 
55
74
  ## Try it
56
75
 
@@ -66,8 +85,8 @@ namespace per run. In an application, apply the SQL through your migration
66
85
  runner and use a stable namespace.
67
86
 
68
87
  ```sh
69
- npm install @dads-framework/access @dads-framework/postgres @dads-framework/postgres-access zod
70
- npm install -D tsx
88
+ npm install @dads-framework/access @dads-framework/postgres-access pg
89
+ npm install -D tsx @types/pg
71
90
  ```
72
91
 
73
92
  Save as `check-postgres-access.mts` and run `npx tsx check-postgres-access.mts`.
@@ -76,98 +95,133 @@ Save as `check-postgres-access.mts` and run `npx tsx check-postgres-access.mts`.
76
95
 
77
96
  ```ts
78
97
  import { randomUUID } from "node:crypto";
79
- import { access, accessModel, entityHandle } from "@dads-framework/access";
80
- import { relationshipWrite } from "@dads-framework/access/runtime";
81
- import { createPostgresConnection } from "@dads-framework/postgres";
98
+ import { actor, compileAccess, resource } from "@dads-framework/access";
99
+ import { createAccessClient } from "@dads-framework/access/runtime";
82
100
  import {
83
101
  PostgresAuthorization,
84
102
  relationshipSchemaMigration,
103
+ withProtectedPgTransaction,
85
104
  } from "@dads-framework/postgres-access";
86
- import { z } from "zod";
105
+ import { Pool } from "pg";
87
106
 
88
107
  const connectionString = process.env.DATABASE_URL;
89
108
  if (!connectionString) throw new Error("Set DATABASE_URL.");
90
109
 
91
- const user = entityHandle({ wireName: "user", idSchema: z.string() });
92
- const team = entityHandle({
93
- wireName: "team",
94
- idSchema: z.string(),
95
- kind: "scope",
96
- });
97
- const teamAccess = access(team, {
98
- roles: { member: user },
99
- permissions: (roles) => ({ view: [roles.member] }),
110
+ const user = actor("user");
111
+ const organization = resource("organization", {
112
+ roles: { admin: user, member: user },
113
+ can: ({ admin, member }) => ({
114
+ manage: admin,
115
+ view: [admin, member],
116
+ }),
117
+ children: {
118
+ task: {
119
+ inherit: "all",
120
+ roles: { assignee: user },
121
+ can: ({ assignee }) => ({ edit: assignee }),
122
+ },
123
+ },
100
124
  });
101
- const model = accessModel([
102
- access(user, { roles: {}, permissions: () => ({}) }),
103
- teamAccess,
104
- ]);
105
-
106
- const connection = createPostgresConnection(
107
- { connectionString, schema: {} },
108
- console,
109
- );
125
+ const model = compileAccess([organization]);
126
+
127
+ const pool = new Pool({ connectionString });
110
128
  try {
111
- await connection.pool.query(relationshipSchemaMigration.sql);
129
+ await pool.query(relationshipSchemaMigration.sql);
112
130
  const authorization = new PostgresAuthorization({
113
131
  model,
114
132
  namespace: randomUUID(),
115
- executor: connection.pool,
116
- });
117
- const resource = { type: team.wireName, id: "team-1" };
118
- const subject = { type: user.wireName, id: "alice" };
119
- const relation = teamAccess.roles.member.roleName;
120
- const query = {
121
- resource,
122
- subject,
123
- permission: teamAccess.permissions.view.permissionName,
124
- };
125
-
126
- console.log(await authorization.check(query));
127
- await authorization.writeRelationships([
128
- relationshipWrite(resource, relation, subject),
129
- ]);
130
- console.log(await authorization.check(query));
131
- await authorization.deleteRelationships({
132
- resourceType: resource.type,
133
- resourceId: resource.id,
134
- relation,
135
- subject,
133
+ executor: pool,
136
134
  });
137
- console.log(await authorization.check(query));
135
+ const access = createAccessClient(authorization);
136
+
137
+ console.log(
138
+ await access.can(user("alice"), organization.task("task-1").view),
139
+ );
140
+ await withProtectedPgTransaction(
141
+ { pool, authorization },
142
+ async ({ authorization: scoped }) => {
143
+ const txAccess = createAccessClient(scoped);
144
+ await txAccess.add(user("alice"), organization("org-1").member);
145
+ await txAccess.add(
146
+ organization("org-1"),
147
+ organization.task("task-1").organization,
148
+ );
149
+ },
150
+ );
151
+ console.log(
152
+ await access.can(user("alice"), organization.task("task-1").view),
153
+ );
154
+ await access.remove(user("alice"), organization("org-1").member);
155
+ console.log(
156
+ await access.can(user("alice"), organization.task("task-1").view),
157
+ );
138
158
  } finally {
139
- await connection.close();
159
+ await pool.end();
140
160
  }
141
161
  ```
142
162
 
143
- The script prints `false`, `true`, and `false` as the membership is granted
144
- and revoked.
163
+ The script prints `false`, `true`, and `false` as organization membership is
164
+ granted and revoked while `task` inherits `view` from `organization`.
145
165
 
146
166
  ## Use it
147
167
 
148
- Choose Postgres for an app that already uses Postgres and can keep relationship facts beside its data. Install the relationship schema through the app's migration runner. Configure a stable namespace for this model, and select the backend at application composition. Use the same model for Postgres policy compilation and HTTP scope planning.
149
-
150
- Bind `TransactionalAccessChanges` as the enqueue port and
151
- `AlreadyAppliedAccessChanges` as the after-commit dispatcher. The
152
- application passes its active transaction to `enqueue(entries, tx)`.
153
- Relationship facts and the business row then commit or roll back together.
154
-
155
- In Postgres mode, start neither the access-change projector nor the SpiceDB migration runner. Successful writes return an empty consistency token. Data visibility follows the caller's Postgres transaction. The after-commit dispatcher is a no-op because committed facts are already visible. Keep any application locks that coordinate work beyond projecting authorization facts.
156
-
157
- Choose the backend based on the model features the application needs, its
158
- transaction requirements, and measurements with its own data and traffic.
159
- The [SpiceDB adapter](../authorization/README.md) provides a separate graph
160
- store, with a Postgres outbox for writes.
168
+ Choose Postgres for an app that already uses Postgres and can keep relationship
169
+ facts beside its data. Install `relationshipSchemaMigration.sql` through the
170
+ app's migration runner. Configure a stable namespace for this model, and pass a
171
+ plain `pg.Pool` as `executor` when constructing `PostgresAuthorization`. Use
172
+ `createAccessClient(authorization)` from `@dads-framework/access/runtime` for
173
+ typed `add`, `remove`, `can`, `list`, `whoCan`, and `listDirect` calls.
174
+
175
+ When integrating with Dads outbox ports, bind `TransactionalAccessChanges` as
176
+ the enqueue port and `AlreadyAppliedAccessChanges` as the after-commit
177
+ dispatcher. Pass the active transaction to `enqueue(entries, tx)` so
178
+ relationship facts and business rows commit or roll back together.
179
+
180
+ In Postgres mode, start neither the access-change projector nor the SpiceDB
181
+ migration runner. Successful writes return an empty consistency token. Data
182
+ visibility follows the caller's Postgres transaction. The after-commit
183
+ dispatcher is a no-op because committed facts are already visible. Keep any
184
+ application locks that coordinate work beyond projecting authorization facts.
185
+
186
+ To evolve stored relationships between model revisions or migrate a live
187
+ SpiceDB deployment into PostgreSQL, use
188
+ [`@dads-framework/spicedb-access/migration`](../spicedb-access/README.md).
189
+ The [SpiceDB adapter](../spicedb-access/README.md) remains available when you
190
+ need a separate graph store with a Postgres outbox.
161
191
 
162
192
  ## What it refuses to do
163
193
 
164
- Compilation rejects missing relation or permission targets, empty expressions, and local permission cycles. Cross-entity permission cycles are unsupported by the SQL engine. Each arrow needs one direct target entity type. Permission checks require a concrete subject; relationship writes can contain wildcard and subject-set tuples.
165
-
166
- The enqueue port rejects a database handle in place of an application transaction. Its transaction-bound changes are exact tuple writes or deletes. A broad revocation sweep needs its filters passed to a transaction-bound adapter if it must commit with the business update.
194
+ Compilation rejects missing relation or permission targets, empty expressions,
195
+ local same-entity permission cycles, non-monotonic arrow cycles (cycles passing
196
+ through `excluding` / `.unless()` or `throughAll` / `every()`), non-linear
197
+ multi-branch cycles, and unproductive cycles with no base case. Arrows need at
198
+ least one direct target entity type that defines the requested permission;
199
+ target types on a polymorphic relation that do not define the permission are
200
+ skipped. Permission checks and resource lookups require a concrete subject;
201
+ `lookupSubjects` requires a concrete resource and a non-empty subject type;
202
+ relationship writes can contain wildcard and subject-set tuples.
203
+
204
+ The enqueue port rejects a database handle in place of an application
205
+ transaction. Its transaction-bound changes are exact tuple writes or deletes. A
206
+ broad revocation sweep needs its filters passed to a transaction-bound adapter
207
+ if it must commit with the business update.
167
208
 
168
209
  ## Contract
169
210
 
170
- `PostgresAuthorization` implements the authorization port's checks, ordered bulk checks, discovery, relationship writes and filtered deletes, direct-subject listing, and relationship existence reads. Unknown permission names give denied checks and empty lookup results. Invalid tuple writes and failed storage operations reject.
211
+ `PostgresAuthorization` implements the authorization port's checks, ordered bulk
212
+ checks, resource discovery (`lookupResources`), transitive subject discovery
213
+ (`lookupSubjects`), relationship writes and filtered deletes, direct-subject
214
+ listing, and relationship existence reads. Unknown permission names give denied
215
+ checks, empty resource lookups, and `{ subjects: [], hasWildcard: false }` for
216
+ `lookupSubjects`. Invalid tuple writes and failed storage operations reject.
217
+
218
+ - **Compiled SQL list filters (`compileFilter` / `resolveFilter`)**: `authorization.compileFilter({ subject, permission, resourceType, idColumn, scopeColumns?, paramOffset? })` and `authorization.resolveFilter(...)` return `{ sql, values }` so paginated, sorted `SELECT ... WHERE ... LIMIT N` queries filter authorized rows in one database round trip without loading ID lists into Node. Pass `scopeColumns: "auto"` to derive parent foreign-key mappings automatically from `columnRelations`. Validates `idColumn` strictly and fails closed to `FALSE` on unknown permissions.
219
+ - **Column-backed relations (`columnRelations`)**: Bind single-target FK relations directly to columns on application tables (parent FKs such as `documents.org_id`, recursive self-FKs such as `folders.parent_id`, or direct actor FKs such as `documents.owner_id`) so authorization reads them directly with zero dual-writes and zero duplicate tuple storage. `NULL` values mean no relationship. `writeRelationships` and `deleteRelationships` refuse manual mutations on column-backed relations to preserve a single source of truth. Run `await authorization.verifyColumnRelations()` at startup to verify live columns and check reverse-lookup indexes, and generate recommended index DDL with `columnRelationIndexSql(bindings)`. Cannot be combined with `reuseLookupResultsOn`.
220
+ - **Expiring relationships (`expiresAt`)**: `relationshipSchemaMigration` creates `expires_at timestamptz NULL` with a partial index (`dad_authorization_relationship_expires_at`). Existing v1 installations can apply the additive `relationshipExpirationMigration` (version 2). `writeRelationships` persists `expiresAt ?? null` with `ON CONFLICT (...) DO UPDATE SET expires_at = EXCLUDED.expires_at` so re-writing a tuple updates or clears its expiration. Every read (`check`, `checkMany`, `lookupResources`, `lookupSubjects`, `compileFilter`, `listDirectSubjects`, and `relationshipExists`) filters `(expires_at IS NULL OR expires_at > now())` using transaction-scoped Postgres `now()`.
221
+ - **Polymorphic arrows**: Relations with multiple direct entity types (such as `parents: [organization, folder]`) lower parent arrows and `every()` across every target entity type that defines the target permission, matching `subject_kind` per branch across checks, resource lookups, filters, shared point checks, and subject lookups.
222
+ - **Recursive arrows**: Monotonic self-referential and mutually recursive arrow cycles (such as nested folders with `recursive: true`) compile to `WITH RECURSIVE` CTEs with `UNION` deduplication so cyclic tuple data terminates safely across `check`, `checkMany`, `lookupResources`, `compileFilter`, and `lookupSubjects`.
223
+ - **Intersection arrows (`every()`)**: Compiles to SpiceDB's `.all()` semantics (`EXISTS` at least one non-expired parent tuple `AND NOT EXISTS` a non-expired parent tuple failing the target permission) across `check`, `checkMany`, `lookupResources`, `compileFilter`, and `lookupSubjects`.
224
+ - **Transitive `lookupSubjects`**: Evaluates a single parameterized SQL query returning sorted unique concrete `subjects` and `hasWildcard` across direct roles, recursive usersets, wildcards, `allOf`, `.unless()`, polymorphic arrows, recursive arrows, `every()`, and `expires_at`. Available on root, `inTransaction`, `inDrizzleTransaction`, and protected transaction scopes.
171
225
 
172
226
  For operations on a root adapter, `queryTimeoutMs` defaults to 5,000 ms. It
173
227
  is a client deadline for executors that honor node-postgres query options.
@@ -183,15 +237,24 @@ CONTAINER_PER_FILE=1 npm run test:integration -w @dads-framework/postgres-access
183
237
 
184
238
  The [benchmark notes](./BENCHMARK.md) explain which read paths were measured.
185
239
 
240
+ ### Testing (`@dads-framework/postgres-access/testing`)
241
+
242
+ Use `provePostgresFilterParity({ db, authorization, table, idColumn, permission, scopeColumns?, subjects })`
243
+ on a plain `pg.Pool` or client (no Drizzle required) to prove that
244
+ `compileFilter`, `compileFilter({ scopeColumns })`, and `resolveFilter` return
245
+ the exact same row IDs as `lookupResources` for every subject. Combine with
246
+ `proveAccess` or `proveWorld` from `@dads-framework/access/testing` to run
247
+ multi-step Postgres scenarios under a single `await`.
248
+
186
249
  ### Optimize point checks
187
250
 
188
251
  For a direct node-postgres pool, opt in by passing
189
- `executor: preparePostgresChecks(connection.pool)`. Share the wrapper across
190
- authorization namespaces. The wrapper can admit up to 64 distinct SQL shapes
191
- of at most 4 KiB each and 32 KiB total per pool lifetime. Other shapes execute
192
- unnamed, as do bulk checks, lookups, and writes. PostgreSQL decides when each
193
- connection can reuse a generic plan. New connections and the first checks on
194
- each connection still pay planning costs.
252
+ `executor: preparePostgresChecks(pool)`. Share the wrapper across authorization
253
+ namespaces. The wrapper can admit up to 64 distinct SQL shapes of at most 4 KiB
254
+ each and 32 KiB total per pool lifetime. Other shapes execute unnamed, as do
255
+ bulk checks, lookups, and writes. PostgreSQL decides when each connection can
256
+ reuse a generic plan. New connections and the first checks on each connection
257
+ still pay planning costs.
195
258
 
196
259
  Checks always read the facts visible to the executing transaction. The wrapper
197
260
  stores statement names and SQL shapes, and PostgreSQL stores plans per
@@ -248,17 +311,17 @@ GRANT SELECT ON dad_lookup_revision.epoch, dad_lookup_revision.namespace
248
311
  const authorization = new PostgresAuthorization({
249
312
  model,
250
313
  namespace: "workspace",
251
- executor: connection.pool,
252
- reuseLookupResultsOn: connection.pool,
314
+ executor: pool,
315
+ reuseLookupResultsOn: pool,
253
316
  });
254
317
  ```
255
318
 
256
- You can pass `preparePostgresChecks(connection.pool)` as the executor with the
257
- same pool. Write and read-only transaction clients do not qualify. Remove the
258
- option before rolling the optional migration back. Failed validation rejects
259
- the operation and clears retained answers. Table-wide tuple `SELECT` is checked
260
- for every reuse, so revoking it prevents reuse even if revision metadata is
261
- still readable.
319
+ You can pass `preparePostgresChecks(pool)` as the executor with the same pool.
320
+ Write and read-only transaction clients do not qualify. Remove the option
321
+ before rolling the optional migration back. Failed validation rejects the
322
+ operation and clears retained answers. Table-wide tuple `SELECT` is checked for
323
+ every reuse, so revoking it prevents reuse even if revision metadata is still
324
+ readable.
262
325
 
263
326
  The migration marks each touched namespace in the same transaction as
264
327
  INSERT, DELETE, or UPDATE. Moving a tuple marks both namespaces, and
@@ -1,9 +1,10 @@
1
1
  import { type AccessModel } from "@dads-framework/access";
2
2
  import type { AuthorizationModelDefinition } from "./policy/policy-model.js";
3
+ import { type ColumnRelationBinding } from "./policy/column-relations.js";
3
4
  export type CompiledAccessPolicy = {
4
5
  readonly model: AuthorizationModelDefinition;
5
6
  /** The engine's permission name for an authored permission or direct relation. */
6
7
  permissionName(entity: string, name: string): string | undefined;
7
8
  };
8
- export declare function compileAccessPolicy(access: AccessModel): CompiledAccessPolicy;
9
+ export declare function compileAccessPolicy(access: AccessModel, columnRelations?: readonly ColumnRelationBinding[]): CompiledAccessPolicy;
9
10
  //# sourceMappingURL=compile-access-policy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile-access-policy.d.ts","sourceRoot":"","sources":["../src/compile-access-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EACV,4BAA4B,EAG7B,MAAM,0BAA0B,CAAC;AAOlC,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,CAAC,KAAK,EAAE,4BAA4B,CAAC;IAC7C,kFAAkF;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAClE,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,oBAAoB,CA0B7E"}
1
+ {"version":3,"file":"compile-access-policy.d.ts","sourceRoot":"","sources":["../src/compile-access-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EACV,4BAA4B,EAG7B,MAAM,0BAA0B,CAAC;AAMlC,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,8BAA8B,CAAC;AAGtC,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,CAAC,KAAK,EAAE,4BAA4B,CAAC;IAC7C,kFAAkF;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAClE,CAAC;AAEF,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,EACnB,eAAe,CAAC,EAAE,SAAS,qBAAqB,EAAE,GACjD,oBAAoB,CAgCtB"}
@@ -1,10 +1,12 @@
1
1
  import { emitAccessIr, } from "@dads-framework/access";
2
2
  import { lowerPermissions, } from "./lower-permissions.js";
3
- export function compileAccessPolicy(access) {
3
+ import { compileColumnRelations, } from "./policy/column-relations.js";
4
+ import { analyzePermissionCycles } from "./policy/permission-cycles.js";
5
+ export function compileAccessPolicy(access, columnRelations) {
4
6
  const definitions = emitAccessIr(access);
5
7
  const byName = new Map(definitions.map((entry) => [entry.wireName, entry]));
6
8
  const generated = new Map(definitions.map((entry) => [entry.wireName, rolePermissions(entry)]));
7
- const model = {
9
+ const baseModel = {
8
10
  entities: definitions.map((entry, index) => ({
9
11
  wireName: entry.wireName,
10
12
  sourceName: `entity_${index}`,
@@ -13,6 +15,11 @@ export function compileAccessPolicy(access) {
13
15
  permissions: definitions.flatMap((entry) => compiledPermissions(entry, { byName, generated })),
14
16
  lifecycle: [],
15
17
  };
18
+ const compiledColumns = compileColumnRelations(baseModel, columnRelations);
19
+ const model = compiledColumns.length === 0
20
+ ? baseModel
21
+ : { ...baseModel, columnRelations: compiledColumns };
22
+ analyzePermissionCycles(model);
16
23
  return {
17
24
  model,
18
25
  permissionName: (entity, name) => {
@@ -1 +1 @@
1
- {"version":3,"file":"compile-access-policy.js","sourceRoot":"","sources":["../src/compile-access-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,GAGb,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,gBAAgB,GAEjB,MAAM,wBAAwB,CAAC;AAQhC,MAAM,UAAU,mBAAmB,CAAC,MAAmB;IACrD,MAAM,WAAW,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IACzC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAG,IAAI,GAAG,CACvB,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CACrE,CAAC;IACF,MAAM,KAAK,GAAiC;QAC1C,QAAQ,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;YAC3C,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,UAAU,EAAE,UAAU,KAAK,EAAE;SAC9B,CAAC,CAAC;QACH,SAAS,EAAE,WAAW,CAAC,OAAO,CAAC,cAAc,CAAC;QAC9C,WAAW,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CACzC,mBAAmB,CAAC,KAAK,EAAE,EAAE,MAAM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,EAAE,CAAC;QACpC,IAAI,SAAiB,CAAC;QACtB,GAAG,CAAC;YACF,SAAS,GAAG,iBAAiB,MAAM,EAAE,CAAC;YACtC,MAAM,IAAI,CAAC,CAAC;QACd,CAAC,QAAQ,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;QAC/B,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -1,5 +1,5 @@
1
- import type { DrizzleHandle } from "@dads-framework/postgres";
1
+ import type { DrizzleExecuteLike } from "./drizzle-structural.js";
2
2
  import type { PostgresAccessExecutor } from "./postgres-authorization.js";
3
3
  /** Bridge compiled, numbered placeholders to the transaction's bound Drizzle parameters. */
4
- export declare function transactionExecutor(transaction: Pick<DrizzleHandle, "execute">): PostgresAccessExecutor;
4
+ export declare function transactionExecutor(transaction: DrizzleExecuteLike): PostgresAccessExecutor;
5
5
  //# sourceMappingURL=drizzle-executor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle-executor.d.ts","sourceRoot":"","sources":["../src/drizzle-executor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAE1E,4FAA4F;AAC5F,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,GAC1C,sBAAsB,CAMxB"}
1
+ {"version":3,"file":"drizzle-executor.d.ts","sourceRoot":"","sources":["../src/drizzle-executor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAG1E,4FAA4F;AAC5F,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,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AAK,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IACxC,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC7C,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { PostgresQueryResult } from "./postgres-types.js";
2
+ /** Structural Drizzle SQL wrapper shape without importing `drizzle-orm`. */
3
+ export type DrizzleQueryLike = {
4
+ getSQL(): unknown;
5
+ };
6
+ /** Minimal structural Drizzle execute boundary (`PgTransaction` and `NodePgDatabase` satisfy this). */
7
+ export type DrizzleExecuteLike = {
8
+ execute(query: DrizzleQueryLike | string): PromiseLike<PostgresQueryResult>;
9
+ };
10
+ /** Minimal structural Drizzle transaction options boundary. */
11
+ export type DrizzleTransactionConfigLike = {
12
+ readonly isolationLevel?: "read uncommitted" | "read committed" | "repeatable read" | "serializable";
13
+ };
14
+ /** Minimal structural Drizzle database boundary (`NodePgDatabase` satisfies this). */
15
+ export type DrizzleDatabaseLike<Tx extends DrizzleExecuteLike = DrizzleExecuteLike> = {
16
+ transaction<Result>(work: (tx: Tx) => Promise<Result>, config?: DrizzleTransactionConfigLike): Promise<Result>;
17
+ };
18
+ /**
19
+ * Detect a Drizzle `PgTransaction` instance via Drizzle's well-known
20
+ * `Symbol.for("drizzle:entityKind")` metadata without loading `drizzle-orm`.
21
+ */
22
+ export declare function isDrizzlePgTransaction(value: unknown): boolean;
23
+ //# sourceMappingURL=drizzle-structural.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle-structural.d.ts","sourceRoot":"","sources":["../src/drizzle-structural.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAI/D,4EAA4E;AAC5E,MAAM,MAAM,gBAAgB,GAAG;IAC7B,MAAM,IAAI,OAAO,CAAC;CACnB,CAAC;AAEF,uGAAuG;AACvG,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,GAAG,WAAW,CAAC,mBAAmB,CAAC,CAAC;CAC7E,CAAC;AAEF,+DAA+D;AAC/D,MAAM,MAAM,4BAA4B,GAAG;IACzC,QAAQ,CAAC,cAAc,CAAC,EACtB,kBAAkB,GAAG,gBAAgB,GAAG,iBAAiB,GAAG,cAAc,CAAC;CAC9E,CAAC;AAEF,sFAAsF;AACtF,MAAM,MAAM,mBAAmB,CAC7B,EAAE,SAAS,kBAAkB,GAAG,kBAAkB,IAChD;IACF,WAAW,CAAC,MAAM,EAChB,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,EACjC,MAAM,CAAC,EAAE,4BAA4B,GACpC,OAAO,CAAC,MAAM,CAAC,CAAC;CACpB,CAAC;AAEF;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAmB9D"}