@happyvertical/sql 0.88.1 → 0.88.2

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.
package/README.md CHANGED
@@ -130,6 +130,20 @@ await pgDb.query(`SELECT ('{"db":true}'::jsonb ? 'db') AS has_db`);
130
130
 
131
131
  For PostgreSQL, a single array argument is treated as a values list unless the SQL shows a single array-typed placeholder, such as `$1::text[]`, `CAST($1 AS text[])`, `ANY($1)`, or the equivalent legacy `?` placeholder form. Transaction handles follow the same raw query behavior as the root database handle.
132
132
 
133
+ When a raw query or schema alteration fails, the adapter throws a
134
+ `DatabaseError` whose message includes the database driver's diagnostic. The
135
+ error also carries a native `cause`, and `JSON.stringify(error)` includes a
136
+ shallow cause summary with common driver fields such as `code`, `detail`,
137
+ `hint`, `severity`, and `errno`.
138
+
139
+ The cause is a sanitized snapshot rather than the original driver object.
140
+ Statements, bound parameter values, connection credentials, and
141
+ credential-shaped driver text are redacted from the message, context, cause,
142
+ stack, and JSON form. This makes the error safe for ordinary application and CI
143
+ logging while keeping migration failures actionable. Use the driver's error
144
+ code and the non-secret diagnostic details for troubleshooting; do not expect
145
+ `error.cause` to have object identity with the driver's thrown error.
146
+
133
147
  ### CRUD Helpers
134
148
 
135
149
  ```typescript
@@ -4,29 +4,205 @@ import { DatabaseError } from "@happyvertical/utils";
4
4
  * Shared SQL utilities that work in both browser and Node.js environments
5
5
  */
6
6
  /**
7
- * Formats a database error to include all relevant details
7
+ * Formats a database error to include its useful non-secret details.
8
8
  *
9
9
  * Database drivers often include additional properties beyond just `message`:
10
10
  * - PostgreSQL: code, detail, hint, severity
11
11
  * - DuckDB: may include additional context
12
12
  * - SQLite/LibSQL: may include errno, code
13
13
  *
14
- * This function extracts all available error properties to provide
15
- * better debugging information.
14
+ * This function extracts an allowlist of driver properties and redacts
15
+ * credential-shaped text. When parameter values are available, prefer
16
+ * {@link wrapDatabaseError}; it also redacts values echoed by the driver.
16
17
  *
17
18
  * @param error - The caught error object
18
19
  * @returns Formatted error string with all available error details
19
20
  */
20
21
  function formatDbError(error) {
21
- const dbError = error;
22
+ return formatDbErrorWithSecrets(error, []);
23
+ }
24
+ var DRIVER_ERROR_FIELDS = [
25
+ "code",
26
+ "detail",
27
+ "hint",
28
+ "severity",
29
+ "errno"
30
+ ];
31
+ var SENSITIVE_CONTEXT_KEY = /^(?:args?|parameters?|params?|queries|query|sql|values?)$/i;
32
+ var CREDENTIAL_KEY_PART = /^(?:credential|credentials|passphrase|password|pwd|secret|token)$/i;
33
+ var CREDENTIAL_KEY_QUALIFIER = /^(?:access|api|auth|client|private|refresh|service|signing)$/i;
34
+ var DATABASE_USER_KEY = /^(?:user(?:name)?|(?:database|db|pg|postgres|postgresql)[._-]?user(?:name)?)$/i;
35
+ var DATABASE_URL_USERINFO = /\b((?:https?|libsql|postgres|postgresql):\/\/)[^\s/@]+@/giu;
36
+ var DATABASE_URL = /\b(?:https?|libsql|postgres|postgresql):\/\/[^\s"'`<>()]+/giu;
37
+ var CREDENTIAL_ASSIGNMENT = /(?<![\p{L}\p{N}_-])(["']?)([\p{L}\p{N}_.-]+(?: key)?)\1(\s*[:=]\s*)(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s,;}\]]+)/giu;
38
+ var BEARER_CREDENTIAL = /\bbearer\s+[^\s,;]+/giu;
39
+ var SQL_NUMERIC_LITERAL = /(?<![\p{L}\p{N}_$])[-+]?(?:\d(?:_?\d)*(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:e[-+]?\d(?:_?\d)*)?(?![\p{L}\p{N}_$])/giu;
40
+ var POSTGRES_KEY_VALUE = /(\bKey\s*\([^\r\n)]*\)\s*=\s*\()([\s\S]*?)(\)\s*(?:already exists|is duplicated)\b)/giu;
41
+ var POSTGRES_FAILING_ROW = /(\bFailing row contains\s*\()([\s\S]*)(\)(?:\.|$))/giu;
42
+ var CAST_INPUT_VALUE = /(\bwith value\s+)([\s\S]*?)(\s+(?:can't|cannot)\s+be cast\b)/giu;
43
+ function isCredentialKey(key) {
44
+ if (DATABASE_USER_KEY.test(key)) return true;
45
+ const parts = key.replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, "$1 $2").split(/[^\p{L}\p{N}]+/u).filter(Boolean);
46
+ if (parts.length === 1 && /^(?:auth|credential|key|pass)$/i.test(parts[0])) return true;
47
+ if (parts.some((part) => CREDENTIAL_KEY_PART.test(part))) return true;
48
+ return parts.some((part, index) => /^(?:key|auth)$/i.test(part) && index > 0 && CREDENTIAL_KEY_QUALIFIER.test(parts[index - 1]));
49
+ }
50
+ function toDriverError(error) {
51
+ return error && (typeof error === "object" || typeof error === "function") ? error : {};
52
+ }
53
+ function redactUrl(value) {
54
+ try {
55
+ const url = new URL(value);
56
+ if (url.username) url.username = "[redacted]";
57
+ if (url.password) url.password = "[redacted]";
58
+ for (const key of url.searchParams.keys()) if (isCredentialKey(key)) url.searchParams.set(key, "[redacted]");
59
+ if (url.hash) url.hash = "[redacted]";
60
+ return url.toString();
61
+ } catch {
62
+ return value.replace(/\/\/[^/@\s]+@/u, "//[redacted]@");
63
+ }
64
+ }
65
+ function redactKnownValue(input, value) {
66
+ if (!value || !input.includes(value)) return input;
67
+ if (!/^[\p{L}\p{N}_-]+$/u.test(value)) return input.split(value).join("[redacted]");
68
+ const identifierCharacter = /^[\p{L}\p{N}_-]$/u;
69
+ let cursor = 0;
70
+ let redacted = "";
71
+ let match = input.indexOf(value);
72
+ while (match !== -1) {
73
+ const end = match + value.length;
74
+ const before = [...input.slice(Math.max(0, match - 2), match)].at(-1);
75
+ const afterCodePoint = input.codePointAt(end);
76
+ const after = afterCodePoint === void 0 ? void 0 : String.fromCodePoint(afterCodePoint);
77
+ const bounded = (!before || !identifierCharacter.test(before)) && (!after || !identifierCharacter.test(after));
78
+ redacted += input.slice(cursor, match);
79
+ redacted += bounded ? "[redacted]" : value;
80
+ cursor = end;
81
+ match = input.indexOf(value, cursor);
82
+ }
83
+ return redacted + input.slice(cursor);
84
+ }
85
+ function redactDatabaseErrorText(value, knownSecrets) {
86
+ let redacted = value.replace(DATABASE_URL_USERINFO, "$1[redacted]@").replace(DATABASE_URL, redactUrl).replace(CREDENTIAL_ASSIGNMENT, (assignment, quote, key, delimiter) => isCredentialKey(key) ? `${quote}${key}${quote}${delimiter}[redacted]` : assignment).replace(BEARER_CREDENTIAL, "Bearer [redacted]").replace(POSTGRES_KEY_VALUE, (_match, prefix, _value, suffix) => `${prefix}[redacted]${suffix}`).replace(POSTGRES_FAILING_ROW, (_match, prefix, _value, suffix) => `${prefix}[redacted]${suffix}`).replace(CAST_INPUT_VALUE, (_match, prefix, _value, suffix) => `${prefix}[redacted]${suffix}`);
87
+ for (const secret of [...new Set(knownSecrets)].sort((left, right) => right.length - left.length)) redacted = redactKnownValue(redacted, secret);
88
+ return redacted;
89
+ }
90
+ function collectSensitiveValues(value, output, seen) {
91
+ if (typeof value === "string") {
92
+ if (value) output.add(value);
93
+ return;
94
+ }
95
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
96
+ output.add(String(value));
97
+ return;
98
+ }
99
+ if (!value || typeof value !== "object" || seen.has(value)) return;
100
+ seen.add(value);
101
+ try {
102
+ if (value instanceof Date) {
103
+ output.add(value.toISOString());
104
+ return;
105
+ }
106
+ if (ArrayBuffer.isView(value)) {
107
+ const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
108
+ if (bytes.length > 0) {
109
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
110
+ output.add([...bytes].join(","));
111
+ output.add(hex);
112
+ output.add(`\\x${hex}`);
113
+ output.add(`\\x${hex.toUpperCase()}`);
114
+ output.add(`<Buffer ${[...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(" ")}>`);
115
+ if (typeof Buffer !== "undefined") output.add(Buffer.from(bytes).toString("base64"));
116
+ }
117
+ return;
118
+ }
119
+ } catch {
120
+ return;
121
+ }
122
+ try {
123
+ const serialized = JSON.stringify(value);
124
+ if (serialized && serialized !== "{}" && serialized !== "[]") output.add(serialized);
125
+ } catch {}
126
+ let descriptors;
127
+ try {
128
+ descriptors = Object.getOwnPropertyDescriptors(value);
129
+ } catch {
130
+ return;
131
+ }
132
+ for (const [key, descriptor] of Object.entries(descriptors)) if (key !== "length" && "value" in descriptor) collectSensitiveValues(descriptor.value, output, seen);
133
+ }
134
+ function collectSqlLiterals(sql, output) {
135
+ if (sql) output.add(sql);
136
+ for (const match of sql.matchAll(/'((?:''|[^'])*)'/gu)) {
137
+ const literal = match[1].replaceAll("''", "'");
138
+ if (literal) output.add(literal);
139
+ }
140
+ for (const match of sql.matchAll(/\$\$([\s\S]*?)\$\$/gu)) if (match[1]) output.add(match[1]);
141
+ for (const match of sql.matchAll(/\$([A-Za-z_][A-Za-z0-9_]*)\$([\s\S]*?)\$\1\$/gu)) if (match[2]) output.add(match[2]);
142
+ for (const match of sql.matchAll(SQL_NUMERIC_LITERAL)) {
143
+ output.add(match[0]);
144
+ output.add(match[0].replaceAll("_", ""));
145
+ }
146
+ }
147
+ function contextSecrets(context) {
148
+ const output = /* @__PURE__ */ new Set();
149
+ for (const [key, value] of Object.entries(context)) if (/^(?:args?|parameters?|params?|values?)$/i.test(key)) collectSensitiveValues(value, output, /* @__PURE__ */ new Set());
150
+ else if (/^(?:queries|query|sql)$/i.test(key) && typeof value === "string") collectSqlLiterals(value, output);
151
+ return [...output];
152
+ }
153
+ function sanitizeContextValue(value, knownSecrets, seen) {
154
+ if (typeof value === "string") return redactDatabaseErrorText(value, knownSecrets);
155
+ if (!value || typeof value !== "object") return value;
156
+ if (seen.has(value)) return "[circular]";
157
+ seen.add(value);
158
+ if (Array.isArray(value)) return value.map((entry) => sanitizeContextValue(entry, knownSecrets, seen));
159
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, isCredentialKey(key) ? "[redacted]" : sanitizeContextValue(entry, knownSecrets, seen)]));
160
+ }
161
+ function sanitizeDatabaseErrorContext(context, knownSecrets) {
162
+ return Object.fromEntries(Object.entries(context).map(([key, value]) => [key, SENSITIVE_CONTEXT_KEY.test(key) || isCredentialKey(key) ? "[redacted]" : sanitizeContextValue(value, knownSecrets, /* @__PURE__ */ new WeakSet())]));
163
+ }
164
+ function formatDbErrorWithSecrets(error, knownSecrets) {
165
+ const dbError = toDriverError(error);
22
166
  const parts = [];
23
- if (dbError.message) parts.push(dbError.message);
24
- if (dbError.code) parts.push(`code=${dbError.code}`);
25
- if (dbError.detail) parts.push(`detail=${dbError.detail}`);
26
- if (dbError.hint) parts.push(`hint=${dbError.hint}`);
27
- if (dbError.severity) parts.push(`severity=${dbError.severity}`);
167
+ if (dbError.message) parts.push(redactDatabaseErrorText(dbError.message, knownSecrets));
168
+ if (dbError.code) parts.push(`code=${redactDatabaseErrorText(dbError.code, knownSecrets)}`);
169
+ if (dbError.detail) parts.push(`detail=${redactDatabaseErrorText(dbError.detail, knownSecrets)}`);
170
+ if (dbError.hint) parts.push(`hint=${redactDatabaseErrorText(dbError.hint, knownSecrets)}`);
171
+ if (dbError.severity) parts.push(`severity=${redactDatabaseErrorText(dbError.severity, knownSecrets)}`);
28
172
  if (dbError.errno !== void 0) parts.push(`errno=${dbError.errno}`);
29
- return parts.length > 0 ? parts.join(", ") : String(error);
173
+ return parts.length > 0 ? parts.join(", ") : redactDatabaseErrorText(String(error), knownSecrets);
174
+ }
175
+ function safeDatabaseCause(error, knownSecrets) {
176
+ const dbError = toDriverError(error);
177
+ const message = dbError.message ? redactDatabaseErrorText(dbError.message, knownSecrets) : formatDbErrorWithSecrets(error, knownSecrets);
178
+ const cause = new Error(message);
179
+ cause.name = dbError.name ? redactDatabaseErrorText(dbError.name, knownSecrets) : "DatabaseDriverError";
180
+ for (const field of DRIVER_ERROR_FIELDS) {
181
+ const value = dbError[field];
182
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") Object.defineProperty(cause, field, {
183
+ configurable: true,
184
+ enumerable: true,
185
+ value: typeof value === "string" ? redactDatabaseErrorText(value, knownSecrets) : value,
186
+ writable: true
187
+ });
188
+ }
189
+ return cause;
190
+ }
191
+ /**
192
+ * Wraps an engine failure in a serializable, secret-safe DatabaseError.
193
+ *
194
+ * Raw SQL and parameter values are replaced in context. The native `cause` is
195
+ * a sanitized driver-error snapshot rather than the original object so normal
196
+ * Error inspection cannot bypass the same redaction applied to messages and
197
+ * JSON serialization.
198
+ */
199
+ function wrapDatabaseError(message, error, context = {}) {
200
+ const knownSecrets = contextSecrets(context);
201
+ const originalError = formatDbErrorWithSecrets(error, knownSecrets);
202
+ return new DatabaseError(`${message}: ${originalError}`, {
203
+ ...sanitizeDatabaseErrorContext(context, knownSecrets),
204
+ originalError
205
+ }, safeDatabaseCause(error, knownSecrets));
30
206
  }
31
207
  /**
32
208
  * Resolves the column list for a multi-row INSERT and rejects batches whose
@@ -979,6 +1155,6 @@ function validateDatabaseCacheOptions(options) {
979
1155
  if (options.dbid === "") throw new Error("Database cache dbid must be a non-empty string");
980
1156
  }
981
1157
  //#endregion
982
- export { unwrapRawKey as _, generateAddColumnStatement as a, validateColumnNames as c, DatabaseSchemaManager as d, buildWhere as f, resolveInsertColumns as g, raw as h, escapeStringLiteral as i, validateIndexName as l, parseConditionKey as m, validateDatabaseCacheOptions as n, generateCreateIndexStatement as o, formatDbError as p, escapeQuotedIdentifier as r, validateColumnName as s, ConnectionCache as t, validateTableName as u };
1158
+ export { unwrapRawKey as _, generateAddColumnStatement as a, validateColumnNames as c, DatabaseSchemaManager as d, buildWhere as f, resolveInsertColumns as g, raw as h, escapeStringLiteral as i, validateIndexName as l, parseConditionKey as m, validateDatabaseCacheOptions as n, generateCreateIndexStatement as o, formatDbError as p, escapeQuotedIdentifier as r, validateColumnName as s, ConnectionCache as t, validateTableName as u, wrapDatabaseError as v };
983
1159
 
984
- //# sourceMappingURL=connection-cache-6EMfKWpo.js.map
1160
+ //# sourceMappingURL=connection-cache-C32-070B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-cache-C32-070B.js","names":["#connections","#pending","#evictions","#requests","#clearing","#failedClosures","#registerRequest","#throwIfCancelled","#throwIfFailedClosure","#waitForEviction","#clearError","#finishRequest","#clearKey","#cancelRequests"],"sources":["../../src/shared/utils.ts","../../src/schema-manager.ts","../../src/shared/alter-utils.ts","../../src/shared/connection-cache.ts"],"sourcesContent":["/**\n * Shared SQL utilities that work in both browser and Node.js environments\n */\n\nimport { DatabaseError } from '@happyvertical/utils';\nimport type { WhereClause } from './types.js';\n\n/**\n * Formats a database error to include its useful non-secret details.\n *\n * Database drivers often include additional properties beyond just `message`:\n * - PostgreSQL: code, detail, hint, severity\n * - DuckDB: may include additional context\n * - SQLite/LibSQL: may include errno, code\n *\n * This function extracts an allowlist of driver properties and redacts\n * credential-shaped text. When parameter values are available, prefer\n * {@link wrapDatabaseError}; it also redacts values echoed by the driver.\n *\n * @param error - The caught error object\n * @returns Formatted error string with all available error details\n */\nexport function formatDbError(error: unknown): string {\n return formatDbErrorWithSecrets(error, []);\n}\n\ntype DriverError = {\n name?: string;\n message?: string;\n code?: string;\n detail?: string;\n hint?: string;\n severity?: string;\n errno?: number;\n};\n\nconst DRIVER_ERROR_FIELDS = [\n 'code',\n 'detail',\n 'hint',\n 'severity',\n 'errno',\n] as const;\n\nconst SENSITIVE_CONTEXT_KEY =\n /^(?:args?|parameters?|params?|queries|query|sql|values?)$/i;\nconst CREDENTIAL_KEY_PART =\n /^(?:credential|credentials|passphrase|password|pwd|secret|token)$/i;\nconst CREDENTIAL_KEY_QUALIFIER =\n /^(?:access|api|auth|client|private|refresh|service|signing)$/i;\nconst DATABASE_USER_KEY =\n /^(?:user(?:name)?|(?:database|db|pg|postgres|postgresql)[._-]?user(?:name)?)$/i;\nconst DATABASE_URL_USERINFO =\n /\\b((?:https?|libsql|postgres|postgresql):\\/\\/)[^\\s/@]+@/giu;\nconst DATABASE_URL =\n /\\b(?:https?|libsql|postgres|postgresql):\\/\\/[^\\s\"'`<>()]+/giu;\nconst CREDENTIAL_ASSIGNMENT =\n /(?<![\\p{L}\\p{N}_-])([\"']?)([\\p{L}\\p{N}_.-]+(?: key)?)\\1(\\s*[:=]\\s*)(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|[^\\s,;}\\]]+)/giu;\nconst BEARER_CREDENTIAL = /\\bbearer\\s+[^\\s,;]+/giu;\nconst SQL_NUMERIC_LITERAL =\n /(?<![\\p{L}\\p{N}_$])[-+]?(?:\\d(?:_?\\d)*(?:\\.(?:\\d(?:_?\\d)*)?)?|\\.\\d(?:_?\\d)*)(?:e[-+]?\\d(?:_?\\d)*)?(?![\\p{L}\\p{N}_$])/giu;\nconst POSTGRES_KEY_VALUE =\n /(\\bKey\\s*\\([^\\r\\n)]*\\)\\s*=\\s*\\()([\\s\\S]*?)(\\)\\s*(?:already exists|is duplicated)\\b)/giu;\nconst POSTGRES_FAILING_ROW =\n /(\\bFailing row contains\\s*\\()([\\s\\S]*)(\\)(?:\\.|$))/giu;\nconst CAST_INPUT_VALUE =\n /(\\bwith value\\s+)([\\s\\S]*?)(\\s+(?:can't|cannot)\\s+be cast\\b)/giu;\n\nfunction isCredentialKey(key: string): boolean {\n if (DATABASE_USER_KEY.test(key)) return true;\n\n const parts = key\n .replace(/([\\p{Ll}\\p{N}])(\\p{Lu})/gu, '$1 $2')\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean);\n if (parts.length === 1 && /^(?:auth|credential|key|pass)$/i.test(parts[0])) {\n return true;\n }\n if (parts.some((part) => CREDENTIAL_KEY_PART.test(part))) return true;\n\n return parts.some(\n (part, index) =>\n /^(?:key|auth)$/i.test(part) &&\n index > 0 &&\n CREDENTIAL_KEY_QUALIFIER.test(parts[index - 1]),\n );\n}\n\nfunction toDriverError(error: unknown): DriverError {\n return error && (typeof error === 'object' || typeof error === 'function')\n ? (error as DriverError)\n : {};\n}\n\nfunction redactUrl(value: string): string {\n try {\n const url = new URL(value);\n if (url.username) url.username = '[redacted]';\n if (url.password) url.password = '[redacted]';\n for (const key of url.searchParams.keys()) {\n if (isCredentialKey(key)) {\n url.searchParams.set(key, '[redacted]');\n }\n }\n if (url.hash) url.hash = '[redacted]';\n return url.toString();\n } catch {\n return value.replace(/\\/\\/[^/@\\s]+@/u, '//[redacted]@');\n }\n}\n\nfunction redactKnownValue(input: string, value: string): string {\n if (!value || !input.includes(value)) return input;\n if (!/^[\\p{L}\\p{N}_-]+$/u.test(value)) {\n return input.split(value).join('[redacted]');\n }\n\n const identifierCharacter = /^[\\p{L}\\p{N}_-]$/u;\n let cursor = 0;\n let redacted = '';\n let match = input.indexOf(value);\n while (match !== -1) {\n const end = match + value.length;\n const before = [...input.slice(Math.max(0, match - 2), match)].at(-1);\n const afterCodePoint = input.codePointAt(end);\n const after =\n afterCodePoint === undefined\n ? undefined\n : String.fromCodePoint(afterCodePoint);\n const bounded =\n (!before || !identifierCharacter.test(before)) &&\n (!after || !identifierCharacter.test(after));\n\n redacted += input.slice(cursor, match);\n redacted += bounded ? '[redacted]' : value;\n cursor = end;\n match = input.indexOf(value, cursor);\n }\n\n return redacted + input.slice(cursor);\n}\n\nfunction redactDatabaseErrorText(\n value: string,\n knownSecrets: readonly string[],\n): string {\n let redacted = value\n .replace(DATABASE_URL_USERINFO, '$1[redacted]@')\n .replace(DATABASE_URL, redactUrl)\n .replace(\n CREDENTIAL_ASSIGNMENT,\n (assignment, quote: string, key: string, delimiter: string) =>\n isCredentialKey(key)\n ? `${quote}${key}${quote}${delimiter}[redacted]`\n : assignment,\n )\n .replace(BEARER_CREDENTIAL, 'Bearer [redacted]')\n .replace(\n POSTGRES_KEY_VALUE,\n (_match, prefix: string, _value: string, suffix: string) =>\n `${prefix}[redacted]${suffix}`,\n )\n .replace(\n POSTGRES_FAILING_ROW,\n (_match, prefix: string, _value: string, suffix: string) =>\n `${prefix}[redacted]${suffix}`,\n )\n .replace(\n CAST_INPUT_VALUE,\n (_match, prefix: string, _value: string, suffix: string) =>\n `${prefix}[redacted]${suffix}`,\n );\n\n for (const secret of [...new Set(knownSecrets)].sort(\n (left, right) => right.length - left.length,\n )) {\n redacted = redactKnownValue(redacted, secret);\n }\n\n return redacted;\n}\n\nfunction collectSensitiveValues(\n value: unknown,\n output: Set<string>,\n seen: Set<object>,\n): void {\n if (typeof value === 'string') {\n if (value) output.add(value);\n return;\n }\n if (\n typeof value === 'number' ||\n typeof value === 'bigint' ||\n typeof value === 'boolean'\n ) {\n output.add(String(value));\n return;\n }\n if (!value || typeof value !== 'object' || seen.has(value)) return;\n seen.add(value);\n\n try {\n if (value instanceof Date) {\n output.add(value.toISOString());\n return;\n }\n\n if (ArrayBuffer.isView(value)) {\n const bytes = new Uint8Array(\n value.buffer,\n value.byteOffset,\n value.byteLength,\n );\n if (bytes.length > 0) {\n const hex = [...bytes]\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n output.add([...bytes].join(','));\n output.add(hex);\n output.add(`\\\\x${hex}`);\n output.add(`\\\\x${hex.toUpperCase()}`);\n output.add(\n `<Buffer ${[...bytes]\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join(' ')}>`,\n );\n if (typeof Buffer !== 'undefined') {\n output.add(Buffer.from(bytes).toString('base64'));\n }\n }\n return;\n }\n } catch {\n return;\n }\n\n try {\n const serialized = JSON.stringify(value);\n if (serialized && serialized !== '{}' && serialized !== '[]') {\n output.add(serialized);\n }\n } catch {\n // Cyclic bind values are still traversed below.\n }\n\n let descriptors: Record<string, PropertyDescriptor>;\n try {\n descriptors = Object.getOwnPropertyDescriptors(value);\n } catch {\n // A proxy trap must not replace the database failure being reported.\n return;\n }\n\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (key !== 'length' && 'value' in descriptor) {\n collectSensitiveValues(descriptor.value, output, seen);\n }\n }\n}\n\nfunction collectSqlLiterals(sql: string, output: Set<string>): void {\n // Some drivers include the complete statement in their diagnostics. Treat\n // an exact echo as sensitive even when it contains no parseable literals.\n if (sql) output.add(sql);\n\n for (const match of sql.matchAll(/'((?:''|[^'])*)'/gu)) {\n const literal = match[1].replaceAll(\"''\", \"'\");\n if (literal) output.add(literal);\n }\n\n for (const match of sql.matchAll(/\\$\\$([\\s\\S]*?)\\$\\$/gu)) {\n if (match[1]) output.add(match[1]);\n }\n\n for (const match of sql.matchAll(\n /\\$([A-Za-z_][A-Za-z0-9_]*)\\$([\\s\\S]*?)\\$\\1\\$/gu,\n )) {\n if (match[2]) output.add(match[2]);\n }\n\n for (const match of sql.matchAll(SQL_NUMERIC_LITERAL)) {\n output.add(match[0]);\n output.add(match[0].replaceAll('_', ''));\n }\n}\n\nfunction contextSecrets(context: Record<string, unknown>): string[] {\n const output = new Set<string>();\n for (const [key, value] of Object.entries(context)) {\n if (/^(?:args?|parameters?|params?|values?)$/i.test(key)) {\n collectSensitiveValues(value, output, new Set());\n } else if (\n /^(?:queries|query|sql)$/i.test(key) &&\n typeof value === 'string'\n ) {\n collectSqlLiterals(value, output);\n }\n }\n return [...output];\n}\n\nfunction sanitizeContextValue(\n value: unknown,\n knownSecrets: readonly string[],\n seen: WeakSet<object>,\n): unknown {\n if (typeof value === 'string') {\n return redactDatabaseErrorText(value, knownSecrets);\n }\n if (!value || typeof value !== 'object') return value;\n if (seen.has(value)) return '[circular]';\n seen.add(value);\n\n if (Array.isArray(value)) {\n return value.map((entry) =>\n sanitizeContextValue(entry, knownSecrets, seen),\n );\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n isCredentialKey(key)\n ? '[redacted]'\n : sanitizeContextValue(entry, knownSecrets, seen),\n ]),\n );\n}\n\nfunction sanitizeDatabaseErrorContext(\n context: Record<string, unknown>,\n knownSecrets: readonly string[],\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(context).map(([key, value]) => [\n key,\n SENSITIVE_CONTEXT_KEY.test(key) || isCredentialKey(key)\n ? '[redacted]'\n : sanitizeContextValue(value, knownSecrets, new WeakSet()),\n ]),\n );\n}\n\nfunction formatDbErrorWithSecrets(\n error: unknown,\n knownSecrets: readonly string[],\n): string {\n const dbError = toDriverError(error);\n\n const parts: string[] = [];\n\n if (dbError.message) {\n parts.push(redactDatabaseErrorText(dbError.message, knownSecrets));\n }\n if (dbError.code) {\n parts.push(`code=${redactDatabaseErrorText(dbError.code, knownSecrets)}`);\n }\n if (dbError.detail) {\n parts.push(\n `detail=${redactDatabaseErrorText(dbError.detail, knownSecrets)}`,\n );\n }\n if (dbError.hint) {\n parts.push(`hint=${redactDatabaseErrorText(dbError.hint, knownSecrets)}`);\n }\n if (dbError.severity) {\n parts.push(\n `severity=${redactDatabaseErrorText(dbError.severity, knownSecrets)}`,\n );\n }\n if (dbError.errno !== undefined) parts.push(`errno=${dbError.errno}`);\n\n return parts.length > 0\n ? parts.join(', ')\n : redactDatabaseErrorText(String(error), knownSecrets);\n}\n\nfunction safeDatabaseCause(\n error: unknown,\n knownSecrets: readonly string[],\n): Error {\n const dbError = toDriverError(error);\n const message = dbError.message\n ? redactDatabaseErrorText(dbError.message, knownSecrets)\n : formatDbErrorWithSecrets(error, knownSecrets);\n const cause = new Error(message);\n cause.name = dbError.name\n ? redactDatabaseErrorText(dbError.name, knownSecrets)\n : 'DatabaseDriverError';\n\n for (const field of DRIVER_ERROR_FIELDS) {\n const value = dbError[field];\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n Object.defineProperty(cause, field, {\n configurable: true,\n enumerable: true,\n value:\n typeof value === 'string'\n ? redactDatabaseErrorText(value, knownSecrets)\n : value,\n writable: true,\n });\n }\n }\n\n return cause;\n}\n\n/**\n * Wraps an engine failure in a serializable, secret-safe DatabaseError.\n *\n * Raw SQL and parameter values are replaced in context. The native `cause` is\n * a sanitized driver-error snapshot rather than the original object so normal\n * Error inspection cannot bypass the same redaction applied to messages and\n * JSON serialization.\n */\nexport function wrapDatabaseError(\n message: string,\n error: unknown,\n context: Record<string, unknown> = {},\n): DatabaseError {\n const knownSecrets = contextSecrets(context);\n const originalError = formatDbErrorWithSecrets(error, knownSecrets);\n return new DatabaseError(\n `${message}: ${originalError}`,\n {\n ...sanitizeDatabaseErrorContext(context, knownSecrets),\n originalError,\n },\n safeDatabaseCause(error, knownSecrets),\n );\n}\n\n/**\n * Resolves the column list for a multi-row INSERT and rejects batches whose\n * records disagree on it.\n *\n * A batch INSERT emits one column list for the whole statement, so it can only\n * come from the first record. That leaves two ways for a later record to be\n * written wrongly, both of them silent:\n *\n * - Its keys are the same but in a different insertion order. Callers that\n * bound values with `Object.values(record)` bound them by position, so the\n * values cross-assigned into each other's columns. Projecting each record\n * through the returned column list — `keys.map((key) => record[key])` — is\n * what makes key order irrelevant, and every caller must do it.\n * - Its key set genuinely differs. An extra key has no column to go to and a\n * missing one has no value, so the record cannot be expressed by this\n * statement at all. Guessing (dropping the extra, writing NULL for the\n * missing) is what makes the failure invisible, so this throws instead.\n *\n * A key whose value is `undefined` counts as absent. Adapters that serialize\n * records first drop such keys before this point while the rest pass them\n * through, so comparing raw key lists would make the same batch throw on some\n * adapters and silently write NULL on others. Only the comparison ignores them;\n * the returned column list is untouched, so each adapter keeps its own\n * single-record handling of `undefined`.\n *\n * @param table - Table being inserted into, for error context\n * @param records - Non-empty batch, as the adapter will bind it\n * @returns Column list taken from the first record\n * @throws DatabaseError if any later record's key set differs from the first's\n */\nexport function resolveInsertColumns(\n table: string,\n records: Record<string, any>[],\n): string[] {\n const definedKeys = (record: Record<string, any>) =>\n new Set(Object.keys(record).filter((key) => record[key] !== undefined));\n\n const keys = Object.keys(records[0]);\n const expected = definedKeys(records[0]);\n\n for (let index = 1; index < records.length; index++) {\n const recordKeys = definedKeys(records[index]);\n const missing = [...expected].filter((key) => !recordKeys.has(key));\n const extra = [...recordKeys].filter((key) => !expected.has(key));\n\n if (missing.length === 0 && extra.length === 0) {\n continue;\n }\n\n const problems = [\n missing.length > 0 ? `missing ${missing.join(', ')}` : '',\n extra.length > 0 ? `unexpected ${extra.join(', ')}` : '',\n ].filter(Boolean);\n\n throw new DatabaseError(\n `Batch insert records must all have the same keys; record ${index} has ${problems.join(\n ' and ',\n )} relative to record 0 (${[...expected].join(', ')})`,\n {\n table,\n recordIndex: index,\n expectedKeys: keys,\n recordKeys: [...recordKeys],\n missing,\n extra,\n hint: 'A batch INSERT writes one column list for every row, taken from the first record, so record 0 defines the columns even when it is the one that looks wrong. A key whose value is undefined counts as absent. Split records with differing keys into separate insert() calls, or fill the gaps explicitly with null.',\n },\n );\n }\n\n return keys;\n}\n\n/**\n * Map of valid SQL operators for use in WHERE clauses\n */\nconst VALID_OPERATORS = {\n '=': '=',\n '>': '>',\n '>=': '>=',\n '<': '<',\n '<=': '<=',\n '!=': '!=',\n like: 'LIKE',\n in: 'IN',\n 'not in': 'NOT IN',\n} as const;\n\nfunction isSimpleSqlIdentifier(field: string): boolean {\n return /^[a-zA-Z0-9_.]+$/.test(field);\n}\n\ndeclare const rawSqlKeyBrand: unique symbol;\n\n/**\n * A WHERE-clause key produced by {@link raw}: SQL text the caller vouches for,\n * exempt from the identifier validation `buildWhere` applies to every other key.\n */\nexport type RawSqlKey = string & { readonly [rawSqlKeyBrand]: true };\n\n/**\n * Marks a condition key as caller-authored SQL text.\n *\n * A fixed, non-secret sentinel rather than a random per-process token. A random\n * token has to travel inside the key, which means it reaches every place a key\n * is echoed — error messages, logs, each adapter's `DatabaseError` context — and\n * one disclosure would let a caller mint raw keys for the life of the process.\n * A registry of minted expressions avoids that but is not referentially\n * transparent: it would make `raw('revenue >')` in one query change what the\n * plain key `'revenue >'` means in every other one.\n *\n * The NUL delimiters cannot appear in an identifier or in SQL a developer would\n * write, so the marker never collides with a legitimate key.\n */\nconst RAW_KEY_PREFIX = '\\u0000hv-sql-raw\\u0000';\n\n/**\n * Marks a WHERE-clause key as SQL expression text rather than an identifier.\n *\n * {@link buildWhere} validates every condition key as a plain identifier. Wrap a\n * key in `raw()` to opt one condition out of that check:\n *\n * ```typescript\n * buildWhere({\n * status: 'paid', // validated as an identifier\n * [raw('SUM(total) >')]: 100, // caller-authored SQL, not validated\n * });\n * ```\n *\n * Never build the argument from end-user input. `raw()` is an assertion that\n * the caller, not the request, authored this SQL.\n *\n * The returned key carries a marker, so it is a distinct string from the bare\n * expression: minting `raw('revenue >')` never changes what the plain key\n * `'revenue >'` means anywhere else.\n *\n * The marker is a fixed sentinel, not a secret. It stops an expression key being\n * used by accident — the shape of the key no longer grants raw access, a call to\n * `raw()` does — but a caller that controls a whole key string verbatim,\n * including the NUL-delimited marker, can still reproduce it. Validate at your\n * own trust boundary; do not rely on this as the only barrier against hostile\n * input.\n *\n * Enforcement is at runtime: `WhereClause` keys are plain `string`, so a\n * computed key widens and TypeScript will not reject an unmarked expression key\n * at the call site.\n *\n * A trailing operator is recognised only if it is one of `=`, `!=`, `>`, `>=`,\n * `<`, `<=`, `like`, `in`, `not in`. Any other trailing token is treated as part\n * of the expression and `=` is appended, so `raw('name ILIKE')` silently emits\n * `name ILIKE = $1`, which the database then rejects. Fold an unsupported\n * operator into the expression instead: `raw('LOWER(name) like')`.\n *\n * @param expression - SQL field or expression text, optionally ending in a\n * supported operator (for example `SUM(total) >`)\n * @returns A branded key for use in a {@link WhereClause}\n * @throws If the expression is empty\n */\nexport function raw(expression: string): RawSqlKey {\n // Unwrap first so raw(raw(x)) === raw(x) and a marker can never nest into the\n // emitted SQL.\n const trimmed = unwrapRawKey(expression).key.trim();\n if (!trimmed) {\n throw new Error('raw() requires a non-empty SQL expression');\n }\n return `${RAW_KEY_PREFIX}${trimmed}` as RawSqlKey;\n}\n\n/**\n * Splits the raw marker off a condition key.\n * @internal\n */\nexport function unwrapRawKey(fullKey: string): {\n key: string;\n isRaw: boolean;\n} {\n return fullKey.startsWith(RAW_KEY_PREFIX)\n ? { key: fullKey.slice(RAW_KEY_PREFIX.length), isRaw: true }\n : { key: fullKey, isRaw: false };\n}\n\nexport function parseConditionKey(fullKey: string): {\n field: string;\n operator: string;\n} {\n const trimmed = fullKey.trim();\n const lower = trimmed.toLowerCase();\n const operators = ['not in', 'like', 'in', '!=', '>=', '<=', '>', '<', '='];\n\n for (const operator of operators) {\n if (lower.endsWith(` ${operator}`)) {\n return {\n field: trimmed.slice(0, -(operator.length + 1)).trim(),\n operator,\n };\n }\n }\n\n // Deliberately no `explicitOperator` flag: \"key ends in an operator\" was the\n // condition that used to suppress identifier validation, and that was the\n // vulnerability. Nothing should gate trust on the shape of the key again.\n return { field: trimmed, operator: '=' };\n}\n\n/**\n * SQL adapter type for adapter-specific query generation\n */\nexport type SqlAdapterType = 'sqlite' | 'postgres' | 'duckdb' | 'json';\n\n/**\n * Builds a single condition for a WHERE clause\n * @internal\n */\nconst buildCondition = (\n fullKey: string,\n value: any,\n currIndex: { value: number },\n adapterType?: SqlAdapterType,\n): { sql: string; values: any[] } => {\n const { key, isRaw } = unwrapRawKey(fullKey);\n const { field, operator } = parseConditionKey(key);\n if (!isRaw && !isSimpleSqlIdentifier(field)) {\n throw new Error(\n `Invalid SQL identifier: ${field}. Condition keys must be plain ` +\n 'identifiers; wrap developer-authored SQL expressions in raw().',\n );\n }\n const sqlOperator =\n VALID_OPERATORS[operator as keyof typeof VALID_OPERATORS] || '=';\n const values: any[] = [];\n\n let sql: string;\n\n if (value === null) {\n sql = `${field} IS ${sqlOperator === '=' ? 'NULL' : 'NOT NULL'}`;\n } else if (\n (sqlOperator === 'IN' || sqlOperator === 'NOT IN') &&\n Array.isArray(value)\n ) {\n if (value.length === 0) {\n throw new Error(`${sqlOperator} requires at least one value`);\n }\n const placeholders = value.map(() => `$${currIndex.value++}`).join(', ');\n sql = `${field} ${sqlOperator} (${placeholders})`;\n values.push(...value);\n } else if (value instanceof Date) {\n // DuckDB/JSON need CAST to TIMESTAMP to prevent ANY type inference (issue #540)\n // SQLite/PostgreSQL handle ISO strings natively without CAST\n const needsCast = adapterType === 'duckdb' || adapterType === 'json';\n if (needsCast) {\n sql = `${field} ${sqlOperator} CAST($${currIndex.value++} AS TIMESTAMP)`;\n } else {\n sql = `${field} ${sqlOperator} $${currIndex.value++}`;\n }\n values.push(value.toISOString());\n } else {\n sql = `${field} ${sqlOperator} $${currIndex.value++}`;\n values.push(value);\n }\n\n return { sql, values };\n};\n\n/**\n * Builds a SQL WHERE clause with parameterized values and flexible operators\n *\n * @param where - Conditions as object (AND-only) or 2D array (OR/AND compound)\n * @param startIndex - Starting index for parameter numbering (default: 1)\n * @param adapterType - Database adapter type. Controls Date handling:\n * - `'duckdb'` / `'json'`: Wraps Date values in `CAST($N AS TIMESTAMP)` to\n * prevent DuckDB ANY-type inference issues.\n * - `'sqlite'` / `'postgres'` / `undefined`: Passes ISO strings directly\n * (these adapters handle ISO timestamp strings natively).\n *\n * Every condition key is validated as a plain SQL identifier, with or without\n * an operator suffix. To use expression text as a key, wrap it in {@link raw}:\n *\n * ```typescript\n * buildWhere({ [raw('LOWER(status) =')]: 'paid' });\n * ```\n *\n * `raw()` is the only way to reach expression text, so mapping untrusted input\n * into a condition key throws rather than emitting attacker-controlled SQL.\n *\n * @returns Object containing the SQL clause and array of values\n * @throws If a key that is not wrapped in {@link raw} is not a plain identifier\n *\n * @example Basic Usage (Object format - AND-only):\n * ```typescript\n * buildWhere({\n * 'status': 'active', // equals operator is default\n * 'price >': 100, // greater than\n * 'stock <=': 5, // less than or equal\n * 'category in': ['A', 'B'], // IN clause for arrays\n * 'name like': '%shirt%' // LIKE for pattern matching\n * });\n * ```\n *\n * @example 2D Array Format (OR/AND compound logic):\n * ```typescript\n * // WHERE (status = 'active' AND price > 100) OR (status = 'pending' AND priority = 'high')\n * buildWhere([\n * [{ status: 'active' }, { 'price >': 100 }],\n * [{ status: 'pending' }, { priority: 'high' }]\n * ]);\n * ```\n *\n * @example NULL Handling:\n * ```typescript\n * buildWhere({\n * 'deleted_at': null, // becomes \"deleted_at IS NULL\"\n * 'updated_at !=': null, // becomes \"updated_at IS NOT NULL\"\n * 'status': 'active' // regular comparison\n * });\n * ```\n *\n * @example Common Patterns:\n * ```typescript\n * // Price range\n * buildWhere({\n * 'price >=': 10,\n * 'price <': 100\n * });\n *\n * // Date filtering\n * buildWhere({\n * 'created_at >': startDate,\n * 'created_at <=': endDate,\n * 'deleted_at': null\n * });\n *\n * // Search with LIKE\n * buildWhere({\n * 'title like': '%search%',\n * 'description like': '%search%',\n * 'status': 'published'\n * });\n *\n * // Multiple values with IN\n * buildWhere({\n * 'role in': ['admin', 'editor'],\n * 'active': true,\n * 'last_login !=': null\n * });\n * ```\n *\n * The function handles:\n * - Standard comparisons (=, >, >=, <, <=, !=)\n * - NULL checks (IS NULL, IS NOT NULL)\n * - IN clauses for arrays\n * - LIKE for pattern matching\n * - Object format: Multiple conditions combined with AND\n * - 2D array format: Inner arrays ANDed, outer array ORed\n */\nexport const buildWhere = (\n where: WhereClause,\n startIndex = 1,\n adapterType?: SqlAdapterType,\n) => {\n let sql = '';\n const values: any[] = [];\n const currIndex = { value: startIndex };\n\n // Handle 2D array format for OR/AND compound logic\n if (Array.isArray(where)) {\n if (where.length === 0) {\n return { sql: '', values: [] };\n }\n\n const orGroups: string[] = [];\n\n for (const andGroup of where) {\n if (!Array.isArray(andGroup) || andGroup.length === 0) {\n continue;\n }\n\n const andConditions: string[] = [];\n\n for (const conditionObj of andGroup) {\n for (const [fullKey, value] of Object.entries(conditionObj)) {\n const result = buildCondition(fullKey, value, currIndex, adapterType);\n andConditions.push(result.sql);\n values.push(...result.values);\n }\n }\n\n if (andConditions.length > 0) {\n // Wrap AND group in parentheses\n orGroups.push(`(${andConditions.join(' AND ')})`);\n }\n }\n\n if (orGroups.length > 0) {\n sql = `WHERE ${orGroups.join(' OR ')}`;\n }\n\n return { sql, values };\n }\n\n // Handle object format (original behavior - AND-only)\n if (where && Object.keys(where).length > 0) {\n sql = 'WHERE ';\n for (const [fullKey, value] of Object.entries(where)) {\n const result = buildCondition(fullKey, value, currIndex, adapterType);\n\n if (sql !== 'WHERE ') {\n sql += ' AND ';\n }\n\n sql += result.sql;\n values.push(...result.values);\n }\n }\n\n return { sql, values };\n};\n","/**\n * Schema management and dependency resolution for JSON manifests\n * Moved from SMRT package to SQL package for proper separation of concerns\n */\n\nimport type {\n DatabaseInterface,\n IndexDefinition,\n SchemaDefinition,\n SchemaInitializationOptions,\n TriggerDefinition,\n} from './shared/types.js';\n\n/**\n * Result returned by DatabaseSchemaManager.initializeSchemas()\n *\n * Contains the list of schemas that were successfully initialized,\n * any that were skipped (already up to date), errors encountered,\n * and the total execution time in milliseconds.\n */\nexport interface SchemaInitializationResult {\n initialized: string[];\n skipped: string[];\n errors: Array<{ schema: string; error: string }>;\n executionTime: number;\n}\n\n/**\n * Manages schema initialization from JSON manifests with dependency resolution\n *\n * Handles topological sorting of schema dependencies, table creation,\n * index and trigger setup, and version tracking to avoid redundant re-initialization.\n */\nexport class DatabaseSchemaManager {\n private static initializationLock = new Map<string, Promise<void>>();\n private initializedSchemas = new Set<string>();\n private schemaVersions = new Map<string, string>();\n\n /**\n * Initializes database schemas from a JSON manifest with dependency resolution\n *\n * Schemas are topologically sorted by their declared dependencies and\n * initialized in order. Supports legacy raw-SQL schemas via the `schema` option,\n * JSON manifests via the `manifest` option, and schema overrides for extending\n * base schemas.\n *\n * @param db - Database interface to execute DDL against\n * @param options - Schema initialization options (manifest, overrides, force, debug)\n * @returns Result with lists of initialized/skipped schemas, errors, and execution time\n */\n async initializeSchemas(\n db: DatabaseInterface,\n options: SchemaInitializationOptions,\n ): Promise<SchemaInitializationResult> {\n const startTime = Date.now();\n const result: SchemaInitializationResult = {\n initialized: [],\n skipped: [],\n errors: [],\n executionTime: 0,\n };\n\n try {\n let schemas: Record<string, SchemaDefinition> = {};\n\n // Handle legacy SQL schema format\n if (options.schema) {\n console.log(\n '[schema] Legacy SQL schema provided, converting to manifest format',\n );\n // For legacy support, we'll still use the original syncSchema method\n if (db.syncSchema) {\n await db.syncSchema(options.schema);\n result.initialized.push('legacy-sql');\n }\n result.executionTime = Date.now() - startTime;\n return result;\n }\n\n // Handle JSON manifest format\n if (options.manifest) {\n schemas = { ...options.manifest.schemas };\n }\n\n // Apply schema overrides\n if (options.overrides) {\n schemas = { ...schemas, ...options.overrides };\n }\n\n if (Object.keys(schemas).length === 0) {\n console.warn('[schema] No schemas provided for initialization');\n result.executionTime = Date.now() - startTime;\n return result;\n }\n\n // Build dependency graph\n const dependencyGraph = this.buildDependencyGraph(schemas);\n\n // Get initialization order\n const initializationOrder = this.resolveDependencies(dependencyGraph);\n\n if (options.debug) {\n console.log('[schema] Initialization order:', initializationOrder);\n }\n\n // Initialize schemas in dependency order\n for (const schemaName of initializationOrder) {\n const schema = schemas[schemaName];\n if (!schema) continue;\n\n try {\n await this.initializeSchema(db, schemaName, schema, {\n force: options.force,\n debug: options.debug,\n });\n result.initialized.push(schemaName);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n result.errors.push({ schema: schemaName, error: errorMessage });\n\n if (options.debug) {\n console.error(\n `[schema] Failed to initialize ${schemaName}:`,\n error,\n );\n }\n }\n }\n\n result.executionTime = Date.now() - startTime;\n\n if (options.debug) {\n console.log('[schema] Initialization complete:', result);\n }\n\n return result;\n } catch (error) {\n result.executionTime = Date.now() - startTime;\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n result.errors.push({\n schema: 'dependency-resolution',\n error: errorMessage,\n });\n return result;\n }\n }\n\n /**\n * Initialize a single schema\n */\n private async initializeSchema(\n db: DatabaseInterface,\n schemaName: string,\n schema: SchemaDefinition,\n options: { force?: boolean; debug?: boolean },\n ): Promise<void> {\n const { tableName, version } = schema;\n const lockKey = `${schemaName}:${tableName}`;\n\n // Check if already being initialized\n if (DatabaseSchemaManager.initializationLock.has(lockKey)) {\n await DatabaseSchemaManager.initializationLock.get(lockKey);\n return;\n }\n\n // Check if already initialized and up to date\n if (!options.force && this.isSchemaUpToDate(schemaName, version)) {\n if (options.debug) {\n console.log(`[schema] Skipping ${schemaName} - already up to date`);\n }\n return;\n }\n\n // Create initialization promise\n const initPromise = this.performSchemaInitialization(\n db,\n schemaName,\n schema,\n options,\n );\n DatabaseSchemaManager.initializationLock.set(lockKey, initPromise);\n\n try {\n await initPromise;\n this.markSchemaInitialized(schemaName, version);\n } finally {\n DatabaseSchemaManager.initializationLock.delete(lockKey);\n }\n }\n\n /**\n * Perform the actual schema initialization\n */\n private async performSchemaInitialization(\n db: DatabaseInterface,\n schemaName: string,\n schema: SchemaDefinition,\n options: { force?: boolean; debug?: boolean },\n ): Promise<void> {\n const { tableName, columns, indexes, triggers } = schema;\n\n if (options.debug) {\n console.log(`[schema] Initializing ${schemaName} (${tableName})`);\n }\n\n // Check if table exists\n const tableExists = await db.tableExists(tableName);\n\n if (!tableExists) {\n // Create table\n await this.createTable(db, schema);\n\n // Create indexes\n for (const index of indexes) {\n await this.createIndex(db, tableName, index);\n }\n\n // Create triggers\n for (const trigger of triggers) {\n await this.createTrigger(db, trigger);\n }\n } else if (options.force) {\n // Recreate table if forced\n await db.query(`DROP TABLE IF EXISTS ${tableName}`);\n await this.createTable(db, schema);\n\n for (const index of indexes) {\n await this.createIndex(db, tableName, index);\n }\n\n for (const trigger of triggers) {\n await this.createTrigger(db, trigger);\n }\n } else {\n // Table exists, check for schema changes\n await this.updateSchemaIfNeeded(db, schema);\n }\n }\n\n /**\n * Create table from schema definition\n */\n private async createTable(\n db: DatabaseInterface,\n schema: SchemaDefinition,\n ): Promise<void> {\n const { tableName, columns, foreignKeys } = schema;\n\n const columnDefinitions: string[] = [];\n\n // Add column definitions\n for (const [columnName, columnDef] of Object.entries(columns)) {\n let def = `${columnName} ${columnDef.type}`;\n\n if (columnDef.primaryKey) def += ' PRIMARY KEY';\n if (columnDef.unique && !columnDef.primaryKey) def += ' UNIQUE';\n if (columnDef.notNull) def += ' NOT NULL';\n if (columnDef.defaultValue !== undefined) {\n def += ` DEFAULT ${columnDef.defaultValue}`;\n }\n if (columnDef.check) def += ` CHECK (${columnDef.check})`;\n\n columnDefinitions.push(def);\n }\n\n // Add foreign key constraints\n for (const fk of foreignKeys) {\n let fkDef = `FOREIGN KEY (${fk.column}) REFERENCES ${fk.referencesTable}(${fk.referencesColumn})`;\n if (fk.onDelete) fkDef += ` ON DELETE ${fk.onDelete}`;\n if (fk.onUpdate) fkDef += ` ON UPDATE ${fk.onUpdate}`;\n columnDefinitions.push(fkDef);\n }\n\n const createTableSQL = `CREATE TABLE ${tableName} (\\n ${columnDefinitions.join(',\\n ')}\\n)`;\n await db.query(createTableSQL);\n }\n\n /**\n * Create index from definition\n */\n private async createIndex(\n db: DatabaseInterface,\n tableName: string,\n index: IndexDefinition,\n ): Promise<void> {\n const uniqueClause = index.unique ? 'UNIQUE ' : '';\n const whereClause = index.where ? ` WHERE ${index.where}` : '';\n const createIndexSQL = `CREATE ${uniqueClause}INDEX ${index.name} ON ${tableName} (${index.columns.join(', ')})${whereClause}`;\n\n await db.query(createIndexSQL);\n }\n\n /**\n * Create trigger from definition\n */\n private async createTrigger(\n db: DatabaseInterface,\n trigger: TriggerDefinition,\n ): Promise<void> {\n const conditionClause = trigger.condition\n ? ` WHEN ${trigger.condition}`\n : '';\n const createTriggerSQL = `CREATE TRIGGER ${trigger.name} ${trigger.when} ${trigger.event} ON ${trigger.table}${conditionClause} BEGIN ${trigger.body} END`;\n\n await db.query(createTriggerSQL);\n }\n\n /**\n * Update schema if changes are detected\n */\n private async updateSchemaIfNeeded(\n _db: DatabaseInterface,\n schema: SchemaDefinition,\n ): Promise<void> {\n // For now, just log that update is needed\n // In future, implement ALTER TABLE logic\n console.log(\n `[schema] Schema update logic not yet implemented for ${schema.tableName}`,\n );\n }\n\n /**\n * Build dependency graph from schemas\n */\n private buildDependencyGraph(\n schemas: Record<string, SchemaDefinition>,\n ): Map<string, string[]> {\n const graph = new Map<string, string[]>();\n\n for (const [schemaName, schema] of Object.entries(schemas)) {\n const dependencies = schema.dependencies.filter((dep) =>\n Object.values(schemas).some((s) => s.tableName === dep),\n );\n graph.set(\n schemaName,\n dependencies.map(\n (dep) =>\n Object.entries(schemas).find(\n ([_, s]) => s.tableName === dep,\n )?.[0] || dep,\n ),\n );\n }\n\n return graph;\n }\n\n /**\n * Resolve dependencies using topological sort\n */\n private resolveDependencies(graph: Map<string, string[]>): string[] {\n const resolved: string[] = [];\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n const visit = (node: string) => {\n if (visiting.has(node)) {\n throw new Error(`Circular dependency detected involving ${node}`);\n }\n if (visited.has(node)) return;\n\n visiting.add(node);\n const dependencies = graph.get(node) || [];\n\n for (const dep of dependencies) {\n if (graph.has(dep)) {\n visit(dep);\n }\n }\n\n visiting.delete(node);\n visited.add(node);\n resolved.push(node);\n };\n\n for (const node of graph.keys()) {\n if (!visited.has(node)) {\n visit(node);\n }\n }\n\n return resolved;\n }\n\n /**\n * Check if schema is up to date\n */\n private isSchemaUpToDate(schemaName: string, version: string): boolean {\n return (\n this.initializedSchemas.has(schemaName) &&\n this.schemaVersions.get(schemaName) === version\n );\n }\n\n /**\n * Mark schema as initialized\n */\n private markSchemaInitialized(schemaName: string, version: string): void {\n this.initializedSchemas.add(schemaName);\n this.schemaVersions.set(schemaName, version);\n }\n\n /**\n * Reset initialization state (for testing)\n */\n reset(): void {\n this.initializedSchemas.clear();\n this.schemaVersions.clear();\n DatabaseSchemaManager.initializationLock.clear();\n }\n}\n","/**\n * Shared utilities for ALTER TABLE operations\n *\n * Provides database-agnostic utilities for generating ALTER TABLE statements,\n * handling column definitions, and creating indexes.\n */\n\nimport type { ColumnDefinitionWithName, IndexDefinition } from './types.js';\n\n/**\n * Database dialect type for SQL generation\n */\nexport type DatabaseDialect = 'sqlite' | 'postgres' | 'duckdb';\n\n/**\n * Generates an ALTER TABLE ADD COLUMN statement\n *\n * @param table - Table name\n * @param column - Column definition with name\n * @param dialect - Database dialect\n * @returns SQL statement string\n *\n * @example\n * ```typescript\n * const sql = generateAddColumnStatement('users', {\n * name: 'email',\n * type: 'TEXT',\n * unique: true,\n * notNull: false\n * }, 'sqlite');\n * // Returns: \"ALTER TABLE users ADD COLUMN email TEXT UNIQUE\"\n * ```\n */\nexport function generateAddColumnStatement(\n table: string,\n column: ColumnDefinitionWithName,\n _dialect: DatabaseDialect,\n): string {\n const parts: string[] = [column.name, column.type];\n\n // Primary key\n if (column.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // NOT NULL constraint\n if (column.notNull) {\n parts.push('NOT NULL');\n }\n\n // UNIQUE constraint\n if (column.unique) {\n parts.push('UNIQUE');\n }\n\n // DEFAULT clause\n if (column.defaultValue !== undefined) {\n const defaultClause = generateDefaultClause(\n column.type,\n column.defaultValue,\n );\n parts.push(`DEFAULT ${defaultClause}`);\n }\n\n // CHECK constraint\n if (column.check) {\n parts.push(`CHECK (${column.check})`);\n }\n\n // Foreign key (inline for some databases)\n if (column.foreignKey) {\n const fk = column.foreignKey;\n const fkParts = [`REFERENCES ${fk.table}(${fk.column})`];\n\n if (fk.onDelete) {\n fkParts.push(`ON DELETE ${fk.onDelete}`);\n }\n\n if (fk.onUpdate) {\n fkParts.push(`ON UPDATE ${fk.onUpdate}`);\n }\n\n parts.push(fkParts.join(' '));\n }\n\n const columnDef = parts.join(' ');\n return `ALTER TABLE ${table} ADD COLUMN ${columnDef}`;\n}\n\n/**\n * Generates a DEFAULT clause for a column definition\n *\n * Handles proper formatting and escaping of default values based on column type.\n *\n * @param columnType - SQL column type (TEXT, INTEGER, BOOLEAN, etc.)\n * @param defaultValue - Default value to format\n * @returns Formatted default value string\n *\n * @example\n * ```typescript\n * generateDefaultClause('TEXT', 'hello'); // Returns: \"'hello'\"\n * generateDefaultClause('INTEGER', 42); // Returns: \"42\"\n * generateDefaultClause('BOOLEAN', true); // Returns: \"true\"\n * generateDefaultClause('TEXT', null); // Returns: \"NULL\"\n * ```\n */\nexport function generateDefaultClause(\n columnType: string,\n defaultValue: any,\n): string {\n if (defaultValue === null) {\n return 'NULL';\n }\n\n const typeUpper = columnType.toUpperCase();\n\n // String types - need quotes\n if (\n typeUpper.includes('TEXT') ||\n typeUpper.includes('CHAR') ||\n typeUpper.includes('VARCHAR') ||\n typeUpper.includes('STRING')\n ) {\n // Handle empty strings\n if (defaultValue === '') {\n return \"''\";\n }\n // Escape single quotes\n const escaped = String(defaultValue).replace(/'/g, \"''\");\n return `'${escaped}'`;\n }\n\n // Boolean types\n if (typeUpper.includes('BOOL')) {\n return defaultValue ? 'true' : 'false';\n }\n\n // Numeric types - no quotes\n if (\n typeUpper.includes('INT') ||\n typeUpper.includes('REAL') ||\n typeUpper.includes('FLOAT') ||\n typeUpper.includes('DOUBLE') ||\n typeUpper.includes('NUMERIC') ||\n typeUpper.includes('DECIMAL')\n ) {\n return String(defaultValue);\n }\n\n // JSON types\n if (typeUpper.includes('JSON')) {\n if (typeof defaultValue === 'string') {\n return `'${defaultValue.replace(/'/g, \"''\")}'`;\n }\n return `'${JSON.stringify(defaultValue).replace(/'/g, \"''\")}'`;\n }\n\n // Date/timestamp types\n if (\n typeUpper.includes('DATE') ||\n typeUpper.includes('TIME') ||\n typeUpper.includes('TIMESTAMP')\n ) {\n if (defaultValue instanceof Date) {\n return `'${defaultValue.toISOString()}'`;\n }\n return `'${String(defaultValue).replace(/'/g, \"''\")}'`;\n }\n\n // Default: treat as string\n if (typeof defaultValue === 'string') {\n return `'${defaultValue.replace(/'/g, \"''\")}'`;\n }\n\n return String(defaultValue);\n}\n\n/**\n * Generates a CREATE INDEX statement\n *\n * @param table - Table name\n * @param index - Index definition\n * @returns SQL CREATE INDEX statement\n *\n * @example\n * ```typescript\n * const sql = generateCreateIndexStatement('users', {\n * name: 'idx_users_email',\n * columns: ['email'],\n * unique: true\n * });\n * // Returns: \"CREATE UNIQUE INDEX idx_users_email ON users (email)\"\n * ```\n */\nexport function generateCreateIndexStatement(\n table: string,\n index: IndexDefinition,\n): string {\n const parts: string[] = ['CREATE'];\n\n // UNIQUE modifier\n if (index.unique) {\n parts.push('UNIQUE');\n }\n\n parts.push('INDEX');\n\n // Index name\n parts.push(index.name);\n\n // ON table\n parts.push(`ON ${table}`);\n\n // Column list\n const columns = index.columns.join(', ');\n parts.push(`(${columns})`);\n\n // WHERE clause (partial index)\n if (index.where) {\n parts.push(`WHERE ${index.where}`);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Validates a table name to prevent SQL injection\n *\n * The argument must be a primitive string. `RegExp.prototype.test` coerces its\n * argument with `toString`, so an object whose `toString` returns a valid name\n * on the call the validator makes and a different one on the call the caller's\n * `${table}` interpolation makes would pass here and then reach SQL. Rejecting\n * non-strings up front closes that gap: the value validated is the value\n * interpolated, because a primitive string cannot observe how many times it is\n * read.\n *\n * @param tableName - Table name to validate\n * @throws Error if the value is not a string or contains invalid characters\n */\nexport function validateTableName(tableName: string): void {\n if (\n typeof tableName !== 'string' ||\n !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)\n ) {\n throw new Error(\n `Invalid table name: ${tableName}. Table names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`,\n );\n }\n}\n\n/**\n * Validates a column name to prevent SQL injection\n *\n * Rejects non-strings for the same reason as {@link validateTableName}: a value\n * whose `toString` differs between the validation read and the interpolation\n * read would otherwise slip a different identifier into SQL than the one\n * checked here.\n *\n * @param columnName - Column name to validate\n * @throws Error if the value is not a string or contains invalid characters\n */\nexport function validateColumnName(columnName: string): void {\n if (\n typeof columnName !== 'string' ||\n !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(columnName)\n ) {\n throw new Error(\n `Invalid column name: ${columnName}. Column names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`,\n );\n }\n}\n\n/**\n * Validates every identifier in a column list to prevent SQL injection\n *\n * Column names reaching the CRUD methods come from `Object.keys(data)` and the\n * caller's `conflictColumns`, both of which are interpolated into SQL. They are\n * checked rather than quoted deliberately: the accepted shape has no character\n * that can end an identifier, so quoting adds nothing to safety, and quoting a\n * name on PostgreSQL makes it case-sensitive, which would silently change which\n * column an existing caller addresses.\n *\n * @param columnNames - Column names to validate\n * @throws Error if any column name contains invalid characters\n */\nexport function validateColumnNames(columnNames: string[]): void {\n for (const columnName of columnNames) {\n validateColumnName(columnName);\n }\n}\n\n/**\n * Escapes an identifier for interpolation inside double quotes\n *\n * For the positions that already quote the identifier — the DuckDB and JSON\n * upsert statements, which quote to match their schema generator — quoting is\n * what makes the identifier safe, so the only thing that has to be handled is\n * a quote character inside the name. Doubling it is the SQL escape.\n *\n * This is deliberately more permissive than {@link validateColumnName}: those\n * adapters accept column names that are not plain identifiers (`Full Name`,\n * `user-id`, `2024_total`), which matters most for the JSON adapter, whose\n * columns come straight from the keys of whatever JSON it was pointed at.\n * Rejecting them would break working code to fix an injection that quoting\n * already prevents.\n *\n * @param identifier - Identifier to place inside double quotes\n * @returns The identifier with embedded quotes doubled\n * @throws Error if the identifier is empty or contains a NUL byte\n */\nexport function escapeQuotedIdentifier(identifier: string): string {\n // Coerce to a primitive string first. The escape's safety rests on\n // `replaceAll`/`includes` being the real `String` methods, but a crafted\n // object could supply its own that return unescaped SQL while its `toString`\n // reads as a benign name elsewhere. Coercing once runs its `toString` here\n // and pins an immutable primitive for the length check and the escape, so the\n // value escaped is the value returned.\n const value = String(identifier);\n if (value.length === 0 || value.includes('\\0')) {\n throw new Error(\n `Invalid column name: ${JSON.stringify(value)}. Column names must be non-empty and must not contain a NUL byte.`,\n );\n }\n return value.replaceAll('\"', '\"\"');\n}\n\n/**\n * Escapes a value for interpolation inside a single-quoted SQL string literal\n *\n * The DuckDB-backed adapters read JSON through `read_json_auto('<path>')`, and\n * a file path is not something an identifier validator can check — paths\n * legitimately contain spaces, dots and, on Linux and macOS, quotes. Doubling\n * the quote is the SQL escape, and it is what keeps a file named `x'.json`\n * from ending the literal and starting a statement.\n *\n * @param value - Value to place inside single quotes\n * @returns The value with embedded single quotes doubled\n * @throws Error if the value contains a NUL byte\n */\nexport function escapeStringLiteral(value: string): string {\n // Coerce to a primitive string first, for the same reason as\n // {@link escapeQuotedIdentifier}: the escape must run on an immutable\n // primitive, not on an object that could supply its own `replaceAll`.\n const text = String(value);\n if (text.includes('\\0')) {\n throw new Error(\n `Invalid SQL string literal: ${JSON.stringify(text)}. Values must not contain a NUL byte.`,\n );\n }\n return text.replaceAll(\"'\", \"''\");\n}\n\n/**\n * Validates an index name to prevent SQL injection\n *\n * @param indexName - Index name to validate\n * @throws Error if index name contains invalid characters\n */\nexport function validateIndexName(indexName: string): void {\n if (\n typeof indexName !== 'string' ||\n !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)\n ) {\n throw new Error(\n `Invalid index name: ${indexName}. Index names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`,\n );\n }\n}\n","import type { DatabaseCacheOptions } from './types';\n\ntype PendingConnection<T> = {\n invalidated: false | 'clear' | 'evict';\n promise: Promise<T>;\n};\n\ntype EvictionChain<T> = {\n promise: Promise<void>;\n state: {\n invalidated: Set<PendingConnection<T>>;\n invalidation: 'clear' | 'evict';\n };\n};\n\ntype CacheRequest = {\n cancelled: boolean;\n done: Promise<void>;\n finish: () => void;\n};\n\n/** Race-safe async resource cache used by database adapters. */\nexport class ConnectionCache<T> {\n readonly #connections = new Map<string, T>();\n readonly #pending = new Map<string, PendingConnection<T>>();\n readonly #evictions = new Map<string, EvictionChain<T>>();\n readonly #requests = new Map<string, Set<CacheRequest>>();\n readonly #clearing = new Map<string, number>();\n readonly #failedClosures = new Map<\n string,\n { error: unknown; resources: Set<T> }\n >();\n\n async getOrCreate(\n key: string | undefined,\n options: DatabaseCacheOptions,\n create: () => Promise<T>,\n close: (connection: T) => Promise<void>,\n ): Promise<T> {\n validateDatabaseCacheOptions(options);\n const request =\n key && options.cache !== false ? this.#registerRequest(key) : undefined;\n try {\n this.#throwIfCancelled(request);\n if (key && options.clearCache) {\n await this.evict(key, close);\n this.#throwIfCancelled(request);\n }\n if (key) this.#throwIfFailedClosure(key);\n\n if (!key || options.cache === false) {\n return create();\n }\n\n while (true) {\n if (this.#evictions.has(key)) {\n await this.#waitForEviction(key);\n this.#throwIfCancelled(request);\n }\n this.#throwIfFailedClosure(key);\n\n const cached = this.#connections.get(key);\n if (cached) {\n return cached;\n }\n\n let pending = this.#pending.get(key);\n if (!pending) {\n this.#throwIfCancelled(request);\n pending = { invalidated: false, promise: create() };\n this.#pending.set(key, pending);\n }\n\n let connection: T;\n try {\n connection = await pending.promise;\n } catch (error) {\n if (this.#pending.get(key) === pending) {\n this.#pending.delete(key);\n }\n throw error;\n }\n\n if (pending.invalidated || this.#evictions.has(key)) {\n if (this.#evictions.has(key)) {\n await this.#waitForEviction(key);\n }\n this.#throwIfCancelled(request);\n if (pending.invalidated === 'clear') {\n throw this.#clearError();\n }\n continue;\n }\n\n this.#throwIfCancelled(request);\n if (this.#pending.get(key) === pending) {\n this.#pending.delete(key);\n }\n this.#connections.set(key, connection);\n return connection;\n }\n } finally {\n if (request && key) {\n this.#finishRequest(key, request);\n }\n }\n }\n\n async evict(\n key: string,\n close: (connection: T) => Promise<void>,\n invalidation: 'clear' | 'evict' = 'evict',\n ) {\n const previous = this.#evictions.get(key);\n const state = previous?.state ?? {\n invalidated: new Set<PendingConnection<T>>(),\n invalidation,\n };\n if (invalidation === 'clear') {\n state.invalidation = 'clear';\n for (const pending of state.invalidated) {\n pending.invalidated = 'clear';\n }\n }\n\n const eviction = (previous?.promise ?? Promise.resolve()).then(async () => {\n const resources = new Set<T>(\n this.#failedClosures.get(key)?.resources ?? [],\n );\n this.#failedClosures.delete(key);\n const cached = this.#connections.get(key);\n this.#connections.delete(key);\n if (cached) resources.add(cached);\n\n const pending = this.#pending.get(key);\n this.#pending.delete(key);\n if (pending) {\n state.invalidated.add(pending);\n pending.invalidated = state.invalidation;\n // The original initializer caller still observes its rejection. For\n // eviction, a stale failure means there is simply no resource to close.\n const initialized = await pending.promise.catch(() => undefined);\n if (initialized !== undefined) resources.add(initialized);\n }\n\n const closeResults = await Promise.allSettled(\n [...resources].map(async (resource) => {\n await close(resource);\n return resource;\n }),\n );\n const failures = closeResults.filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n );\n if (failures.length) {\n const resourceList = [...resources];\n const failedResources = new Set<T>();\n closeResults.forEach((result, index) => {\n if (result.status === 'rejected') {\n failedResources.add(resourceList[index]);\n }\n });\n const error =\n failures.length === 1\n ? failures[0].reason\n : new AggregateError(\n failures.map((failure) => failure.reason),\n 'Multiple database connections failed to close',\n );\n this.#failedClosures.set(key, {\n error,\n resources: failedResources,\n });\n throw error;\n }\n });\n\n const chain = { promise: eviction, state };\n this.#evictions.set(key, chain);\n try {\n await eviction;\n } finally {\n if (this.#evictions.get(key) === chain) {\n this.#evictions.delete(key);\n }\n }\n }\n\n async clear(close: (connection: T) => Promise<void>) {\n const keys = new Set([\n ...this.#connections.keys(),\n ...this.#pending.keys(),\n ...this.#evictions.keys(),\n ...this.#requests.keys(),\n ...this.#clearing.keys(),\n ...this.#failedClosures.keys(),\n ]);\n const results = await Promise.allSettled(\n [...keys].map((key) => this.#clearKey(key, close)),\n );\n const failures = results.filter(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n if (failures.length === 1) throw failures[0].reason;\n if (failures.length > 1) {\n throw new AggregateError(\n failures.map((failure) => failure.reason),\n 'Multiple database connection cache entries failed to clear',\n );\n }\n }\n\n forget(connection: T): void {\n for (const [key, cached] of this.#connections) {\n if (cached === connection) {\n this.#connections.delete(key);\n }\n }\n }\n\n /** @internal Test-only visibility; includes every retained namespace. */\n get size(): number {\n return (\n this.#connections.size +\n this.#pending.size +\n this.#evictions.size +\n this.#requests.size +\n this.#clearing.size +\n this.#failedClosures.size\n );\n }\n\n async #clearKey(key: string, close: (connection: T) => Promise<void>) {\n this.#clearing.set(key, (this.#clearing.get(key) ?? 0) + 1);\n try {\n this.#cancelRequests(key);\n await this.evict(key, close, 'clear');\n while (this.#requests.get(key)?.size) {\n this.#cancelRequests(key);\n await Promise.all(\n [...(this.#requests.get(key) ?? [])].map((request) => request.done),\n );\n }\n } finally {\n const remaining = (this.#clearing.get(key) ?? 1) - 1;\n if (remaining === 0) this.#clearing.delete(key);\n else this.#clearing.set(key, remaining);\n }\n }\n\n #cancelRequests(key: string): void {\n for (const request of this.#requests.get(key) ?? []) {\n request.cancelled = true;\n }\n }\n\n #clearError(): Error {\n return new Error(\n 'Database connection initialization was cancelled by cache clear',\n );\n }\n\n #finishRequest(key: string, request: CacheRequest): void {\n const requests = this.#requests.get(key);\n requests?.delete(request);\n if (requests?.size === 0) this.#requests.delete(key);\n request.finish();\n }\n\n #registerRequest(key: string): CacheRequest {\n let finish = () => {};\n const done = new Promise<void>((resolve) => {\n finish = resolve;\n });\n const request = {\n cancelled: this.#clearing.has(key),\n done,\n finish,\n };\n const requests = this.#requests.get(key) ?? new Set<CacheRequest>();\n requests.add(request);\n this.#requests.set(key, requests);\n return request;\n }\n\n #throwIfCancelled(request: CacheRequest | undefined): void {\n if (request?.cancelled) throw this.#clearError();\n }\n\n #throwIfFailedClosure(key: string): void {\n const failure = this.#failedClosures.get(key);\n if (failure) throw failure.error;\n }\n\n async #waitForEviction(key: string): Promise<void> {\n while (true) {\n const eviction = this.#evictions.get(key);\n if (!eviction) return;\n await eviction.promise;\n }\n }\n}\n\nexport function validateDatabaseCacheOptions(options: DatabaseCacheOptions) {\n if (options.dbid === '') {\n throw new Error('Database cache dbid must be a non-empty string');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,cAAc,OAAwB;CACpD,OAAO,yBAAyB,OAAO,CAAC,CAAC;AAC3C;AAYA,IAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,wBACJ;AACF,IAAM,sBACJ;AACF,IAAM,2BACJ;AACF,IAAM,oBACJ;AACF,IAAM,wBACJ;AACF,IAAM,eACJ;AACF,IAAM,wBACJ;AACF,IAAM,oBAAoB;AAC1B,IAAM,sBACJ;AACF,IAAM,qBACJ;AACF,IAAM,uBACJ;AACF,IAAM,mBACJ;AAEF,SAAS,gBAAgB,KAAsB;CAC7C,IAAI,kBAAkB,KAAK,GAAG,GAAG,OAAO;CAExC,MAAM,QAAQ,IACX,QAAQ,6BAA6B,OAAO,CAAC,CAC7C,M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AM,UAAU;GACd,WAAW,KAAKC,UAAU,IAAI,GAAG;GACjC;GACA;EACF;EACA,MAAM,WAAW,KAAKD,UAAU,IAAI,GAAG,qBAAK,IAAI,IAAkB;EAClE,SAAS,IAAI,OAAO;EACpB,KAAKA,UAAU,IAAI,KAAK,QAAQ;EAChC,OAAO;CACT;CAEA,kBAAkB,SAAyC;EACzD,IAAI,SAAS,WAAW,MAAM,KAAKO,YAAY;CACjD;CAEA,sBAAsB,KAAmB;EACvC,MAAM,UAAU,KAAKL,gBAAgB,IAAI,GAAG;EAC5C,IAAI,SAAS,MAAM,QAAQ;CAC7B;CAEA,MAAMI,iBAAiB,KAA4B;EACjD,OAAO,MAAM;GACX,MAAM,WAAW,KAAKP,WAAW,IAAI,GAAG;GACxC,IAAI,CAAC,UAAU;GACf,MAAM,SAAS;EACjB;CACF;AACF;AAEA,SAAgB,6BAA6B,SAA+B;CAC1E,IAAI,QAAQ,SAAS,IACnB,MAAM,IAAI,MAAM,gDAAgD;AAEpE"}
@@ -1,4 +1,4 @@
1
- import { a as generateAddColumnStatement, c as validateColumnNames, d as DatabaseSchemaManager, f as buildWhere, g as resolveInsertColumns, i as escapeStringLiteral, l as validateIndexName, n as validateDatabaseCacheOptions, o as generateCreateIndexStatement, p as formatDbError, r as escapeQuotedIdentifier, s as validateColumnName, u as validateTableName } from "./connection-cache-6EMfKWpo.js";
1
+ import { a as generateAddColumnStatement, c as validateColumnNames, d as DatabaseSchemaManager, f as buildWhere, g as resolveInsertColumns, i as escapeStringLiteral, l as validateIndexName, n as validateDatabaseCacheOptions, o as generateCreateIndexStatement, p as formatDbError, r as escapeQuotedIdentifier, s as validateColumnName, u as validateTableName, v as wrapDatabaseError } from "./connection-cache-C32-070B.js";
2
2
  import { n as throwWithDuckDBCleanup, r as convertUniqueIndexesToInlineConstraints, t as createDuckDBResourceCloser } from "./duckdb-resources-Cci6Lo6H.js";
3
3
  import { t as redactDatabaseUrl } from "./redact-database-url-CfMDvSdy.js";
4
4
  import { n as resolveSchemas, r as createTransactionLock, t as NestedTransactionError } from "./types-uVFHgaSU.js";
@@ -715,10 +715,9 @@ async function getDatabase(options = {}) {
715
715
  rows
716
716
  };
717
717
  } catch (e) {
718
- throw new DatabaseError("Failed to execute raw query", {
718
+ throw wrapDatabaseError("Failed to execute raw query", e, {
719
719
  sql,
720
- args,
721
- originalError: formatDbError(e)
720
+ args
722
721
  });
723
722
  }
724
723
  };
@@ -913,14 +912,15 @@ async function getDatabase(options = {}) {
913
912
  addColumn: async (table, column) => {
914
913
  validateTableName(table);
915
914
  validateColumnName(column.name);
915
+ let sql;
916
916
  try {
917
- const sql = generateAddColumnStatement(table, column, "duckdb");
917
+ sql = generateAddColumnStatement(table, column, "duckdb");
918
918
  await connection.run(sql);
919
919
  } catch (e) {
920
- throw new DatabaseError("Failed to add column to table", {
920
+ throw wrapDatabaseError("Failed to add column to table", e, {
921
921
  table,
922
922
  column: column.name,
923
- originalError: formatDbError(e)
923
+ ...sql ? { sql } : {}
924
924
  });
925
925
  }
926
926
  },
@@ -936,14 +936,15 @@ async function getDatabase(options = {}) {
936
936
  validateTableName(table);
937
937
  validateIndexName(index.name);
938
938
  for (const col of index.columns) validateColumnName(col);
939
+ let sql;
939
940
  try {
940
- const sql = generateCreateIndexStatement(table, index);
941
+ sql = generateCreateIndexStatement(table, index);
941
942
  await connection.run(sql);
942
943
  } catch (e) {
943
- throw new DatabaseError("Failed to create index on table", {
944
+ throw wrapDatabaseError("Failed to create index on table", e, {
944
945
  table,
945
946
  index: index.name,
946
- originalError: formatDbError(e)
947
+ ...sql ? { sql } : {}
947
948
  });
948
949
  }
949
950
  }
@@ -1086,4 +1087,4 @@ async function getDatabase(options = {}) {
1086
1087
  //#endregion
1087
1088
  export { getDatabase };
1088
1089
 
1089
- //# sourceMappingURL=duckdb-D2Nah7NF.js.map
1090
+ //# sourceMappingURL=duckdb-CY0_khO7.js.map