@happyvertical/sql 0.86.2 → 0.86.4

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 (43) hide show
  1. package/README.md +41 -0
  2. package/dist/chunks/{alter-utils-DeDDAATm.js → connection-cache-6EMfKWpo.js} +196 -2
  3. package/dist/chunks/connection-cache-6EMfKWpo.js.map +1 -0
  4. package/dist/chunks/{duckdb-jSSa2MbC.js → duckdb-D2Nah7NF.js} +22 -10
  5. package/dist/chunks/duckdb-D2Nah7NF.js.map +1 -0
  6. package/dist/chunks/{duckdb-schema-utils-B-XBP8QF.js → duckdb-resources-Cci6Lo6H.js} +43 -2
  7. package/dist/chunks/duckdb-resources-Cci6Lo6H.js.map +1 -0
  8. package/dist/chunks/redact-database-url-CfMDvSdy.js +33 -0
  9. package/dist/chunks/redact-database-url-CfMDvSdy.js.map +1 -0
  10. package/dist/chunks/{sqlite-Crx5PQ3G.js → sqlite-B2bnGN2x.js} +106 -85
  11. package/dist/chunks/sqlite-B2bnGN2x.js.map +1 -0
  12. package/dist/chunks/sqlite-connection-cache-0iFbrrI3.js +65 -0
  13. package/dist/chunks/sqlite-connection-cache-0iFbrrI3.js.map +1 -0
  14. package/dist/chunks/{sqlite-native-DCAaADpP.js → sqlite-native-Dc8eFStu.js} +44 -31
  15. package/dist/chunks/sqlite-native-Dc8eFStu.js.map +1 -0
  16. package/dist/chunks/types-uVFHgaSU.js.map +1 -1
  17. package/dist/duckdb.d.ts.map +1 -1
  18. package/dist/index.js +119 -118
  19. package/dist/index.js.map +1 -1
  20. package/dist/json.d.ts +5 -5
  21. package/dist/json.d.ts.map +1 -1
  22. package/dist/postgres.d.ts +18 -5
  23. package/dist/postgres.d.ts.map +1 -1
  24. package/dist/shared/connection-cache.d.ts +13 -0
  25. package/dist/shared/connection-cache.d.ts.map +1 -0
  26. package/dist/shared/duckdb-resources.d.ts +8 -0
  27. package/dist/shared/duckdb-resources.d.ts.map +1 -0
  28. package/dist/shared/redact-database-url.d.ts +3 -0
  29. package/dist/shared/redact-database-url.d.ts.map +1 -0
  30. package/dist/shared/sqlite-connection-cache.d.ts +4 -0
  31. package/dist/shared/sqlite-connection-cache.d.ts.map +1 -0
  32. package/dist/shared/types.d.ts +37 -4
  33. package/dist/shared/types.d.ts.map +1 -1
  34. package/dist/sqlite-native.d.ts +8 -0
  35. package/dist/sqlite-native.d.ts.map +1 -1
  36. package/dist/sqlite.d.ts +4 -4
  37. package/dist/sqlite.d.ts.map +1 -1
  38. package/package.json +2 -2
  39. package/dist/chunks/alter-utils-DeDDAATm.js.map +0 -1
  40. package/dist/chunks/duckdb-jSSa2MbC.js.map +0 -1
  41. package/dist/chunks/duckdb-schema-utils-B-XBP8QF.js.map +0 -1
  42. package/dist/chunks/sqlite-Crx5PQ3G.js.map +0 -1
  43. package/dist/chunks/sqlite-native-DCAaADpP.js.map +0 -1
package/README.md CHANGED
@@ -50,6 +50,47 @@ const jsonDb = await getDatabase({
50
50
  });
51
51
  ```
52
52
 
53
+ ### Connection caching and cleanup
54
+
55
+ PostgreSQL, JSON, and explicitly identified SQLite connections are shared by
56
+ default. Pass `cache: false` when a caller needs a distinct adapter that is
57
+ never read from or inserted into the shared cache:
58
+
59
+ ```typescript
60
+ const isolated = await getDatabase({
61
+ type: 'postgres',
62
+ url: process.env.DATABASE_URL,
63
+ cache: false,
64
+ });
65
+
66
+ try {
67
+ await isolated.query('SELECT 1');
68
+ } finally {
69
+ await isolated.close?.();
70
+ }
71
+ ```
72
+
73
+ `clearCache: true` preserves the existing evict-then-cache behavior: it waits
74
+ for the matching cached or initializing adapter to close, then returns a fresh
75
+ cached adapter. Combine it with `cache: false` to evict first and return an
76
+ uncached replacement. A concurrent initializer caught by eviction is closed
77
+ and cannot repopulate the cache.
78
+
79
+ The JSON adapter's exported `clearConnectionCache()` helper is asynchronous:
80
+ always `await clearConnectionCache()` before opening a replacement connection.
81
+
82
+ An explicit `dbid` is an opaque, stable caller-owned cache identity and must be
83
+ non-empty. Without
84
+ one, PostgreSQL derives a credential- and pool-option-sensitive identity using
85
+ a process-keyed digest; connection URLs, usernames, passwords, and option names
86
+ are not stored in readable cache keys. SQLite caches only connections with a
87
+ `dbid` (automatically assigned to the default `:memory:` path). JSON derives an
88
+ identity from its directory and behavior options.
89
+
90
+ DuckDB already creates a fresh adapter for every call, so `cache` and
91
+ `clearCache` are accepted for uniform configuration but do not change its
92
+ behavior. Call `close()` on uncached and DuckDB adapters when finished.
93
+
53
94
  Configuration is also loaded from `HAVE_SQL_*` environment variables (e.g. `HAVE_SQL_TYPE`, `HAVE_SQL_URL`). User-provided options take precedence.
54
95
 
55
96
  ### Template Literal Queries
@@ -785,6 +785,200 @@ function validateIndexName(indexName) {
785
785
  if (typeof indexName !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)) throw new Error(`Invalid index name: ${indexName}. Index names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`);
786
786
  }
787
787
  //#endregion
788
- export { validateColumnName as a, validateTableName as c, formatDbError as d, parseConditionKey as f, unwrapRawKey as h, generateCreateIndexStatement as i, DatabaseSchemaManager as l, resolveInsertColumns as m, escapeStringLiteral as n, validateColumnNames as o, raw as p, generateAddColumnStatement as r, validateIndexName as s, escapeQuotedIdentifier as t, buildWhere as u };
788
+ //#region src/shared/connection-cache.ts
789
+ /** Race-safe async resource cache used by database adapters. */
790
+ var ConnectionCache = class {
791
+ #connections = /* @__PURE__ */ new Map();
792
+ #pending = /* @__PURE__ */ new Map();
793
+ #evictions = /* @__PURE__ */ new Map();
794
+ #requests = /* @__PURE__ */ new Map();
795
+ #clearing = /* @__PURE__ */ new Map();
796
+ #failedClosures = /* @__PURE__ */ new Map();
797
+ async getOrCreate(key, options, create, close) {
798
+ validateDatabaseCacheOptions(options);
799
+ const request = key && options.cache !== false ? this.#registerRequest(key) : void 0;
800
+ try {
801
+ this.#throwIfCancelled(request);
802
+ if (key && options.clearCache) {
803
+ await this.evict(key, close);
804
+ this.#throwIfCancelled(request);
805
+ }
806
+ if (key) this.#throwIfFailedClosure(key);
807
+ if (!key || options.cache === false) return create();
808
+ while (true) {
809
+ if (this.#evictions.has(key)) {
810
+ await this.#waitForEviction(key);
811
+ this.#throwIfCancelled(request);
812
+ }
813
+ this.#throwIfFailedClosure(key);
814
+ const cached = this.#connections.get(key);
815
+ if (cached) return cached;
816
+ let pending = this.#pending.get(key);
817
+ if (!pending) {
818
+ this.#throwIfCancelled(request);
819
+ pending = {
820
+ invalidated: false,
821
+ promise: create()
822
+ };
823
+ this.#pending.set(key, pending);
824
+ }
825
+ let connection;
826
+ try {
827
+ connection = await pending.promise;
828
+ } catch (error) {
829
+ if (this.#pending.get(key) === pending) this.#pending.delete(key);
830
+ throw error;
831
+ }
832
+ if (pending.invalidated || this.#evictions.has(key)) {
833
+ if (this.#evictions.has(key)) await this.#waitForEviction(key);
834
+ this.#throwIfCancelled(request);
835
+ if (pending.invalidated === "clear") throw this.#clearError();
836
+ continue;
837
+ }
838
+ this.#throwIfCancelled(request);
839
+ if (this.#pending.get(key) === pending) this.#pending.delete(key);
840
+ this.#connections.set(key, connection);
841
+ return connection;
842
+ }
843
+ } finally {
844
+ if (request && key) this.#finishRequest(key, request);
845
+ }
846
+ }
847
+ async evict(key, close, invalidation = "evict") {
848
+ const previous = this.#evictions.get(key);
849
+ const state = previous?.state ?? {
850
+ invalidated: /* @__PURE__ */ new Set(),
851
+ invalidation
852
+ };
853
+ if (invalidation === "clear") {
854
+ state.invalidation = "clear";
855
+ for (const pending of state.invalidated) pending.invalidated = "clear";
856
+ }
857
+ const eviction = (previous?.promise ?? Promise.resolve()).then(async () => {
858
+ const resources = new Set(this.#failedClosures.get(key)?.resources ?? []);
859
+ this.#failedClosures.delete(key);
860
+ const cached = this.#connections.get(key);
861
+ this.#connections.delete(key);
862
+ if (cached) resources.add(cached);
863
+ const pending = this.#pending.get(key);
864
+ this.#pending.delete(key);
865
+ if (pending) {
866
+ state.invalidated.add(pending);
867
+ pending.invalidated = state.invalidation;
868
+ const initialized = await pending.promise.catch(() => void 0);
869
+ if (initialized !== void 0) resources.add(initialized);
870
+ }
871
+ const closeResults = await Promise.allSettled([...resources].map(async (resource) => {
872
+ await close(resource);
873
+ return resource;
874
+ }));
875
+ const failures = closeResults.filter((result) => result.status === "rejected");
876
+ if (failures.length) {
877
+ const resourceList = [...resources];
878
+ const failedResources = /* @__PURE__ */ new Set();
879
+ closeResults.forEach((result, index) => {
880
+ if (result.status === "rejected") failedResources.add(resourceList[index]);
881
+ });
882
+ const error = failures.length === 1 ? failures[0].reason : new AggregateError(failures.map((failure) => failure.reason), "Multiple database connections failed to close");
883
+ this.#failedClosures.set(key, {
884
+ error,
885
+ resources: failedResources
886
+ });
887
+ throw error;
888
+ }
889
+ });
890
+ const chain = {
891
+ promise: eviction,
892
+ state
893
+ };
894
+ this.#evictions.set(key, chain);
895
+ try {
896
+ await eviction;
897
+ } finally {
898
+ if (this.#evictions.get(key) === chain) this.#evictions.delete(key);
899
+ }
900
+ }
901
+ async clear(close) {
902
+ const keys = /* @__PURE__ */ new Set([
903
+ ...this.#connections.keys(),
904
+ ...this.#pending.keys(),
905
+ ...this.#evictions.keys(),
906
+ ...this.#requests.keys(),
907
+ ...this.#clearing.keys(),
908
+ ...this.#failedClosures.keys()
909
+ ]);
910
+ const failures = (await Promise.allSettled([...keys].map((key) => this.#clearKey(key, close)))).filter((result) => result.status === "rejected");
911
+ if (failures.length === 1) throw failures[0].reason;
912
+ if (failures.length > 1) throw new AggregateError(failures.map((failure) => failure.reason), "Multiple database connection cache entries failed to clear");
913
+ }
914
+ forget(connection) {
915
+ for (const [key, cached] of this.#connections) if (cached === connection) this.#connections.delete(key);
916
+ }
917
+ /** @internal Test-only visibility; includes every retained namespace. */
918
+ get size() {
919
+ return this.#connections.size + this.#pending.size + this.#evictions.size + this.#requests.size + this.#clearing.size + this.#failedClosures.size;
920
+ }
921
+ async #clearKey(key, close) {
922
+ this.#clearing.set(key, (this.#clearing.get(key) ?? 0) + 1);
923
+ try {
924
+ this.#cancelRequests(key);
925
+ await this.evict(key, close, "clear");
926
+ while (this.#requests.get(key)?.size) {
927
+ this.#cancelRequests(key);
928
+ await Promise.all([...this.#requests.get(key) ?? []].map((request) => request.done));
929
+ }
930
+ } finally {
931
+ const remaining = (this.#clearing.get(key) ?? 1) - 1;
932
+ if (remaining === 0) this.#clearing.delete(key);
933
+ else this.#clearing.set(key, remaining);
934
+ }
935
+ }
936
+ #cancelRequests(key) {
937
+ for (const request of this.#requests.get(key) ?? []) request.cancelled = true;
938
+ }
939
+ #clearError() {
940
+ return /* @__PURE__ */ new Error("Database connection initialization was cancelled by cache clear");
941
+ }
942
+ #finishRequest(key, request) {
943
+ const requests = this.#requests.get(key);
944
+ requests?.delete(request);
945
+ if (requests?.size === 0) this.#requests.delete(key);
946
+ request.finish();
947
+ }
948
+ #registerRequest(key) {
949
+ let finish = () => {};
950
+ const done = new Promise((resolve) => {
951
+ finish = resolve;
952
+ });
953
+ const request = {
954
+ cancelled: this.#clearing.has(key),
955
+ done,
956
+ finish
957
+ };
958
+ const requests = this.#requests.get(key) ?? /* @__PURE__ */ new Set();
959
+ requests.add(request);
960
+ this.#requests.set(key, requests);
961
+ return request;
962
+ }
963
+ #throwIfCancelled(request) {
964
+ if (request?.cancelled) throw this.#clearError();
965
+ }
966
+ #throwIfFailedClosure(key) {
967
+ const failure = this.#failedClosures.get(key);
968
+ if (failure) throw failure.error;
969
+ }
970
+ async #waitForEviction(key) {
971
+ while (true) {
972
+ const eviction = this.#evictions.get(key);
973
+ if (!eviction) return;
974
+ await eviction.promise;
975
+ }
976
+ }
977
+ };
978
+ function validateDatabaseCacheOptions(options) {
979
+ if (options.dbid === "") throw new Error("Database cache dbid must be a non-empty string");
980
+ }
981
+ //#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 };
789
983
 
790
- //# sourceMappingURL=alter-utils-DeDDAATm.js.map
984
+ //# sourceMappingURL=connection-cache-6EMfKWpo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-cache-6EMfKWpo.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 all relevant 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 all available error properties to provide\n * better debugging information.\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 const dbError = error as {\n message?: string;\n code?: string;\n detail?: string;\n hint?: string;\n severity?: string;\n errno?: number;\n cause?: unknown;\n };\n\n const parts: string[] = [];\n\n if (dbError.message) parts.push(dbError.message);\n if (dbError.code) parts.push(`code=${dbError.code}`);\n if (dbError.detail) parts.push(`detail=${dbError.detail}`);\n if (dbError.hint) parts.push(`hint=${dbError.hint}`);\n if (dbError.severity) parts.push(`severity=${dbError.severity}`);\n if (dbError.errno !== undefined) parts.push(`errno=${dbError.errno}`);\n\n return parts.length > 0 ? parts.join(', ') : String(error);\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":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cAAc,OAAwB;CACpD,MAAM,UAAU;CAUhB,MAAM,QAAkB,CAAC;CAEzB,IAAI,QAAQ,SAAS,MAAM,KAAK,QAAQ,OAAO;CAC/C,IAAI,QAAQ,MAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;CACnD,IAAI,QAAQ,QAAQ,MAAM,KAAK,UAAU,QAAQ,QAAQ;CACzD,IAAI,QAAQ,MAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;CACnD,IAAI,QAAQ,UAAU,MAAM,KAAK,YAAY,QAAQ,UAAU;CAC/D,IAAI,QAAQ,UAAU,KAAA,GAAW,MAAM,KAAK,SAAS,QAAQ,OAAO;CAEpE,OAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,KAAK;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,qBACd,OACA,SACU;CACV,MAAM,eAAe,WACnB,IAAI,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,QAAQ,OAAO,SAAS,KAAA,CAAS,CAAC;CAExE,MAAM,OAAO,OAAO,KAAK,QAAQ,EAAE;CACnC,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c,GAAG,KAAKA,UAAU,OAAO,GAAG;QACzC,KAAKA,UAAU,IAAI,KAAK,SAAS;EACxC;CACF;CAEA,gBAAgB,KAAmB;EACjC,KAAK,MAAM,WAAW,KAAKD,UAAU,IAAI,GAAG,KAAK,CAAC,GAChD,QAAQ,YAAY;CAExB;CAEA,cAAqB;EACnB,uBAAO,IAAI,MACT,iEACF;CACF;CAEA,eAAe,KAAa,SAA6B;EACvD,MAAM,WAAW,KAAKA,UAAU,IAAI,GAAG;EACvC,UAAU,OAAO,OAAO;EACxB,IAAI,UAAU,SAAS,GAAG,KAAKA,UAAU,OAAO,GAAG;EACnD,QAAQ,OAAO;CACjB;CAEA,iBAAiB,KAA2B;EAC1C,IAAI,eAAe,CAAC;EACpB,MAAM,OAAO,IAAI,SAAe,YAAY;GAC1C,SAAS;EACX,CAAC;EACD,MAAM,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,5 +1,6 @@
1
- import { a as validateColumnName, c as validateTableName, d as formatDbError, i as generateCreateIndexStatement, l as DatabaseSchemaManager, m as resolveInsertColumns, n as escapeStringLiteral, o as validateColumnNames, r as generateAddColumnStatement, s as validateIndexName, t as escapeQuotedIdentifier, u as buildWhere } from "./alter-utils-DeDDAATm.js";
2
- import { t as convertUniqueIndexesToInlineConstraints } from "./duckdb-schema-utils-B-XBP8QF.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 } from "./connection-cache-6EMfKWpo.js";
2
+ import { n as throwWithDuckDBCleanup, r as convertUniqueIndexesToInlineConstraints, t as createDuckDBResourceCloser } from "./duckdb-resources-Cci6Lo6H.js";
3
+ import { t as redactDatabaseUrl } from "./redact-database-url-CfMDvSdy.js";
3
4
  import { n as resolveSchemas, r as createTransactionLock, t as NestedTransactionError } from "./types-uVFHgaSU.js";
4
5
  import { DatabaseError } from "@happyvertical/utils";
5
6
  import { readdir } from "node:fs/promises";
@@ -75,21 +76,27 @@ async function createDuckDBConnection(options) {
75
76
  const { url = ":memory:", dataDir = "./data", autoRegisterJSON = true } = options;
76
77
  const schemas = resolveSchemas(options.schemas) ?? {};
77
78
  const resolvedUrl = resolveDuckDBUrl(url);
79
+ let instance;
80
+ let connection;
78
81
  try {
79
82
  const { DuckDBInstance } = await import(
80
83
  /* @vite-ignore */
81
84
  "@duckdb/node-api"
82
85
  );
83
- const connection = await (await DuckDBInstance.create(resolvedUrl)).connect();
86
+ instance = await DuckDBInstance.create(resolvedUrl);
87
+ connection = await instance.connect();
84
88
  if (schemas && Object.keys(schemas).length > 0) await createTablesFromSchemas(connection, schemas);
85
89
  if (autoRegisterJSON && dataDir) await registerJSONFiles(connection, dataDir);
86
- return connection;
90
+ return {
91
+ connection,
92
+ instance
93
+ };
87
94
  } catch (error) {
88
- const errorMessage = error instanceof Error ? error.message : String(error);
89
- throw new DatabaseError(`Failed to create DuckDB connection: ${errorMessage}`, {
90
- url,
95
+ const errorMessage = redactDatabaseUrl(error instanceof Error ? error.message : String(error));
96
+ return throwWithDuckDBCleanup(new DatabaseError(`Failed to create DuckDB connection: ${errorMessage}`, {
97
+ url: redactDatabaseUrl(url),
91
98
  originalError: errorMessage
92
- });
99
+ }), createDuckDBResourceCloser(connection, instance));
93
100
  }
94
101
  }
95
102
  /**
@@ -150,11 +157,13 @@ function convertBigInts(obj) {
150
157
  * @returns Database interface for DuckDB
151
158
  */
152
159
  async function getDatabase(options = {}) {
153
- const connection = await createDuckDBConnection(options);
160
+ validateDatabaseCacheOptions(options);
161
+ const { connection, instance } = await createDuckDBConnection(options);
154
162
  const writeStrategy = options.writeStrategy || "none";
155
163
  const dataDir = options.dataDir || "./data";
156
164
  const url = resolveDuckDBUrl(options.url || ":memory:");
157
165
  const connectionLock = createTransactionLock("duckdb", options.transactionQueueTimeout);
166
+ const closeResources = createDuckDBResourceCloser(connection, instance);
158
167
  /**
159
168
  * Inserts one or more records into a table
160
169
  *
@@ -1068,10 +1077,13 @@ async function getDatabase(options = {}) {
1068
1077
  beginTransaction,
1069
1078
  getTableSchema,
1070
1079
  alterTable,
1080
+ close: async () => {
1081
+ await closeResources();
1082
+ },
1071
1083
  exportTable
1072
1084
  };
1073
1085
  }
1074
1086
  //#endregion
1075
1087
  export { getDatabase };
1076
1088
 
1077
- //# sourceMappingURL=duckdb-jSSa2MbC.js.map
1089
+ //# sourceMappingURL=duckdb-D2Nah7NF.js.map