@dads-framework/postgres 0.0.0-stage → 0.1.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 (160) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +75 -2
  3. package/dist/drizzle.d.ts +9 -0
  4. package/dist/drizzle.d.ts.map +1 -0
  5. package/dist/drizzle.js +2 -0
  6. package/dist/drizzle.js.map +1 -0
  7. package/dist/index.d.ts +13 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +12 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/lib/attributed-pool.d.ts +95 -0
  12. package/dist/lib/attributed-pool.d.ts.map +1 -0
  13. package/dist/lib/attributed-pool.js +128 -0
  14. package/dist/lib/attributed-pool.js.map +1 -0
  15. package/dist/lib/bytea-column.d.ts +37 -0
  16. package/dist/lib/bytea-column.d.ts.map +1 -0
  17. package/dist/lib/bytea-column.js +20 -0
  18. package/dist/lib/bytea-column.js.map +1 -0
  19. package/dist/lib/checked-out-client-errors.d.ts +22 -0
  20. package/dist/lib/checked-out-client-errors.d.ts.map +1 -0
  21. package/dist/lib/checked-out-client-errors.js +28 -0
  22. package/dist/lib/checked-out-client-errors.js.map +1 -0
  23. package/dist/lib/connect-postgres-client.d.ts +16 -0
  24. package/dist/lib/connect-postgres-client.d.ts.map +1 -0
  25. package/dist/lib/connect-postgres-client.js +14 -0
  26. package/dist/lib/connect-postgres-client.js.map +1 -0
  27. package/dist/lib/counting-client.d.ts +39 -0
  28. package/dist/lib/counting-client.d.ts.map +1 -0
  29. package/dist/lib/counting-client.js +102 -0
  30. package/dist/lib/counting-client.js.map +1 -0
  31. package/dist/lib/create-postgres-connection.d.ts +65 -0
  32. package/dist/lib/create-postgres-connection.d.ts.map +1 -0
  33. package/dist/lib/create-postgres-connection.js +68 -0
  34. package/dist/lib/create-postgres-connection.js.map +1 -0
  35. package/dist/lib/event-actor-columns.d.ts +49 -0
  36. package/dist/lib/event-actor-columns.d.ts.map +1 -0
  37. package/dist/lib/event-actor-columns.js +37 -0
  38. package/dist/lib/event-actor-columns.js.map +1 -0
  39. package/dist/lib/inet-column.d.ts +37 -0
  40. package/dist/lib/inet-column.d.ts.map +1 -0
  41. package/dist/lib/inet-column.js +17 -0
  42. package/dist/lib/inet-column.js.map +1 -0
  43. package/dist/lib/load-page-and-total.d.ts +16 -0
  44. package/dist/lib/load-page-and-total.d.ts.map +1 -0
  45. package/dist/lib/load-page-and-total.js +16 -0
  46. package/dist/lib/load-page-and-total.js.map +1 -0
  47. package/dist/lib/postgres-pool-laws.d.ts +6 -0
  48. package/dist/lib/postgres-pool-laws.d.ts.map +1 -0
  49. package/dist/lib/postgres-pool-laws.js +58 -0
  50. package/dist/lib/postgres-pool-laws.js.map +1 -0
  51. package/dist/lib/synced-rows.d.ts +97 -0
  52. package/dist/lib/synced-rows.d.ts.map +1 -0
  53. package/dist/lib/synced-rows.js +158 -0
  54. package/dist/lib/synced-rows.js.map +1 -0
  55. package/dist/lib/unique-violation.d.ts +10 -0
  56. package/dist/lib/unique-violation.d.ts.map +1 -0
  57. package/dist/lib/unique-violation.js +24 -0
  58. package/dist/lib/unique-violation.js.map +1 -0
  59. package/dist/lib/update-at-row-version.d.ts +31 -0
  60. package/dist/lib/update-at-row-version.d.ts.map +1 -0
  61. package/dist/lib/update-at-row-version.js +14 -0
  62. package/dist/lib/update-at-row-version.js.map +1 -0
  63. package/dist/lib/xid8-column.d.ts +38 -0
  64. package/dist/lib/xid8-column.d.ts.map +1 -0
  65. package/dist/lib/xid8-column.js +18 -0
  66. package/dist/lib/xid8-column.js.map +1 -0
  67. package/dist/postgres.tsbuildinfo +1 -0
  68. package/dist/testing/create-test-pool.d.ts +35 -0
  69. package/dist/testing/create-test-pool.d.ts.map +1 -0
  70. package/dist/testing/create-test-pool.js +47 -0
  71. package/dist/testing/create-test-pool.js.map +1 -0
  72. package/dist/testing/deterministic-uuid.d.ts +2 -0
  73. package/dist/testing/deterministic-uuid.d.ts.map +1 -0
  74. package/dist/testing/deterministic-uuid.js +20 -0
  75. package/dist/testing/deterministic-uuid.js.map +1 -0
  76. package/dist/testing/global-setup/container-tier-semaphore.d.ts +51 -0
  77. package/dist/testing/global-setup/container-tier-semaphore.d.ts.map +1 -0
  78. package/dist/testing/global-setup/container-tier-semaphore.js +129 -0
  79. package/dist/testing/global-setup/container-tier-semaphore.js.map +1 -0
  80. package/dist/testing/global-setup/decide-shared-test-postgres.d.ts +51 -0
  81. package/dist/testing/global-setup/decide-shared-test-postgres.d.ts.map +1 -0
  82. package/dist/testing/global-setup/decide-shared-test-postgres.js +109 -0
  83. package/dist/testing/global-setup/decide-shared-test-postgres.js.map +1 -0
  84. package/dist/testing/global-setup/index.d.ts +16 -0
  85. package/dist/testing/global-setup/index.d.ts.map +1 -0
  86. package/dist/testing/global-setup/index.js +151 -0
  87. package/dist/testing/global-setup/index.js.map +1 -0
  88. package/dist/testing/global-setup/refuse-disabled-container-cleanup.d.ts +34 -0
  89. package/dist/testing/global-setup/refuse-disabled-container-cleanup.d.ts.map +1 -0
  90. package/dist/testing/global-setup/refuse-disabled-container-cleanup.js +45 -0
  91. package/dist/testing/global-setup/refuse-disabled-container-cleanup.js.map +1 -0
  92. package/dist/testing/global-setup/refuse-low-memory-runs.d.ts +176 -0
  93. package/dist/testing/global-setup/refuse-low-memory-runs.d.ts.map +1 -0
  94. package/dist/testing/global-setup/refuse-low-memory-runs.js +388 -0
  95. package/dist/testing/global-setup/refuse-low-memory-runs.js.map +1 -0
  96. package/dist/testing/global-setup/refuse-slow-local-test-mode.d.ts +5 -0
  97. package/dist/testing/global-setup/refuse-slow-local-test-mode.d.ts.map +1 -0
  98. package/dist/testing/global-setup/refuse-slow-local-test-mode.js +18 -0
  99. package/dist/testing/global-setup/refuse-slow-local-test-mode.js.map +1 -0
  100. package/dist/testing/global-setup/refuse-stacked-container-runs.d.ts +106 -0
  101. package/dist/testing/global-setup/refuse-stacked-container-runs.d.ts.map +1 -0
  102. package/dist/testing/global-setup/refuse-stacked-container-runs.js +284 -0
  103. package/dist/testing/global-setup/refuse-stacked-container-runs.js.map +1 -0
  104. package/dist/testing/global-setup/remove-stale-testcontainers.d.ts +33 -0
  105. package/dist/testing/global-setup/remove-stale-testcontainers.d.ts.map +1 -0
  106. package/dist/testing/global-setup/remove-stale-testcontainers.js +165 -0
  107. package/dist/testing/global-setup/remove-stale-testcontainers.js.map +1 -0
  108. package/dist/testing/global-setup/retired-database-touches.d.ts +16 -0
  109. package/dist/testing/global-setup/retired-database-touches.d.ts.map +1 -0
  110. package/dist/testing/global-setup/retired-database-touches.js +73 -0
  111. package/dist/testing/global-setup/retired-database-touches.js.map +1 -0
  112. package/dist/testing/global-setup/schema-keyed-coverage.d.ts +56 -0
  113. package/dist/testing/global-setup/schema-keyed-coverage.d.ts.map +1 -0
  114. package/dist/testing/global-setup/schema-keyed-coverage.js +84 -0
  115. package/dist/testing/global-setup/schema-keyed-coverage.js.map +1 -0
  116. package/dist/testing/global-setup/skip-unless-container-tests.d.ts +31 -0
  117. package/dist/testing/global-setup/skip-unless-container-tests.d.ts.map +1 -0
  118. package/dist/testing/global-setup/skip-unless-container-tests.js +33 -0
  119. package/dist/testing/global-setup/skip-unless-container-tests.js.map +1 -0
  120. package/dist/testing/global-setup/start-migrated-template-postgres.d.ts +20 -0
  121. package/dist/testing/global-setup/start-migrated-template-postgres.d.ts.map +1 -0
  122. package/dist/testing/global-setup/start-migrated-template-postgres.js +53 -0
  123. package/dist/testing/global-setup/start-migrated-template-postgres.js.map +1 -0
  124. package/dist/testing/global-setup/verify-schema-keyed-suite.d.ts +43 -0
  125. package/dist/testing/global-setup/verify-schema-keyed-suite.d.ts.map +1 -0
  126. package/dist/testing/global-setup/verify-schema-keyed-suite.js +201 -0
  127. package/dist/testing/global-setup/verify-schema-keyed-suite.js.map +1 -0
  128. package/dist/testing/global-setup/worktree-identity.d.ts +21 -0
  129. package/dist/testing/global-setup/worktree-identity.d.ts.map +1 -0
  130. package/dist/testing/global-setup/worktree-identity.js +30 -0
  131. package/dist/testing/global-setup/worktree-identity.js.map +1 -0
  132. package/dist/testing/index.d.ts +11 -0
  133. package/dist/testing/index.d.ts.map +1 -0
  134. package/dist/testing/index.js +11 -0
  135. package/dist/testing/index.js.map +1 -0
  136. package/dist/testing/rehearsal-postgres.d.ts +20 -0
  137. package/dist/testing/rehearsal-postgres.d.ts.map +1 -0
  138. package/dist/testing/rehearsal-postgres.js +61 -0
  139. package/dist/testing/rehearsal-postgres.js.map +1 -0
  140. package/dist/testing/start-test-postgres.d.ts +59 -0
  141. package/dist/testing/start-test-postgres.d.ts.map +1 -0
  142. package/dist/testing/start-test-postgres.js +241 -0
  143. package/dist/testing/start-test-postgres.js.map +1 -0
  144. package/dist/testing/test-postgres-storage.d.ts +44 -0
  145. package/dist/testing/test-postgres-storage.d.ts.map +1 -0
  146. package/dist/testing/test-postgres-storage.js +88 -0
  147. package/dist/testing/test-postgres-storage.js.map +1 -0
  148. package/dist/testing/truncate-tables.d.ts +31 -0
  149. package/dist/testing/truncate-tables.d.ts.map +1 -0
  150. package/dist/testing/truncate-tables.js +39 -0
  151. package/dist/testing/truncate-tables.js.map +1 -0
  152. package/dist/testing/violated-foreign-key.d.ts +14 -0
  153. package/dist/testing/violated-foreign-key.d.ts.map +1 -0
  154. package/dist/testing/violated-foreign-key.js +78 -0
  155. package/dist/testing/violated-foreign-key.js.map +1 -0
  156. package/dist/testing/with-database.d.ts +2 -0
  157. package/dist/testing/with-database.d.ts.map +1 -0
  158. package/dist/testing/with-database.js +6 -0
  159. package/dist/testing/with-database.js.map +1 -0
  160. package/package.json +88 -4
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Counting the statements a request actually issues.
3
+ *
4
+ * `request_log.duration_ms` has never said whether 900ms was three slow
5
+ * queries or three hundred fast ones. This installs the counter at the one
6
+ * place every statement passes through — the checked-out client — so the
7
+ * answer arrives without a single call site changing.
8
+ *
9
+ * Three things about `pg` make this less obvious than it looks:
10
+ *
11
+ * - **`pool.query` uses the CALLBACK form.** `pg-pool` dispatches a plain
12
+ * statement as `client.query(text, values, callback)` and hands back its own
13
+ * promise, so a wrapper that only understood promises would silently stop
14
+ * counting the single-statement path — which is most of this codebase, since
15
+ * Drizzle issues its non-transactional queries that way.
16
+ * - **A client outlives its checkout.** `pg` returns the same client object to
17
+ * the pool and hands it out again, so instrumenting on every checkout would
18
+ * wrap the wrapper and count one statement twice, then four times. The
19
+ * `WeakSet` below makes it once per client, for the life of that client.
20
+ * - **`query` is overloaded eight ways** — text, config, values, callback,
21
+ * submittable. Rather than re-implement pg's overload resolution (and get it
22
+ * wrong the first time pg adds a shape), the wrapper forwards whatever it
23
+ * was given, untouched, and only decides how to learn that the statement
24
+ * finished. `Object.defineProperty` installs it for the same reason: it
25
+ * replaces the method without having to restate a signature this module has
26
+ * no business owning.
27
+ *
28
+ * The actor stamp is deliberately NOT counted: it is the pool's own cost, not
29
+ * the request's, and it is issued before this wrapper is installed.
30
+ */
31
+ import { chargeDatabaseQuery, countDatabaseQuery, } from "@dads-framework/request-work";
32
+ function isForwardingCall(value) {
33
+ return typeof value === "function";
34
+ }
35
+ /**
36
+ * Clients already carrying the counter. A `WeakSet` rather than a flag on the
37
+ * client: it adds no property to an object `pg` owns, and it forgets the
38
+ * client exactly when the client is collected.
39
+ */
40
+ const instrumented = new WeakSet();
41
+ /**
42
+ * Installs the statement counter on `client`, once. Safe to call on every
43
+ * checkout — the second call and every one after it do nothing.
44
+ *
45
+ * Takes any object so it can be proved against a hand-written client with no
46
+ * database in sight, and does nothing to one that has no `query` to replace.
47
+ */
48
+ export function countStatementsOn(client) {
49
+ if (instrumented.has(client))
50
+ return;
51
+ if (!("query" in client))
52
+ return;
53
+ const issueStatement = client.query;
54
+ if (!isForwardingCall(issueStatement))
55
+ return;
56
+ instrumented.add(client);
57
+ Object.defineProperty(client, "query", {
58
+ configurable: true,
59
+ writable: true,
60
+ enumerable: false,
61
+ value: countingQuery(issueStatement.bind(client)),
62
+ });
63
+ }
64
+ function countingQuery(issueStatement) {
65
+ return (...args) => {
66
+ const callback = args.at(-1);
67
+ if (isForwardingCall(callback)) {
68
+ return issueStatement(...chargedCallbackArgs(args, callback));
69
+ }
70
+ const outcome = issueStatement(...args);
71
+ if (isThenable(outcome))
72
+ return chargeThenable(outcome);
73
+ // A submittable (a cursor, a COPY stream) finishes on its own events
74
+ // rather than on a promise or a callback. It is one statement either way,
75
+ // so it is counted as one with no elapsed time attributed to it.
76
+ countDatabaseQuery(0);
77
+ return outcome;
78
+ };
79
+ }
80
+ /**
81
+ * The same arguments, with the caller's callback wrapped so the statement is
82
+ * charged the moment `pg` reports it done — success or failure alike.
83
+ */
84
+ function chargedCallbackArgs(args, callback) {
85
+ const startedAt = performance.now();
86
+ const charged = (...callbackArgs) => {
87
+ countDatabaseQuery(performance.now() - startedAt);
88
+ return callback(...callbackArgs);
89
+ };
90
+ return [...args.slice(0, -1), charged];
91
+ }
92
+ /** The promise form, charged through the shared wrapper so both agree. */
93
+ function chargeThenable(outcome) {
94
+ return chargeDatabaseQuery(() => outcome);
95
+ }
96
+ function isThenable(value) {
97
+ return (typeof value === "object" &&
98
+ value !== null &&
99
+ "then" in value &&
100
+ typeof value.then === "function");
101
+ }
102
+ //# sourceMappingURL=counting-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"counting-client.js","sourceRoot":"","sources":["../../src/lib/counting-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EACL,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AAYtC,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,UAAU,CAAC;AACrC,CAAC;AAED;;;;GAIG;AACH,MAAM,YAAY,GAAG,IAAI,OAAO,EAAU,CAAC;AAE3C;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAc;IAC9C,IAAI,YAAY,CA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AkB,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC,CAAC;QAClD,OAAO,QAAQ,CAAC,GAAG,YAAY,CAAC,CAAC;IACnC,CAAC,CAAC;IACF,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC;AAED,0EAA0E;AAC1E,SAAS,cAAc,CAAC,OAA6B;IACnD,OAAO,mBAAmB,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,UAAU,CAAC,KAAc;IAChC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU,CACjC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,65 @@
1
+ import { type NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ import { Pool } from "pg";
3
+ import { type AuditActorSource } from "./attributed-pool.js";
4
+ export type CreatePostgresConnectionOptions<TSchema extends Record<string, unknown> = Record<string, unknown>> = {
5
+ /** Runtime Drizzle schema, assembled by the composition root from domain exports. */
6
+ readonly schema: TSchema;
7
+ /** Postgres connection string from the validated environment. */
8
+ readonly connectionString: string;
9
+ /**
10
+ * Where the pool reads the audit actor on every checkout. Given
11
+ * one, the returned `pool` IS the attributed pool, so the raw-pool consumers
12
+ * that share it — `PostgresOwnerLock`, the participant coordinator, the
13
+ * Better Auth adapter — are attributed by construction rather than by
14
+ * remembering to be.
15
+ *
16
+ * Optional because the migrator and the schema generator build connections
17
+ * that run DDL against databases whose audit trigger does not exist yet.
18
+ */
19
+ readonly auditActorSource?: AuditActorSource;
20
+ /**
21
+ * The most connections this pool opens at once. Omitted, pg's own default
22
+ * (10) applies, which is what every deployed process runs. Tests that boot
23
+ * many apps against one shared Postgres pass a smaller number so the sum
24
+ * of their pools fits under its `max_connections`.
25
+ */
26
+ readonly maxConnections?: number;
27
+ /**
28
+ * Settings every connection of this pool starts with, sent as Postgres
29
+ * startup options (`-c name=value`), so they hold from a connection's first
30
+ * statement and no checkout can miss them. Omitted, connections start with
31
+ * none. Names and values are plain words (letters, digits, `_`, `.`); any
32
+ * other refuses the construction, since a startup option cannot carry a
33
+ * space unescaped. A connection string that names its own `options`
34
+ * overrides these (pg lets the string win), so callers pass none there.
35
+ */
36
+ readonly sessionSettings?: Readonly<Record<string, string>>;
37
+ };
38
+ export type PostgresConnection<TSchema extends Record<string, unknown> = Record<string, unknown>> = {
39
+ readonly pool: Pool;
40
+ readonly drizzle: NodePgDatabase<TSchema> & {
41
+ $client: Pool;
42
+ };
43
+ /** Ends the pool — wired into app shutdown by the composition root. */
44
+ readonly close: () => Promise<void>;
45
+ };
46
+ export type PostgresPoolErrorLog = {
47
+ error(obj: object, msg?: string): void;
48
+ };
49
+ /**
50
+ * The one Drizzle/pg construction point. Generic over the schema so the
51
+ * composition root's handle keeps its table types.
52
+ *
53
+ * Two process-discipline walls live here: client errors are LOGGED, never
54
+ * left unlistened — an unlistened 'error' event kills the process (the
55
+ * classic Node/pg crash). pg emits an idle client's error on the pool and a
56
+ * checked-out client's on the client itself, so both are listened for. And
57
+ * close() is idempotent so teardown paths can never trip "end called twice".
58
+ *
59
+ * With `auditActorSource`, the pool it builds stamps the current actor onto
60
+ * every checkout. One pool object serves Drizzle and the raw-pool
61
+ * consumers, so attribution is a property of the connection rather than
62
+ * something 61 writer files have to remember.
63
+ */
64
+ export declare function createPostgresConnection<TSchema extends Record<string, unknown>>(options: CreatePostgresConnectionOptions<TSchema>, log: PostgresPoolErrorLog): PostgresConnection<TSchema>;
65
+ //# sourceMappingURL=create-postgres-connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-postgres-connection.d.ts","sourceRoot":"","sources":["../../src/lib/create-postgres-connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,KAAK,cAAc,EAAE,MAAM,2B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AAO,CAAC,EAEvC,OAAO,EAAE,+BAA+B,CAAC,OAAO,CAAC,EACjD,GAAG,EAAE,oBAAoB,GACxB,kBAAkB,CAAC,OAAO,CAAC,CAqC7B"}
@@ -0,0 +1,68 @@
1
+ import { drizzle } from "drizzle-orm/node-postgres";
2
+ import { Pool } from "pg";
3
+ import { createAttributedPool, } from "./attributed-pool.js";
4
+ import { listenForCheckedOutClientErrors } from "./checked-out-client-errors.js";
5
+ /**
6
+ * The one Drizzle/pg construction point. Generic over the schema so the
7
+ * composition root's handle keeps its table types.
8
+ *
9
+ * Two process-discipline walls live here: client errors are LOGGED, never
10
+ * left unlistened — an unlistened 'error' event kills the process (the
11
+ * classic Node/pg crash). pg emits an idle client's error on the pool and a
12
+ * checked-out client's on the client itself, so both are listened for. And
13
+ * close() is idempotent so teardown paths can never trip "end called twice".
14
+ *
15
+ * With `auditActorSource`, the pool it builds stamps the current actor onto
16
+ * every checkout. One pool object serves Drizzle and the raw-pool
17
+ * consumers, so attribution is a property of the connection rather than
18
+ * something 61 writer files have to remember.
19
+ */
20
+ export function createPostgresConnection(options, log) {
21
+ const poolConfig = {
22
+ connectionString: options.connectionString,
23
+ ...(options.maxConnections === undefined
24
+ ? {}
25
+ : { max: options.maxConnections }),
26
+ ...(options.sessionSettings === undefined
27
+ ? {}
28
+ : { options: startupOptionsOf(options.sessionSettings) }),
29
+ };
30
+ const pool = options.auditActorSource === undefined
31
+ ? new Pool(poolConfig)
32
+ : createAttributedPool(poolConfig, options.auditActorSource);
33
+ pool.on("error", (error) => {
34
+ log.error({ event: "database.idle-client-error", err: error }, "idle postgres client errored (connection dropped)");
35
+ });
36
+ listenForCheckedOutClientErrors(pool, (error) => {
37
+ log.error({ event: "database.checked-out-client-error", err: error }, "checked-out postgres client errored (connection dropped)");
38
+ });
39
+ const drizzleHandle = drizzle(pool, { schema: options.schema });
40
+ let ended = false;
41
+ return {
42
+ pool,
43
+ drizzle: drizzleHandle,
44
+ close: () => {
45
+ if (ended)
46
+ return Promise.resolve();
47
+ ended = true;
48
+ return pool.end();
49
+ },
50
+ };
51
+ }
52
+ const PLAIN_SETTING_WORD = /^[A-Za-z0-9_.]+$/;
53
+ /**
54
+ * `{ "a.b": "on" }` → `-c a.b=on`: the startup options that set each
55
+ * setting on a new connection. Refuses a name or value that is not a plain
56
+ * word, rather than escape it.
57
+ */
58
+ function startupOptionsOf(settings) {
59
+ return Object.entries(settings)
60
+ .map(([name, value]) => {
61
+ if (!PLAIN_SETTING_WORD.test(name) || !PLAIN_SETTING_WORD.test(value)) {
62
+ throw new Error(`Session setting ${JSON.stringify(name)} = ${JSON.stringify(value)} is not a plain word (letters, digits, _ and . only).`);
63
+ }
64
+ return `-c ${name}=${value}`;
65
+ })
66
+ .join(" ");
67
+ }
68
+ //# sourceMappingURL=create-postgres-connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-postgres-connection.js","sourceRoot":"","sources":["../../src/lib/create-postgres-connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAuB,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC1B,OAAO,EACL,oBAAoB,GAErB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AAoDjF;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,wBAAwB,CAGtC,OAAiD,EACjD,GAAyB;IAEzB,MAAM,UAAU,GAAG;QACjB,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;QAC1C,GAAG,CAAC,OAAO,CAAC,cAAc,KAAK,SAAS;YACtC,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,cAAc,EAAE,CAAC;QACpC,GAAG,CAAC,OAAO,CAAC,eAAe,KAAK,SAAS;YACvC,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,OAAO,EAAE,gBAAgB,CAAC,OAA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B,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACtE,MAAM,IAAI,KAAK,CACb,mBAAmB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,uDAAuD,CAC1H,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;IAC/B,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAC;AACf,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * How an event actor is spelled in columns.
3
+ *
4
+ * Five append-only event tables across four domains — organization membership,
5
+ * facility membership, platform staff, support session, platform work
6
+ * assignment — carry the same column trio: `actor_type`, `actor_user_id`,
7
+ * `actor_system`. Splitting the actor rather than storing one
8
+ * `actor_subject_id` is deliberate: SCIM, JIT SSO, and the expiry sweep act
9
+ * without a human, and "the directory sync did this" must never be forced to
10
+ * masquerade as a user id.
11
+ *
12
+ * The mapping from the union to those three columns was written out nine times
13
+ * before 2026-08-17 — the same two ternaries, once per writer, with nothing
14
+ * keeping them honest. It lives here because the trio is a persistence
15
+ * CONVENTION shared across domains, the same kind of thing as
16
+ * `loadPageAndTotal`, and because every one of those writers already depends on
17
+ * this library for `DrizzleHandle` — so nothing gains a project edge by using
18
+ * it.
19
+ *
20
+ * The actor UNION stays domain-owned. Each domain declares its own `EventActor`
21
+ * (drizzle-kit loads schema files standalone, so storage vocabulary cannot be
22
+ * centralized), and this function accepts the shape structurally rather than
23
+ * importing any domain's copy.
24
+ *
25
+ * Deliberately NOT a row builder. Each table's other columns differ — the
26
+ * parent id is named for its own aggregate, and only facility membership
27
+ * carries `event_source` — so each domain keeps its own `eventValues` composer
28
+ * and spreads this into it. And the event `id` is never produced here: ids are
29
+ * minted at the call site, in view of the insert, which is the rule
30
+ * an application can enforce.
31
+ */
32
+ /** Exactly one of the two shapes — the union keeps both halves valid.
33
+ * Generic over the user-id type so a domain whose union carries a branded
34
+ * `UserId` keeps the brand through to its column, still without this kit
35
+ * importing any domain's contract. */
36
+ export type PersistedEventActor<TUserId extends string = string> = {
37
+ readonly type: "USER";
38
+ readonly userId: TUserId;
39
+ } | {
40
+ readonly type: "SYSTEM";
41
+ readonly system: string;
42
+ };
43
+ export type EventActorColumns<TUserId extends string = string> = {
44
+ readonly actorType: "USER" | "SYSTEM";
45
+ readonly actorUserId: TUserId | null;
46
+ readonly actorSystem: string | null;
47
+ };
48
+ export declare function eventActorColumns<TUserId extends string>(actor: PersistedEventActor<TUserId>): EventActorColumns<TUserId>;
49
+ //# sourceMappingURL=event-actor-columns.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-actor-columns.d.ts","sourceRoot":"","sources":["../../src/lib/event-actor-columns.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH;;;sCAGsC;AACtC,MAAM,MAAM,mBAAmB,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM,IAC3D;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GACnD;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzD,MAAM,MAAM,iBAAiB,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM,IAAI;IAC/D,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,QAAQ,CAAC;IACtC,QAAQ,CAAC,WAAW,EAAE,OAAO,GAAG,IAAI,CAAC;IACrC,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CACrC,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,OAAO,SAAS,MAAM,EACtD,KAAK,EAAE,mBAAmB,CAAC,OAAO,CAAC,GAClC,iBAAiB,CAAC,OAAO,CAAC,CAI5B"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * How an event actor is spelled in columns.
3
+ *
4
+ * Five append-only event tables across four domains — organization membership,
5
+ * facility membership, platform staff, support session, platform work
6
+ * assignment — carry the same column trio: `actor_type`, `actor_user_id`,
7
+ * `actor_system`. Splitting the actor rather than storing one
8
+ * `actor_subject_id` is deliberate: SCIM, JIT SSO, and the expiry sweep act
9
+ * without a human, and "the directory sync did this" must never be forced to
10
+ * masquerade as a user id.
11
+ *
12
+ * The mapping from the union to those three columns was written out nine times
13
+ * before 2026-08-17 — the same two ternaries, once per writer, with nothing
14
+ * keeping them honest. It lives here because the trio is a persistence
15
+ * CONVENTION shared across domains, the same kind of thing as
16
+ * `loadPageAndTotal`, and because every one of those writers already depends on
17
+ * this library for `DrizzleHandle` — so nothing gains a project edge by using
18
+ * it.
19
+ *
20
+ * The actor UNION stays domain-owned. Each domain declares its own `EventActor`
21
+ * (drizzle-kit loads schema files standalone, so storage vocabulary cannot be
22
+ * centralized), and this function accepts the shape structurally rather than
23
+ * importing any domain's copy.
24
+ *
25
+ * Deliberately NOT a row builder. Each table's other columns differ — the
26
+ * parent id is named for its own aggregate, and only facility membership
27
+ * carries `event_source` — so each domain keeps its own `eventValues` composer
28
+ * and spreads this into it. And the event `id` is never produced here: ids are
29
+ * minted at the call site, in view of the insert, which is the rule
30
+ * an application can enforce.
31
+ */
32
+ export function eventActorColumns(actor) {
33
+ return actor.type === "USER"
34
+ ? { actorType: "USER", actorUserId: actor.userId, actorSystem: null }
35
+ : { actorType: "SYSTEM", actorUserId: null, actorSystem: actor.system };
36
+ }
37
+ //# sourceMappingURL=event-actor-columns.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-actor-columns.js","sourceRoot":"","sources":["../../src/lib/event-actor-columns.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAgBH,MAAM,UAAU,iBAAiB,CAC/B,KAAmC;IAEnC,OAAO,KAAK,CAAC,IAAI,KAAK,MAAM;QAC1B,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE;QACrE,CAAC,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Postgres `inet` (an IP address, with an optional network prefix) as a
3
+ * Drizzle column.
4
+ *
5
+ * drizzle-orm ships no `inet` builder, and the type exists in the schema for
6
+ * one reason: `request_log.ip`. node-postgres has no
7
+ * parser registered for the type, so it arrives as the text Postgres printed
8
+ * — which is also the only representation callers need: nothing here does
9
+ * subnet arithmetic, it is an address to record and compare by.
10
+ */
11
+ export declare const inet: {
12
+ (): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{
13
+ name: "";
14
+ dataType: 'custom';
15
+ columnType: 'PgCustomColumn';
16
+ data: string;
17
+ driverParam: string;
18
+ enumValues: undefined;
19
+ }>;
20
+ <TConfig extends Record<string, any> & unknown>(fieldConfig?: TConfig | undefined): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{
21
+ name: "";
22
+ dataType: 'custom';
23
+ columnType: 'PgCustomColumn';
24
+ data: string;
25
+ driverParam: string;
26
+ enumValues: undefined;
27
+ }>;
28
+ <TName extends string>(dbName: TName, fieldConfig?: unknown): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{
29
+ name: TName;
30
+ dataType: 'custom';
31
+ columnType: 'PgCustomColumn';
32
+ data: string;
33
+ driverParam: string;
34
+ enumValues: undefined;
35
+ }>;
36
+ };
37
+ //# sourceMappingURL=inet-column.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inet-column.d.ts","sourceRoot":"","sources":["../../src/lib/inet-column.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;CAIf,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { customType } from "drizzle-orm/pg-core";
2
+ /**
3
+ * Postgres `inet` (an IP address, with an optional network prefix) as a
4
+ * Drizzle column.
5
+ *
6
+ * drizzle-orm ships no `inet` builder, and the type exists in the schema for
7
+ * one reason: `request_log.ip`. node-postgres has no
8
+ * parser registered for the type, so it arrives as the text Postgres printed
9
+ * — which is also the only representation callers need: nothing here does
10
+ * subnet arithmetic, it is an address to record and compare by.
11
+ */
12
+ export const inet = customType({
13
+ dataType() {
14
+ return "inet";
15
+ },
16
+ });
17
+ //# sourceMappingURL=inet-column.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inet-column.js","sourceRoot":"","sources":["../../src/lib/inet-column.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,UAAU,CAAuC;IACnE,QAAQ;QACN,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAC,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The list-endpoint pair every reader repeats: the page of rows and the
3
+ * total count run concurrently against the same WHERE, and a missing count
4
+ * row (empty table) is zero, not undefined. The caller builds both queries —
5
+ * this helper only owns the concurrency and the unwrap, so it can never
6
+ * drift from what the adapter actually selects.
7
+ */
8
+ export declare function loadPageAndTotal<T>(rowsQuery: PromiseLike<T[]>, totalQuery: PromiseLike<{
9
+ total: number;
10
+ }[]>): Promise<{
11
+ rows: readonly T[];
12
+ total: number;
13
+ }>;
14
+ /** Zero-based SQL OFFSET from the API's one-based page convention. */
15
+ export declare function sqlOffsetForPage(page: number, perPage: number): number;
16
+ //# sourceMappingURL=load-page-and-total.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-page-and-total.d.ts","sourceRoot":"","sources":["../../src/lib/load-page-and-total.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EACtC,SAAS,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,EAC3B,UAAU,EAAE,WAAW,CAAC;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,GAC3C,OAAO,CAAC;IAAE,IAAI,EAAE,SAAS,CAAC,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAGhD;AAED,sEAAsE;AACtE,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAEtE"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The list-endpoint pair every reader repeats: the page of rows and the
3
+ * total count run concurrently against the same WHERE, and a missing count
4
+ * row (empty table) is zero, not undefined. The caller builds both queries —
5
+ * this helper only owns the concurrency and the unwrap, so it can never
6
+ * drift from what the adapter actually selects.
7
+ */
8
+ export async function loadPageAndTotal(rowsQuery, totalQuery) {
9
+ const [rows, totals] = await Promise.all([rowsQuery, totalQuery]);
10
+ return { rows, total: totals[0]?.total ?? 0 };
11
+ }
12
+ /** Zero-based SQL OFFSET from the API's one-based page convention. */
13
+ export function sqlOffsetForPage(page, perPage) {
14
+ return (page - 1) * perPage;
15
+ }
16
+ //# sourceMappingURL=load-page-and-total.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-page-and-total.js","sourceRoot":"","sources":["../../src/lib/load-page-and-total.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,SAA2B,EAC3B,UAA4C;IAE5C,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC;IAClE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;AAChD,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAE,OAAe;IAC5D,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { Pool, PoolConfig } from "pg";
2
+ type RegisterPoolLaw = (name: string, run: (connectionString: string, observer: Pool) => Promise<void>) => void;
3
+ /** Applies the same connection lifecycle and isolation laws to each pool. */
4
+ export declare function runPostgresPoolLaws(open: (options: PoolConfig) => Pool, register: RegisterPoolLaw): void;
5
+ export {};
6
+ //# sourceMappingURL=postgres-pool-laws.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-pool-laws.d.ts","sourceRoot":"","sources":["../../src/lib/postgres-pool-laws.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAc,UAAU,EAAE,MAAM,IAAI,CAAC;AAEvD,KAAK,eAAe,GAAG,CACrB,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,CAAC,gBAAgB,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,KAC7D,IAAI,CAAC;AAEV,6EAA6E;AAC7E,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,IAAI,EACnC,QAAQ,EAAE,eAAe,GACxB,IAAI,CA+BN"}
@@ -0,0 +1,58 @@
1
+ import { deepEqual, equal, rejects } from "node:assert/strict";
2
+ import { sql } from "drizzle-orm";
3
+ import { drizzle } from "drizzle-orm/node-postgres";
4
+ /** Applies the same connection lifecycle and isolation laws to each pool. */
5
+ export function runPostgresPoolLaws(open, register) {
6
+ register("releases a checkout for reuse and closes the pool", async (connectionString) => {
7
+ const pool = open({ connectionString, max: 1 });
8
+ try {
9
+ const client = await pool.connect();
10
+ const before = await pidBeforeRelease(client);
11
+ const after = await pool.query("select pg_backend_pid() as pid");
12
+ equal(typeof before.rows[0]?.pid, "number");
13
+ deepEqual(after.rows, before.rows);
14
+ }
15
+ finally {
16
+ await pool.end();
17
+ }
18
+ await rejects(() => pool.query("select 1"), Error);
19
+ });
20
+ register("isolates Drizzle writes until commit and rolls back errors", async (connectionString, observer) => {
21
+ const pool = open({ connectionString, max: 1 });
22
+ try {
23
+ await proveTransactionIsolation(drizzle(pool), observer);
24
+ }
25
+ finally {
26
+ await pool.end();
27
+ }
28
+ });
29
+ }
30
+ async function pidBeforeRelease(client) {
31
+ try {
32
+ return await client.query("select pg_backend_pid() as pid");
33
+ }
34
+ finally {
35
+ client.release();
36
+ }
37
+ }
38
+ async function proveTransactionIsolation(db, observer) {
39
+ const refused = new Error("Rollback requested");
40
+ await observer.query("truncate pool_conformance_writes");
41
+ await rejects(() => db.transaction(async (tx) => {
42
+ await tx.execute(sql `insert into pool_conformance_writes values (1)`);
43
+ const row = await tx.execute(sql `select value from pool_conformance_writes`);
44
+ deepEqual(row.rows, [{ value: 1 }]);
45
+ deepEqual(await visibleWrites(observer), []);
46
+ throw refused;
47
+ }), (error) => error === refused);
48
+ deepEqual(await visibleWrites(observer), []);
49
+ await db.transaction(async (tx) => {
50
+ await tx.execute(sql `insert into pool_conformance_writes values (2)`);
51
+ });
52
+ deepEqual(await visibleWrites(observer), [{ value: 2 }]);
53
+ }
54
+ async function visibleWrites(pool) {
55
+ const result = await pool.query("select value from pool_conformance_writes order by value");
56
+ return result.rows;
57
+ }
58
+ //# sourceMappingURL=postgres-pool-laws.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-pool-laws.js","sourceRoot":"","sources":["../../src/lib/postgres-pool-laws.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,2BAA2B,CA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K,UAAU,aAAa,CAC1B,IAAU;IAEV,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAC7B,0DAA0D,CAC3D,CAAC;IACF,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC"}
@@ -0,0 +1,97 @@
1
+ import { type SQL } from "drizzle-orm";
2
+ import type { AnyPgColumn } from "drizzle-orm/pg-core";
3
+ import type { DrizzleHandle } from "../drizzle.js";
4
+ /** The transaction a page of synced rows is written in; the caller owns its commit. */
5
+ export type SyncedRowTransaction = Parameters<Parameters<DrizzleHandle["transaction"]>[0]>[0];
6
+ /**
7
+ * One row of a copy kept in step with another database, as that database
8
+ * has it now. `data` is the row's fields as sent, parsed by the table's
9
+ * owner when written. `takeNext` writes the row whatever its stored
10
+ * version; otherwise an upsert writes only a newer version, or the same
11
+ * version with other values.
12
+ */
13
+ export type SyncedRowChange<Table extends string> = {
14
+ readonly table: Table;
15
+ readonly op: "upsert";
16
+ readonly id: string;
17
+ readonly rowVersion: number;
18
+ readonly data: unknown;
19
+ readonly takeNext: boolean;
20
+ } | {
21
+ readonly table: Table;
22
+ readonly op: "delete";
23
+ readonly id: string;
24
+ readonly takeNext: boolean;
25
+ };
26
+ /**
27
+ * - `applied`: the row was written or deleted.
28
+ * - `already_current`: the stored row is newer, or the same version with the same values.
29
+ * - `missing_parent`: a row it points at is not here yet; nothing was written.
30
+ * - `refused`: the database or the owner refused it; `code` says why.
31
+ */
32
+ export type SyncedRowOutcome<Table extends string> = {
33
+ readonly table: Table;
34
+ readonly id: string;
35
+ readonly outcome: "applied" | "already_current" | "missing_parent" | "refused";
36
+ readonly code: string | null;
37
+ };
38
+ /** Written by an upsert whose data the owner could not read; nothing was stored. */
39
+ export declare const SYNCED_VALUE_UNKNOWN = "unknown_value";
40
+ /**
41
+ * Written by an upsert to an append-only table whose stored row, under the
42
+ * same id, holds other values. Such a row is never changed, so nothing was
43
+ * stored; the outcome is `refused` with `SYNC_IMMUTABLE_ROW_DIFFERS`.
44
+ */
45
+ export declare const SYNCED_ROW_IMMUTABLE_DIFFERS = "immutable_row_differs";
46
+ /**
47
+ * How one owner writes its tables: true when a row was written or deleted.
48
+ * `Tx` is the page's transaction; only a test names another.
49
+ */
50
+ export type SyncedRowWriter<Table extends string, Tx = SyncedRowTransaction> = {
51
+ upsert(tx: Tx, change: Extract<SyncedRowChange<Table>, {
52
+ op: "upsert";
53
+ }>): Promise<boolean | typeof SYNCED_VALUE_UNKNOWN | typeof SYNCED_ROW_IMMUTABLE_DIFFERS>;
54
+ delete(tx: Tx, table: Table, id: string): Promise<boolean>;
55
+ /**
56
+ * Moves aside the other stored rows holding a unique value this upsert
57
+ * carries (a name or code the cloud has since given to this row), to a
58
+ * value nothing else holds, keeping their row version so their own cloud
59
+ * row still applies. Answers how many it moved. A table whose unique
60
+ * values cannot trade places leaves it out.
61
+ */
62
+ moveKeyHoldersAside?(tx: Tx, change: Extract<SyncedRowChange<Table>, {
63
+ op: "upsert";
64
+ }>): Promise<number>;
65
+ };
66
+ /**
67
+ * Writes one page of synced rows inside the caller's transaction: upserts
68
+ * parents first, then deletes children first, whatever order the page
69
+ * used. Each change runs in its own savepoint and answers one outcome, in
70
+ * that written order. An upsert whose parent is not here answers
71
+ * `missing_parent`; a delete whose children stay answers `refused` with
72
+ * `SYNC_ROW_HAS_CHILDREN`; data the owner cannot read answers `refused`
73
+ * with `SYNC_VALUE_UNKNOWN`; an append-only row the owner holds with other
74
+ * values answers `refused` with `SYNC_IMMUTABLE_ROW_DIFFERS`. An upsert whose unique value another stored
75
+ * row still holds first moves that stale row aside, when the owner can
76
+ * (`moveKeyHoldersAside`), and is written. Otherwise it answers
77
+ * `missing_parent` with `SYNC_ROW_KEY_TAKEN`: that row is one the cloud has
78
+ * since deleted or changed, and its own change runs after this one (deletes
79
+ * run last), so the held row is retried once it has gone, never dropped.
80
+ * One whose parent turns out to be missing once the key is free answers
81
+ * `missing_parent`, with the move rolled back.
82
+ */
83
+ export declare function applySyncedRows<Table extends string>(tx: SyncedRowTransaction, changes: readonly SyncedRowChange<Table>[], tablesParentsFirst: readonly Table[], writer: SyncedRowWriter<Table>): Promise<SyncedRowOutcome<Table>[]>;
84
+ /**
85
+ * The stored row is older, or holds the same version with other values. A
86
+ * same-version row with the same values is left alone, so a repeated page
87
+ * writes nothing (no audit or sync log row either). Undefined when the
88
+ * caller takes the next row whatever its version.
89
+ */
90
+ export declare function newerOrDifferent(rowVersion: AnyPgColumn, synced: readonly AnyPgColumn[], takeNext?: boolean): SQL | undefined;
91
+ /** The value an `INSERT … ON CONFLICT` proposed for `column`. */
92
+ export declare function excluded(column: AnyPgColumn): SQL;
93
+ /** Each named column's proposed value, under the same names: an `ON CONFLICT` `set`. */
94
+ export declare function excludedAll<Name extends string>(columns: Readonly<Record<Name, AnyPgColumn>>): Partial<Record<Name, SQL>>;
95
+ /** The SQLSTATE of a refused statement; drizzle wraps the driver error in `cause`. */
96
+ export declare function sqlStateOf(error: unknown): string | null;
97
+ //# sourceMappingURL=synced-rows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"synced-rows.d.ts","sourceRoot":"","sources":["../../src/lib/synced-rows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAO,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,uFAAuF;AACvF,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAC3C,UAAU,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAC5C,CAAC,CAAC,CAAC,CAAC;AAEL;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,CAAC,KAAK,SAAS,MAAM,IAC5C;IACE,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACtB,QAAQ,CAAC,EAA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