@nextlyhq/adapter-drizzle 0.0.2-alpha.7 → 0.0.2-alpha.70

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 (64) hide show
  1. package/README.md +25 -1
  2. package/dist/adapter-BypoOEEN.d.cts +1166 -0
  3. package/dist/adapter-CSP-Ek-L.d.ts +1166 -0
  4. package/dist/index-BYb6cDli.d.ts +1168 -0
  5. package/dist/index-C4HJsfwA.d.cts +1168 -0
  6. package/dist/index.cjs +2302 -1085
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +5 -9
  9. package/dist/index.d.ts +5 -9
  10. package/dist/index.mjs +2301 -1083
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/migrations.cjs +345 -146
  13. package/dist/migrations.cjs.map +1 -1
  14. package/dist/migrations.d.cts +93 -109
  15. package/dist/migrations.d.ts +93 -109
  16. package/dist/migrations.mjs +344 -144
  17. package/dist/migrations.mjs.map +1 -1
  18. package/dist/schema/index.cjs +21 -6
  19. package/dist/schema/index.cjs.map +1 -1
  20. package/dist/schema/index.d.cts +5 -116
  21. package/dist/schema/index.d.ts +5 -116
  22. package/dist/schema/index.mjs +20 -4
  23. package/dist/schema/index.mjs.map +1 -1
  24. package/dist/schema-Bkkr3JMC.d.cts +264 -0
  25. package/dist/schema-Bkkr3JMC.d.ts +264 -0
  26. package/dist/schema-name.cjs +42 -0
  27. package/dist/schema-name.cjs.map +1 -0
  28. package/dist/schema-name.d.cts +12 -0
  29. package/dist/schema-name.d.ts +12 -0
  30. package/dist/schema-name.mjs +40 -0
  31. package/dist/schema-name.mjs.map +1 -0
  32. package/dist/text-match.cjs +50 -0
  33. package/dist/text-match.cjs.map +1 -0
  34. package/dist/text-match.d.cts +32 -0
  35. package/dist/text-match.d.ts +32 -0
  36. package/dist/text-match.mjs +48 -0
  37. package/dist/text-match.mjs.map +1 -0
  38. package/dist/types/index.cjs +8 -24
  39. package/dist/types/index.d.cts +3 -210
  40. package/dist/types/index.d.ts +3 -210
  41. package/dist/types/index.mjs +1 -21
  42. package/dist/types-CNyA1oIm.cjs +185 -0
  43. package/dist/types-CNyA1oIm.cjs.map +1 -0
  44. package/dist/types-CaF_5jNk.mjs +150 -0
  45. package/dist/types-CaF_5jNk.mjs.map +1 -0
  46. package/dist/version-check.cjs +119 -127
  47. package/dist/version-check.cjs.map +1 -1
  48. package/dist/version-check.d.cts +54 -39
  49. package/dist/version-check.d.ts +54 -39
  50. package/dist/version-check.mjs +117 -125
  51. package/dist/version-check.mjs.map +1 -1
  52. package/package.json +23 -17
  53. package/dist/adapter-BxJVtttb.d.ts +0 -592
  54. package/dist/adapter-nvlxFkF-.d.cts +0 -592
  55. package/dist/core-CVO7WYDj.d.cts +0 -74
  56. package/dist/core-CVO7WYDj.d.ts +0 -74
  57. package/dist/error-um1d_3Uo.d.cts +0 -105
  58. package/dist/error-um1d_3Uo.d.ts +0 -105
  59. package/dist/migration-BbO5meEV.d.cts +0 -622
  60. package/dist/migration-Qe70wDOC.d.ts +0 -622
  61. package/dist/schema-BDn8WfSL.d.cts +0 -200
  62. package/dist/schema-BIQ0YQZ_.d.ts +0 -200
  63. package/dist/types/index.cjs.map +0 -1
  64. package/dist/types/index.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,1134 +1,2352 @@
1
- import { getTableColumns, desc, asc, and, or, not, like, notBetween, between, isNotNull, isNull, notInArray, inArray, ilike, lte, gte, lt, gt, ne, eq } from 'drizzle-orm';
2
-
3
- // src/adapter.ts
1
+ import { caseInsensitiveContains, containsPattern } from "./text-match.mjs";
2
+ import { i as isDatabaseError, n as createDatabaseError } from "./types-CaF_5jNk.mjs";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { Column, SQL, and, asc, between, count, desc, eq, getColumns, gt, gte, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notBetween, notInArray, or, sql } from "drizzle-orm";
5
+ // src/column-kinds.ts
6
+ /**
7
+ * Whether a column stores JSON, in the spelling each dialect's column class
8
+ * reports. Drizzle serializes objects for these itself, so a value that
9
+ * arrives already serialized has to be parsed first or it is serialized
10
+ * twice.
11
+ *
12
+ * SQLite matches only text columns declared with `{ mode: "json" }`
13
+ * (`SQLiteTextJson`, dataType `json`). A plain `SQLiteText` column stores a
14
+ * serialized string as it is and must not be parsed, or better-sqlite3 is
15
+ * handed an object it cannot bind.
16
+ */
17
+ function isJsonColumn(column) {
18
+ return column.dataType === "json" || column.columnType === "PgJsonb" || column.columnType === "PgJson" || column.columnType === "MySqlJson" || column.columnType === "SQLiteTextJson";
19
+ }
20
+ /**
21
+ * Whether a value is a structured document — a plain object or an array —
22
+ * rather than a scalar, a date, or binary. What a driver does with one of
23
+ * these when the column is not modelled differs (node-postgres spells an
24
+ * array as a PostgreSQL array literal, mysql2 as a value list), and none of
25
+ * it is JSON; serializing here is what makes the same bytes land everywhere.
26
+ */
27
+ function isStructuredValue(value) {
28
+ if (value === null || typeof value !== "object") return false;
29
+ if (value instanceof Date) return false;
30
+ if (Buffer.isBuffer(value) || ArrayBuffer.isView(value)) return false;
31
+ return true;
32
+ }
33
+ /**
34
+ * How a value binds to a column the runtime model does not declare, on a
35
+ * driver that binds scalars, dates and binary natively: structured values are
36
+ * serialized as JSON text, everything else passes through.
37
+ */
38
+ function bindStructuredAsJson(value) {
39
+ return isStructuredValue(value) ? JSON.stringify(value) : value;
40
+ }
41
+ // src/drizzle-order.ts
42
+ /**
43
+ * Turn order specifications into drizzle order clauses.
44
+ *
45
+ * Extracted from `DrizzleAdapter.select` so the rendered SQL can be asserted
46
+ * directly. That matters more than it looks: `OrderBySpec.nulls` was declared,
47
+ * documented as "can be explicitly controlled", and read NOWHERE — every caller
48
+ * that set it silently got the dialect default instead, and no test could have
49
+ * caught that while the mapping lived inline in a method that needs a database.
50
+ *
51
+ * ## Why null placement is a leading sort key, not `NULLS FIRST/LAST`
52
+ *
53
+ * That clause is not portable: PostgreSQL and SQLite accept it, MySQL does not.
54
+ * `col IS NULL` is a boolean expression all three evaluate, and sorting on it
55
+ * ascending puts non-null rows first — which is `NULLS LAST` by another name,
56
+ * spelled in something every supported engine understands.
57
+ *
58
+ * The defaults genuinely disagree, which is why the control exists at all:
59
+ * PostgreSQL treats NULL as largest and puts it FIRST on a descending order,
60
+ * while MySQL and SQLite treat it as smallest and put it last. A "newest
61
+ * scheduled first" list containing undated drafts therefore returns different
62
+ * rows per engine, and under a limit it can return only drafts.
63
+ */
64
+ function buildDrizzleOrderBy(columns, orderBy) {
65
+ if (!orderBy?.length) return [];
66
+ return orderBy.flatMap((spec) => {
67
+ const col = columns[spec.column];
68
+ if (!col) return [];
69
+ const direction = spec.direction === "desc" ? desc(col) : asc(col);
70
+ if (spec.nulls === void 0) return [direction];
71
+ const isNull = sql`${col} is null`;
72
+ return [spec.nulls === "last" ? asc(isNull) : desc(isNull), direction];
73
+ });
74
+ }
75
+ // src/drizzle-where.ts
4
76
  function buildDrizzleWhere(table, where) {
5
- const columns = getTableColumns(table);
6
- return processWhereClause(columns, where);
77
+ return processWhereClause(getColumns(table), where);
7
78
  }
8
79
  function processWhereClause(columns, where) {
9
- const parts = [];
10
- if (where.and?.length) {
11
- const andParts = where.and.map((item) => {
12
- if (isWhereCondition(item)) {
13
- return buildCondition(columns, item);
14
- }
15
- return processWhereClause(columns, item);
16
- }).filter((p) => p !== void 0);
17
- if (andParts.length) {
18
- parts.push(and(...andParts));
19
- }
20
- }
21
- if (where.or?.length) {
22
- const orParts = where.or.map((item) => {
23
- if (isWhereCondition(item)) {
24
- return buildCondition(columns, item);
25
- }
26
- return processWhereClause(columns, item);
27
- }).filter((p) => p !== void 0);
28
- if (orParts.length) {
29
- parts.push(or(...orParts));
30
- }
31
- }
32
- if (where.not) {
33
- const notItem = where.not;
34
- const notCondition = isWhereCondition(notItem) ? buildCondition(columns, notItem) : processWhereClause(columns, notItem);
35
- if (notCondition) {
36
- parts.push(not(notCondition));
37
- }
38
- }
39
- if (parts.length === 0) return void 0;
40
- if (parts.length === 1) return parts[0];
41
- return and(...parts);
80
+ const parts = [];
81
+ if (where.and?.length) {
82
+ const andParts = where.and.map((item) => {
83
+ if (isWhereCondition(item)) return buildCondition(columns, item);
84
+ return processWhereClause(columns, item);
85
+ }).filter((p) => p !== void 0);
86
+ if (andParts.length) parts.push(and(...andParts));
87
+ }
88
+ if (where.or?.length) {
89
+ const orParts = where.or.map((item) => {
90
+ if (isWhereCondition(item)) return buildCondition(columns, item);
91
+ return processWhereClause(columns, item);
92
+ }).filter((p) => p !== void 0);
93
+ if (orParts.length) parts.push(or(...orParts));
94
+ }
95
+ if (where.not) {
96
+ const notItem = where.not;
97
+ const notCondition = isWhereCondition(notItem) ? buildCondition(columns, notItem) : processWhereClause(columns, notItem);
98
+ if (notCondition) parts.push(not(notCondition));
99
+ }
100
+ if (parts.length === 0) {
101
+ if (namesABranch(where)) throw new Error(`Where clause produced no condition: ${JSON.stringify(where)}. Every branch resolved to nothing, which would match every row. Pass {} to mean "no filter".`);
102
+ return;
103
+ }
104
+ if (parts.length === 1) return parts[0];
105
+ return and(...parts);
42
106
  }
43
107
  function isWhereCondition(item) {
44
- return "column" in item && "op" in item;
108
+ return "column" in item && "op" in item;
109
+ }
110
+ /**
111
+ * Whether the clause asked for a constraint at all — as opposed to being the empty clause a
112
+ * caller passes to mean "no filter".
113
+ *
114
+ * An empty `and`/`or` array does NOT count: nothing was named, so nothing could be dropped.
115
+ * What counts is a branch with members in it, or a `not`, because those are the shapes that can
116
+ * resolve to nothing and leave the caller believing a filter was applied.
117
+ */
118
+ function namesABranch(where) {
119
+ return Boolean(where.and?.length || where.or?.length || where.not);
45
120
  }
46
121
  function buildCondition(columns, cond) {
47
- const column = columns[cond.column];
48
- if (!column) {
49
- throw new Error(
50
- `Column "${cond.column}" not found in table. Available: ${Object.keys(columns).join(", ")}`
51
- );
52
- }
53
- const col = column;
54
- switch (cond.op) {
55
- case "=":
56
- return eq(col, cond.value);
57
- case "!=":
58
- return ne(col, cond.value);
59
- case ">":
60
- return gt(col, cond.value);
61
- case "<":
62
- return lt(col, cond.value);
63
- case ">=":
64
- return gte(col, cond.value);
65
- case "<=":
66
- return lte(col, cond.value);
67
- case "LIKE":
68
- return like(col, cond.value);
69
- case "ILIKE":
70
- return ilike(col, cond.value);
71
- case "IN":
72
- return inArray(col, cond.value);
73
- case "NOT IN":
74
- return notInArray(col, cond.value);
75
- case "IS NULL":
76
- return isNull(col);
77
- case "IS NOT NULL":
78
- return isNotNull(col);
79
- case "BETWEEN":
80
- return between(col, cond.value, cond.valueTo);
81
- case "NOT BETWEEN":
82
- return notBetween(col, cond.value, cond.valueTo);
83
- case "CONTAINS":
84
- return like(col, `%${String(cond.value)}%`);
85
- default:
86
- throw new Error(`Unsupported operator: ${cond.op}`);
87
- }
122
+ const column = columns[cond.column];
123
+ if (!column) throw new Error(`Column "${cond.column}" not found in table. Available: ${Object.keys(columns).join(", ")}`);
124
+ const col = column;
125
+ switch (cond.op) {
126
+ case "=": return eq(col, cond.value);
127
+ case "!=": return ne(col, cond.value);
128
+ case ">": return gt(col, cond.value);
129
+ case "<": return lt(col, cond.value);
130
+ case ">=": return gte(col, cond.value);
131
+ case "<=": return lte(col, cond.value);
132
+ case "LIKE": return like(col, cond.value);
133
+ case "ILIKE": return sql`lower(${col}) like lower(${cond.value})`;
134
+ case "IN": return inArray(col, cond.value);
135
+ case "NOT IN": return notInArray(col, cond.value);
136
+ case "IS NULL": return isNull(col);
137
+ case "IS NOT NULL": return isNotNull(col);
138
+ case "BETWEEN": return between(col, cond.value, cond.valueTo);
139
+ case "NOT BETWEEN": return notBetween(col, cond.value, cond.valueTo);
140
+ case "CONTAINS": return sql`${col} like ${containsPattern(String(cond.value))} escape '!'`;
141
+ case "ICONTAINS": return caseInsensitiveContains(col, String(cond.value));
142
+ default: throw new Error(`Unsupported operator: ${cond.op}`);
143
+ }
88
144
  }
89
-
90
- // src/types/error.ts
91
- function isDatabaseError(error) {
92
- return typeof error === "object" && error !== null && "kind" in error && typeof error.kind === "string";
145
+ // src/pinned-transaction.ts
146
+ /**
147
+ * Replaces `db`'s `transaction` with one that runs each transaction on a
148
+ * connection from `checkout`.
149
+ *
150
+ * Drizzle, bound to that single connection, runs BEGIN, the work and COMMIT
151
+ * or ROLLBACK as it always does. When the transaction fails, a second
152
+ * ROLLBACK goes to the connection: a no-op when Drizzle's own reached it,
153
+ * and the confirmation that the connection is out of the transaction when
154
+ * Drizzle's did not. If that ROLLBACK fails too, nothing can confirm it, and
155
+ * the connection is closed rather than pooled. The work's own error is what
156
+ * the caller receives, never a ROLLBACK's.
157
+ *
158
+ * @param db - A Drizzle handle on the adapter's pool
159
+ * @param checkout - Checks out a connection for one transaction
160
+ * @returns The same handle, its `transaction` replaced
161
+ */
162
+ function pinTransactions(db, checkout) {
163
+ const pinned = async (work, config) => {
164
+ const connection = await checkout();
165
+ let dirty = false;
166
+ let workFailure;
167
+ try {
168
+ return await connection.drizzle.transaction(async (tx) => {
169
+ try {
170
+ return await work(tx);
171
+ } catch (error) {
172
+ workFailure = { error };
173
+ throw error;
174
+ }
175
+ }, config);
176
+ } catch (error) {
177
+ await connection.rollback().catch(() => {
178
+ dirty = true;
179
+ });
180
+ throw workFailure ? workFailure.error : error;
181
+ } finally {
182
+ connection.release(dirty);
183
+ }
184
+ };
185
+ Object.defineProperty(db, "transaction", {
186
+ value: pinned,
187
+ configurable: true,
188
+ writable: true
189
+ });
190
+ return db;
93
191
  }
94
- function createDatabaseError(options) {
95
- const error = new Error(options.message);
96
- error.name = "DatabaseError";
97
- error.kind = options.kind;
98
- if (options.code !== void 0) error.code = options.code;
99
- if (options.constraint !== void 0) error.constraint = options.constraint;
100
- if (options.table !== void 0) error.table = options.table;
101
- if (options.column !== void 0) error.column = options.column;
102
- if (options.detail !== void 0) error.detail = options.detail;
103
- if (options.hint !== void 0) error.hint = options.hint;
104
- if (options.cause !== void 0) error.cause = options.cause;
105
- return error;
192
+ // src/transaction-forwarders.ts
193
+ /**
194
+ * Create CRUD and Drizzle instance forwarding methods for a TransactionContext.
195
+ *
196
+ * @remarks
197
+ * TransactionContext delegates its CRUD methods to the adapter's Drizzle CRUD
198
+ * implementation while binding the transaction executor so queries run inside
199
+ * the transaction rather than on the connection pool.
200
+ *
201
+ * @param delegator - Object providing the underlying adapter CRUD methods
202
+ * @param txDb - Thunk returning the transaction-bound Drizzle instance
203
+ * @returns Object with forwarded TransactionContext methods
204
+ */
205
+ function createTransactionForwarders(delegator, txDb) {
206
+ return {
207
+ select: async (table, options) => {
208
+ return delegator.select(table, options, txDb());
209
+ },
210
+ selectOne: async (table, options) => {
211
+ return delegator.selectOne(table, options, txDb());
212
+ },
213
+ updateCount: async (table, data, where) => {
214
+ return delegator.updateCount(table, data, where, txDb());
215
+ },
216
+ delete: async (table, where, options) => {
217
+ return delegator.delete(table, where, options, txDb());
218
+ },
219
+ upsert: async (table, data, options) => {
220
+ return delegator.upsert(table, data, options, txDb());
221
+ },
222
+ getDrizzle: () => txDb()
223
+ };
224
+ }
225
+ /**
226
+ * The Drizzle handles one transaction hands out, built once each.
227
+ *
228
+ * `bare` is the instance the delegated CRUD and `getDrizzle()` run on. `withRelations(relations)` is `drizzleWithRelations`: an instance
229
+ * on the SAME connection whose `query` namespace is populated, so relational
230
+ * reads stay inside the transaction. Both are built lazily — a transaction
231
+ * using only raw execute never constructs one — and the relational ones are
232
+ * memoized per relations object, exactly as `getDrizzle()` memoizes its
233
+ * pooled ones.
234
+ *
235
+ * Shared because the three adapters differ only in how they build an
236
+ * instance on their connection, which is what `build` supplies.
237
+ */
238
+ function transactionDrizzleHandles(build) {
239
+ let bareInstance;
240
+ const bare = () => bareInstance ??= build();
241
+ const relational = /* @__PURE__ */ new WeakMap();
242
+ const withRelations = (relations) => {
243
+ let cached = relational.get(relations);
244
+ if (cached === void 0) {
245
+ cached = build(relations);
246
+ relational.set(relations, cached);
247
+ }
248
+ return cached;
249
+ };
250
+ return {
251
+ bare,
252
+ withRelations
253
+ };
254
+ }
255
+ // src/update-statement.ts
256
+ /**
257
+ * The transactional UPDATE, assembled by the adapter rather than by the
258
+ * Drizzle query builder.
259
+ *
260
+ * `db.update(table).set(row)` builds its SET clause by walking the table's
261
+ * DECLARED columns and probing `row` for each — never the other way round —
262
+ * so a key naming a column the runtime model does not declare is dropped
263
+ * without a word. One place relies on writing exactly such a column: the
264
+ * localization transition window. `localized` has been flipped on a
265
+ * collection, the runtime model has moved its translatable columns to a
266
+ * companion table that does not exist yet, and the physical main table still
267
+ * holds them. The default locale keeps writing there until the companion
268
+ * appears, and the transactional INSERT already reaches it because every
269
+ * adapter builds that statement itself. This is the UPDATE half of the same
270
+ * rule, shared by the three adapters so the statement is spelled once.
271
+ *
272
+ * Built on Drizzle's `sql` template rather than a string, so each dialect
273
+ * quotes identifiers and numbers placeholders its own way, and the WHERE is
274
+ * the `buildDrizzleWhere` every other read and write goes through — the raw
275
+ * where builders were removed on purpose and this does not bring one back.
276
+ * It returns at most the rows' identity: a caller who asked for the rows back
277
+ * gets them from a read on the same transaction, decoded the way every read
278
+ * is decoded, rather than from a RETURNING list this module would have to
279
+ * decode a second way — and on a dialect with RETURNING that read is by the
280
+ * identities this statement reports, so it is exactly the rows it changed.
281
+ *
282
+ * A value binds in one of three ways, decided per column:
283
+ * - a column the model DECLARES binds through that column's own encoder.
284
+ * `sql.param(value, column)` is the `Param` the query builder would have
285
+ * made for it, so a date, a JSON document or a boolean reaches the driver
286
+ * as the bytes the builder sent before this existed — for every caller
287
+ * that was already using the builder;
288
+ * - a column it does NOT declare binds through the adapter's own sanitizer,
289
+ * which is how that adapter's transactional INSERT binds every value;
290
+ * - a value that is itself a `Column` or an `SQL` fragment is an expression
291
+ * (`{ destination: table.source }` copies a column) and is written as one,
292
+ * which is what the query builder's `mapUpdateSet` does with it.
293
+ *
294
+ * A declared column with an `$onUpdate` callback that the caller did not name
295
+ * is assigned the callback's value, as the query builder assigns it on every
296
+ * update it builds.
297
+ *
298
+ * A key whose value is `undefined` is not written at all — JSON's meaning of
299
+ * an absent key, and what the builder's `mapUpdateSet` did with it; under
300
+ * both spellings of one column the later key decides, undefined included.
301
+ * `null` is written as NULL. A key naming no column on the physical table is
302
+ * a SQL error from the database: the query builder was the one path that
303
+ * could not say so, which is the defect the transition window was hiding
304
+ * behind. A patch that names nothing is refused before any `$onUpdate`
305
+ * column is considered, as the query builder refused it.
306
+ *
307
+ * @module update-statement
308
+ */
309
+ function isBindableColumn(value) {
310
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.mapToDriverValue === "function";
311
+ }
312
+ /**
313
+ * A JSON column's encoder serializes whatever it is given, so a value that
314
+ * arrives already serialized would be serialized twice. The query-builder path
315
+ * parses such a string first; this keeps the same bytes on the wire.
316
+ */
317
+ function valueForJsonColumn(value) {
318
+ if (typeof value !== "string") return value;
319
+ try {
320
+ return JSON.parse(value);
321
+ } catch {
322
+ return value;
323
+ }
324
+ }
325
+ /**
326
+ * A table's columns, indexed by both spellings a caller may use, and the
327
+ * declared columns in order for the `$onUpdate` sweep.
328
+ */
329
+ function columnsOf(tableObj) {
330
+ const byName = /* @__PURE__ */ new Map();
331
+ const declared = [];
332
+ for (const [jsName, column] of Object.entries(getColumns(tableObj))) {
333
+ if (!isBindableColumn(column)) continue;
334
+ byName.set(column.name, column);
335
+ byName.set(jsName, column);
336
+ declared.push(column);
337
+ }
338
+ return {
339
+ byName,
340
+ declared
341
+ };
342
+ }
343
+ /** How one value is written: as the expression it already is, or bound. */
344
+ function boundValue(value, column, bindUnmodeled) {
345
+ if (is(value, SQL) || is(value, Column)) return sql`${value}`;
346
+ if (column) return sql`${sql.param(isJsonColumn(column) ? valueForJsonColumn(value) : value, column)}`;
347
+ return sql`${sql.param(bindUnmodeled(value))}`;
348
+ }
349
+ /**
350
+ * Build the UPDATE for one table.
351
+ *
352
+ * @returns the statement, or `null` when there is nothing to write — every
353
+ * key was `undefined`, or there were none. An UPDATE with an empty SET is a
354
+ * syntax error, so the adapter refuses it by name instead of running it.
355
+ */
356
+ function buildUpdateStatement(input) {
357
+ const { byName, declared } = columnsOf(input.tableObj);
358
+ const assignments = /* @__PURE__ */ new Map();
359
+ for (const [key, value] of Object.entries(input.data)) {
360
+ const column = byName.get(key);
361
+ const name = column?.name ?? key;
362
+ if (value === void 0) {
363
+ assignments.delete(name);
364
+ continue;
365
+ }
366
+ assignments.set(name, sql`${sql.identifier(name)} = ${boundValue(value, column, input.bindUnmodeled)}`);
367
+ }
368
+ if (assignments.size === 0) return null;
369
+ for (const column of declared) {
370
+ if (assignments.has(column.name) || column.onUpdateFn === void 0) continue;
371
+ const value = column.onUpdateFn();
372
+ assignments.set(column.name, sql`${sql.identifier(column.name)} = ${boundValue(value, column, input.bindUnmodeled)}`);
373
+ }
374
+ const statement = sql`UPDATE ${input.tableObj} SET ${sql.join([...assignments.values()], sql`, `)}`;
375
+ const condition = buildDrizzleWhere(input.tableObj, input.where);
376
+ if (condition) statement.append(sql` WHERE ${condition}`);
377
+ if (input.returning && input.returning.length > 0) statement.append(sql` RETURNING ${sql.join(input.returning, sql`, `)}`);
378
+ return statement;
106
379
  }
107
-
108
380
  // src/adapter.ts
381
+ /**
382
+ * Base database adapter abstract class.
383
+ *
384
+ * @remarks
385
+ * This abstract class provides the foundation for all dialect-specific database adapters
386
+ * (PostgreSQL, MySQL, SQLite). It defines required abstract methods that must be implemented
387
+ * by subclasses, while providing default implementations for CRUD operations and query building.
388
+ *
389
+ * Dialect adapters can override any default method to provide optimized implementations.
390
+ *
391
+ * @packageDocumentation
392
+ */
393
+ /**
394
+ * Where a test harness installs the observer {@link DrizzleAdapter.notePoolAccess}
395
+ * reports a transaction escape to: a global registry key rather than an
396
+ * import, so the harness and every copy of this package agree on it.
397
+ */
398
+ const TRANSACTION_ESCAPE_OBSERVER = Symbol.for("nextly.transactionEscapeObserver");
399
+ /**
400
+ * The SQL text a pool call was handed: a string, or the `text` (pg) or `sql`
401
+ * (mysql2) of a query object. Undefined for a connection checkout.
402
+ */
403
+ function statementOf(argument) {
404
+ if (typeof argument === "string") return argument;
405
+ if (typeof argument !== "object" || argument === null) return void 0;
406
+ const { text, sql } = argument;
407
+ if (typeof text === "string") return text;
408
+ return typeof sql === "string" ? sql : void 0;
409
+ }
410
+ /** The escape observer a test harness installed; undefined in production. */
411
+ function escapeObserver() {
412
+ const observe = globalThis[TRANSACTION_ESCAPE_OBSERVER];
413
+ return typeof observe === "function" ? observe : void 0;
414
+ }
415
+ /**
416
+ * The current stack, deep enough to reach the code that made the query. The
417
+ * driver's and Drizzle's own frames fill V8's default of ten, which cut every
418
+ * report off before its caller. Raised only for this capture and restored
419
+ * after, so nothing else sees the deeper limit; it runs only for an observer a
420
+ * test harness installed.
421
+ */
422
+ function deepStack() {
423
+ const limit = Error.stackTraceLimit;
424
+ try {
425
+ Error.stackTraceLimit = 64;
426
+ return (/* @__PURE__ */ new Error()).stack ?? "";
427
+ } finally {
428
+ Error.stackTraceLimit = limit;
429
+ }
430
+ }
431
+ /**
432
+ * Matches the `dataType` a Drizzle timestamp/datetime column reports, in both
433
+ * the bare form and the object-qualified form some column classes carry.
434
+ */
435
+ const DATE_DATA_TYPE = /(?:^|\s)date$/;
436
+ /**
437
+ * How far an echoed timestamp may sit from the one that was bound and still
438
+ * count as the same value.
439
+ *
440
+ * A column with no fractional precision keeps whole seconds, so a stored value
441
+ * can differ from the bound one by up to a second without anything being wrong.
442
+ * Every real UTC offset is at least fifteen minutes, so a shift is never
443
+ * mistaken for rounding.
444
+ */
445
+ /**
446
+ * Stem for the alias a statement spells a timestamp's wall clock out under.
447
+ *
448
+ * Short on purpose. PostgreSQL truncates an identifier at 63 bytes, and a
449
+ * truncated alias is worse than a rejected one: the statement still succeeds,
450
+ * the lookup misses the name it asked for, and the row keeps both the driver's
451
+ * value and a stray property. A stem plus an index stays far inside the limit
452
+ * whatever the column is called.
453
+ */
454
+ const WALL_CLOCK_ALIAS_STEM = "__nx_wc";
455
+ /**
456
+ * A timestamp as the database itself spells it, in a fixed field order.
457
+ *
458
+ * Matched rather than handed to `new Date`, so nothing depends on the host's
459
+ * parsing of a partial date. The fraction is optional and of any length, which
460
+ * covers PostgreSQL's milliseconds and MySQL's microseconds alike.
461
+ */
462
+ const WALL_CLOCK_PATTERN = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?$/;
463
+ /**
464
+ * Read a database's own rendering of a timestamp as UTC.
465
+ *
466
+ * The statement wrote a UTC wall clock, so reading one back as UTC is what
467
+ * makes a write agree with a later read. The rendering is one the statement
468
+ * asked for by name, so its shape does not depend on a session setting.
469
+ *
470
+ * Anything that does not match answers nothing, leaving the driver's value in
471
+ * place rather than replacing it with an `Invalid Date`.
472
+ */
473
+ function parseWallClockAsUtc(text) {
474
+ const match = WALL_CLOCK_PATTERN.exec(text.trim());
475
+ if (!match) return void 0;
476
+ const [, year, month, day, hour, minute, second, fraction = ""] = match;
477
+ const millis = Number(`${fraction}000`.slice(0, 3));
478
+ const parsed = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second), millis));
479
+ if (Number(year) < 100) parsed.setUTCFullYear(Number(year));
480
+ return parsed;
481
+ }
482
+ /** Whether a table property is a date column that can convert its own values. */
483
+ function isDateColumn(colDef) {
484
+ if (!colDef || typeof colDef !== "object") return false;
485
+ const candidate = colDef;
486
+ return typeof candidate.mapFromDriverValue === "function" && typeof candidate.mapToDriverValue === "function" && DATE_DATA_TYPE.test(String(candidate.dataType));
487
+ }
488
+ /**
489
+ * Whether a date column records the zone its value belongs to.
490
+ *
491
+ * A column declared WITH a time zone stores an instant, so a driver reading it
492
+ * back gets the same moment whatever zone either end is in -- there is nothing
493
+ * ambiguous to resolve and nothing to correct. Rendering one as text would
494
+ * spell it in the session's zone, and reading that as UTC would move it.
495
+ */
496
+ function carriesTimeZone(colDef) {
497
+ return colDef.withTimezone === true;
498
+ }
499
+ /**
500
+ * Abstract base class for database adapters.
501
+ *
502
+ * @remarks
503
+ * All dialect-specific adapters must extend this class and implement the abstract methods.
504
+ * Default implementations are provided for CRUD operations, which can be overridden for
505
+ * optimization or dialect-specific behavior.
506
+ *
507
+ * ## Required Implementations
508
+ *
509
+ * Subclasses must implement:
510
+ * - `dialect` - Database dialect identifier
511
+ * - `connect()` - Establish database connection
512
+ * - `disconnect()` - Close database connection
513
+ * - `executeQuery()` - Execute raw SQL query
514
+ * - `transaction()` - Execute operations within a transaction
515
+ * - `getCapabilities()` - Report database feature support
516
+ *
517
+ * ## Optional Overrides
518
+ *
519
+ * Subclasses can override default CRUD methods for optimization:
520
+ * - `select()`, `selectOne()` - Custom query optimization
521
+ * - `insert()`, `insertMany()` - Bulk insert optimization
522
+ * - `update()`, `delete()` - Custom update/delete logic
523
+ * - `upsert()` - Dialect-specific upsert syntax
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * export class PostgresAdapter extends DrizzleAdapter {
528
+ * readonly dialect = 'postgresql' as const;
529
+ *
530
+ * async connect() {
531
+ * this.pool = new Pool({ connectionString: this.config.url });
532
+ * // ... connection logic
533
+ * }
534
+ *
535
+ * async executeQuery<T>(sql: string, params?: SqlParam[]) {
536
+ * const result = await this.pool.query(sql, params);
537
+ * return result.rows as T[];
538
+ * }
539
+ *
540
+ * // ... other required methods
541
+ * }
542
+ * ```
543
+ *
544
+ * @public
545
+ */
546
+ /**
547
+ * Rows affected by a write, normalised across the driver shapes Drizzle returns.
548
+ *
549
+ * mysql2 resolves to `[ResultSetHeader, FieldPacket[]]`, so treating any array
550
+ * as a row list reports the tuple length — a constant 2 whether the statement
551
+ * matched nothing, one row, or many. Callers that branch on the count (a
552
+ * conditional claim, a retention loop) silently get the wrong answer on MySQL,
553
+ * so the header is read first. node-postgres reports `rowCount` and
554
+ * better-sqlite3 reports `changes`; a plain array is a RETURNING row list, whose
555
+ * length is the count.
556
+ */
557
+ function affectedRowCount(result) {
558
+ if (Array.isArray(result)) {
559
+ const header = result[0];
560
+ if (header && typeof header.affectedRows === "number") return header.affectedRows;
561
+ return result.length;
562
+ }
563
+ const record = result;
564
+ const rowCount = record?.rowCount;
565
+ if (typeof rowCount === "number") return rowCount;
566
+ const changes = record?.changes;
567
+ if (typeof changes === "number") return changes;
568
+ return 0;
569
+ }
109
570
  var DrizzleAdapter = class {
110
- // ============================================================
111
- // Drizzle Query API Support
112
- // ============================================================
113
- /**
114
- * Table resolver for looking up Drizzle table objects by name.
115
- * When set, CRUD methods use Drizzle's query API instead of raw SQL.
116
- * Set via setTableResolver() after boot-time schema loading.
117
- */
118
- tableResolver = null;
119
- /**
120
- * Set the table resolver for Drizzle query API support.
121
- * When a resolver is set, CRUD methods (select, insert, update, delete, upsert)
122
- * will use Drizzle's query API (db.select().from(), etc.) instead of raw SQL
123
- * string building. Falls back to raw SQL if the resolver doesn't have the table.
124
- *
125
- * @param resolver - TableResolver implementation (e.g. SchemaRegistry)
126
- */
127
- setTableResolver(resolver) {
128
- this.tableResolver = resolver;
129
- }
130
- /**
131
- * Get a Drizzle table object by name from the resolver.
132
- * Returns null if no resolver is set or table is not found.
133
- */
134
- getTableObject(tableName) {
135
- return this.tableResolver?.getTable(tableName) ?? null;
136
- }
137
- /**
138
- * Map data keys from SQL column names (snake_case) to Drizzle JS property names (camelCase).
139
- * Drizzle schemas define columns as e.g. `createdAt: timestamp("created_at")` — the JS
140
- * property is `createdAt` but the SQL column is `created_at`. Services pass snake_case keys
141
- * because they match the DB column names. This method maps them to the JS names Drizzle expects.
142
- */
143
- mapDataToColumnNames(tableObj, data) {
144
- if (!tableObj || typeof tableObj !== "object") return data;
145
- const sqlToJs = /* @__PURE__ */ new Map();
146
- const jsonColumns = /* @__PURE__ */ new Set();
147
- for (const [jsName, colDef] of Object.entries(
148
- tableObj
149
- )) {
150
- if (!colDef || typeof colDef !== "object" || !("name" in colDef) || typeof colDef.name !== "string")
151
- continue;
152
- const sqlName = colDef.name;
153
- sqlToJs.set(sqlName, jsName);
154
- const dataType = colDef.dataType;
155
- const columnType = colDef.columnType;
156
- if (dataType === "json" || columnType === "PgJsonb" || columnType === "PgJson" || columnType === "MySqlJson" || columnType === "SQLiteTextJson") {
157
- jsonColumns.add(jsName);
158
- }
159
- }
160
- if (sqlToJs.size === 0) return data;
161
- const mapped = {};
162
- for (const [key, value] of Object.entries(data)) {
163
- const jsKey = sqlToJs.get(key) ?? key;
164
- if (jsonColumns.has(jsKey) && typeof value === "string") {
165
- try {
166
- mapped[jsKey] = JSON.parse(value);
167
- } catch {
168
- mapped[jsKey] = value;
169
- }
170
- } else {
171
- mapped[jsKey] = value;
172
- }
173
- }
174
- return mapped;
175
- }
176
- // ============================================================
177
- // Connection Status (Default implementations, can override)
178
- // ============================================================
179
- /**
180
- * Check if the adapter is currently connected.
181
- *
182
- * @remarks
183
- * Default implementation returns false. Subclasses should override
184
- * to provide accurate connection status.
185
- *
186
- * @returns True if connected, false otherwise
187
- */
188
- isConnected() {
189
- return false;
190
- }
191
- /**
192
- * Get connection pool statistics.
193
- *
194
- * @remarks
195
- * Returns null by default. Subclasses with connection pooling
196
- * should override to provide pool statistics.
197
- *
198
- * @returns Pool statistics or null if not applicable
199
- */
200
- getPoolStats() {
201
- return null;
202
- }
203
- // ============================================================
204
- // Timeout Utilities
205
- // ============================================================
206
- /**
207
- * Default query timeout in milliseconds.
208
- *
209
- * @remarks
210
- * This value is used by executeWithTimeout() when no explicit timeout
211
- * is provided. Subclasses should set this from their config.
212
- *
213
- * @default 15000 (15 seconds)
214
- *
215
- * @protected
216
- */
217
- defaultQueryTimeoutMs = 15e3;
218
- /**
219
- * Execute an async operation with a timeout.
220
- *
221
- * @remarks
222
- * Wraps an async operation with a timeout that aborts if the operation
223
- * exceeds the specified duration. Uses Promise.race for clean timeout
224
- * handling without memory leaks.
225
- *
226
- * When the timeout is reached, a DatabaseError with kind 'timeout' is thrown.
227
- * Note that this does NOT cancel the underlying database query - it only
228
- * prevents the calling code from waiting indefinitely. For true query
229
- * cancellation, use database-level statement timeouts (PostgreSQL) or
230
- * similar mechanisms.
231
- *
232
- * @param operation - Async operation to execute
233
- * @param timeoutMs - Timeout in milliseconds (defaults to defaultQueryTimeoutMs)
234
- * @returns Result of the operation
235
- *
236
- * @throws {DatabaseError} With kind 'timeout' if operation exceeds timeout
237
- *
238
- * @example
239
- * ```typescript
240
- * // Use default timeout
241
- * const result = await adapter.executeWithTimeout(
242
- * () => adapter.select('users', { limit: 1000 })
243
- * );
244
- *
245
- * // Use custom timeout for specific operation
246
- * const result = await adapter.executeWithTimeout(
247
- * () => adapter.select('large_table'),
248
- * 60000 // 60 seconds for large queries
249
- * );
250
- * ```
251
- *
252
- * @public
253
- */
254
- async executeWithTimeout(operation, timeoutMs) {
255
- const timeout = timeoutMs ?? this.defaultQueryTimeoutMs;
256
- if (timeout <= 0) {
257
- return operation();
258
- }
259
- let timeoutId;
260
- const timeoutPromise = new Promise((_, reject) => {
261
- timeoutId = setTimeout(() => {
262
- reject(
263
- this.createDatabaseError(
264
- "timeout",
265
- `Query execution timed out after ${timeout}ms`
266
- )
267
- );
268
- }, timeout);
269
- });
270
- try {
271
- const result = await Promise.race([operation(), timeoutPromise]);
272
- return result;
273
- } finally {
274
- if (timeoutId !== void 0) {
275
- clearTimeout(timeoutId);
276
- }
277
- }
278
- }
279
- /**
280
- * Set the default query timeout.
281
- *
282
- * @remarks
283
- * This method allows runtime configuration of the default timeout.
284
- * Subclasses should call this in their constructor or connect() method
285
- * based on their configuration.
286
- *
287
- * @param timeoutMs - Timeout in milliseconds (0 to disable)
288
- *
289
- * @protected
290
- */
291
- setDefaultQueryTimeout(timeoutMs) {
292
- this.defaultQueryTimeoutMs = timeoutMs;
293
- }
294
- /**
295
- * Get the current default query timeout.
296
- *
297
- * @returns Current default timeout in milliseconds
298
- *
299
- * @public
300
- */
301
- getDefaultQueryTimeout() {
302
- return this.defaultQueryTimeoutMs;
303
- }
304
- // ============================================================
305
- // CRUD Operations (Default implementations, can override)
306
- // ============================================================
307
- /**
308
- * Select multiple records from a table.
309
- *
310
- * @remarks
311
- * Default implementation builds a SELECT query and executes it.
312
- * Subclasses can override for optimization or dialect-specific features.
313
- *
314
- * @param table - Table name
315
- * @param options - Select options (filtering, sorting, pagination)
316
- * @returns Array of matching records
317
- *
318
- * @throws {DatabaseError} If query fails
319
- *
320
- * @example
321
- * ```typescript
322
- * const users = await adapter.select('users', {
323
- * where: { and: [{ column: 'role', op: '=', value: 'admin' }] },
324
- * orderBy: [{ column: 'created_at', direction: 'desc' }],
325
- * limit: 10
326
- * });
327
- * ```
328
- */
329
- async select(table, options) {
330
- const tableObj = this.getTableObject(table);
331
- if (tableObj) {
332
- try {
333
- const db = this.getDrizzle();
334
- let query = db.select().from(tableObj);
335
- if (options?.where) {
336
- const whereCondition = buildDrizzleWhere(
337
- tableObj,
338
- options.where
339
- );
340
- if (whereCondition) {
341
- query = query.where(whereCondition);
342
- }
343
- }
344
- if (options?.orderBy?.length) {
345
- const columns = getTableColumns(tableObj);
346
- const orderClauses = options.orderBy.map((o) => {
347
- const col = columns[o.column];
348
- if (!col) return void 0;
349
- return o.direction === "desc" ? desc(col) : asc(col);
350
- }).filter(Boolean);
351
- if (orderClauses.length) {
352
- query = query.orderBy(...orderClauses);
353
- }
354
- }
355
- if (options?.limit !== void 0) {
356
- query = query.limit(options.limit);
357
- }
358
- if (options?.offset !== void 0) {
359
- query = query.offset(options.offset);
360
- }
361
- return await query;
362
- } catch (error) {
363
- throw this.handleQueryError(error, "select", table);
364
- }
365
- }
366
- throw this.createDatabaseError(
367
- "query",
368
- `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`,
369
- void 0
370
- );
371
- }
372
- /**
373
- * Select a single record from a table.
374
- *
375
- * @remarks
376
- * Default implementation uses `select()` with limit 1 and returns first result.
377
- * Returns null if no matching record is found.
378
- *
379
- * @param table - Table name
380
- * @param options - Select options
381
- * @returns First matching record or null
382
- *
383
- * @throws {DatabaseError} If query fails
384
- *
385
- * @example
386
- * ```typescript
387
- * const user = await adapter.selectOne('users', {
388
- * where: { and: [{ column: 'email', op: '=', value: 'user@example.com' }] }
389
- * });
390
- * ```
391
- */
392
- async selectOne(table, options) {
393
- const results = await this.select(table, { ...options, limit: 1 });
394
- return results.length > 0 ? results[0] : null;
395
- }
396
- /**
397
- * Insert a single record into a table.
398
- *
399
- * @remarks
400
- * Default implementation handles databases with and without RETURNING support.
401
- * For databases without RETURNING (MySQL), performs INSERT followed by SELECT.
402
- *
403
- * @param table - Table name
404
- * @param data - Record data to insert
405
- * @param options - Insert options
406
- * @returns Inserted record (with RETURNING columns if specified)
407
- *
408
- * @throws {DatabaseError} If insert fails
409
- *
410
- * @example
411
- * ```typescript
412
- * const user = await adapter.insert('users', {
413
- * email: 'user@example.com',
414
- * name: 'John Doe'
415
- * }, { returning: ['id', 'email', 'created_at'] });
416
- * ```
417
- */
418
- async insert(table, data, options) {
419
- const tableObj = this.getTableObject(table);
420
- if (tableObj) {
421
- try {
422
- const mappedData = this.mapDataToColumnNames(tableObj, data);
423
- const db = this.getDrizzle();
424
- const caps = this.getCapabilities();
425
- if (caps.supportsReturning && options?.returning) {
426
- const result2 = await db.insert(tableObj).values(mappedData).returning();
427
- return Array.isArray(result2) ? result2[0] : result2;
428
- }
429
- const result = await db.insert(tableObj).values(mappedData);
430
- if (!caps.supportsReturning && options?.returning) {
431
- if (data.id !== void 0) {
432
- return await this.selectOne(table, {
433
- where: {
434
- and: [{ column: "id", op: "=", value: data.id }]
435
- }
436
- });
437
- }
438
- }
439
- return Array.isArray(result) ? result[0] : result;
440
- } catch (error) {
441
- throw this.handleQueryError(error, "insert", table);
442
- }
443
- }
444
- throw this.createDatabaseError(
445
- "query",
446
- `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`,
447
- void 0
448
- );
449
- }
450
- /**
451
- * Insert multiple records into a table.
452
- *
453
- * @remarks
454
- * Default implementation performs individual inserts in sequence.
455
- * Subclasses can override for bulk insert optimization (e.g., COPY in PostgreSQL).
456
- *
457
- * @param table - Table name
458
- * @param data - Array of records to insert
459
- * @param options - Insert options
460
- * @returns Inserted records (with RETURNING columns if specified)
461
- *
462
- * @throws {DatabaseError} If insert fails
463
- *
464
- * @example
465
- * ```typescript
466
- * const users = await adapter.insertMany('users', [
467
- * { email: 'user1@example.com', name: 'User 1' },
468
- * { email: 'user2@example.com', name: 'User 2' }
469
- * ], { returning: ['id'] });
470
- * ```
471
- */
472
- async insertMany(table, data, options) {
473
- if (data.length === 0) {
474
- return [];
475
- }
476
- const results = [];
477
- for (const record of data) {
478
- const result = await this.insert(table, record, options);
479
- results.push(result);
480
- }
481
- return results;
482
- }
483
- /**
484
- * Update records in a table.
485
- *
486
- * @remarks
487
- * Default implementation builds an UPDATE query with WHERE clause.
488
- * Returns updated records if RETURNING is supported and requested.
489
- *
490
- * @param table - Table name
491
- * @param data - Data to update
492
- * @param where - Conditions for records to update
493
- * @param options - Update options
494
- * @returns Updated records (with RETURNING columns if specified)
495
- *
496
- * @throws {DatabaseError} If update fails
497
- *
498
- * @example
499
- * ```typescript
500
- * const updated = await adapter.update('users',
501
- * { status: 'active' },
502
- * { and: [{ column: 'id', op: '=', value: userId }] },
503
- * { returning: ['id', 'status', 'updated_at'] }
504
- * );
505
- * ```
506
- */
507
- async update(table, data, where, options) {
508
- const tableObj = this.getTableObject(table);
509
- if (tableObj) {
510
- try {
511
- const db = this.getDrizzle();
512
- const caps = this.getCapabilities();
513
- const mappedData = this.mapDataToColumnNames(tableObj, data);
514
- let query = db.update(tableObj).set(mappedData);
515
- const whereCondition = buildDrizzleWhere(tableObj, where);
516
- if (whereCondition) {
517
- query = query.where(whereCondition);
518
- }
519
- if (caps.supportsReturning && options?.returning) {
520
- return await query.returning();
521
- }
522
- await query;
523
- if (!caps.supportsReturning && options?.returning) {
524
- return await this.select(table, { where });
525
- }
526
- return [];
527
- } catch (error) {
528
- throw this.handleQueryError(error, "update", table);
529
- }
530
- }
531
- throw this.createDatabaseError(
532
- "query",
533
- `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`,
534
- void 0
535
- );
536
- }
537
- /**
538
- * Delete records from a table.
539
- *
540
- * @remarks
541
- * Default implementation builds a DELETE query with WHERE clause.
542
- * Returns the number of deleted records.
543
- *
544
- * @param table - Table name
545
- * @param where - Conditions for records to delete
546
- * @param options - Delete options
547
- * @returns Number of deleted records
548
- *
549
- * @throws {DatabaseError} If delete fails
550
- *
551
- * @example
552
- * ```typescript
553
- * const count = await adapter.delete('users', {
554
- * and: [{ column: 'status', op: '=', value: 'inactive' }]
555
- * });
556
- * console.log(`Deleted ${count} users`);
557
- * ```
558
- */
559
- async delete(table, where, _options) {
560
- const tableObj = this.getTableObject(table);
561
- if (tableObj) {
562
- try {
563
- const db = this.getDrizzle();
564
- let query = db.delete(tableObj);
565
- const whereCondition = buildDrizzleWhere(tableObj, where);
566
- if (whereCondition) {
567
- query = query.where(whereCondition);
568
- }
569
- const result = await query;
570
- return Array.isArray(result) ? result.length : result?.rowCount ?? result?.changes ?? 0;
571
- } catch (error) {
572
- throw this.handleQueryError(error, "delete", table);
573
- }
574
- }
575
- throw this.createDatabaseError(
576
- "query",
577
- `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`,
578
- void 0
579
- );
580
- }
581
- /**
582
- * Upsert (INSERT or UPDATE) a record.
583
- *
584
- * @remarks
585
- * Default implementation uses dialect-specific ON CONFLICT syntax.
586
- * PostgreSQL/SQLite: ON CONFLICT ... DO UPDATE
587
- * MySQL: ON DUPLICATE KEY UPDATE
588
- *
589
- * @param table - Table name
590
- * @param data - Record data
591
- * @param options - Upsert options (must specify conflict columns)
592
- * @returns Upserted record (with RETURNING columns if specified)
593
- *
594
- * @throws {DatabaseError} If upsert fails
595
- *
596
- * @example
597
- * ```typescript
598
- * const user = await adapter.upsert('users', {
599
- * email: 'user@example.com',
600
- * name: 'Updated Name'
601
- * }, {
602
- * conflictColumns: ['email'],
603
- * updateColumns: ['name'],
604
- * returning: ['id', 'email', 'name']
605
- * });
606
- * ```
607
- */
608
- async upsert(table, data, options) {
609
- const tableObj = this.getTableObject(table);
610
- if (tableObj) {
611
- try {
612
- const db = this.getDrizzle();
613
- const caps = this.getCapabilities();
614
- const columns = getTableColumns(tableObj);
615
- const conflictTarget = options.conflictColumns.map((col) => columns[col]).filter(Boolean);
616
- const conflictSet = new Set(options.conflictColumns);
617
- const updateData = {};
618
- const updateColumns = options.updateColumns ?? Object.keys(data);
619
- for (const key of updateColumns) {
620
- if (!conflictSet.has(key) && key in data) {
621
- updateData[key] = data[key];
622
- }
623
- }
624
- let query;
625
- if (caps.supportsOnConflict) {
626
- query = db.insert(tableObj).values(data).onConflictDoUpdate({
627
- target: conflictTarget,
628
- set: updateData
629
- });
630
- } else {
631
- query = db.insert(tableObj).values(data);
632
- }
633
- if (caps.supportsReturning) {
634
- const result = await query.returning();
635
- return Array.isArray(result) ? result[0] : result;
636
- }
637
- await query;
638
- if (options.conflictColumns.length && data[options.conflictColumns[0]] !== void 0) {
639
- return await this.selectOne(table, {
640
- where: {
641
- and: [
642
- {
643
- column: options.conflictColumns[0],
644
- op: "=",
645
- value: data[options.conflictColumns[0]]
646
- }
647
- ]
648
- }
649
- });
650
- }
651
- return data;
652
- } catch (error) {
653
- throw this.handleQueryError(error, "upsert", table);
654
- }
655
- }
656
- throw this.createDatabaseError(
657
- "query",
658
- `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`,
659
- void 0
660
- );
661
- }
662
- // ============================================================
663
- // Migration Support (Default implementations, can override)
664
- // ============================================================
665
- /**
666
- * Run pending migrations.
667
- *
668
- * @remarks
669
- * Default implementation is a placeholder. Subclasses should implement
670
- * migration tracking and execution logic.
671
- *
672
- * @param migrations - Array of migrations to run
673
- * @returns Migration result with applied and pending migrations
674
- *
675
- * @throws {DatabaseError} If migration fails
676
- */
677
- // Base implementation throws synchronously; dialect adapters override with async logic.
678
- // eslint-disable-next-line @typescript-eslint/require-await
679
- async migrate(_migrations) {
680
- throw this.createDatabaseError(
681
- "query",
682
- "migrate() must be implemented by dialect-specific adapter. Use PostgresAdapter, MySqlAdapter, or SqliteAdapter.",
683
- void 0
684
- );
685
- }
686
- /**
687
- * Rollback the last migration.
688
- *
689
- * @remarks
690
- * Default implementation is a placeholder. Subclasses should implement
691
- * migration rollback logic.
692
- *
693
- * @returns Migration result after rollback
694
- *
695
- * @throws {DatabaseError} If rollback fails
696
- */
697
- // Base implementation throws synchronously; dialect adapters override with async logic.
698
- // eslint-disable-next-line @typescript-eslint/require-await
699
- async rollback() {
700
- throw this.createDatabaseError(
701
- "query",
702
- "rollback() must be implemented by dialect-specific adapter. Use PostgresAdapter, MySqlAdapter, or SqliteAdapter.",
703
- void 0
704
- );
705
- }
706
- /**
707
- * Get migration status.
708
- *
709
- * @remarks
710
- * Default implementation is a placeholder. Subclasses should implement
711
- * migration status checking.
712
- *
713
- * @returns Current migration status
714
- *
715
- * @throws {DatabaseError} If status check fails
716
- */
717
- async getMigrationStatus() {
718
- try {
719
- const rows = await this.executeQuery(`SELECT * FROM "__drizzle_migrations" ORDER BY created_at ASC`);
720
- const applied = rows.map((r) => ({
721
- id: String(r.id),
722
- name: r.hash,
723
- appliedAt: new Date(r.created_at),
724
- checksum: r.hash
725
- }));
726
- return {
727
- applied,
728
- pending: [],
729
- current: applied.length > 0 ? applied[applied.length - 1].id : null
730
- };
731
- } catch {
732
- return { applied: [], pending: [], current: null };
733
- }
734
- }
735
- // ============================================================
736
- // Schema Operations (Default implementations, can override)
737
- // ============================================================
738
- /**
739
- * Create a new table.
740
- *
741
- * @remarks
742
- * Default implementation is a placeholder. Subclasses should implement
743
- * table creation logic.
744
- *
745
- * @param definition - Table definition
746
- * @param options - Creation options
747
- *
748
- * @throws {DatabaseError} If table creation fails
749
- */
750
- async createTable(definition, options) {
751
- const columnDefs = definition.columns.map((col) => {
752
- let colSql = `${this.escapeIdentifier(col.name)} ${col.type.toUpperCase()}`;
753
- if (col.primaryKey) colSql += " PRIMARY KEY";
754
- if (col.nullable === false) colSql += " NOT NULL";
755
- if (col.unique) colSql += " UNIQUE";
756
- if (col.default !== void 0) {
757
- colSql += ` DEFAULT ${renderDefaultValue(col.default, col.name)}`;
758
- }
759
- return colSql;
760
- });
761
- const ifNotExists = options?.ifNotExists !== false ? "IF NOT EXISTS " : "";
762
- const query = `CREATE TABLE ${ifNotExists}${this.escapeIdentifier(definition.name)} (
763
- ${columnDefs.join(",\n ")}
764
- )`;
765
- try {
766
- await this.executeQuery(query);
767
- } catch (error) {
768
- throw this.handleQueryError(error, "createTable", definition.name);
769
- }
770
- }
771
- /**
772
- * Drop a table.
773
- *
774
- * @remarks
775
- * Default implementation is a placeholder. Subclasses should implement
776
- * table dropping logic.
777
- *
778
- * @param tableName - Name of table to drop
779
- * @param options - Drop options
780
- *
781
- * @throws {DatabaseError} If table drop fails
782
- */
783
- async dropTable(tableName, options) {
784
- const ifExists = options?.ifExists !== false ? "IF EXISTS " : "";
785
- const cascade = options?.cascade ? " CASCADE" : "";
786
- const query = `DROP TABLE ${ifExists}${this.escapeIdentifier(tableName)}${cascade}`;
787
- try {
788
- await this.executeQuery(query);
789
- } catch (error) {
790
- throw this.handleQueryError(error, "dropTable", tableName);
791
- }
792
- }
793
- /**
794
- * Alter an existing table.
795
- *
796
- * @remarks
797
- * Default implementation is a placeholder. Subclasses should implement
798
- * table alteration logic.
799
- *
800
- * @param tableName - Name of table to alter
801
- * @param operations - Alteration operations
802
- * @param options - Alter options
803
- *
804
- * @throws {DatabaseError} If table alteration fails
805
- */
806
- async alterTable(tableName, operations, _options) {
807
- const quotedTable = this.escapeIdentifier(tableName);
808
- for (const op of operations) {
809
- let query;
810
- switch (op.kind) {
811
- case "add_column": {
812
- let colDef = `${this.escapeIdentifier(op.column.name)} ${op.column.type.toUpperCase()}`;
813
- if (op.column.nullable === false) colDef += " NOT NULL";
814
- if (op.column.unique) colDef += " UNIQUE";
815
- if (op.column.default !== void 0) {
816
- const defaultVal = typeof op.column.default === "object" && op.column.default !== null && "sql" in op.column.default ? op.column.default.sql : typeof op.column.default === "string" ? `'${op.column.default}'` : String(op.column.default);
817
- colDef += ` DEFAULT ${defaultVal}`;
818
- }
819
- query = `ALTER TABLE ${quotedTable} ADD COLUMN ${colDef}`;
820
- break;
821
- }
822
- case "drop_column": {
823
- const cascade = op.cascade ? " CASCADE" : "";
824
- query = `ALTER TABLE ${quotedTable} DROP COLUMN ${this.escapeIdentifier(op.columnName)}${cascade}`;
825
- break;
826
- }
827
- case "rename_column":
828
- query = `ALTER TABLE ${quotedTable} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;
829
- break;
830
- case "modify_column": {
831
- query = `ALTER TABLE ${quotedTable} ALTER COLUMN ${this.escapeIdentifier(op.column.name)} TYPE ${op.column.type.toUpperCase()}`;
832
- break;
833
- }
834
- case "add_constraint":
835
- {
836
- const constraintCols = op.constraint.columns ?? [];
837
- const colList = constraintCols.map((c) => this.escapeIdentifier(c)).join(", ");
838
- if (op.constraint.type === "check" && op.constraint.expression) {
839
- query = `ALTER TABLE ${quotedTable} ADD CONSTRAINT ${this.escapeIdentifier(op.constraint.name)} CHECK (${op.constraint.expression})`;
840
- } else {
841
- query = `ALTER TABLE ${quotedTable} ADD CONSTRAINT ${this.escapeIdentifier(op.constraint.name)} ${op.constraint.type.toUpperCase()} (${colList})`;
842
- }
843
- break;
844
- }
845
- case "drop_constraint": {
846
- const cascadeConstraint = op.cascade ? " CASCADE" : "";
847
- query = `ALTER TABLE ${quotedTable} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}${cascadeConstraint}`;
848
- break;
849
- }
850
- default:
851
- throw this.createDatabaseError(
852
- "query",
853
- `Unsupported alter table operation: ${op.kind}`,
854
- void 0
855
- );
856
- }
857
- try {
858
- await this.executeQuery(query);
859
- } catch (error) {
860
- throw this.handleQueryError(error, "alterTable", tableName);
861
- }
862
- }
863
- }
864
- /**
865
- * Check if a table exists in the database.
866
- *
867
- * @remarks
868
- * Uses dialect-specific information schema queries to check table existence.
869
- * This is useful for development mode auto-sync to determine whether to
870
- * CREATE or DROP/CREATE tables.
871
- *
872
- * @param tableName - Name of table to check
873
- * @param schema - Optional schema name (defaults to 'public' for PostgreSQL)
874
- * @returns True if table exists, false otherwise
875
- *
876
- * @throws {DatabaseError} If query fails
877
- *
878
- * @example
879
- * ```typescript
880
- * const exists = await adapter.tableExists('users');
881
- * if (exists) {
882
- * await adapter.dropTable('users');
883
- * }
884
- * await adapter.createTable(userTableDef);
885
- * ```
886
- */
887
- async tableExists(tableName, schema) {
888
- try {
889
- let sql;
890
- const params = [];
891
- switch (this.dialect) {
892
- case "postgresql":
893
- sql = `
571
+ /**
572
+ * Whether a `transaction()` call made from the current async context would
573
+ * join a transaction already open on this adapter, as a savepoint, rather
574
+ * than open one of its own.
575
+ *
576
+ * A caller about to do something no rollback can undo — removing a stored
577
+ * file, say — asks this first: work that joins an enclosing transaction is
578
+ * undone with it, while the effect it performs after its own savepoint
579
+ * releases is not.
580
+ *
581
+ * False here. Concrete rather than abstract so existing adapters keep
582
+ * working unchanged, and false is right for a pooled adapter: a call made
583
+ * inside another transaction's work opens its own transaction on its own
584
+ * connection, which commits independently.
585
+ *
586
+ * @returns True when the call would nest in an open transaction
587
+ */
588
+ inTransaction() {
589
+ return false;
590
+ }
591
+ /**
592
+ * The transaction each async flow is inside, kept per flow rather than per
593
+ * connection: on SQLite every request shares the one connection, and
594
+ * another request's open transaction says nothing about this one.
595
+ */
596
+ flowTransactions = new AsyncLocalStorage();
597
+ /** Each pool's reporting views, by method list (`observedPool`). Gone with the pool. */
598
+ observedPools = /* @__PURE__ */ new WeakMap();
599
+ /**
600
+ * Whether the calling async flow is inside a transaction on this adapter
601
+ * that has not finished: its own, or one it was started from inside.
602
+ *
603
+ * A write that must outlive any rollback — a count of a failed attempt, the
604
+ * spend of a single-use secret — asks this before running in a transaction
605
+ * of its own. Made inside an open transaction on SQLite, it joins that
606
+ * transaction as a savepoint and is undone with it. On PostgreSQL and MySQL
607
+ * it would commit on a connection of its own, so refusing it there too
608
+ * keeps code that passes on one dialect from failing on another. Unlike
609
+ * {@link inTransaction}, which asks whether a call would nest and is always
610
+ * false on a pooled adapter, this answers alike on every dialect, and
611
+ * another flow's open transaction never answers true.
612
+ *
613
+ * Covers transactions opened through {@link transaction} and through the
614
+ * Drizzle handle's own `transaction` on the dialects whose handle takes
615
+ * async work. A dialect that keeps scopes of its own judges from those
616
+ * instead; an adapter that does neither answers false.
617
+ *
618
+ * @experimental
619
+ * @returns True while a transaction the calling flow is inside is open
620
+ */
621
+ transactionOpenInFlow() {
622
+ for (let at = this.flowTransactions.getStore(); at !== void 0; at = at.enclosing) if (at.open) return true;
623
+ return false;
624
+ }
625
+ /**
626
+ * Run a whole transaction, from its BEGIN until its COMMIT or ROLLBACK has
627
+ * run, as the calling flow's open transaction, for
628
+ * {@link transactionOpenInFlow}. A dialect's `transaction` runs through
629
+ * this unless it judges the flow from scopes of its own.
630
+ *
631
+ * The transaction counts as open for its work and for anything the work
632
+ * starts, awaited or not, until it has finished. Something the work starts
633
+ * that outlives it then sees it closed, or the one enclosing it still open.
634
+ *
635
+ * @param run - The transaction, BEGIN to COMMIT or ROLLBACK
636
+ * @returns What `run` resolves to
637
+ */
638
+ runInFlowTransaction(run) {
639
+ const scope = {
640
+ open: true,
641
+ connected: false,
642
+ enclosing: this.flowTransactions.getStore(),
643
+ openedAt: escapeObserver() === void 0 ? void 0 : deepStack()
644
+ };
645
+ return this.flowTransactions.run(scope, async () => {
646
+ try {
647
+ return await run();
648
+ } finally {
649
+ scope.open = false;
650
+ }
651
+ });
652
+ }
653
+ /**
654
+ * Record that the calling flow's transaction now holds its own connection.
655
+ *
656
+ * A pooled dialect calls this right after checking out the connection a
657
+ * transaction runs on, so {@link notePoolAccess} can tell that checkout,
658
+ * which belongs to the transaction, from any later one, which escapes it.
659
+ */
660
+ markFlowTransactionConnected() {
661
+ const scope = this.flowTransactions.getStore();
662
+ if (scope !== void 0) scope.connected = true;
663
+ }
664
+ /**
665
+ * Check out, through `checkout`, the connection the calling flow's
666
+ * transaction runs on. A transaction opened inside another's work takes a
667
+ * second connection, so the checkout is reported first
668
+ * ({@link notePoolAccess}); once it holds its own, the transaction is
669
+ * marked connected, so its later checkouts are told apart from it.
670
+ *
671
+ * @param checkout - Takes a connection from the dialect's pool
672
+ * @returns The connection
673
+ */
674
+ async connectFlowTransaction(checkout) {
675
+ this.notePoolAccess();
676
+ const connection = await checkout();
677
+ this.markFlowTransactionConnected();
678
+ return connection;
679
+ }
680
+ /**
681
+ * Called by a pooled dialect before it takes anything from its pool: a
682
+ * query, or a connection checkout.
683
+ *
684
+ * While the calling flow is inside a transaction that already holds its own
685
+ * connection, a pool access runs on another connection: outside the
686
+ * transaction, blind to its uncommitted writes, not undone by its rollback,
687
+ * and able to stall a small pool. Such an access is reported to the
688
+ * observer a test harness installs under
689
+ * `Symbol.for("nextly.transactionEscapeObserver")`, with the stack that
690
+ * names its call site. With no observer installed, which is every
691
+ * production process, this is one property read.
692
+ *
693
+ * @param statement - What the pool call was handed, its SQL passed on so
694
+ * the harness can say which statement escaped; nothing for a checkout
695
+ */
696
+ notePoolAccess(statement) {
697
+ const observe = escapeObserver();
698
+ if (observe === void 0) return;
699
+ for (let at = this.flowTransactions.getStore(); at !== void 0; at = at.enclosing) if (at.open && at.connected) {
700
+ observe({
701
+ dialect: this.dialect,
702
+ stack: deepStack(),
703
+ openedAt: at.openedAt,
704
+ statement: statementOf(statement)
705
+ });
706
+ return;
707
+ }
708
+ }
709
+ /**
710
+ * `pool`, with {@link notePoolAccess} called before each of `methods`, for
711
+ * handing to code that queries the pool directly, such as Drizzle's handle.
712
+ * Everything else, `instanceof` included, reaches the pool unchanged.
713
+ *
714
+ * One view per pool and method list, made once: every Drizzle handle on the pool is given the
715
+ * same one, so `getDrizzle()` and `getDrizzle(relations)` share a `$client`, as they did when
716
+ * each was handed the pool itself.
717
+ *
718
+ * @param pool - The driver's pool
719
+ * @param methods - The pool methods that take a connection
720
+ * @returns A view of `pool` that reports those calls
721
+ */
722
+ observedPool(pool, methods) {
723
+ const key = methods.join(",");
724
+ const views = this.observedPools.get(pool) ?? /* @__PURE__ */ new Map();
725
+ this.observedPools.set(pool, views);
726
+ const cached = views.get(key);
727
+ if (cached) return cached;
728
+ const view = new Proxy(pool, { get: (target, property, receiver) => {
729
+ const value = Reflect.get(target, property, receiver);
730
+ if (typeof property !== "string" || !methods.includes(property) || typeof value !== "function") return value;
731
+ return (...args) => {
732
+ this.notePoolAccess(args[0]);
733
+ return Reflect.apply(value, target, args);
734
+ };
735
+ } });
736
+ views.set(key, view);
737
+ return view;
738
+ }
739
+ /**
740
+ * Run each of a pool-bound Drizzle handle's transactions on a connection
741
+ * `checkout` hands it, and return that connection as the adapter's own
742
+ * `transaction()` does: closed rather than pooled when no ROLLBACK can be
743
+ * confirmed on it, and never leaked by a failed BEGIN (`pinTransactions`).
744
+ *
745
+ * For PostgreSQL's and MySQL's handles. Apply it before
746
+ * {@link trackFlowTransactions}, which wraps whatever `transaction` the
747
+ * handle has at that point.
748
+ *
749
+ * @param db - A Drizzle handle on this adapter's pool
750
+ * @param checkout - Checks out a connection for one transaction
751
+ * @returns The same handle, its `transaction` replaced
752
+ */
753
+ pinDrizzleTransactions(db, checkout) {
754
+ return pinTransactions(db, checkout);
755
+ }
756
+ /**
757
+ * Make a Drizzle handle's own `transaction` count for
758
+ * {@link transactionOpenInFlow}, as the adapter's does.
759
+ *
760
+ * Core's services run their transactions through the handle on PostgreSQL
761
+ * and MySQL; without this, a call made inside one would be refused on
762
+ * SQLite, where they go through the adapter, and let through on the
763
+ * others. Not for SQLite's handle: its `transaction` takes only
764
+ * synchronous work, which no async flow can be inside.
765
+ *
766
+ * @param db - A Drizzle handle this adapter created
767
+ * @returns The same handle, its `transaction` tracked
768
+ */
769
+ trackFlowTransactions(db) {
770
+ const transactor = db;
771
+ const untracked = transactor.transaction.bind(transactor);
772
+ const tracked = (work, config) => this.runInFlowTransaction(() => untracked(work, config));
773
+ Object.defineProperty(db, "transaction", {
774
+ value: tracked,
775
+ configurable: true,
776
+ writable: true
777
+ });
778
+ return db;
779
+ }
780
+ /**
781
+ * Run `effect` once the write made from the current async context has
782
+ * committed: an event, a hook, a cache flush, anything outside the database
783
+ * that must not happen for a change that is rolled back.
784
+ *
785
+ * A caller invokes this after its own transaction has resolved. Where that
786
+ * transaction was nested in an enclosing one, as a savepoint, the change is
787
+ * not durable yet, and an adapter that nests (see {@link inTransaction})
788
+ * holds `effect` until the outermost transaction commits, and drops it when
789
+ * that transaction, or the savepoint it was registered in, rolls back. A
790
+ * held effect runs after the commit, before the outermost `transaction()`
791
+ * call resolves, in registration order; one that then throws or rejects is
792
+ * handed to `onDeferredFailure` rather than failing a transaction that has
793
+ * committed.
794
+ *
795
+ * Here `effect` runs now and the returned promise settles with it, its
796
+ * failure included. Concrete rather than abstract, as `inTransaction` is,
797
+ * and right for a pooled adapter: each transaction has its own connection
798
+ * and has committed by the time its caller continues.
799
+ *
800
+ * @experimental
801
+ * @param effect - What to run once the change is durable
802
+ * @param onDeferredFailure - Receives the error of a held effect that fails
803
+ * @returns Settles once `effect` has run, or once it has been held
804
+ */
805
+ async afterCommit(effect, _onDeferredFailure) {
806
+ await effect();
807
+ }
808
+ /**
809
+ * Table resolver for looking up Drizzle table objects by name.
810
+ * When set, CRUD methods use Drizzle's query API instead of raw SQL.
811
+ * Set via setTableResolver() after boot-time schema loading.
812
+ */
813
+ tableResolver = null;
814
+ /**
815
+ * Set the table resolver for Drizzle query API support.
816
+ * When a resolver is set, CRUD methods (select, insert, update, delete, upsert)
817
+ * will use Drizzle's query API (db.select().from(), etc.) instead of raw SQL
818
+ * string building. Falls back to raw SQL if the resolver doesn't have the table.
819
+ *
820
+ * @param resolver - TableResolver implementation (e.g. SchemaRegistry)
821
+ */
822
+ setTableResolver(resolver) {
823
+ this.tableResolver = resolver;
824
+ }
825
+ /**
826
+ * Get a Drizzle table object by name from the resolver.
827
+ * Returns null if no resolver is set or table is not found.
828
+ */
829
+ getTableObject(tableName) {
830
+ return this.tableResolver?.getTable(tableName) ?? null;
831
+ }
832
+ /**
833
+ * Run a Drizzle-built statement and return its rows.
834
+ *
835
+ * @remarks
836
+ * The CRUD methods resolve their table through the schema registry and reject
837
+ * any name it does not declare, which leaves no way to read from a table the
838
+ * ORM does not know — one mid-rename, above all — except by assembling SQL and
839
+ * quoting identifiers by hand. This takes Drizzle's `sql` template instead, so
840
+ * the dialect in use decides the quoting and the parameter binding.
841
+ *
842
+ * Concrete rather than abstract so existing adapters keep working unchanged.
843
+ * The three drivers disagree about both the call and the result: node-postgres
844
+ * returns `{ rows }`, mysql2 a `[rows, fields]` tuple, and better-sqlite3 has
845
+ * no `execute` at all and answers `all`. Keeping that here rather than at each
846
+ * call site is the point — a caller reasoning about it would be reasoning
847
+ * about a driver it cannot see.
848
+ *
849
+ * @param statement - Drizzle `sql` template to run
850
+ * @returns Rows the statement produced
851
+ */
852
+ async queryStatement(statement) {
853
+ if (this.getCapabilities().dialect === "sqlite") return await this.getDrizzle().all(statement);
854
+ const result = await this.getDrizzle().execute(statement);
855
+ if (Array.isArray(result)) return Array.isArray(result[0]) ? result[0] : result;
856
+ if (typeof result === "object" && result !== null && Array.isArray(result.rows)) return result.rows;
857
+ throw this.createDatabaseError("query", "Drizzle statement returned a result shape this adapter does not recognise; refusing to report it as an empty result.", void 0);
858
+ }
859
+ /**
860
+ * Map data keys from SQL column names (snake_case) to Drizzle JS property names (camelCase).
861
+ * Drizzle schemas define columns as e.g. `createdAt: timestamp("created_at")` — the JS
862
+ * property is `createdAt` but the SQL column is `created_at`. Services pass snake_case keys
863
+ * because they match the DB column names. This method maps them to the JS names Drizzle expects.
864
+ */
865
+ mapDataToColumnNames(tableObj, data) {
866
+ if (!tableObj || typeof tableObj !== "object") return data;
867
+ const sqlToJs = /* @__PURE__ */ new Map();
868
+ const jsonColumns = /* @__PURE__ */ new Set();
869
+ for (const [jsName, colDef] of Object.entries(tableObj)) {
870
+ if (!colDef || typeof colDef !== "object" || !("name" in colDef) || typeof colDef.name !== "string") continue;
871
+ const sqlName = colDef.name;
872
+ sqlToJs.set(sqlName, jsName);
873
+ if (isJsonColumn(colDef)) jsonColumns.add(jsName);
874
+ }
875
+ if (sqlToJs.size === 0) return data;
876
+ const mapped = {};
877
+ for (const [key, value] of Object.entries(data)) {
878
+ const jsKey = sqlToJs.get(key) ?? key;
879
+ if (jsonColumns.has(jsKey) && typeof value === "string") try {
880
+ mapped[jsKey] = JSON.parse(value);
881
+ } catch {
882
+ mapped[jsKey] = value;
883
+ }
884
+ else mapped[jsKey] = value;
885
+ }
886
+ return mapped;
887
+ }
888
+ /**
889
+ * Map data keys from Drizzle JS property names to SQL column names for the
890
+ * raw-SQL transaction insert path. The transaction context builds INSERT
891
+ * statements from Object.keys(data) used directly as column identifiers, so a
892
+ * table whose Drizzle property names differ from its SQL column names
893
+ * (camelCase core tables like nextly_versions) needs its keys translated
894
+ * first. For tables whose property names already equal their column names
895
+ * (the dynamic dc_/single_/comp_ tables) every lookup is identity, so
896
+ * existing callers are unaffected.
897
+ */
898
+ mapKeysToSqlColumns(tableObj, data) {
899
+ if (!tableObj || typeof tableObj !== "object") return data;
900
+ const jsToSql = /* @__PURE__ */ new Map();
901
+ for (const [jsName, colDef] of Object.entries(tableObj)) if (colDef && typeof colDef === "object" && "name" in colDef && typeof colDef.name === "string") jsToSql.set(jsName, colDef.name);
902
+ if (jsToSql.size === 0) return data;
903
+ const out = {};
904
+ for (const [key, value] of Object.entries(data)) out[jsToSql.get(key) ?? key] = value;
905
+ return out;
906
+ }
907
+ /**
908
+ * Map a list of column identifiers (Drizzle property names) to their SQL
909
+ * column names, for the raw-SQL transaction insert paths that build a
910
+ * RETURNING clause from `options.returning`. Same identity behavior as
911
+ * `mapKeysToSqlColumns`: names that are already SQL columns (the dynamic
912
+ * dc_/single_/comp_ tables) pass through unchanged.
913
+ */
914
+ mapColumnNamesToSql(tableObj, names) {
915
+ if (!tableObj || typeof tableObj !== "object") return names;
916
+ const jsToSql = /* @__PURE__ */ new Map();
917
+ for (const [jsName, colDef] of Object.entries(tableObj)) if (colDef && typeof colDef === "object" && "name" in colDef && typeof colDef.name === "string") jsToSql.set(jsName, colDef.name);
918
+ if (jsToSql.size === 0) return names;
919
+ return names.map((n) => jsToSql.get(n) ?? n);
920
+ }
921
+ /**
922
+ * Remap a raw-SQL result row's KEYS from SQL column names to Drizzle property
923
+ * names, so the raw-SQL transaction insert paths return the same key casing
924
+ * as the non-transactional (Drizzle) insert. Keys only - values are left
925
+ * untouched, so this does not change how JSON/date columns are decoded. For
926
+ * tables whose property names already equal their SQL columns (the dynamic
927
+ * dc_/single_/comp_ tables) every lookup is identity, so existing callers see
928
+ * no change.
929
+ */
930
+ mapRowKeysToJs(tableObj, row) {
931
+ if (!tableObj || typeof tableObj !== "object" || !row || typeof row !== "object") return row;
932
+ const sqlToJs = /* @__PURE__ */ new Map();
933
+ for (const [jsName, colDef] of Object.entries(tableObj)) if (colDef && typeof colDef === "object" && "name" in colDef && typeof colDef.name === "string") sqlToJs.set(colDef.name, jsName);
934
+ if (sqlToJs.size === 0) return row;
935
+ const out = {};
936
+ for (const [key, value] of Object.entries(row)) out[sqlToJs.get(key) ?? key] = value;
937
+ return out;
938
+ }
939
+ /**
940
+ * Decode a raw-SQL result row's DATE column values the way a Drizzle query
941
+ * would, so a write answers with the same representation a read of the same
942
+ * column gives.
943
+ *
944
+ * A Drizzle query path runs every value through its column definition; a
945
+ * raw-SQL path does not, so a dialect that stores a timestamp as a number
946
+ * answers a write with that number while every read answers a `Date`. Only
947
+ * date columns are touched, and a value that is already a `Date` is left
948
+ * alone, so a driver that decodes on its own is unaffected.
949
+ *
950
+ * Runs after {@link mapRowKeysToJs}: keys are Drizzle property names by then,
951
+ * which is what the table definition is keyed by.
952
+ */
953
+ mapDateValuesFromDriver(tableObj, row) {
954
+ if (!tableObj || typeof tableObj !== "object" || !row || typeof row !== "object") return row;
955
+ let decoded;
956
+ for (const [jsName, colDef] of Object.entries(tableObj)) {
957
+ if (!isDateColumn(colDef)) continue;
958
+ const value = row[jsName];
959
+ if (value == null || value instanceof Date) continue;
960
+ decoded ??= { ...row };
961
+ decoded[jsName] = colDef.mapFromDriverValue(value);
962
+ }
963
+ return decoded ?? row;
964
+ }
965
+ /**
966
+ * Encode a row's DATE values the way a Drizzle query would before binding
967
+ * them, so what lands in the column does not depend on the server's timezone.
968
+ *
969
+ * A column declared without a time zone stores a wall clock and records
970
+ * nothing about which zone it belongs to, so both ends have to agree. Drizzle
971
+ * writes UTC and reads UTC. A driver handed a `Date` writes the LOCAL wall
972
+ * clock instead, and the same row then reads back shifted by the offset --
973
+ * on a UTC server the two agree and nothing is visibly wrong, which is why
974
+ * this survives CI.
975
+ *
976
+ * Only date columns are touched. A value that is not a `Date` is left as it
977
+ * is, so a caller that already encoded one is not encoded twice.
978
+ *
979
+ * Keys may be spelled either way at this point, so both the Drizzle property
980
+ * name and the SQL column name resolve.
981
+ */
982
+ mapDateValuesToDriver(tableObj, data) {
983
+ if (!tableObj || typeof tableObj !== "object" || !data) return data;
984
+ const dateColumns = /* @__PURE__ */ new Map();
985
+ for (const [jsName, colDef] of Object.entries(tableObj)) {
986
+ if (!isDateColumn(colDef)) continue;
987
+ dateColumns.set(jsName, colDef);
988
+ const sqlName = colDef.name;
989
+ if (typeof sqlName === "string") dateColumns.set(sqlName, colDef);
990
+ }
991
+ if (dateColumns.size === 0) return data;
992
+ let encoded;
993
+ for (const [key, value] of Object.entries(data)) {
994
+ if (!(value instanceof Date)) continue;
995
+ const column = dateColumns.get(key);
996
+ if (!column) continue;
997
+ encoded ??= { ...data };
998
+ encoded[key] = column.mapToDriverValue(value);
999
+ }
1000
+ return encoded ?? data;
1001
+ }
1002
+ /**
1003
+ * Bring a row about to be written through a raw-SQL statement into the shape
1004
+ * a Drizzle query would have bound: SQL column names for keys, encoded values
1005
+ * for date columns.
1006
+ *
1007
+ * The mirror of {@link mapRowFromRawSql}. The raw-SQL write paths exist
1008
+ * because a dialect needs SQL a Drizzle query cannot express, not because
1009
+ * their callers want different values in the table.
1010
+ */
1011
+ mapRowToRawSql(tableObj, data) {
1012
+ return this.mapDateValuesToDriver(tableObj, this.mapKeysToSqlColumns(tableObj, data));
1013
+ }
1014
+ /**
1015
+ * Bring a raw-SQL result row into the shape a Drizzle query would have
1016
+ * produced: Drizzle property names for keys, decoded values for date columns.
1017
+ *
1018
+ * The raw-SQL write paths exist because a dialect needs SQL a Drizzle query
1019
+ * cannot express, not because their callers want a different row shape, so
1020
+ * every one of them ends here.
1021
+ */
1022
+ mapRowFromRawSql(tableObj, row, aliases = []) {
1023
+ const mapped = this.mapDateValuesFromDriver(tableObj, this.mapRowKeysToJs(tableObj, row));
1024
+ return this.applyWallClockAliases(mapped, aliases);
1025
+ }
1026
+ /**
1027
+ * The date columns a statement is about to return, and the alias each one's
1028
+ * wall clock is spelled out under.
1029
+ *
1030
+ * A driver turns a timestamp into a `Date` using ITS zone before any of this
1031
+ * code runs, and that conversion is lossy: a wall clock inside a
1032
+ * daylight-saving gap is a local time that does not exist, so the driver
1033
+ * normalizes it and the original is gone. Asking the database for the wall
1034
+ * clock as text alongside the row is the only way to read it exactly.
1035
+ *
1036
+ * `"*"` covers every date column; a projection covers only the ones it asked
1037
+ * for, so a caller still gets back what it requested and nothing more.
1038
+ */
1039
+ dateWallClockAliases(tableObj, returning) {
1040
+ if (!tableObj || typeof tableObj !== "object" || returning === void 0) return [];
1041
+ const requested = returning === "*" ? void 0 : new Set(returning.map(String));
1042
+ const taken = /* @__PURE__ */ new Set();
1043
+ for (const [jsName, colDef] of Object.entries(tableObj)) {
1044
+ taken.add(jsName);
1045
+ const columnName = colDef.name;
1046
+ if (typeof columnName === "string") taken.add(columnName);
1047
+ }
1048
+ let next = 0;
1049
+ const freeAlias = () => {
1050
+ let candidate = `${WALL_CLOCK_ALIAS_STEM}${next++}`;
1051
+ while (taken.has(candidate)) candidate = `${WALL_CLOCK_ALIAS_STEM}${next++}`;
1052
+ taken.add(candidate);
1053
+ return candidate;
1054
+ };
1055
+ const aliases = [];
1056
+ for (const [jsName, colDef] of Object.entries(tableObj)) {
1057
+ if (!isDateColumn(colDef)) continue;
1058
+ if (carriesTimeZone(colDef)) continue;
1059
+ const sqlName = colDef.name;
1060
+ if (typeof sqlName !== "string") continue;
1061
+ if (requested && !requested.has(sqlName) && !requested.has(jsName)) continue;
1062
+ aliases.push({
1063
+ sqlName,
1064
+ alias: freeAlias(),
1065
+ jsName
1066
+ });
1067
+ }
1068
+ return aliases;
1069
+ }
1070
+ /**
1071
+ * Replace each date in a row with the wall clock the database spelled out,
1072
+ * read as UTC, and drop the aliases that carried it.
1073
+ *
1074
+ * The statement writes a UTC wall clock, so reading one back as UTC is what
1075
+ * makes a write and a later read agree. Whatever the column actually stored
1076
+ * is what arrives -- a column keeping only whole seconds reports whole
1077
+ * seconds -- because this is the database's own text, not a value
1078
+ * reconstructed from the one that was bound.
1079
+ */
1080
+ applyWallClockAliases(row, aliases) {
1081
+ if (!row || typeof row !== "object" || aliases.length === 0) return row;
1082
+ const record = row;
1083
+ let resolved;
1084
+ for (const { alias, jsName } of aliases) {
1085
+ if (!(alias in record)) continue;
1086
+ resolved ??= { ...record };
1087
+ const text = resolved[alias];
1088
+ delete resolved[alias];
1089
+ if (typeof text !== "string") continue;
1090
+ const parsed = parseWallClockAsUtc(text);
1091
+ if (parsed !== void 0) resolved[jsName] = parsed;
1092
+ }
1093
+ return resolved ?? row;
1094
+ }
1095
+ /**
1096
+ * Build a Drizzle column projection object (`{ propertyName: column }`) from a
1097
+ * requested column list, used by `select` (columns) and `insert` (returning).
1098
+ * A requested name resolves against either the Drizzle property name
1099
+ * (camelCase) or the SQL column name (snake_case); the projection is keyed by
1100
+ * the property name so the row shape matches a full select. Returns undefined
1101
+ * for `"*"` or when nothing resolves, so callers fall back to all columns.
1102
+ */
1103
+ buildColumnProjection(tableObj, names) {
1104
+ if (names == null || names === "*" || !tableObj || typeof tableObj !== "object") return;
1105
+ const { projection } = this.resolveColumns(tableObj, names);
1106
+ return Object.keys(projection).length ? projection : void 0;
1107
+ }
1108
+ /**
1109
+ * The requested column names split into what this table has and what it does not.
1110
+ *
1111
+ * One resolution, reported both ways, because two callers need different halves
1112
+ * of the same answer: a projection drops what it cannot find, while a distinct
1113
+ * count has to REFUSE it. Resolving twice would let the two disagree about what
1114
+ * "found" means — the SQL-name alias below is exactly the kind of detail a
1115
+ * second implementation gets wrong — and the count would then reject a column
1116
+ * the projection happily uses.
1117
+ *
1118
+ * Both spellings resolve: a caller may name the Drizzle property or the SQL
1119
+ * column, and either maps to the same projection key.
1120
+ */
1121
+ resolveColumns(tableObj, names) {
1122
+ const cols = getColumns(tableObj);
1123
+ const byAnyName = {};
1124
+ for (const [jsName, col] of Object.entries(cols)) {
1125
+ byAnyName[jsName] = {
1126
+ jsName,
1127
+ col
1128
+ };
1129
+ const sqlName = col?.name;
1130
+ if (typeof sqlName === "string") byAnyName[sqlName] = {
1131
+ jsName,
1132
+ col
1133
+ };
1134
+ }
1135
+ const projection = {};
1136
+ const unresolved = [];
1137
+ for (const name of names) {
1138
+ const hit = byAnyName[name];
1139
+ if (hit) projection[hit.jsName] = hit.col;
1140
+ else unresolved.push(name);
1141
+ }
1142
+ return {
1143
+ projection,
1144
+ unresolved
1145
+ };
1146
+ }
1147
+ /**
1148
+ * Check if the adapter is currently connected.
1149
+ *
1150
+ * @remarks
1151
+ * Default implementation returns false. Subclasses should override
1152
+ * to provide accurate connection status.
1153
+ *
1154
+ * @returns True if connected, false otherwise
1155
+ */
1156
+ isConnected() {
1157
+ return false;
1158
+ }
1159
+ /**
1160
+ * Get connection pool statistics.
1161
+ *
1162
+ * @remarks
1163
+ * Returns null by default. Subclasses with connection pooling
1164
+ * should override to provide pool statistics.
1165
+ *
1166
+ * @returns Pool statistics or null if not applicable
1167
+ */
1168
+ getPoolStats() {
1169
+ return null;
1170
+ }
1171
+ /**
1172
+ * Default query timeout in milliseconds.
1173
+ *
1174
+ * @remarks
1175
+ * This value is used by executeWithTimeout() when no explicit timeout
1176
+ * is provided. Subclasses should set this from their config.
1177
+ *
1178
+ * @default 15000 (15 seconds)
1179
+ *
1180
+ * @protected
1181
+ */
1182
+ defaultQueryTimeoutMs = 15e3;
1183
+ /**
1184
+ * Execute an async operation with a timeout.
1185
+ *
1186
+ * @remarks
1187
+ * Wraps an async operation with a timeout that aborts if the operation
1188
+ * exceeds the specified duration. Uses Promise.race for clean timeout
1189
+ * handling without memory leaks.
1190
+ *
1191
+ * When the timeout is reached, a DatabaseError with kind 'timeout' is thrown.
1192
+ * Note that this does NOT cancel the underlying database query - it only
1193
+ * prevents the calling code from waiting indefinitely. For true query
1194
+ * cancellation, use database-level statement timeouts (PostgreSQL) or
1195
+ * similar mechanisms.
1196
+ *
1197
+ * @param operation - Async operation to execute
1198
+ * @param timeoutMs - Timeout in milliseconds (defaults to defaultQueryTimeoutMs)
1199
+ * @returns Result of the operation
1200
+ *
1201
+ * @throws {DatabaseError} With kind 'timeout' if operation exceeds timeout
1202
+ *
1203
+ * @example
1204
+ * ```typescript
1205
+ * // Use default timeout
1206
+ * const result = await adapter.executeWithTimeout(
1207
+ * () => adapter.select('users', { limit: 1000 })
1208
+ * );
1209
+ *
1210
+ * // Use custom timeout for specific operation
1211
+ * const result = await adapter.executeWithTimeout(
1212
+ * () => adapter.select('large_table'),
1213
+ * 60000 // 60 seconds for large queries
1214
+ * );
1215
+ * ```
1216
+ *
1217
+ * @public
1218
+ */
1219
+ async executeWithTimeout(operation, timeoutMs) {
1220
+ const timeout = timeoutMs ?? this.defaultQueryTimeoutMs;
1221
+ if (timeout <= 0) return operation();
1222
+ let timeoutId;
1223
+ const timeoutPromise = new Promise((_, reject) => {
1224
+ timeoutId = setTimeout(() => {
1225
+ reject(this.createDatabaseError("timeout", `Query execution timed out after ${timeout}ms`));
1226
+ }, timeout);
1227
+ });
1228
+ try {
1229
+ return await Promise.race([operation(), timeoutPromise]);
1230
+ } finally {
1231
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
1232
+ }
1233
+ }
1234
+ /**
1235
+ * Set the default query timeout.
1236
+ *
1237
+ * @remarks
1238
+ * This method allows runtime configuration of the default timeout.
1239
+ * Subclasses should call this in their constructor or connect() method
1240
+ * based on their configuration.
1241
+ *
1242
+ * @param timeoutMs - Timeout in milliseconds (0 to disable)
1243
+ *
1244
+ * @protected
1245
+ */
1246
+ setDefaultQueryTimeout(timeoutMs) {
1247
+ this.defaultQueryTimeoutMs = timeoutMs;
1248
+ }
1249
+ /**
1250
+ * Get the current default query timeout.
1251
+ *
1252
+ * @returns Current default timeout in milliseconds
1253
+ *
1254
+ * @public
1255
+ */
1256
+ getDefaultQueryTimeout() {
1257
+ return this.defaultQueryTimeoutMs;
1258
+ }
1259
+ /**
1260
+ * Select multiple records from a table.
1261
+ *
1262
+ * @remarks
1263
+ * Default implementation builds a SELECT query and executes it.
1264
+ * Subclasses can override for optimization or dialect-specific features.
1265
+ *
1266
+ * @param table - Table name
1267
+ * @param options - Select options (filtering, sorting, pagination)
1268
+ * @returns Array of matching records
1269
+ *
1270
+ * @throws {DatabaseError} If query fails
1271
+ *
1272
+ * @example
1273
+ * ```typescript
1274
+ * const users = await adapter.select('users', {
1275
+ * where: { and: [{ column: 'role', op: '=', value: 'admin' }] },
1276
+ * orderBy: [{ column: 'created_at', direction: 'desc' }],
1277
+ * limit: 10
1278
+ * });
1279
+ * ```
1280
+ */
1281
+ async select(table, options, executor) {
1282
+ const tableObj = this.getTableObject(table);
1283
+ if (tableObj) try {
1284
+ const db = executor ?? this.getDrizzle();
1285
+ const projection = options?.columns?.length ? this.buildColumnProjection(tableObj, options.columns) : void 0;
1286
+ let query = projection ? db.select(projection).from(tableObj) : db.select().from(tableObj);
1287
+ if (options?.where) {
1288
+ const whereCondition = buildDrizzleWhere(tableObj, options.where);
1289
+ if (whereCondition) query = query.where(whereCondition);
1290
+ }
1291
+ if (options?.orderBy?.length) {
1292
+ const orderClauses = buildDrizzleOrderBy(getColumns(tableObj), options.orderBy);
1293
+ if (orderClauses.length) query = query.orderBy(...orderClauses);
1294
+ }
1295
+ if (options?.limit !== void 0) query = query.limit(options.limit);
1296
+ if (options?.offset !== void 0) query = query.offset(options.offset);
1297
+ if (options?.forUpdate && !executor) throw this.createDatabaseError("query", "forUpdate requires a transaction executor: a lock request on the pooled connection takes no durable lock and cannot prevent a concurrent write.", void 0);
1298
+ if (options?.forUpdate && this.dialect !== "sqlite") query = query.for("update");
1299
+ return await query;
1300
+ } catch (error) {
1301
+ throw this.handleQueryError(error, "select", table);
1302
+ }
1303
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1304
+ }
1305
+ /**
1306
+ * Select a single record from a table.
1307
+ *
1308
+ * @remarks
1309
+ * Default implementation uses `select()` with limit 1 and returns first result.
1310
+ * Returns null if no matching record is found.
1311
+ *
1312
+ * @param table - Table name
1313
+ * @param options - Select options
1314
+ * @returns First matching record or null
1315
+ *
1316
+ * @throws {DatabaseError} If query fails
1317
+ *
1318
+ * @example
1319
+ * ```typescript
1320
+ * const user = await adapter.selectOne('users', {
1321
+ * where: { and: [{ column: 'email', op: '=', value: 'user@example.com' }] }
1322
+ * });
1323
+ * ```
1324
+ */
1325
+ /** The registered table object, or a refusal naming what is missing. */
1326
+ requireTableObject(table) {
1327
+ const tableObj = this.getTableObject(table);
1328
+ if (tableObj) return tableObj;
1329
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1330
+ }
1331
+ /**
1332
+ * The columns a distinct count groups by, or `undefined` for a row count.
1333
+ *
1334
+ * 🔴 EVERY named column must resolve, not merely one of them. A `distinctOn`
1335
+ * naming no column this table has would fall through to a row count, and one
1336
+ * naming a valid column beside a misspelled or since-removed column would
1337
+ * count distinct over a NARROWER key than the caller asked for. Both answer a
1338
+ * different question than the one asked, silently; the second is the worse of
1339
+ * the two, because a subset key groups more rows together and so UNDERCOUNTS,
1340
+ * which reads as a plausible number rather than as a fault. Refused here,
1341
+ * where the mistake was made, rather than surfacing as a wrong figure.
1342
+ */
1343
+ countProjection(tableObj, table, options) {
1344
+ const distinctOn = options?.distinctOn;
1345
+ if (!distinctOn?.length) return void 0;
1346
+ const { projection, unresolved } = this.resolveColumns(tableObj, distinctOn);
1347
+ if (unresolved.length > 0) throw this.createDatabaseError("query", `distinctOn names ${unresolved.length === 1 ? "a column" : "columns"} that do not exist on "${table}": ${unresolved.join(", ")}`, void 0);
1348
+ return projection;
1349
+ }
1350
+ /**
1351
+ * `COUNT(*)` over a `SELECT DISTINCT` subquery.
1352
+ *
1353
+ * Its own function because it is a genuinely different query from the plain
1354
+ * count rather than a variation on one, and because building both inline made
1355
+ * the public method a chain of decisions the complexity gate objected to
1356
+ * before a reader would have.
1357
+ */
1358
+ async countDistinctRows(db, tableObj, projection, where) {
1359
+ const inner = db.selectDistinct(projection).from(tableObj).$dynamic();
1360
+ const distinctRows = where ? inner.where(where) : inner;
1361
+ const [row] = await db.select({ value: count() }).from(distinctRows.as("nextly_distinct"));
1362
+ return Number(row?.value ?? 0);
1363
+ }
1364
+ /** `COUNT(*)` over the table itself. */
1365
+ async countAllRows(db, tableObj, where) {
1366
+ const base = db.select({ value: count() }).from(tableObj).$dynamic();
1367
+ const [row] = await (where ? base.where(where) : base);
1368
+ return Number(row?.value ?? 0);
1369
+ }
1370
+ /**
1371
+ * How many rows match, or how many DISTINCT combinations of some columns do.
1372
+ *
1373
+ * The data layer had no count at all: collection totals go through
1374
+ * `countEntries`, an access-controlled path built for collection tables, and
1375
+ * nothing could count a system table. A caller wanting one selected the rows
1376
+ * and measured the array, which transfers every row to learn a number and
1377
+ * cannot be bounded without making the number wrong.
1378
+ *
1379
+ * 🔴 `distinctOn` compiles to `COUNT(*)` over a `SELECT DISTINCT` SUBQUERY,
1380
+ * never to `COUNT(DISTINCT a, b)`. The inline form is not portable and fails
1381
+ * in the direction that is hardest to notice -- MySQL accepts it, PostgreSQL
1382
+ * needs a row constructor, and SQLite rejects it outright with "wrong number
1383
+ * of arguments to function count()" -- so a query written against one engine
1384
+ * is a syntax error on another. The subquery is the single form all three
1385
+ * accept, and building it here rather than at each call site is what keeps
1386
+ * the answer identical per dialect.
1387
+ */
1388
+ async count(table, options, executor) {
1389
+ const tableObj = this.requireTableObject(table);
1390
+ try {
1391
+ const db = executor ?? this.getDrizzle();
1392
+ const where = options?.where ? buildDrizzleWhere(tableObj, options.where) : void 0;
1393
+ const projection = this.countProjection(tableObj, table, options);
1394
+ return projection ? await this.countDistinctRows(db, tableObj, projection, where) : await this.countAllRows(db, tableObj, where);
1395
+ } catch (error) {
1396
+ throw this.handleQueryError(error, "count", table);
1397
+ }
1398
+ }
1399
+ async selectOne(table, options, executor) {
1400
+ const results = await this.select(table, {
1401
+ ...options,
1402
+ limit: 1
1403
+ }, executor);
1404
+ return results.length > 0 ? results[0] : null;
1405
+ }
1406
+ /**
1407
+ * Insert a single record into a table.
1408
+ *
1409
+ * @remarks
1410
+ * Default implementation handles databases with and without RETURNING support.
1411
+ * For databases without RETURNING (MySQL), performs INSERT followed by SELECT.
1412
+ *
1413
+ * @param table - Table name
1414
+ * @param data - Record data to insert
1415
+ * @param options - Insert options
1416
+ * @returns Inserted record (with RETURNING columns if specified)
1417
+ *
1418
+ * @throws {DatabaseError} If insert fails
1419
+ *
1420
+ * @example
1421
+ * ```typescript
1422
+ * const user = await adapter.insert('users', {
1423
+ * email: 'user@example.com',
1424
+ * name: 'John Doe'
1425
+ * }, { returning: ['id', 'email', 'created_at'] });
1426
+ * ```
1427
+ */
1428
+ async insert(table, data, options) {
1429
+ const tableObj = this.getTableObject(table);
1430
+ if (tableObj) try {
1431
+ const mappedData = this.mapDataToColumnNames(tableObj, data);
1432
+ const db = this.getDrizzle();
1433
+ const caps = this.getCapabilities();
1434
+ const returning = options?.returning;
1435
+ const wantsReturning = returning != null && !(Array.isArray(returning) && returning.length === 0);
1436
+ if (caps.supportsReturning && wantsReturning) {
1437
+ const projection = this.buildColumnProjection(tableObj, returning);
1438
+ const insertQuery = db.insert(tableObj).values(mappedData);
1439
+ const result = await (projection ? insertQuery.returning(projection) : insertQuery.returning());
1440
+ return Array.isArray(result) ? result[0] : result;
1441
+ }
1442
+ const result = await db.insert(tableObj).values(mappedData);
1443
+ if (!caps.supportsReturning && wantsReturning && data.id !== void 0) return await this.selectOne(table, {
1444
+ columns: returning === "*" ? void 0 : returning,
1445
+ where: { and: [{
1446
+ column: "id",
1447
+ op: "=",
1448
+ value: data.id
1449
+ }] }
1450
+ });
1451
+ return Array.isArray(result) ? result[0] : result;
1452
+ } catch (error) {
1453
+ throw this.handleQueryError(error, "insert", table);
1454
+ }
1455
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1456
+ }
1457
+ /**
1458
+ * Insert multiple records into a table.
1459
+ *
1460
+ * @remarks
1461
+ * Default implementation performs individual inserts in sequence.
1462
+ * Subclasses can override for bulk insert optimization (e.g., COPY in PostgreSQL).
1463
+ *
1464
+ * @param table - Table name
1465
+ * @param data - Array of records to insert
1466
+ * @param options - Insert options
1467
+ * @returns Inserted records (with RETURNING columns if specified)
1468
+ *
1469
+ * @throws {DatabaseError} If insert fails
1470
+ *
1471
+ * @example
1472
+ * ```typescript
1473
+ * const users = await adapter.insertMany('users', [
1474
+ * { email: 'user1@example.com', name: 'User 1' },
1475
+ * { email: 'user2@example.com', name: 'User 2' }
1476
+ * ], { returning: ['id'] });
1477
+ * ```
1478
+ */
1479
+ async insertMany(table, data, options) {
1480
+ if (data.length === 0) return [];
1481
+ const results = [];
1482
+ for (const record of data) {
1483
+ const result = await this.insert(table, record, options);
1484
+ results.push(result);
1485
+ }
1486
+ return results;
1487
+ }
1488
+ /**
1489
+ * Update records in a table.
1490
+ *
1491
+ * @remarks
1492
+ * Default implementation builds an UPDATE query with WHERE clause.
1493
+ * Returns updated records if RETURNING is supported and requested.
1494
+ *
1495
+ * @param table - Table name
1496
+ * @param data - Data to update
1497
+ * @param where - Conditions for records to update
1498
+ * @param options - Update options
1499
+ * @returns Updated records (with RETURNING columns if specified)
1500
+ *
1501
+ * @throws {DatabaseError} If update fails
1502
+ *
1503
+ * @example
1504
+ * ```typescript
1505
+ * const updated = await adapter.update('users',
1506
+ * { status: 'active' },
1507
+ * { and: [{ column: 'id', op: '=', value: userId }] },
1508
+ * { returning: ['id', 'status', 'updated_at'] }
1509
+ * );
1510
+ * ```
1511
+ */
1512
+ async update(table, data, where, options, executor) {
1513
+ const tableObj = this.getTableObject(table);
1514
+ if (tableObj) try {
1515
+ const db = executor ?? this.getDrizzle();
1516
+ const caps = this.getCapabilities();
1517
+ const mappedData = this.mapDataToColumnNames(tableObj, data);
1518
+ let query = db.update(tableObj).set(mappedData);
1519
+ const whereCondition = buildDrizzleWhere(tableObj, where);
1520
+ if (whereCondition) query = query.where(whereCondition);
1521
+ if (caps.supportsReturning && options?.returning) return await query.returning();
1522
+ await query;
1523
+ if (!caps.supportsReturning && options?.returning) return await this.select(table, { where }, executor);
1524
+ return [];
1525
+ } catch (error) {
1526
+ throw this.handleQueryError(error, "update", table);
1527
+ }
1528
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1529
+ }
1530
+ /**
1531
+ * Update records in a table and report how many rows the statement affected.
1532
+ *
1533
+ * The count is the whole return value, mirroring `delete`. `update` cannot answer this: without
1534
+ * `returning` it discards the driver's count, and WITH `returning` on a dialect that lacks
1535
+ * RETURNING it re-SELECTs using the same WHERE — so a conditional update that just changed a
1536
+ * column named in that WHERE reads back zero rows and a write that landed reports as unmatched.
1537
+ * Reading the driver's own count has no second query to disagree with the first.
1538
+ *
1539
+ * 🔴 MySQL reports CHANGED rows, not matched rows: an UPDATE that matches a row but writes values
1540
+ * identical to what it holds counts zero. A caller using this as a compare-and-set must therefore
1541
+ * include a column the write always moves — a version bump, a timestamp with enough resolution —
1542
+ * so that matched implies changed. Postgres (`rowCount`) and SQLite (`changes`) count matched
1543
+ * rows and do not need the precaution, which is exactly why it cannot be dropped: the dialect
1544
+ * where the distinction exists is the one with no RETURNING to fall back on.
1545
+ */
1546
+ async updateCount(table, data, where, executor) {
1547
+ const tableObj = this.getTableObject(table);
1548
+ if (tableObj) try {
1549
+ const db = executor ?? this.getDrizzle();
1550
+ const mappedData = this.mapDataToColumnNames(tableObj, data);
1551
+ const statement = db.update(tableObj).set(mappedData);
1552
+ const whereCondition = buildDrizzleWhere(tableObj, where);
1553
+ return affectedRowCount(await (whereCondition ? statement.where(whereCondition) : statement));
1554
+ } catch (error) {
1555
+ throw this.handleQueryError(error, "update", table);
1556
+ }
1557
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1558
+ }
1559
+ /**
1560
+ * Delete records from a table.
1561
+ *
1562
+ * @remarks
1563
+ * Default implementation builds a DELETE query with WHERE clause.
1564
+ * Returns the number of deleted records.
1565
+ *
1566
+ * @param table - Table name
1567
+ * @param where - Conditions for records to delete
1568
+ * @param options - Delete options
1569
+ * @returns Number of deleted records
1570
+ *
1571
+ * @throws {DatabaseError} If delete fails
1572
+ *
1573
+ * @example
1574
+ * ```typescript
1575
+ * const count = await adapter.delete('users', {
1576
+ * and: [{ column: 'status', op: '=', value: 'inactive' }]
1577
+ * });
1578
+ * console.log(`Deleted ${count} users`);
1579
+ * ```
1580
+ */
1581
+ async delete(table, where, _options, executor) {
1582
+ const tableObj = this.getTableObject(table);
1583
+ if (tableObj) try {
1584
+ let query = (executor ?? this.getDrizzle()).delete(tableObj);
1585
+ const whereCondition = buildDrizzleWhere(tableObj, where);
1586
+ if (whereCondition) query = query.where(whereCondition);
1587
+ return affectedRowCount(await query);
1588
+ } catch (error) {
1589
+ throw this.handleQueryError(error, "delete", table);
1590
+ }
1591
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1592
+ }
1593
+ /**
1594
+ * Upsert (INSERT or UPDATE) a record.
1595
+ *
1596
+ * @remarks
1597
+ * Default implementation uses dialect-specific ON CONFLICT syntax.
1598
+ * PostgreSQL/SQLite: ON CONFLICT ... DO UPDATE
1599
+ * MySQL: the MySQL adapter overrides this, resolving the conflict by the
1600
+ * conflict columns (see its `upsert`)
1601
+ *
1602
+ * @param table - Table name
1603
+ * @param data - Record data
1604
+ * @param options - Upsert options (must specify conflict columns)
1605
+ * @returns Upserted record (with RETURNING columns if specified)
1606
+ *
1607
+ * @throws {DatabaseError} If upsert fails
1608
+ *
1609
+ * @example
1610
+ * ```typescript
1611
+ * const user = await adapter.upsert('users', {
1612
+ * email: 'user@example.com',
1613
+ * name: 'Updated Name'
1614
+ * }, {
1615
+ * conflictColumns: ['email'],
1616
+ * updateColumns: ['name'],
1617
+ * returning: ['id', 'email', 'name']
1618
+ * });
1619
+ * ```
1620
+ */
1621
+ async upsert(table, data, options, executor) {
1622
+ const tableObj = this.getTableObject(table);
1623
+ if (tableObj) try {
1624
+ const db = executor ?? this.getDrizzle();
1625
+ const caps = this.getCapabilities();
1626
+ const columns = getColumns(tableObj);
1627
+ const conflictTarget = options.conflictColumns.map((col) => columns[col]).filter(Boolean);
1628
+ const conflictSet = new Set(options.conflictColumns);
1629
+ const updateData = {};
1630
+ const updateColumns = options.updateColumns ?? Object.keys(data);
1631
+ for (const key of updateColumns) if (!conflictSet.has(key) && key in data) updateData[key] = data[key];
1632
+ const keepExisting = Object.keys(updateData).length === 0;
1633
+ this.assertUpsertTarget(table, data, options, keepExisting);
1634
+ let query;
1635
+ if (caps.supportsOnConflict) {
1636
+ const inserted = db.insert(tableObj).values(data);
1637
+ query = keepExisting ? inserted.onConflictDoNothing({ target: conflictTarget }) : inserted.onConflictDoUpdate({
1638
+ target: conflictTarget,
1639
+ set: updateData
1640
+ });
1641
+ } else query = db.insert(tableObj).values(data);
1642
+ if (caps.supportsReturning) {
1643
+ const result = await query.returning();
1644
+ const row = Array.isArray(result) ? result[0] : result;
1645
+ if (row !== void 0) return row;
1646
+ } else await query;
1647
+ const conflictValues = options.conflictColumns.map((column) => [column, data[column]]);
1648
+ if (conflictValues.length > 0 && conflictValues.every(([, value]) => value !== void 0)) return await this.selectOne(table, { where: { and: conflictValues.map(([column, value]) => ({
1649
+ column,
1650
+ op: "=",
1651
+ value
1652
+ })) } }, executor);
1653
+ return data;
1654
+ } catch (error) {
1655
+ throw this.handleQueryError(error, "upsert", table);
1656
+ }
1657
+ throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
1658
+ }
1659
+ /**
1660
+ * Run pending migrations.
1661
+ *
1662
+ * @remarks
1663
+ * Default implementation is a placeholder. Subclasses should implement
1664
+ * migration tracking and execution logic.
1665
+ *
1666
+ * @param migrations - Array of migrations to run
1667
+ * @returns Migration result with applied and pending migrations
1668
+ *
1669
+ * @throws {DatabaseError} If migration fails
1670
+ */
1671
+ async migrate(_migrations) {
1672
+ throw this.createDatabaseError("query", "migrate() must be implemented by dialect-specific adapter. Use PostgresAdapter, MySqlAdapter, or SqliteAdapter.", void 0);
1673
+ }
1674
+ /**
1675
+ * Rollback the last migration.
1676
+ *
1677
+ * @remarks
1678
+ * Default implementation is a placeholder. Subclasses should implement
1679
+ * migration rollback logic.
1680
+ *
1681
+ * @returns Migration result after rollback
1682
+ *
1683
+ * @throws {DatabaseError} If rollback fails
1684
+ */
1685
+ async rollback() {
1686
+ throw this.createDatabaseError("query", "rollback() must be implemented by dialect-specific adapter. Use PostgresAdapter, MySqlAdapter, or SqliteAdapter.", void 0);
1687
+ }
1688
+ /**
1689
+ * Get migration status.
1690
+ *
1691
+ * @remarks
1692
+ * Default implementation is a placeholder. Subclasses should implement
1693
+ * migration status checking.
1694
+ *
1695
+ * @returns Current migration status
1696
+ *
1697
+ * @throws {DatabaseError} If status check fails
1698
+ */
1699
+ async getMigrationStatus() {
1700
+ try {
1701
+ const applied = (await this.executeQuery(`SELECT * FROM "__drizzle_migrations" ORDER BY created_at ASC`)).map((r) => ({
1702
+ id: String(r.id),
1703
+ name: r.hash,
1704
+ appliedAt: new Date(r.created_at),
1705
+ checksum: r.hash
1706
+ }));
1707
+ return {
1708
+ applied,
1709
+ pending: [],
1710
+ current: applied.length > 0 ? applied[applied.length - 1].id : null
1711
+ };
1712
+ } catch {
1713
+ return {
1714
+ applied: [],
1715
+ pending: [],
1716
+ current: null
1717
+ };
1718
+ }
1719
+ }
1720
+ /**
1721
+ * Create a new table.
1722
+ *
1723
+ * @remarks
1724
+ * Default implementation is a placeholder. Subclasses should implement
1725
+ * table creation logic.
1726
+ *
1727
+ * @param definition - Table definition
1728
+ * @param options - Creation options
1729
+ *
1730
+ * @throws {DatabaseError} If table creation fails
1731
+ */
1732
+ async createTable(definition, options) {
1733
+ const columnDefs = definition.columns.map((col) => {
1734
+ let colSql = `${this.escapeIdentifier(col.name)} ${col.type.toUpperCase()}`;
1735
+ if (col.primaryKey) colSql += " PRIMARY KEY";
1736
+ if (col.nullable === false) colSql += " NOT NULL";
1737
+ if (col.unique) colSql += " UNIQUE";
1738
+ if (col.default !== void 0) colSql += ` DEFAULT ${renderDefaultValue(col.default, col.name)}`;
1739
+ return colSql;
1740
+ });
1741
+ const query = `CREATE TABLE ${options?.ifNotExists !== false ? "IF NOT EXISTS " : ""}${this.escapeIdentifier(definition.name)} (\n ${columnDefs.join(",\n ")}\n)`;
1742
+ try {
1743
+ await this.executeQuery(query);
1744
+ } catch (error) {
1745
+ throw this.handleQueryError(error, "createTable", definition.name);
1746
+ }
1747
+ }
1748
+ /**
1749
+ * Drop a table.
1750
+ *
1751
+ * @remarks
1752
+ * Default implementation is a placeholder. Subclasses should implement
1753
+ * table dropping logic.
1754
+ *
1755
+ * @param tableName - Name of table to drop
1756
+ * @param options - Drop options
1757
+ *
1758
+ * @throws {DatabaseError} If table drop fails
1759
+ */
1760
+ async dropTable(tableName, options) {
1761
+ const ifExists = options?.ifExists !== false ? "IF EXISTS " : "";
1762
+ const cascade = options?.cascade ? " CASCADE" : "";
1763
+ const query = `DROP TABLE ${ifExists}${this.escapeIdentifier(tableName)}${cascade}`;
1764
+ try {
1765
+ await this.executeQuery(query);
1766
+ } catch (error) {
1767
+ throw this.handleQueryError(error, "dropTable", tableName);
1768
+ }
1769
+ }
1770
+ /**
1771
+ * Alter an existing table.
1772
+ *
1773
+ * @remarks
1774
+ * Default implementation is a placeholder. Subclasses should implement
1775
+ * table alteration logic.
1776
+ *
1777
+ * @param tableName - Name of table to alter
1778
+ * @param operations - Alteration operations
1779
+ * @param options - Alter options
1780
+ *
1781
+ * @throws {DatabaseError} If table alteration fails
1782
+ */
1783
+ async alterTable(tableName, operations, _options) {
1784
+ const quotedTable = this.escapeIdentifier(tableName);
1785
+ for (const op of operations) {
1786
+ let query;
1787
+ switch (op.kind) {
1788
+ case "add_column": {
1789
+ let colDef = `${this.escapeIdentifier(op.column.name)} ${op.column.type.toUpperCase()}`;
1790
+ if (op.column.nullable === false) colDef += " NOT NULL";
1791
+ if (op.column.unique) colDef += " UNIQUE";
1792
+ if (op.column.default !== void 0) {
1793
+ const defaultVal = typeof op.column.default === "object" && op.column.default !== null && "sql" in op.column.default ? op.column.default.sql : typeof op.column.default === "string" ? `'${op.column.default}'` : String(op.column.default);
1794
+ colDef += ` DEFAULT ${defaultVal}`;
1795
+ }
1796
+ query = `ALTER TABLE ${quotedTable} ADD COLUMN ${colDef}`;
1797
+ break;
1798
+ }
1799
+ case "drop_column": {
1800
+ const cascade = op.cascade ? " CASCADE" : "";
1801
+ query = `ALTER TABLE ${quotedTable} DROP COLUMN ${this.escapeIdentifier(op.columnName)}${cascade}`;
1802
+ break;
1803
+ }
1804
+ case "rename_column":
1805
+ query = `ALTER TABLE ${quotedTable} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;
1806
+ break;
1807
+ case "modify_column":
1808
+ query = `ALTER TABLE ${quotedTable} ALTER COLUMN ${this.escapeIdentifier(op.column.name)} TYPE ${op.column.type.toUpperCase()}`;
1809
+ break;
1810
+ case "add_constraint": {
1811
+ const colList = (op.constraint.columns ?? []).map((c) => this.escapeIdentifier(c)).join(", ");
1812
+ if (op.constraint.type === "check" && op.constraint.expression) query = `ALTER TABLE ${quotedTable} ADD CONSTRAINT ${this.escapeIdentifier(op.constraint.name)} CHECK (${op.constraint.expression})`;
1813
+ else query = `ALTER TABLE ${quotedTable} ADD CONSTRAINT ${this.escapeIdentifier(op.constraint.name)} ${op.constraint.type.toUpperCase()} (${colList})`;
1814
+ break;
1815
+ }
1816
+ case "drop_constraint": {
1817
+ const cascadeConstraint = op.cascade ? " CASCADE" : "";
1818
+ query = `ALTER TABLE ${quotedTable} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}${cascadeConstraint}`;
1819
+ break;
1820
+ }
1821
+ default: throw this.createDatabaseError("query", `Unsupported alter table operation: ${op.kind}`, void 0);
1822
+ }
1823
+ try {
1824
+ await this.executeQuery(query);
1825
+ } catch (error) {
1826
+ throw this.handleQueryError(error, "alterTable", tableName);
1827
+ }
1828
+ }
1829
+ }
1830
+ /**
1831
+ * Check if a table exists in the database.
1832
+ *
1833
+ * @remarks
1834
+ * Uses dialect-specific information schema queries to check table existence.
1835
+ * This is useful for development mode auto-sync to determine whether to
1836
+ * CREATE or DROP/CREATE tables.
1837
+ *
1838
+ * @param tableName - Name of table to check
1839
+ * @param schema - Optional schema name (defaults to 'public' for PostgreSQL)
1840
+ * @returns True if table exists, false otherwise
1841
+ *
1842
+ * @throws {DatabaseError} If query fails
1843
+ *
1844
+ * @example
1845
+ * ```typescript
1846
+ * const exists = await adapter.tableExists('users');
1847
+ * if (exists) {
1848
+ * await adapter.dropTable('users');
1849
+ * }
1850
+ * await adapter.createTable(userTableDef);
1851
+ * ```
1852
+ */
1853
+ async tableExists(tableName, schema) {
1854
+ try {
1855
+ let sql;
1856
+ const params = [];
1857
+ switch (this.dialect) {
1858
+ case "postgresql":
1859
+ sql = `
894
1860
  SELECT EXISTS (
895
1861
  SELECT FROM information_schema.tables
896
- WHERE table_schema = $1
1862
+ WHERE table_schema = COALESCE($1, (
1863
+ SELECT n.nspname FROM pg_class c
1864
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1865
+ WHERE c.oid = to_regclass($2)
1866
+ ))
897
1867
  AND table_name = $2
898
1868
  ) as exists
899
1869
  `;
900
- params.push(schema ?? "public", tableName);
901
- break;
902
- case "mysql":
903
- sql = `
1870
+ params.push(schema ?? null, tableName);
1871
+ break;
1872
+ case "mysql":
1873
+ sql = `
904
1874
  SELECT COUNT(*) as count
905
1875
  FROM information_schema.tables
906
1876
  WHERE table_schema = DATABASE()
907
1877
  AND table_name = ?
908
1878
  `;
909
- params.push(tableName);
910
- break;
911
- case "sqlite":
912
- sql = `
1879
+ params.push(tableName);
1880
+ break;
1881
+ case "sqlite":
1882
+ sql = `
913
1883
  SELECT COUNT(*) as count
914
1884
  FROM sqlite_master
915
1885
  WHERE type = 'table'
916
1886
  AND name = ?
917
1887
  `;
918
- params.push(tableName);
919
- break;
920
- default:
921
- throw this.createDatabaseError(
922
- "query",
923
- `tableExists not implemented for dialect: ${String(this.dialect)}`,
924
- void 0
925
- );
926
- }
927
- const results = await this.executeQuery(
928
- sql,
929
- params
930
- );
931
- if (results.length === 0) {
932
- return false;
933
- }
934
- const row = results[0];
935
- if ("exists" in row) {
936
- return row.exists === true || row.exists === "t" || row.exists === 1;
937
- }
938
- if ("count" in row) {
939
- return Number(row.count) > 0;
940
- }
941
- return false;
942
- } catch (error) {
943
- throw this.handleQueryError(error, "tableExists", tableName);
944
- }
945
- }
946
- /**
947
- * Get list of all tables in the database.
948
- *
949
- * @remarks
950
- * Uses dialect-specific information schema queries to list tables.
951
- * Useful for detecting orphaned tables or validating schema state.
952
- *
953
- * @param schema - Optional schema name (defaults to 'public' for PostgreSQL)
954
- * @returns Array of table names
955
- *
956
- * @throws {DatabaseError} If query fails
957
- */
958
- async listTables(schema) {
959
- try {
960
- let sql;
961
- const params = [];
962
- switch (this.dialect) {
963
- case "postgresql":
964
- sql = `
1888
+ params.push(tableName);
1889
+ break;
1890
+ default: throw this.createDatabaseError("query", `tableExists not implemented for dialect: ${String(this.dialect)}`, void 0);
1891
+ }
1892
+ const results = await this.executeQuery(sql, params);
1893
+ if (results.length === 0) return false;
1894
+ const row = results[0];
1895
+ if ("exists" in row) return row.exists === true || row.exists === "t" || row.exists === 1;
1896
+ if ("count" in row) return Number(row.count) > 0;
1897
+ return false;
1898
+ } catch (error) {
1899
+ throw this.handleQueryError(error, "tableExists", tableName);
1900
+ }
1901
+ }
1902
+ /**
1903
+ * Get list of all tables in the database.
1904
+ *
1905
+ * @remarks
1906
+ * Uses dialect-specific information schema queries to list tables.
1907
+ * Useful for detecting orphaned tables or validating schema state.
1908
+ *
1909
+ * @param schema - Optional schema name (defaults to 'public' for PostgreSQL)
1910
+ * @returns Array of table names
1911
+ *
1912
+ * @throws {DatabaseError} If query fails
1913
+ */
1914
+ async listTables(schema) {
1915
+ try {
1916
+ let sql;
1917
+ const params = [];
1918
+ switch (this.dialect) {
1919
+ case "postgresql":
1920
+ sql = `
965
1921
  SELECT table_name
966
1922
  FROM information_schema.tables
967
1923
  WHERE table_schema = $1
968
1924
  AND table_type = 'BASE TABLE'
969
1925
  ORDER BY table_name
970
1926
  `;
971
- params.push(schema ?? "public");
972
- break;
973
- case "mysql":
974
- sql = `
975
- SELECT table_name
1927
+ params.push(schema ?? "public");
1928
+ break;
1929
+ case "mysql":
1930
+ sql = `
1931
+ SELECT table_name AS table_name
976
1932
  FROM information_schema.tables
977
1933
  WHERE table_schema = DATABASE()
978
1934
  AND table_type = 'BASE TABLE'
979
1935
  ORDER BY table_name
980
1936
  `;
981
- break;
982
- case "sqlite":
983
- sql = `
1937
+ break;
1938
+ case "sqlite":
1939
+ sql = `
984
1940
  SELECT name as table_name
985
1941
  FROM sqlite_master
986
1942
  WHERE type = 'table'
987
1943
  AND name NOT LIKE 'sqlite_%'
988
1944
  ORDER BY name
989
1945
  `;
990
- break;
991
- default:
992
- throw this.createDatabaseError(
993
- "query",
994
- `listTables not implemented for dialect: ${String(this.dialect)}`,
995
- void 0
996
- );
997
- }
998
- const results = await this.executeQuery(
999
- sql,
1000
- params
1001
- );
1002
- return results.map((row) => row.table_name);
1003
- } catch (error) {
1004
- throw this.handleQueryError(error, "listTables", "");
1005
- }
1006
- }
1007
- // ============================================================
1008
- // Protected Utilities
1009
- // ============================================================
1010
- // Old raw SQL query builders (buildSelectQuery, buildInsertQuery, buildUpdateQuery,
1011
- // buildDeleteQuery, buildUpsertQuery, buildWhereClause, buildPlaceholder,
1012
- // buildPlaceholders) have been removed. CRUD methods now use Drizzle query API
1013
- // via the TableResolver set during boot. See drizzle-where.ts for where clause
1014
- // translation.
1015
- // NOTE: The following content up to escapeIdentifier has been removed.
1016
- // If you're looking for the old query builder methods, see git history
1017
- // (commit before "refactor: remove dead SQL builder code").
1018
- /**
1019
- * Escape a table or column identifier.
1020
- *
1021
- * @remarks
1022
- * Default uses double quotes (SQL standard).
1023
- * MySQL adapter should override to use backticks.
1024
- *
1025
- * @param identifier - Identifier to escape
1026
- * @returns Escaped identifier
1027
- *
1028
- * @protected
1029
- */
1030
- escapeIdentifier(identifier) {
1031
- return `"${identifier.replace(/"/g, '""')}"`;
1032
- }
1033
- /**
1034
- * Create a DatabaseError with proper error kind classification.
1035
- *
1036
- * @remarks
1037
- * Protected helper for subclasses to create consistent errors.
1038
- * Subclasses can override to add dialect-specific error classification.
1039
- *
1040
- * @param kind - Error kind
1041
- * @param message - Error message
1042
- * @param cause - Original error
1043
- * @returns DatabaseError instance
1044
- *
1045
- * @protected
1046
- */
1047
- createDatabaseError(kind, message, cause) {
1048
- return createDatabaseError({
1049
- kind,
1050
- message,
1051
- cause
1052
- });
1053
- }
1054
- /**
1055
- * Handle query errors and convert to DatabaseError.
1056
- *
1057
- * @remarks
1058
- * Protected helper for consistent error handling across CRUD operations.
1059
- * Subclasses can override to add dialect-specific error classification.
1060
- *
1061
- * @param error - Original error
1062
- * @param operation - Operation that failed
1063
- * @param table - Table name
1064
- * @returns DatabaseError instance
1065
- *
1066
- * @protected
1067
- */
1068
- handleQueryError(error, operation, table) {
1069
- if (isDatabaseError(error)) {
1070
- return error;
1071
- }
1072
- const errorMessage = error instanceof Error ? error.message : String(error);
1073
- return this.createDatabaseError(
1074
- "query",
1075
- `${operation} operation failed on table '${table}': ${errorMessage}`,
1076
- error instanceof Error ? error : void 0
1077
- );
1078
- }
1946
+ break;
1947
+ default: throw this.createDatabaseError("query", `listTables not implemented for dialect: ${String(this.dialect)}`, void 0);
1948
+ }
1949
+ return (await this.executeQuery(sql, params)).map((row) => row.table_name);
1950
+ } catch (error) {
1951
+ throw this.handleQueryError(error, "listTables", "");
1952
+ }
1953
+ }
1954
+ /**
1955
+ * Escape a table or column identifier.
1956
+ *
1957
+ * @remarks
1958
+ * Default uses double quotes (SQL standard).
1959
+ * MySQL adapter should override to use backticks.
1960
+ *
1961
+ * @param identifier - Identifier to escape
1962
+ * @returns Escaped identifier
1963
+ *
1964
+ * @protected
1965
+ */
1966
+ escapeIdentifier(identifier) {
1967
+ return `"${identifier.replace(/"/g, "\"\"")}"`;
1968
+ }
1969
+ /**
1970
+ * Create a DatabaseError with proper error kind classification.
1971
+ *
1972
+ * @remarks
1973
+ * Protected helper for subclasses to create consistent errors.
1974
+ * Subclasses can override to add dialect-specific error classification.
1975
+ *
1976
+ * @param kind - Error kind
1977
+ * @param message - Error message
1978
+ * @param cause - Original error
1979
+ * @returns DatabaseError instance
1980
+ *
1981
+ * @protected
1982
+ */
1983
+ createDatabaseError(kind, message, cause) {
1984
+ return createDatabaseError({
1985
+ kind,
1986
+ message,
1987
+ cause
1988
+ });
1989
+ }
1990
+ /**
1991
+ * Helper to create transaction context CRUD forwarding methods.
1992
+ *
1993
+ * @param txDb - Thunk returning the transaction-bound Drizzle executor
1994
+ * @returns Object providing forwarded CRUD and getDrizzle methods
1995
+ *
1996
+ * @protected
1997
+ */
1998
+ createTransactionForwarders(txDb) {
1999
+ return createTransactionForwarders(this, txDb);
2000
+ }
2001
+ /**
2002
+ * The Drizzle handles one transaction hands out; see
2003
+ * `transactionDrizzleHandles`. `build` makes an instance on the
2004
+ * transaction's own connection, with the relations config when given one.
2005
+ *
2006
+ * @protected
2007
+ */
2008
+ transactionDrizzleHandles(build) {
2009
+ return transactionDrizzleHandles(build);
2010
+ }
2011
+ /**
2012
+ * A transaction context's `update`, for each adapter to bind.
2013
+ *
2014
+ * Not forwarded to the pooled `update` the way `select` and `delete` are:
2015
+ * that one goes through the Drizzle query builder, which writes the columns
2016
+ * the runtime MODEL declares, and a transaction's update must reach the
2017
+ * columns the physical TABLE has — the localization transition window
2018
+ * writes a column the model has already moved to a companion table that
2019
+ * does not exist yet. The INSERT half of every transaction context already
2020
+ * builds its own statement for that reason; `update-statement.ts` is the
2021
+ * UPDATE half, spelled once for the three adapters, and this runs it: on
2022
+ * the transaction executor, classified with the operation and table named
2023
+ * as the pooled `update` classifies its failures, and read back through
2024
+ * `select` on the same executor when the caller asked for rows.
2025
+ *
2026
+ * That read is by the rows' IDENTITY where the dialect can report it: on
2027
+ * PostgreSQL and SQLite the statement carries `RETURNING <primary key>`, and
2028
+ * the read-back asks for exactly those rows — so a row another transaction
2029
+ * adds under the same predicate meanwhile is not among them, and an update
2030
+ * whose own write falsifies its predicate still reads its rows back. MySQL
2031
+ * has no RETURNING, so there the read re-runs the predicate, as the pooled
2032
+ * `update` always has on that dialect; a table with no primary key in its
2033
+ * model reads back the same way.
2034
+ *
2035
+ * @param txDb - thunk returning the transaction-bound Drizzle instance
2036
+ * @param run - how this dialect runs a statement on that instance, and the
2037
+ * rows it returns when the statement carries RETURNING: better-sqlite3
2038
+ * answers synchronously, the pooled drivers do not
2039
+ * @param bindUnmodeled - how a value binds when the model declares no
2040
+ * column for it; a declared column binds through its own encoder
2041
+ * @returns the context's `update` method
2042
+ */
2043
+ transactionUpdate(txDb, run, bindUnmodeled) {
2044
+ return async (table, data, where, options) => {
2045
+ const wantsRows = this.updateReturnsRows(options?.returning);
2046
+ const tableObj = this.resolvedTableObject(table);
2047
+ const identity = wantsRows && this.getCapabilities().supportsReturning ? this.identityColumns(tableObj) : [];
2048
+ let reported;
2049
+ try {
2050
+ reported = await run(this.buildTransactionUpdate(tableObj, table, data, where, {
2051
+ bindUnmodeled,
2052
+ returning: identity.map((key) => sql`${sql.identifier(key.sqlName)}`)
2053
+ }), identity.length > 0);
2054
+ } catch (error) {
2055
+ throw this.handleQueryError(error, "update", table);
2056
+ }
2057
+ if (!wantsRows) return [];
2058
+ if (identity.length === 0 || !Array.isArray(reported)) return this.select(table, { where }, txDb());
2059
+ const rows = [];
2060
+ for (let at = 0; at < reported.length; at += IDENTITY_READ_BACK_CHUNK) rows.push(...await this.select(table, { where: rowsByIdentity(identity, reported.slice(at, at + IDENTITY_READ_BACK_CHUNK)) }, txDb()));
2061
+ return rows;
2062
+ };
2063
+ }
2064
+ /**
2065
+ * The columns that identify a row of this table, under both spellings: the
2066
+ * SQL name RETURNING reports and the Drizzle property name the query
2067
+ * builder's WHERE is addressed by. Columns flagged primary first; failing
2068
+ * that, the table-level primary key the dialect's table config carries
2069
+ * (`primaryKey({ columns })` leaves each column's flag false), which each
2070
+ * adapter reads through its own dialect. Empty when the model declares
2071
+ * neither, and the read-back falls back to the caller's predicate.
2072
+ */
2073
+ identityColumns(tableObj) {
2074
+ const columns = Object.entries(getColumns(tableObj));
2075
+ const flagged = columns.filter(([, c]) => c.primary === true);
2076
+ return (flagged.length > 0 ? flagged : columns.filter(([, c]) => this.compositePrimaryKey(tableObj).includes(c))).flatMap(([jsName, c]) => typeof c.name === "string" ? [{
2077
+ jsName,
2078
+ sqlName: c.name
2079
+ }] : []);
2080
+ }
2081
+ /**
2082
+ * How a value binds to a column the model does not declare, on a driver
2083
+ * that binds scalars, dates and binary natively: a structured value goes
2084
+ * as JSON text, since what node-postgres and mysql2 make of a bare object
2085
+ * or array is not JSON. For the adapters to hand `transactionUpdate`.
2086
+ */
2087
+ bindUnmodeledStructuredAsJson(value) {
2088
+ return bindStructuredAsJson(value);
2089
+ }
2090
+ /**
2091
+ * Refuse an upsert target every dialect would not answer alike: a conflict
2092
+ * column named twice, which SQLite rejects as no constraint's target and
2093
+ * MySQL would accept; and, when nothing is to be updated, a conflict column
2094
+ * left for the database to fill, since the row that stands is then read
2095
+ * back by a value the caller never gave. Shared with the dialects that
2096
+ * override `upsert`, so the refusals are one rule.
2097
+ */
2098
+ assertUpsertTarget(table, data, options, keepExisting) {
2099
+ const columns = options.conflictColumns;
2100
+ if (new Set(columns).size !== columns.length) throw createDatabaseError({
2101
+ kind: "query",
2102
+ message: `upsert on ${table} names a conflict column more than once (${columns.join(", ")}).`
2103
+ });
2104
+ if (keepExisting && columns.some((column) => data[column] === void 0)) throw createDatabaseError({
2105
+ kind: "query",
2106
+ message: `upsert on ${table} needs a value for every conflict column (${columns.join(", ")}).`
2107
+ });
2108
+ }
2109
+ /**
2110
+ * The columns of a table-level `primaryKey({ columns })`, as the dialect's
2111
+ * table config reports them. The base class cannot read that config without
2112
+ * naming a dialect, so each adapter answers for its own; a dialect that does
2113
+ * not answer reports none.
2114
+ */
2115
+ compositePrimaryKey(_tableObj) {
2116
+ return [];
2117
+ }
2118
+ /** The registered table object, or the error every CRUD method throws without one. */
2119
+ resolvedTableObject(table) {
2120
+ const tableObj = this.getTableObject(table);
2121
+ if (!tableObj || typeof tableObj !== "object") throw this.createDatabaseError("query", `Table "${table}" not found in schema registry. Ensure setTableResolver() has been called during boot.`, void 0);
2122
+ return tableObj;
2123
+ }
2124
+ /**
2125
+ * The statement `transactionUpdate` runs.
2126
+ *
2127
+ * @throws when nothing would be written — every key `undefined`, or none at
2128
+ * all. The query builder refused that too ("No values to set"), and a
2129
+ * patch that names nothing is a caller's mistake rather than a write of
2130
+ * nothing.
2131
+ */
2132
+ buildTransactionUpdate(tableObj, table, data, where, binding) {
2133
+ const statement = buildUpdateStatement({
2134
+ table,
2135
+ tableObj,
2136
+ data,
2137
+ where,
2138
+ bindUnmodeled: binding.bindUnmodeled,
2139
+ returning: binding.returning
2140
+ });
2141
+ if (!statement) throw this.createDatabaseError("query", `No values to set: the update of "${table}" names no column with a defined value.`, void 0);
2142
+ return statement;
2143
+ }
2144
+ /**
2145
+ * Whether a transaction's `update` reads the rows it changed back: the
2146
+ * caller named columns, or `*`. An empty list, like no option at all, asks
2147
+ * for nothing and `update` answers `[]`, as it always has. The rows come
2148
+ * from a read of the update's own WHERE on its own transaction, so they are
2149
+ * the model's view of the row, decoded as every read is decoded — which is
2150
+ * what the query-builder update returned for them, and why the named list
2151
+ * selects nothing narrower.
2152
+ */
2153
+ updateReturnsRows(returning) {
2154
+ return returning !== void 0 && !(Array.isArray(returning) && returning.length === 0);
2155
+ }
2156
+ /**
2157
+ * The driver's own error inside `error`: the first in its `cause` chain that
2158
+ * `isDriverError` recognises, or `error` itself when none does.
2159
+ *
2160
+ * A query that runs through Drizzle fails with Drizzle's `DrizzleQueryError`,
2161
+ * whose message is the SQL statement and which carries no driver code; the
2162
+ * driver's error, the only object that knows what actually went wrong, is
2163
+ * its `cause`. A dialect's {@link classifyError} classifies from what this
2164
+ * returns, so a failure reads the same whether or not Drizzle wrapped it.
2165
+ *
2166
+ * The walk is bounded, because an error chain can be made cyclic and a
2167
+ * classifier that can hang is worse than one that gives up. Falling back to
2168
+ * `error` keeps an error that carries no code anywhere classified as before.
2169
+ *
2170
+ * @param error - The error as it was caught
2171
+ * @param isDriverError - Whether a link in the chain is the driver's error
2172
+ * @returns The driver's error, or `error` when no link is
2173
+ */
2174
+ driverErrorIn(error, isDriverError) {
2175
+ let cursor = error;
2176
+ for (let depth = 0; depth < 10; depth++) {
2177
+ if (cursor === null || typeof cursor !== "object") break;
2178
+ const candidate = cursor;
2179
+ if (isDriverError(candidate)) return candidate;
2180
+ cursor = candidate.cause;
2181
+ }
2182
+ return error ?? {};
2183
+ }
2184
+ /**
2185
+ * Classify an error into a DatabaseError.
2186
+ *
2187
+ * @remarks
2188
+ * Subclasses can override this method to add dialect-specific error code classification.
2189
+ *
2190
+ * @param error - Original error
2191
+ * @param sql - SQL statement that caused the error (optional)
2192
+ * @returns DatabaseError instance
2193
+ *
2194
+ * @protected
2195
+ */
2196
+ classifyError(error, sql) {
2197
+ if (isDatabaseError(error)) return error;
2198
+ const errorMessage = error instanceof Error ? error.message : String(error);
2199
+ return this.createDatabaseError("query", sql ? `Query failed: ${errorMessage}` : errorMessage, error instanceof Error ? error : void 0);
2200
+ }
2201
+ /**
2202
+ * Handle query errors and convert to DatabaseError.
2203
+ *
2204
+ * @remarks
2205
+ * Protected helper for consistent error handling across CRUD operations.
2206
+ * Delegates to `classifyError` and attaches operation and table context if not present.
2207
+ * Subclasses override `classifyError` to provide dialect-specific error code classification.
2208
+ *
2209
+ * @param error - Original error
2210
+ * @param operation - Operation that failed
2211
+ * @param table - Table name
2212
+ * @returns DatabaseError instance
2213
+ *
2214
+ * @protected
2215
+ */
2216
+ handleQueryError(error, operation, table) {
2217
+ const dbError = this.classifyError(error);
2218
+ const context = `${operation} operation failed on table '${table}'`;
2219
+ if (!dbError.message.includes(context)) dbError.message = `${context}: ${dbError.message}`;
2220
+ if (!dbError.table) dbError.table = table;
2221
+ return dbError;
2222
+ }
1079
2223
  };
1080
- var ALLOWED_DEFAULT_SQL_EXPRESSIONS = /* @__PURE__ */ new Set([
1081
- "current_timestamp",
1082
- "now()",
1083
- "gen_random_uuid()",
1084
- "uuid_generate_v4()",
1085
- "current_date",
1086
- "current_time"
2224
+ /**
2225
+ * How many reported rows one read-back statement names. Well under SQLite's
2226
+ * expression-depth limit of a thousand and its default variable limit, and
2227
+ * under PostgreSQL's parameter limit, with a composite key of several columns.
2228
+ */
2229
+ const IDENTITY_READ_BACK_CHUNK = 200;
2230
+ /**
2231
+ * The predicate that names exactly the rows a statement reported, addressed
2232
+ * by the Drizzle property names the where builder resolves: for a single-
2233
+ * column key one `IN` over the reported values; for a composite key one `and`
2234
+ * of every key column per row, `or`-ed together, so the key is matched as a
2235
+ * whole rather than column by column.
2236
+ */
2237
+ function rowsByIdentity(identity, rows) {
2238
+ if (identity.length === 1) {
2239
+ const [key] = identity;
2240
+ return { and: [{
2241
+ column: key.jsName,
2242
+ op: "IN",
2243
+ value: rows.map((row) => row[key.sqlName])
2244
+ }] };
2245
+ }
2246
+ return { or: rows.map((row) => ({ and: identity.map((key) => ({
2247
+ column: key.jsName,
2248
+ op: "=",
2249
+ value: row[key.sqlName]
2250
+ })) })) };
2251
+ }
2252
+ /**
2253
+ * Render a `ColumnDefinition.default` as a SQL fragment
2254
+ * for embedding in a `DEFAULT` clause. DDL is not protected by Drizzle's
2255
+ * prepared statements — these expressions are concatenated into raw SQL —
2256
+ * so we treat the default as untrusted input even though it currently
2257
+ * flows from server-side schema definitions: an admin-defined dynamic
2258
+ * collection would otherwise turn into RCE-on-DB instead of just CMS
2259
+ * admin.
2260
+ *
2261
+ * Rules:
2262
+ *
2263
+ * - **null / number / boolean** → rendered as a SQL literal.
2264
+ * - **string** → quoted; embedded `'` doubled; `;`, `\`, control
2265
+ * characters, and null bytes rejected so they can't break out of
2266
+ * the surrounding quote pair into adjacent DDL.
2267
+ * - **`{ sql: "…" }`** → only the explicit allowlist of named
2268
+ * functions below is honored (case-insensitive). Anything else is
2269
+ * a hard error: the previous code embedded the raw `sql` string
2270
+ * verbatim, which is the SQL injection primitive the audit flagged.
2271
+ */
2272
+ const ALLOWED_DEFAULT_SQL_EXPRESSIONS = /* @__PURE__ */ new Set([
2273
+ "current_timestamp",
2274
+ "now()",
2275
+ "gen_random_uuid()",
2276
+ "uuid_generate_v4()",
2277
+ "current_date",
2278
+ "current_time"
1087
2279
  ]);
1088
2280
  function renderDefaultValue(value, columnName) {
1089
- if (value === null) return "NULL";
1090
- if (typeof value === "number") {
1091
- if (!Number.isFinite(value)) {
1092
- throw new Error(
1093
- `DEFAULT for column "${columnName}" must be a finite number (got ${value}).`
1094
- );
1095
- }
1096
- return String(value);
1097
- }
1098
- if (typeof value === "boolean") {
1099
- return value ? "TRUE" : "FALSE";
1100
- }
1101
- if (typeof value === "string") {
1102
- if (/[;\\\n\r\0]/.test(value)) {
1103
- throw new Error(
1104
- `DEFAULT string for column "${columnName}" contains characters that are not allowed in DDL (no semicolons, backslashes, control chars, or null bytes).`
1105
- );
1106
- }
1107
- return `'${value.replace(/'/g, "''")}'`;
1108
- }
1109
- if (typeof value === "object" && value !== null && "sql" in value) {
1110
- const raw = value.sql;
1111
- if (typeof raw !== "string") {
1112
- throw new Error(
1113
- `DEFAULT for column "${columnName}" has a { sql } expression that is not a string.`
1114
- );
1115
- }
1116
- const normalized = raw.trim().toLowerCase();
1117
- if (!ALLOWED_DEFAULT_SQL_EXPRESSIONS.has(normalized)) {
1118
- throw new Error(
1119
- `DEFAULT for column "${columnName}" uses a SQL expression "${raw}" that is not on the allowlist. Allowed: ${[...ALLOWED_DEFAULT_SQL_EXPRESSIONS].join(", ")}.`
1120
- );
1121
- }
1122
- return raw.trim();
1123
- }
1124
- throw new Error(
1125
- `DEFAULT for column "${columnName}" has an unsupported type (${typeof value}).`
1126
- );
2281
+ if (value === null) return "NULL";
2282
+ if (typeof value === "number") {
2283
+ if (!Number.isFinite(value)) throw new Error(`DEFAULT for column "${columnName}" must be a finite number (got ${value}).`);
2284
+ return String(value);
2285
+ }
2286
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
2287
+ if (typeof value === "string") {
2288
+ if (/[;\\\n\r\0]/.test(value)) throw new Error(`DEFAULT string for column "${columnName}" contains characters that are not allowed in DDL (no semicolons, backslashes, control chars, or null bytes).`);
2289
+ return `'${value.replace(/'/g, "''")}'`;
2290
+ }
2291
+ if (typeof value === "object" && value !== null && "sql" in value) {
2292
+ const raw = value.sql;
2293
+ if (typeof raw !== "string") throw new Error(`DEFAULT for column "${columnName}" has a { sql } expression that is not a string.`);
2294
+ const normalized = raw.trim().toLowerCase();
2295
+ if (!ALLOWED_DEFAULT_SQL_EXPRESSIONS.has(normalized)) throw new Error(`DEFAULT for column "${columnName}" uses a SQL expression "${raw}" that is not on the allowlist. Allowed: ${[...ALLOWED_DEFAULT_SQL_EXPRESSIONS].join(", ")}.`);
2296
+ return raw.trim();
2297
+ }
2298
+ throw new Error(`DEFAULT for column "${columnName}" has an unsupported type (${typeof value}).`);
1127
2299
  }
1128
-
1129
2300
  // src/index.ts
1130
- var version = "0.1.0";
1131
-
2301
+ /**
2302
+ * @nextly/adapter-drizzle
2303
+ *
2304
+ * Shared Drizzle ORM adapter logic for Nextly database adapters.
2305
+ * This package provides the base adapter class and utilities used by
2306
+ * dialect-specific adapters (PostgreSQL, MySQL, SQLite).
2307
+ *
2308
+ * @remarks
2309
+ * This is the main entry point that exports only the core adapter class.
2310
+ * Specialized utilities are available via subpath exports for optimal tree-shaking.
2311
+ *
2312
+ * ## Subpath Exports
2313
+ *
2314
+ * **Types:**
2315
+ * ```typescript
2316
+ * import type {
2317
+ * DatabaseCapabilities,
2318
+ * TransactionContext,
2319
+ * WhereClause,
2320
+ * SelectOptions,
2321
+ * } from '@nextly/adapter-drizzle/types';
2322
+ * ```
2323
+ *
2324
+ * **Query Builder:**
2325
+ * ```typescript
2326
+ * import { QueryBuilder } from '@nextly/adapter-drizzle/query-builder';
2327
+ * ```
2328
+ *
2329
+ * **Migrations:**
2330
+ * ```typescript
2331
+ * import {
2332
+ * calculateChecksum,
2333
+ * sortMigrations,
2334
+ * migrationHelpers,
2335
+ * } from '@nextly/adapter-drizzle/migrations';
2336
+ * ```
2337
+ *
2338
+ * **Schema Utilities:**
2339
+ * ```typescript
2340
+ * import { schemaUtils } from '@nextly/adapter-drizzle/schema';
2341
+ * ```
2342
+ *
2343
+ * @packageDocumentation
2344
+ */
2345
+ /**
2346
+ * Package version
2347
+ * @public
2348
+ */
2349
+ const version = "0.1.0";
1132
2350
  export { DrizzleAdapter, version };
1133
- //# sourceMappingURL=index.mjs.map
2351
+
1134
2352
  //# sourceMappingURL=index.mjs.map