symmetria 1.1.0 → 2.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 (49) hide show
  1. package/README.md +54 -19
  2. package/dist/binding-BiJH76XX.js +245 -0
  3. package/dist/binding-BiJH76XX.js.map +1 -0
  4. package/dist/{profiling-CrinWe63.d.ts → binding-C_39Pgt8.d.ts} +16 -3
  5. package/dist/bun.d.ts +3 -3
  6. package/dist/bun.js +11 -2
  7. package/dist/bun.js.map +1 -1
  8. package/dist/{compile-B3TD9LbS.js → compile-jL3rWA7P.js} +319 -261
  9. package/dist/compile-jL3rWA7P.js.map +1 -0
  10. package/dist/driver.d.ts +4 -3
  11. package/dist/driver.js +2 -2
  12. package/dist/index-DkXJfVJZ.d.ts +398 -0
  13. package/dist/index.d.ts +4 -4
  14. package/dist/index.js +1419 -465
  15. package/dist/index.js.map +1 -1
  16. package/dist/{inspection-DZf70oHB.js → inspection-XCwdKgbn.js} +3 -4
  17. package/dist/{inspection-DZf70oHB.js.map → inspection-XCwdKgbn.js.map} +1 -1
  18. package/dist/internal.d.ts +6 -2
  19. package/dist/internal.js +4 -4
  20. package/dist/pg-BYalsA8o.d.ts +53 -0
  21. package/dist/{pg-D4y92gPt.js → pg-Cx2W_Lmd.js} +29 -12
  22. package/dist/pg-Cx2W_Lmd.js.map +1 -0
  23. package/dist/pg.d.ts +4 -3
  24. package/dist/pg.js +2 -2
  25. package/dist/{pool-C9sl2iHw.d.ts → pool-BSiopqlE.d.ts} +5 -2
  26. package/dist/pool-CFas0E3j.js +354 -0
  27. package/dist/pool-CFas0E3j.js.map +1 -0
  28. package/dist/{assembly-C4GbrzmO.js → table-CQdO0xkD.js} +1364 -876
  29. package/dist/table-CQdO0xkD.js.map +1 -0
  30. package/dist/{types-BB8ndsIR.d.ts → types-BaS_bFak.d.ts} +1240 -708
  31. package/dist/types-DPWc6nQ9.js +389 -0
  32. package/dist/types-DPWc6nQ9.js.map +1 -0
  33. package/dist/{values-BhrNtVaY.js → values-C7U6IIQZ.js} +2 -3
  34. package/dist/values-C7U6IIQZ.js.map +1 -0
  35. package/dist/vector.d.ts +1 -1
  36. package/dist/vector.js +1 -1
  37. package/package.json +5 -1
  38. package/dist/assembly-C4GbrzmO.js.map +0 -1
  39. package/dist/binding-CD-0xNaB.js +0 -12
  40. package/dist/binding-CD-0xNaB.js.map +0 -1
  41. package/dist/compile-B3TD9LbS.js.map +0 -1
  42. package/dist/index-wLTEGtyg.d.ts +0 -29
  43. package/dist/pg-D4y92gPt.js.map +0 -1
  44. package/dist/pg-DS7w6m9g.d.ts +0 -12
  45. package/dist/pool-OKiwLiBZ.js +0 -240
  46. package/dist/pool-OKiwLiBZ.js.map +0 -1
  47. package/dist/types-BavtzvoV.js +0 -35
  48. package/dist/types-BavtzvoV.js.map +0 -1
  49. package/dist/values-BhrNtVaY.js.map +0 -1
package/README.md CHANGED
@@ -56,6 +56,8 @@ package versions.
56
56
  import {
57
57
  schema,
58
58
  table,
59
+ one,
60
+ many,
59
61
  int,
60
62
  text,
61
63
  bigint,
@@ -67,12 +69,13 @@ const users = table({
67
69
  id: int.auto,
68
70
  name: text,
69
71
  email: text.unique,
72
+ posts: many,
70
73
  });
71
74
 
72
75
  const posts = table({
73
76
  id: int.auto,
74
77
  title: text,
75
- author: users.index,
78
+ author: one(users.posts),
76
79
  views: bigint.default(0n),
77
80
  state: oneOf("draft", "published").default("draft"),
78
81
  createdAt: timestamptz.now,
@@ -81,9 +84,12 @@ const posts = table({
81
84
  export const appSchema = schema({ users, posts });
82
85
  ```
83
86
 
84
- Each table can live in its own module. `author: users.index` declares a foreign
85
- key, its index and the `posts.author` / `users.posts` relationships. Columns are
86
- non-null by default. Property names map from camelCase to snake_case.
87
+ Each table can live in its own module. `author: one(users.posts)` declares a
88
+ foreign key, its index and the `posts.author` relationship, and claims the slot
89
+ `posts: many` that `users` declares for the other side; `maybe()` is the
90
+ optional form, `many(tags.posts)` a many-to-many relation with its junction
91
+ table. `author: users.index` is the earlier spelling of the same key. Columns
92
+ are non-null by default. Property names map from camelCase to snake_case.
87
93
  `users.by("email")` references a unique column instead of the primary key and
88
94
  `users.column("created_by")` keeps a legacy column name. Tables that relate
89
95
  through plain columns declare the join predicate instead:
@@ -224,9 +230,10 @@ const totals = database.users(({ name, posts }) => ({
224
230
  Plain columns aggregate through properties (`posts.sum.views`); expressions use
225
231
  the callback form. Filters and pagination select input rows before aggregation.
226
232
  `sum` / `average` return decimal strings or `null`; `minimum` / `maximum`
227
- preserve the column's value type and codec, plus `null`. Empty or all-NULL value
228
- inputs produce `null`; `count()` returns `0` and `exists()` returns `false` for
229
- empty inputs.
233
+ preserve the column's value type and codec, plus `null`, and order JSON values
234
+ as jsonb does (numbers numerically), booleans, `uuid` and `bytea` too. Empty or
235
+ all-NULL value inputs produce `null`; `count()` returns `0` and `exists()`
236
+ returns `false` for empty inputs.
230
237
 
231
238
  ## Enum mappings
232
239
 
@@ -274,6 +281,14 @@ UPDATE or DELETE without `where()` is refused unless `.all()` confirms it.
274
281
 
275
282
  ## Capabilities
276
283
 
284
+ - Relations declared on both sides (`posts: many`, `author: one(users.posts)`,
285
+ `tags: many(tags.posts)`), checked by the types and when the schema is built.
286
+ - `$batch()`: several reads as one statement, with one snapshot of the data.
287
+ - `get(id)` / `find(id)`, whole-row reads
288
+ (`users({ where: { active: true } })`), object filters and ordering,
289
+ `aggregate()`, `upsert()`, and write filters as options.
290
+ - Error classes for `instanceof`: `NotFoundError`, `UniqueViolation`,
291
+ `ForeignKeyViolation` and the rest, with the constraint, table and column.
277
292
  - Shape-first projections, explicit or FK-inferred JOINs, `some`/`none`/`every`.
278
293
  - CRUD, bulk writes, upserts, unique-key lookups with direct writes, reusable
279
294
  RETURNING projections and atomic nested inserts.
@@ -283,18 +298,28 @@ UPDATE or DELETE without `where()` is refused unless `.all()` confirms it.
283
298
  iteration; `count()` and `exists()` on any table or filtered source.
284
299
  - Transactions, nested savepoints, isolation options and row locks.
285
300
  - `Transaction<typeof database>` for schema-specific transaction helpers.
286
- - `$scope()` filters for reads, updates and deletes, including related tables.
301
+ - `$scope()` filters for reads, updates and deletes, including related tables,
302
+ and checks every row a scoped insert, upsert or update writes, like row-level
303
+ security's `WITH CHECK` (`SYMMETRIA_OUT_OF_SCOPE`); reused and prepared
304
+ queries bind the current tenant at every execution.
287
305
  - Bigint, decimal-string, Date and custom codecs, including nested JSON results;
288
306
  `smallint`, `real`, `doublePrecision`, `date`, `time`, `interval`, `bytea` and
289
307
  `inet` as first-class builders.
290
308
  - Conditional upserts: `doUpdate(values, { where: (current, incoming) => … })`.
291
309
  - Any SQL names: `casing: "preserve"` for camelCase databases such as Prisma's,
292
310
  `.named()` on tables and columns, `.onUpdate.cascade` foreign keys and
293
- `timestamp(3)` columns read as UTC dates.
294
- - Exact arithmetic: `plus`, `minus`, `multiply` and `divide` follow PostgreSQL's
295
- promotion, so `quantity.multiply(price)` is a `Decimal`.
311
+ `timestamp(3)` columns read as UTC dates; enum types named and shared with
312
+ `oneOf(...).typeName("Role")`, collations with `text.collate("C")`,
313
+ `int.auto.byDefault` identities that also accept explicit ids, and derived
314
+ names over 63 bytes shortened with a hash.
315
+ - Exact arithmetic typed as PostgreSQL computes it: `quantity.multiply(price)`
316
+ and `quantity.divide(2)` are `Decimal` (division never truncates),
317
+ `quantity.quotient(2)` is integer division, `real` columns stay floats.
296
318
  - `databaseError(error)` describes unique, foreign-key, not-null and check
297
- violations the same way on both drivers; `one()` errors carry a code.
319
+ violations and lost connections the same way on both drivers; `one()` errors
320
+ carry a code. Invalid values (out-of-range numbers, invalid `jsonb(schema)`
321
+ input, `null` for NOT NULL columns) reject the query's promise when it runs;
322
+ mistakes in the query's shape throw where it is built.
298
323
  - Arrays, full-text search with stored `tsvector` columns, weighted documents,
299
324
  ranking and headlines, pgvector embeddings with distance operators and HNSW
300
325
  indexes (`symmetria/vector`), typed JSON paths and Standard Schema JSON
@@ -343,16 +368,26 @@ const database = createDatabase({
343
368
  });
344
369
  ```
345
370
 
346
- `symmetria/driver` re-exports `symmetria/pg`. Install `pg` when using either;
371
+ `symmetria/driver` re-exports `symmetria/pg`. Install `pg` when using either
372
+ (Symmetria declares the pool options itself, so `@types/pg` is not needed);
347
373
  `symmetria/bun` needs no external database driver. Each accepts a URL or its
348
374
  underlying pool options plus `url` and `profiler`.
349
375
 
350
- Both adapters return `{ rows, affectedRows }`, preserve bigint/numeric
351
- precision, support nested transactions and pinned sessions, and drain accepted
352
- operations on close. Session settings belong to a connection: use
353
- `driver.session()` for multi-statement workflows. For isolated PostgreSQL test
354
- schemas, use `testDatabase()` from `symmetria-kit/testing`, optionally passing a
355
- `driver` factory.
376
+ Both adapters return `{ rows, affectedRows }`, read values the same way,
377
+ preserve bigint/numeric precision, support nested transactions and pinned
378
+ sessions, and drain accepted operations on close. Operations on a transaction or
379
+ session run one at a time in call order. Session settings belong to a
380
+ connection: use `driver.session()` for multi-statement workflows; its connection
381
+ is closed afterwards, so its settings, locks and temporary tables never reach
382
+ other queries. For isolated PostgreSQL test schemas, use `testDatabase()` from
383
+ `symmetria-kit/testing`, optionally passing a `driver` factory.
384
+
385
+ Behind a transaction-mode pooler such as PgBouncer, queries, transactions,
386
+ streams and prepared queries work on both adapters; pass `prepare: false` to
387
+ `symmetria/bun` unless the pooler tracks named statements (PgBouncer 1.21+ with
388
+ `max_prepared_statements`), and set `search_path` on the role rather than in the
389
+ URL. `driver.session()` cannot pin a server connection there. See
390
+ [transaction pooling](https://github.com/nokturnal3301/symmetria/blob/main/docs/reference.md#transaction-pooling-pgbouncer).
356
391
 
357
392
  ## License
358
393
 
@@ -0,0 +1,245 @@
1
+ //#region src/errors.ts
2
+ /** A failure Symmetria itself detected; `code` names it for `switch` and logs. */
3
+ var SymmetriaError = class extends Error {
4
+ name = "SymmetriaError";
5
+ code;
6
+ constructor(message, code, options) {
7
+ super(message, options);
8
+ this.code = code;
9
+ }
10
+ };
11
+ /** `one()`, `get()` or a nested `connect` found no row. */
12
+ var NotFoundError = class extends SymmetriaError {
13
+ name = "NotFoundError";
14
+ table;
15
+ constructor(message, table) {
16
+ super(message, "SYMMETRIA_RECORD_NOT_FOUND");
17
+ this.table = table;
18
+ }
19
+ };
20
+ /** `one()` or `maybeOne()` found more than one row. */
21
+ var TooManyRowsError = class extends SymmetriaError {
22
+ name = "TooManyRowsError";
23
+ table;
24
+ constructor(message, table) {
25
+ super(message, "SYMMETRIA_TOO_MANY_ROWS");
26
+ this.table = table;
27
+ }
28
+ };
29
+ /** A write through a `$scope()` database would leave a row outside the scope. */
30
+ var OutOfScopeError = class extends SymmetriaError {
31
+ name = "OutOfScopeError";
32
+ table;
33
+ constructor(message, table, cause) {
34
+ super(message, "SYMMETRIA_OUT_OF_SCOPE", { cause });
35
+ this.table = table;
36
+ }
37
+ };
38
+ /** Two rows of one upsert share a conflict key. */
39
+ var DuplicateConflictKeyError = class extends SymmetriaError {
40
+ name = "DuplicateConflictKeyError";
41
+ table;
42
+ constructor(message, table) {
43
+ super(message, "SYMMETRIA_DUPLICATE_CONFLICT_KEY");
44
+ this.table = table;
45
+ }
46
+ };
47
+ const RESERVED = /* @__PURE__ */ new Set([
48
+ "name",
49
+ "message",
50
+ "stack",
51
+ "cause"
52
+ ]);
53
+ /**
54
+ * A statement PostgreSQL rejected, or a connection that failed, as the
55
+ * built-in adapters throw it. The driver's own error is the `cause`, and its
56
+ * fields (`code`, `errno`, `hint`, `severity`, …) are copied, so code that
57
+ * read them from the driver error keeps working.
58
+ */
59
+ var QueryError = class extends Error {
60
+ name = "QueryError";
61
+ constructor(message, fields, cause) {
62
+ super(message, { cause });
63
+ if (cause && typeof cause === "object") {
64
+ for (const [key, value] of Object.entries(cause)) if (!RESERVED.has(key)) this[key] = value;
65
+ }
66
+ Object.assign(this, fields);
67
+ }
68
+ };
69
+ /** SQLSTATE 23505: a unique or primary key already holds the value. */
70
+ var UniqueViolation = class extends QueryError {
71
+ name = "UniqueViolation";
72
+ };
73
+ /** SQLSTATE 23503: the referenced row is missing, or a referencing row still exists. */
74
+ var ForeignKeyViolation = class extends QueryError {
75
+ name = "ForeignKeyViolation";
76
+ };
77
+ /** SQLSTATE 23502: NULL in a NOT NULL column. */
78
+ var NotNullViolation = class extends QueryError {
79
+ name = "NotNullViolation";
80
+ };
81
+ /** SQLSTATE 23514: a CHECK constraint failed. */
82
+ var CheckViolation = class extends QueryError {
83
+ name = "CheckViolation";
84
+ };
85
+ /** SQLSTATE 23P01: an exclusion constraint failed. */
86
+ var ExclusionViolation = class extends QueryError {
87
+ name = "ExclusionViolation";
88
+ };
89
+ /** SQLSTATE 40001: a concurrent transaction conflicted; `retries` re-runs it. */
90
+ var SerializationFailure = class extends QueryError {
91
+ name = "SerializationFailure";
92
+ };
93
+ /** SQLSTATE 40P01: PostgreSQL ended the transaction to break a deadlock. */
94
+ var DeadlockDetected = class extends QueryError {
95
+ name = "DeadlockDetected";
96
+ };
97
+ /** The connection was lost or could not be opened. */
98
+ var ConnectionError = class extends QueryError {
99
+ name = "ConnectionError";
100
+ };
101
+ //#endregion
102
+ //#region src/driver/errors.ts
103
+ /**
104
+ * PostgreSQL error inspection shared by the adapters: SQLSTATE lookup, the
105
+ * conflict classes a transaction may retry and failed `$scope()` write checks.
106
+ */
107
+ /** The five-character SQLSTATE of a server error (`code` on pg, `errno` on Bun). */
108
+ const sqlState = (error) => {
109
+ if (!error || typeof error !== "object") return;
110
+ const value = error;
111
+ return [value.code, value.errno].find((code) => typeof code === "string" && /^[0-9A-Z]{5}$/.test(code));
112
+ };
113
+ /**
114
+ * The text a failed `$scope()` write check casts to boolean (see the
115
+ * compiler's scope checks), so PostgreSQL aborts the statement with 22P02 and
116
+ * an error that names the check: the statement's own rows (`insert`, `update`)
117
+ * or the existing row of an upsert conflict (`conflict`), and the table.
118
+ */
119
+ const scopeViolationText = (check, table) => `SYMMETRIA_OUT_OF_SCOPE:${check}:${encodeURIComponent(table)}:`;
120
+ /** The text in PostgreSQL's message, whose quotes depend on `lc_messages`. */
121
+ const SCOPE_VIOLATION = /SYMMETRIA_OUT_OF_SCOPE:(insert|update|conflict):([^:]*):\d+/;
122
+ /**
123
+ * PostgreSQL's error for a failed scope check as `SYMMETRIA_OUT_OF_SCOPE`,
124
+ * naming the table, with the driver error as its cause; other errors pass
125
+ * through. Writes and transaction scopes both apply it, so a transaction that
126
+ * a caught violation aborted reports the same error.
127
+ */
128
+ const scopeViolation = (error) => {
129
+ const failed = sqlState(error) === "22P02" ? SCOPE_VIOLATION.exec(String(error.message)) : null;
130
+ if (!failed) return error;
131
+ const table = decodeURIComponent(failed[2]);
132
+ return new OutOfScopeError(failed[1] === "conflict" ? `symmetria: upsert on "${table}" conflicted with a row outside the database scope` : `symmetria: ${failed[1]} on "${table}" would write a row outside the database scope`, table, error);
133
+ };
134
+ /** serialization_failure and deadlock_detected: the transaction can be re-run from the start. */
135
+ const isRetryableTransactionError = (error) => {
136
+ const state = sqlState(error);
137
+ return state === "40001" || state === "40P01";
138
+ };
139
+ /** Connection exceptions (class 08) and the shutdowns that end a session (57P01–57P05). */
140
+ const connectionState = (state) => state.startsWith("08") || /^57P0[1-5]$/.test(state);
141
+ /** Socket and pool failures, which carry no SQLSTATE. */
142
+ const NODE_POSTGRES_CONNECTION = /^(Connection terminated|Client has encountered a connection error|Client was closed|timeout exceeded when trying to connect)/;
143
+ const SOCKET_CODES = /* @__PURE__ */ new Set([
144
+ "ECONNREFUSED",
145
+ "ECONNRESET",
146
+ "ECONNABORTED",
147
+ "EPIPE",
148
+ "ETIMEDOUT",
149
+ "EHOSTUNREACH",
150
+ "ENETUNREACH",
151
+ "ENOTFOUND",
152
+ "EAI_AGAIN"
153
+ ]);
154
+ /**
155
+ * Whether the connection itself failed, rather than a statement: the server
156
+ * ended the session (class 08, 57P01–57P05), a socket error, or a client-side
157
+ * connection loss (`Connection terminated unexpectedly` on node-postgres,
158
+ * `ERR_POSTGRES_CONNECTION_CLOSED` and similar on Bun).
159
+ */
160
+ const isConnectionError = (error) => {
161
+ if (!error || typeof error !== "object") return false;
162
+ const state = sqlState(error);
163
+ if (state) return connectionState(state);
164
+ const { code, message } = error;
165
+ return typeof code === "string" && (SOCKET_CODES.has(code) || /^ERR_POSTGRES_(CONNECTION|IDLE|LIFETIME|TLS)_/.test(code)) || typeof message === "string" && NODE_POSTGRES_CONNECTION.test(message);
166
+ };
167
+ const KINDS = {
168
+ "23505": "unique",
169
+ "23503": "foreign-key",
170
+ "23502": "not-null",
171
+ "23514": "check",
172
+ "23P01": "exclusion",
173
+ "40001": "serialization",
174
+ "40P01": "deadlock"
175
+ };
176
+ /** Failures to open a connection, as opposed to losing one. */
177
+ const UNREACHABLE = /^(ECONNREFUSED|EHOSTUNREACH|ENETUNREACH|ENOTFOUND|EAI_AGAIN|ERR_POSTGRES_CONNECTION_(REFUSED|TIMEOUT)|ERR_POSTGRES_TLS_.+)$/;
178
+ /** 08001 (unable to connect) or 08006 (connection_failure) for a connection error without a SQLSTATE. */
179
+ const connectionFailureState = (error) => {
180
+ if (!isConnectionError(error)) return;
181
+ const { code, message } = error;
182
+ return UNREACHABLE.test(String(code)) || /^timeout exceeded when trying to connect/.test(String(message)) ? "08001" : "08006";
183
+ };
184
+ /**
185
+ * The server error behind a failed query, normalized across both drivers, or
186
+ * undefined for anything else (symmetria errors, programming errors):
187
+ * `if (databaseError(error)?.kind === "unique") …`. A lost or refused
188
+ * connection is `kind: "connection"` on both drivers; without a server
189
+ * SQLSTATE it reports 08006 (connection_failure) or 08001 (unable to connect).
190
+ */
191
+ const databaseError = (error) => {
192
+ const state = sqlState(error) ?? connectionFailureState(error);
193
+ if (!state) return;
194
+ const fields = error;
195
+ const text = (name) => typeof fields[name] === "string" && fields[name] !== "" ? fields[name] : void 0;
196
+ const message = error instanceof Error ? error.message : String(error);
197
+ const column = text("column") ?? /null value in column "([^"]+)"/.exec(message)?.[1];
198
+ const table = text("table");
199
+ const constraint = text("constraint");
200
+ const detail = text("detail");
201
+ return Object.freeze({
202
+ kind: KINDS[state] ?? (connectionState(state) ? "connection" : "other"),
203
+ sqlState: state,
204
+ message,
205
+ ...table ? { table } : {},
206
+ ...column ? { column } : {},
207
+ ...constraint ? { constraint } : {},
208
+ ...detail ? { detail } : {}
209
+ });
210
+ };
211
+ const CLASSES = {
212
+ unique: UniqueViolation,
213
+ "foreign-key": ForeignKeyViolation,
214
+ "not-null": NotNullViolation,
215
+ check: CheckViolation,
216
+ exclusion: ExclusionViolation,
217
+ serialization: SerializationFailure,
218
+ deadlock: DeadlockDetected,
219
+ connection: ConnectionError
220
+ };
221
+ /**
222
+ * A driver's database error as its `QueryError` class, with the driver error
223
+ * as the cause; anything that did not come from the database, and an error
224
+ * that is wrapped already, passes through unchanged.
225
+ */
226
+ const queryError = (error) => {
227
+ if (error instanceof QueryError) return error;
228
+ const described = databaseError(error);
229
+ if (!described) return error;
230
+ const { message, ...fields } = described;
231
+ return new (CLASSES[fields.kind] ?? QueryError)(message, fields, error);
232
+ };
233
+ //#endregion
234
+ //#region src/schema/binding.ts
235
+ /** Rebind compiled schema metadata without evaluating declaration callbacks again. */
236
+ const SCHEMA_BIND = Symbol("symmetria.schema.bind");
237
+ /** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */
238
+ const createDatabase = ({ schema: model, driver }) => {
239
+ if (!model || typeof model[SCHEMA_BIND] !== "function") throw new Error("symmetria: createDatabase() expects a schema() declaration");
240
+ return model[SCHEMA_BIND](driver);
241
+ };
242
+ //#endregion
243
+ export { UniqueViolation as C, TooManyRowsError as S, NotNullViolation as _, isRetryableTransactionError as a, SerializationFailure as b, scopeViolationText as c, ConnectionError as d, DeadlockDetected as f, NotFoundError as g, ForeignKeyViolation as h, isConnectionError as i, sqlState as l, ExclusionViolation as m, createDatabase as n, queryError as o, DuplicateConflictKeyError as p, databaseError as r, scopeViolation as s, SCHEMA_BIND as t, CheckViolation as u, OutOfScopeError as v, SymmetriaError as x, QueryError as y };
244
+
245
+ //# sourceMappingURL=binding-BiJH76XX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding-BiJH76XX.js","names":[],"sources":["../src/errors.ts","../src/driver/errors.ts","../src/schema/binding.ts"],"sourcesContent":["/**\n * Error classes: Symmetria's own failures carry a `code`, and database\n * failures from the built-in adapters carry what PostgreSQL reported, so both\n * can be told apart with `instanceof`.\n */\nimport type { DatabaseErrorKind } from \"./driver/errors\";\n\n/** A failure Symmetria itself detected; `code` names it for `switch` and logs. */\nexport class SymmetriaError extends Error {\n override name = \"SymmetriaError\";\n readonly code: string;\n\n constructor(message: string, code: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** `one()`, `get()` or a nested `connect` found no row. */\nexport class NotFoundError extends SymmetriaError {\n override name = \"NotFoundError\";\n readonly table: string;\n\n constructor(message: string, table: string) {\n super(message, \"SYMMETRIA_RECORD_NOT_FOUND\");\n this.table = table;\n }\n}\n\n/** `one()` or `maybeOne()` found more than one row. */\nexport class TooManyRowsError extends SymmetriaError {\n override name = \"TooManyRowsError\";\n readonly table: string;\n\n constructor(message: string, table: string) {\n super(message, \"SYMMETRIA_TOO_MANY_ROWS\");\n this.table = table;\n }\n}\n\n/** A write through a `$scope()` database would leave a row outside the scope. */\nexport class OutOfScopeError extends SymmetriaError {\n override name = \"OutOfScopeError\";\n readonly table: string;\n\n constructor(message: string, table: string, cause: unknown) {\n super(message, \"SYMMETRIA_OUT_OF_SCOPE\", { cause });\n this.table = table;\n }\n}\n\n/** Two rows of one upsert share a conflict key. */\nexport class DuplicateConflictKeyError extends SymmetriaError {\n override name = \"DuplicateConflictKeyError\";\n readonly table: string;\n\n constructor(message: string, table: string) {\n super(message, \"SYMMETRIA_DUPLICATE_CONFLICT_KEY\");\n this.table = table;\n }\n}\n\n/** What `QueryError` takes from the driver error it wraps. */\nexport type QueryErrorFields = {\n readonly kind: DatabaseErrorKind;\n readonly sqlState: string;\n readonly table?: string;\n readonly column?: string;\n readonly constraint?: string;\n readonly detail?: string;\n};\n\nconst RESERVED = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * A statement PostgreSQL rejected, or a connection that failed, as the\n * built-in adapters throw it. The driver's own error is the `cause`, and its\n * fields (`code`, `errno`, `hint`, `severity`, …) are copied, so code that\n * read them from the driver error keeps working.\n */\nexport class QueryError extends Error {\n override name = \"QueryError\";\n /** What was violated; `\"other\"` for every SQLSTATE without a class of its own. */\n declare readonly kind: DatabaseErrorKind;\n /** The five-character SQLSTATE, such as `23505`. */\n declare readonly sqlState: string;\n declare readonly table?: string;\n declare readonly column?: string;\n declare readonly constraint?: string;\n /** PostgreSQL's DETAIL, such as `Key (email)=(ada@example.com) already exists.` */\n declare readonly detail?: string;\n\n constructor(message: string, fields: QueryErrorFields, cause: unknown) {\n super(message, { cause });\n\n if (cause && typeof cause === \"object\") {\n for (const [key, value] of Object.entries(cause)) {\n if (!RESERVED.has(key)) {\n (this as Record<string, unknown>)[key] = value;\n }\n }\n }\n\n Object.assign(this, fields);\n }\n}\n\n/** SQLSTATE 23505: a unique or primary key already holds the value. */\nexport class UniqueViolation extends QueryError {\n override name = \"UniqueViolation\";\n}\n\n/** SQLSTATE 23503: the referenced row is missing, or a referencing row still exists. */\nexport class ForeignKeyViolation extends QueryError {\n override name = \"ForeignKeyViolation\";\n}\n\n/** SQLSTATE 23502: NULL in a NOT NULL column. */\nexport class NotNullViolation extends QueryError {\n override name = \"NotNullViolation\";\n}\n\n/** SQLSTATE 23514: a CHECK constraint failed. */\nexport class CheckViolation extends QueryError {\n override name = \"CheckViolation\";\n}\n\n/** SQLSTATE 23P01: an exclusion constraint failed. */\nexport class ExclusionViolation extends QueryError {\n override name = \"ExclusionViolation\";\n}\n\n/** SQLSTATE 40001: a concurrent transaction conflicted; `retries` re-runs it. */\nexport class SerializationFailure extends QueryError {\n override name = \"SerializationFailure\";\n}\n\n/** SQLSTATE 40P01: PostgreSQL ended the transaction to break a deadlock. */\nexport class DeadlockDetected extends QueryError {\n override name = \"DeadlockDetected\";\n}\n\n/** The connection was lost or could not be opened. */\nexport class ConnectionError extends QueryError {\n override name = \"ConnectionError\";\n}\n","/**\n * PostgreSQL error inspection shared by the adapters: SQLSTATE lookup, the\n * conflict classes a transaction may retry and failed `$scope()` write checks.\n */\n\nimport {\n CheckViolation,\n ConnectionError,\n DeadlockDetected,\n ExclusionViolation,\n ForeignKeyViolation,\n NotNullViolation,\n OutOfScopeError,\n QueryError,\n SerializationFailure,\n UniqueViolation,\n} from \"../errors\";\n\n/** The five-character SQLSTATE of a server error (`code` on pg, `errno` on Bun). */\nexport const sqlState = (error: unknown): string | undefined => {\n if (!error || typeof error !== \"object\") {\n return undefined;\n }\n\n const value = error as { code?: unknown; errno?: unknown };\n\n return [value.code, value.errno].find(\n (code): code is string =>\n typeof code === \"string\" && /^[0-9A-Z]{5}$/.test(code),\n );\n};\n\n/**\n * The text a failed `$scope()` write check casts to boolean (see the\n * compiler's scope checks), so PostgreSQL aborts the statement with 22P02 and\n * an error that names the check: the statement's own rows (`insert`, `update`)\n * or the existing row of an upsert conflict (`conflict`), and the table.\n */\nexport const scopeViolationText = (\n check: \"insert\" | \"update\" | \"conflict\",\n table: string,\n): string => `SYMMETRIA_OUT_OF_SCOPE:${check}:${encodeURIComponent(table)}:`;\n\n/** The text in PostgreSQL's message, whose quotes depend on `lc_messages`. */\nconst SCOPE_VIOLATION =\n /SYMMETRIA_OUT_OF_SCOPE:(insert|update|conflict):([^:]*):\\d+/;\n\n/**\n * PostgreSQL's error for a failed scope check as `SYMMETRIA_OUT_OF_SCOPE`,\n * naming the table, with the driver error as its cause; other errors pass\n * through. Writes and transaction scopes both apply it, so a transaction that\n * a caught violation aborted reports the same error.\n */\nexport const scopeViolation = (error: unknown): unknown => {\n const failed =\n sqlState(error) === \"22P02\"\n ? SCOPE_VIOLATION.exec(String((error as { message?: unknown }).message))\n : null;\n\n if (!failed) {\n return error;\n }\n\n const table = decodeURIComponent(failed[2]!);\n\n return new OutOfScopeError(\n failed[1] === \"conflict\"\n ? `symmetria: upsert on \"${table}\" conflicted with a row outside the database scope`\n : `symmetria: ${failed[1]} on \"${table}\" would write a row outside the database scope`,\n table,\n error,\n );\n};\n\n/** serialization_failure and deadlock_detected: the transaction can be re-run from the start. */\nexport const isRetryableTransactionError = (error: unknown): boolean => {\n const state = sqlState(error);\n\n return state === \"40001\" || state === \"40P01\";\n};\n\n/** Connection exceptions (class 08) and the shutdowns that end a session (57P01–57P05). */\nconst connectionState = (state: string): boolean =>\n state.startsWith(\"08\") || /^57P0[1-5]$/.test(state);\n\n/** Socket and pool failures, which carry no SQLSTATE. */\nconst NODE_POSTGRES_CONNECTION =\n /^(Connection terminated|Client has encountered a connection error|Client was closed|timeout exceeded when trying to connect)/;\nconst SOCKET_CODES = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ECONNABORTED\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"EHOSTUNREACH\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n\n/**\n * Whether the connection itself failed, rather than a statement: the server\n * ended the session (class 08, 57P01–57P05), a socket error, or a client-side\n * connection loss (`Connection terminated unexpectedly` on node-postgres,\n * `ERR_POSTGRES_CONNECTION_CLOSED` and similar on Bun).\n */\nexport const isConnectionError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n\n const state = sqlState(error);\n\n if (state) {\n return connectionState(state);\n }\n\n const { code, message } = error as { code?: unknown; message?: unknown };\n\n return (\n (typeof code === \"string\" &&\n (SOCKET_CODES.has(code) ||\n /^ERR_POSTGRES_(CONNECTION|IDLE|LIFETIME|TLS)_/.test(code))) ||\n (typeof message === \"string\" && NODE_POSTGRES_CONNECTION.test(message))\n );\n};\n\n/** What a failed statement violated, by SQLSTATE class, or `connection` when the connection was lost. */\nexport type DatabaseErrorKind =\n | \"unique\"\n | \"foreign-key\"\n | \"not-null\"\n | \"check\"\n | \"exclusion\"\n | \"serialization\"\n | \"deadlock\"\n | \"connection\"\n | \"other\";\n\n/** A server error described the same way for node-postgres and Bun.SQL. */\nexport type DatabaseError = {\n readonly kind: DatabaseErrorKind;\n readonly sqlState: string;\n readonly message: string;\n readonly table?: string;\n readonly column?: string;\n readonly constraint?: string;\n /** PostgreSQL's DETAIL, such as `Key (email)=(ada@example.com) already exists.` */\n readonly detail?: string;\n};\n\nconst KINDS: Record<string, DatabaseErrorKind> = {\n \"23505\": \"unique\",\n \"23503\": \"foreign-key\",\n \"23502\": \"not-null\",\n \"23514\": \"check\",\n \"23P01\": \"exclusion\",\n \"40001\": \"serialization\",\n \"40P01\": \"deadlock\",\n};\n\n/** Failures to open a connection, as opposed to losing one. */\nconst UNREACHABLE =\n /^(ECONNREFUSED|EHOSTUNREACH|ENETUNREACH|ENOTFOUND|EAI_AGAIN|ERR_POSTGRES_CONNECTION_(REFUSED|TIMEOUT)|ERR_POSTGRES_TLS_.+)$/;\n\n/** 08001 (unable to connect) or 08006 (connection_failure) for a connection error without a SQLSTATE. */\nconst connectionFailureState = (error: unknown): string | undefined => {\n if (!isConnectionError(error)) {\n return undefined;\n }\n\n const { code, message } = error as { code?: unknown; message?: unknown };\n\n return UNREACHABLE.test(String(code)) ||\n /^timeout exceeded when trying to connect/.test(String(message))\n ? \"08001\"\n : \"08006\";\n};\n\n/**\n * The server error behind a failed query, normalized across both drivers, or\n * undefined for anything else (symmetria errors, programming errors):\n * `if (databaseError(error)?.kind === \"unique\") …`. A lost or refused\n * connection is `kind: \"connection\"` on both drivers; without a server\n * SQLSTATE it reports 08006 (connection_failure) or 08001 (unable to connect).\n */\nexport const databaseError = (error: unknown): DatabaseError | undefined => {\n const state = sqlState(error) ?? connectionFailureState(error);\n\n if (!state) {\n return undefined;\n }\n\n const fields = error as Record<string, unknown>;\n const text = (name: string): string | undefined =>\n typeof fields[name] === \"string\" && fields[name] !== \"\"\n ? (fields[name] as string)\n : undefined;\n const message = error instanceof Error ? error.message : String(error);\n // node-postgres omits the column of a NOT NULL violation; its message names it.\n const column =\n text(\"column\") ?? /null value in column \"([^\"]+)\"/.exec(message)?.[1];\n const table = text(\"table\");\n const constraint = text(\"constraint\");\n const detail = text(\"detail\");\n\n return Object.freeze({\n kind: KINDS[state] ?? (connectionState(state) ? \"connection\" : \"other\"),\n sqlState: state,\n message,\n ...(table ? { table } : {}),\n ...(column ? { column } : {}),\n ...(constraint ? { constraint } : {}),\n ...(detail ? { detail } : {}),\n });\n};\n\nconst CLASSES: Partial<Record<DatabaseErrorKind, typeof QueryError>> = {\n unique: UniqueViolation,\n \"foreign-key\": ForeignKeyViolation,\n \"not-null\": NotNullViolation,\n check: CheckViolation,\n exclusion: ExclusionViolation,\n serialization: SerializationFailure,\n deadlock: DeadlockDetected,\n connection: ConnectionError,\n};\n\n/**\n * A driver's database error as its `QueryError` class, with the driver error\n * as the cause; anything that did not come from the database, and an error\n * that is wrapped already, passes through unchanged.\n */\nexport const queryError = (error: unknown): unknown => {\n if (error instanceof QueryError) {\n return error;\n }\n\n const described = databaseError(error);\n\n if (!described) {\n return error;\n }\n\n const { message, ...fields } = described;\n\n return new (CLASSES[fields.kind] ?? QueryError)(message, fields, error);\n};\n","import type { Driver } from \"../query/plan/types\";\n\n/** Rebind compiled schema metadata without evaluating declaration callbacks again. */\nexport const SCHEMA_BIND = Symbol(\"symmetria.schema.bind\");\nexport type BindableSchema = {\n readonly [SCHEMA_BIND]: (driver: Driver) => unknown;\n};\n\nexport type DatabaseOptions<Model extends BindableSchema> = {\n readonly schema: Model;\n readonly driver: Driver;\n};\n\n/** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */\nexport const createDatabase = <Model extends BindableSchema>({\n schema: model,\n driver,\n}: DatabaseOptions<Model>): ReturnType<Model[typeof SCHEMA_BIND]> => {\n if (!model || typeof model[SCHEMA_BIND] !== \"function\") {\n throw new Error(\n \"symmetria: createDatabase() expects a schema() declaration\",\n );\n }\n\n return model[SCHEMA_BIND](driver) as ReturnType<Model[typeof SCHEMA_BIND]>;\n};\n"],"mappings":";;AAQA,IAAa,iBAAb,cAAoC,MAAM;CACxC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AI,CAAC;CAC7B,CAAC;AACH;AAEA,MAAM,UAAiE;CACrE,QAAQ;CACR,eAAe;CACf,YAAY;CACZ,OAAO;CACP,WAAW;CACX,eAAe;CACf,UAAU;CACV,YAAY;AACd;;;;;;AAOA,MAAa,cAAc,UAA4B;CACrD,IAAI,iBAAiB,YACnB,OAAO;CAGT,MAAM,YAAY,cAAc,KAAK;CAErC,IAAI,CAAC,WACH,OAAO;CAGT,MAAM,EAAE,SAAS,GAAG,WAAW;CAE/B,OAAO,KAAK,QAAQ,OAAO,SAAS,YAAY,SAAS,QAAQ,KAAK;AACxE;;;;ACpPA,MAAa,cAAc,OAAO,uBAAuB;;AAWzD,MAAa,kBAAgD,EAC3D,QAAQ,OACR,aACmE;CACnE,IAAI,CAAC,SAAS,OAAO,MAAM,iBAAiB,YAC1C,MAAM,IAAI,MACR,4DACF;CAGF,OAAO,MAAM,YAAY,CAAC,MAAM;AAClC"}
@@ -1,4 +1,4 @@
1
- import { r as Driver } from "./types-BB8ndsIR.js";
1
+ import { r as Driver } from "./types-BaS_bFak.js";
2
2
  //#region src/observability/profiling.d.ts
3
3
  type ProfiledQuery = {
4
4
  id: number;
@@ -52,5 +52,18 @@ declare const createProfiler: (options?: {
52
52
  }>;
53
53
  type QueryProfiler = ReturnType<typeof createProfiler>;
54
54
  //#endregion
55
- export { createProfiler as i, ProfiledRequest as n, QueryProfiler as r, ProfiledQuery as t };
56
- //# sourceMappingURL=profiling-CrinWe63.d.ts.map
55
+ //#region src/schema/binding.d.ts
56
+ /** Rebind compiled schema metadata without evaluating declaration callbacks again. */
57
+ declare const SCHEMA_BIND: unique symbol;
58
+ type BindableSchema = {
59
+ readonly [SCHEMA_BIND]: (driver: Driver) => unknown;
60
+ };
61
+ type DatabaseOptions<Model extends BindableSchema> = {
62
+ readonly schema: Model;
63
+ readonly driver: Driver;
64
+ };
65
+ /** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */
66
+ declare const createDatabase: <Model extends BindableSchema>({ schema: model, driver }: DatabaseOptions<Model>) => ReturnType<Model[typeof SCHEMA_BIND]>;
67
+ //#endregion
68
+ export { ProfiledQuery as a, createProfiler as c, createDatabase as i, DatabaseOptions as n, ProfiledRequest as o, SCHEMA_BIND as r, QueryProfiler as s, BindableSchema as t };
69
+ //# sourceMappingURL=binding-C_39Pgt8.d.ts.map
package/dist/bun.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Y as SCHEMA_BIND, c as SessionDriver, l as TransactionDriver, q as BindableSchema, r as Driver } from "./types-BB8ndsIR.js";
2
- import { r as QueryProfiler } from "./profiling-CrinWe63.js";
3
- import { t as PostgresDriver } from "./pool-C9sl2iHw.js";
1
+ import { c as SessionDriver, l as TransactionDriver, r as Driver } from "./types-BaS_bFak.js";
2
+ import { r as SCHEMA_BIND, s as QueryProfiler, t as BindableSchema } from "./binding-C_39Pgt8.js";
3
+ import { t as PostgresDriver } from "./pool-BSiopqlE.js";
4
4
  import { SQL } from "bun";
5
5
  //#region src/driver/bun.d.ts
6
6
  type PostgresOptions = Omit<SQL.PostgresOrMySQLOptions, "adapter" | "bigint"> & {
package/dist/bun.js CHANGED
@@ -1,7 +1,10 @@
1
- import { t as SCHEMA_BIND } from "./binding-CD-0xNaB.js";
2
- import { n as postgresParameters, t as createPostgresDriver } from "./pool-OKiwLiBZ.js";
1
+ import { t as SCHEMA_BIND } from "./binding-BiJH76XX.js";
2
+ import { n as postgresParameters, t as createPostgresDriver } from "./pool-CFas0E3j.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.ts
5
+ /**
6
+ * `symmetria/bun`: PostgreSQL adapter built on Bun's SQL pool.
7
+ */
5
8
  /** Bun reports socket-level failures with ERR_POSTGRES_* codes; server errors carry SQLSTATE codes. */
6
9
  const transportFailure = (error) => {
7
10
  const code = error.code;
@@ -37,6 +40,12 @@ const postgres = (connection) => {
37
40
  return;
38
41
  }
39
42
  reserved.unsafe("ROLLBACK").catch(() => {}).finally(() => reserved.release());
43
+ },
44
+ discard: async () => {
45
+ if (!released) {
46
+ released = true;
47
+ await reserved.close().catch(() => {});
48
+ }
40
49
  }
41
50
  };
42
51
  },
package/dist/bun.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bun.js","names":[],"sources":["../src/driver/bun.ts"],"sourcesContent":["import { SQL } from \"bun\";\nimport { createPostgresDriver, type PostgresDriver } from \"./pool\";\nimport { postgresParameters } from \"./parameters\";\nimport type { CompiledQuery, ExecutionResult } from \"../query/plan/types\";\nimport type { QueryProfiler } from \"../observability/profiling\";\n\nexport type PostgresOptions = Omit<\n SQL.PostgresOrMySQLOptions,\n \"adapter\" | \"bigint\"\n> & { readonly profiler?: QueryProfiler | undefined };\nexport type { PostgresDriver } from \"./pool\";\n\n/** Bun reports socket-level failures with ERR_POSTGRES_* codes; server errors carry SQLSTATE codes. */\nconst transportFailure = (error: Error): boolean => {\n const code: unknown = (error as { code?: unknown }).code;\n\n return typeof code === \"string\" && code.startsWith(\"ERR_\");\n};\n\nexport const postgres = (\n connection: string | PostgresOptions,\n): PostgresDriver => {\n const { profiler, ...options } =\n typeof connection === \"string\" ? { url: connection } : connection;\n const client = new SQL({ ...options, adapter: \"postgres\", bigint: true });\n let cancellation: SQL | undefined;\n\n const execute = async (\n connection: SQL,\n query: CompiledQuery,\n ): Promise<ExecutionResult> => {\n const result = await connection.unsafe<Record<string, unknown>[]>(\n query.sql,\n postgresParameters(query.parameters),\n );\n\n return {\n rows: Array.from(result),\n affectedRows: (result as { count?: number }).count ?? result.length,\n };\n };\n\n return createPostgresDriver(\n {\n execute: (query) => execute(client, query),\n connect: async () => {\n const reserved = await client.reserve();\n let released = false;\n\n return {\n execute: (query) => execute(reserved, query),\n release: (error) => {\n if (released) {\n return;\n }\n\n released = true;\n\n if (!error || transportFailure(error)) {\n reserved.release();\n\n return;\n }\n\n void reserved\n .unsafe(\"ROLLBACK\")\n .catch(() => {})\n .finally(() => reserved.release());\n },\n };\n },\n cancel: async (pid) => {\n cancellation ??= new SQL({\n ...options,\n adapter: \"postgres\",\n bigint: true,\n max: 1,\n });\n\n await cancellation.unsafe(\"SELECT pg_cancel_backend($1)\", [pid]);\n },\n close: async () => {\n try {\n await client.close();\n } finally {\n await cancellation?.close();\n }\n },\n },\n profiler,\n );\n};\n"],"mappings":";;;;;AAaA,MAAM,oBAAoB,UAA0B;CAClD,MAAM,OAAiB,MAA6B;CAEpD,OAAO,OAAO,SAAS,YAAY,KAAK,WAAW,MAAM;AAC3D;AAEA,MAAa,YACX,eACmB;CACnB,MAAM,EAAE,UAAU,GAAG,YACnB,OAAO,eAAe,WAAW,EAAE,KAAK,WAAW,IAAI;CACzD,MAAM,SAAS,IAAI,IAAI;EAAE,GAAG;EAAS,SAAS;EAAY,QAAQ;CAAK,CAAC;CACxE,IAAI;CAEJ,MAAM,UAAU,OACd,YACA,UAC6B;EAC7B,MAAM,SAAS,MAAM,WAAW,OAC9B,MAAM,KACN,mBAAmB,MAAM,UAAU,CACrC;EAEA,OAAO;GACL,MAAM,MAAM,KAAK,MAAM;GACvB,cAAe,OAA8B,SAAS,OAAO;EAC/D;CACF;CAEA,OAAO,qBACL;EACE,UAAU,UAAU,QAAQ,QAAQ,KAAK;EACzC,SAAS,YAAY;GACnB,MAAM,WAAW,MAAM,OAAO,QAAQ;GACtC,IAAI,WAAW;GAEf,OAAO;IACL,UAAU,UAAU,QAAQ,UAAU,KAAK;IAC3C,UAAU,UAAU;KAClB,IAAI,UACF;KAGF,WAAW;KAEX,IAAI,CAAC,SAAS,iBAAiB,KAAK,GAAG;MACrC,SAAS,QAAQ;MAEjB;KACF;KAEA,SACG,OAAO,UAAU,CAAC,CAClB,YAAY,CAAC,CAAC,CAAC,CACf,cAAc,SAAS,QAAQ,CAAC;IACrC;GACF;EACF;EACA,QAAQ,OAAO,QAAQ;GACrB,iBAAiB,IAAI,IAAI;IACvB,GAAG;IACH,SAAS;IACT,QAAQ;IACR,KAAK;GACP,CAAC;GAED,MAAM,aAAa,OAAO,gCAAgC,CAAC,GAAG,CAAC;EACjE;EACA,OAAO,YAAY;GACjB,IAAI;IACF,MAAM,OAAO,MAAM;GACrB,UAAU;IACR,MAAM,cAAc,MAAM;GAC5B;EACF;CACF,GACA,QACF;AACF"}
1
+ {"version":3,"file":"bun.js","names":[],"sources":["../src/driver/bun.ts"],"sourcesContent":["/**\n * `symmetria/bun`: PostgreSQL adapter built on Bun's SQL pool.\n */\nimport { SQL } from \"bun\";\nimport { createPostgresDriver, type PostgresDriver } from \"./pool\";\nimport { postgresParameters } from \"./parameters\";\nimport type { CompiledQuery, ExecutionResult } from \"../query/plan/types\";\nimport type { QueryProfiler } from \"../observability/profiling\";\n\nexport type PostgresOptions = Omit<\n SQL.PostgresOrMySQLOptions,\n \"adapter\" | \"bigint\"\n> & { readonly profiler?: QueryProfiler | undefined };\nexport type { PostgresDriver } from \"./pool\";\n\n/** Bun reports socket-level failures with ERR_POSTGRES_* codes; server errors carry SQLSTATE codes. */\nconst transportFailure = (error: Error): boolean => {\n const code: unknown = (error as { code?: unknown }).code;\n\n return typeof code === \"string\" && code.startsWith(\"ERR_\");\n};\n\nexport const postgres = (\n connection: string | PostgresOptions,\n): PostgresDriver => {\n const { profiler, ...options } =\n typeof connection === \"string\" ? { url: connection } : connection;\n const client = new SQL({ ...options, adapter: \"postgres\", bigint: true });\n let cancellation: SQL | undefined;\n\n const execute = async (\n connection: SQL,\n query: CompiledQuery,\n ): Promise<ExecutionResult> => {\n const result = await connection.unsafe<Record<string, unknown>[]>(\n query.sql,\n postgresParameters(query.parameters),\n );\n\n return {\n rows: Array.from(result),\n affectedRows: (result as { count?: number }).count ?? result.length,\n };\n };\n\n return createPostgresDriver(\n {\n execute: (query) => execute(client, query),\n connect: async () => {\n const reserved = await client.reserve();\n let released = false;\n\n return {\n execute: (query) => execute(reserved, query),\n release: (error) => {\n if (released) {\n return;\n }\n\n released = true;\n\n if (!error || transportFailure(error)) {\n reserved.release();\n\n return;\n }\n\n void reserved\n .unsafe(\"ROLLBACK\")\n .catch(() => {})\n .finally(() => reserved.release());\n },\n // Closing a reserved connection frees its pool slot for a fresh one.\n discard: async () => {\n if (!released) {\n released = true;\n await reserved.close().catch(() => {});\n }\n },\n };\n },\n cancel: async (pid) => {\n cancellation ??= new SQL({\n ...options,\n adapter: \"postgres\",\n bigint: true,\n max: 1,\n });\n\n await cancellation.unsafe(\"SELECT pg_cancel_backend($1)\", [pid]);\n },\n close: async () => {\n try {\n await client.close();\n } finally {\n await cancellation?.close();\n }\n },\n },\n profiler,\n );\n};\n"],"mappings":";;;;;;;;AAgBA,MAAM,oBAAoB,UAA0B;CAClD,MAAM,OAAiB,MAA6B;CAEpD,OAAO,OAAO,SAAS,YAAY,KAAK,WAAW,MAAM;AAC3D;AAEA,MAAa,YACX,eACmB;CACnB,MAAM,EAAE,UAAU,GAAG,YACnB,OAAO,eAAe,WAAW,EAAE,KAAK,WAAW,IAAI;CACzD,MAAM,SAAS,IAAI,IAAI;EAAE,GAAG;EAAS,SAAS;EAAY,QAAQ;CAAK,CAAC;CACxE,IAAI;CAEJ,MAAM,UAAU,OACd,YACA,UAC6B;EAC7B,MAAM,SAAS,MAAM,WAAW,OAC9B,MAAM,KACN,mBAAmB,MAAM,UAAU,CACrC;EAEA,OAAO;GACL,MAAM,MAAM,KAAK,MAAM;GACvB,cAAe,OAA8B,SAAS,OAAO;EAC/D;CACF;CAEA,OAAO,qBACL;EACE,UAAU,UAAU,QAAQ,QAAQ,KAAK;EACzC,SAAS,YAAY;GACnB,MAAM,WAAW,MAAM,OAAO,QAAQ;GACtC,IAAI,WAAW;GAEf,OAAO;IACL,UAAU,UAAU,QAAQ,UAAU,KAAK;IAC3C,UAAU,UAAU;KAClB,IAAI,UACF;KAGF,WAAW;KAEX,IAAI,CAAC,SAAS,iBAAiB,KAAK,GAAG;MACrC,SAAS,QAAQ;MAEjB;KACF;KAEA,SACG,OAAO,UAAU,CAAC,CAClB,YAAY,CAAC,CAAC,CAAC,CACf,cAAc,SAAS,QAAQ,CAAC;IACrC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