@nextlyhq/adapter-drizzle 0.0.2-alpha.68 → 0.0.2-alpha.69

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