@happyvertical/sql 0.112.1 → 0.112.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.
Files changed (51) hide show
  1. package/AGENT.md +65 -3
  2. package/README.md +146 -19
  3. package/dist/aggregate-expression.d.ts +77 -3
  4. package/dist/aggregate-expression.d.ts.map +1 -1
  5. package/dist/aggregate.d.ts +3 -2
  6. package/dist/aggregate.d.ts.map +1 -1
  7. package/dist/chunks/{duckdb-CpeXdf0i.js → duckdb-DCV4JFWK.js} +23 -52
  8. package/dist/chunks/duckdb-DCV4JFWK.js.map +1 -0
  9. package/dist/chunks/{postgres-dialect-DIy5f5YR.js → postgres-dialect-CaNhva-C.js} +28 -328
  10. package/dist/chunks/postgres-dialect-CaNhva-C.js.map +1 -0
  11. package/dist/chunks/query-Dz0TZ0pY.js +970 -0
  12. package/dist/chunks/query-Dz0TZ0pY.js.map +1 -0
  13. package/dist/chunks/{schema-manager-tfASrb_b.js → schema-manager-psLzQ2yh.js} +471 -18
  14. package/dist/chunks/schema-manager-psLzQ2yh.js.map +1 -0
  15. package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js → sqlite-connection-cache-BycfrYfi.js} +2 -2
  16. package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js.map → sqlite-connection-cache-BycfrYfi.js.map} +1 -1
  17. package/dist/chunks/{sqlite-BdM-nAQD.js → sqlite-nNhv0FMq.js} +22 -22
  18. package/dist/chunks/sqlite-nNhv0FMq.js.map +1 -0
  19. package/dist/chunks/{sqlite-native-DngobJtv.js → sqlite-native-CZGNm9zh.js} +40 -37
  20. package/dist/chunks/sqlite-native-CZGNm9zh.js.map +1 -0
  21. package/dist/doctor.d.ts.map +1 -1
  22. package/dist/duckdb.d.ts.map +1 -1
  23. package/dist/index.d.ts +3 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +44 -77
  26. package/dist/index.js.map +1 -1
  27. package/dist/json.d.ts.map +1 -1
  28. package/dist/pglite.js +2 -2
  29. package/dist/query.d.ts +3 -0
  30. package/dist/query.d.ts.map +1 -1
  31. package/dist/query.js +3 -3
  32. package/dist/schema-manager.d.ts.map +1 -1
  33. package/dist/shared/alter-utils.d.ts +43 -7
  34. package/dist/shared/alter-utils.d.ts.map +1 -1
  35. package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
  36. package/dist/shared/postgres-dialect.d.ts.map +1 -1
  37. package/dist/shared/types.d.ts +1 -0
  38. package/dist/shared/types.d.ts.map +1 -1
  39. package/dist/shared/utils.d.ts +12 -1
  40. package/dist/shared/utils.d.ts.map +1 -1
  41. package/dist/sqlite-native.d.ts.map +1 -1
  42. package/dist/sqlite.d.ts.map +1 -1
  43. package/metadata.json +4 -4
  44. package/package.json +4 -4
  45. package/dist/chunks/duckdb-CpeXdf0i.js.map +0 -1
  46. package/dist/chunks/postgres-dialect-DIy5f5YR.js.map +0 -1
  47. package/dist/chunks/query-i6IIkNhF.js +0 -564
  48. package/dist/chunks/query-i6IIkNhF.js.map +0 -1
  49. package/dist/chunks/schema-manager-tfASrb_b.js.map +0 -1
  50. package/dist/chunks/sqlite-BdM-nAQD.js.map +0 -1
  51. package/dist/chunks/sqlite-native-DngobJtv.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-manager-psLzQ2yh.js","names":[],"sources":["../../src/shared/alter-utils.ts","../../src/shared/utils.ts","../../src/schema-manager.ts"],"sourcesContent":["/**\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[] = [\n renderSchemaIdentifier(column.name, dialect, { quoteIdentifiers: true }),\n column.type,\n ];\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 = [\n `REFERENCES ${renderSchemaIdentifier(fk.table, dialect, { quoteIdentifiers: true })}(${renderIdentifierList(fk.column, dialect, { quoteIdentifiers: true })})`,\n ];\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 ${renderSchemaIdentifier(table, dialect, { quoteIdentifiers: true })} 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 dialect?: DatabaseDialect,\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(\n renderSchemaIdentifier(index.name, dialect, { quoteIdentifiers: true }),\n );\n\n // ON table\n parts.push(\n `ON ${renderSchemaIdentifier(table, dialect, { quoteIdentifiers: true })}`,\n );\n\n // Column list\n const columns = index.columns\n .map((column) =>\n renderIndexTerm(column, dialect, { quoteIdentifiers: true }),\n )\n .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 (typeof columnName !== 'string' || !isColumnIdentifier(columnName)) {\n throw new Error(\n `Invalid column name: ${columnName}. Column names must be a plain identifier starting with a letter or underscore, or an explicitly double-quoted identifier.`,\n );\n }\n}\n\n/** Branch-base plain-name contract for adapter addIndex (not raw SQL terms). */\nexport function validatePlainColumnName(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. The\n * accepted shape has no character that can end an identifier. Adapters may\n * render a validated name bare, or quote it under an adapter-specific contract.\n * PostgreSQL upsert uses {@link quotePostgresColumnName}, which canonicalizes\n * the name before quoting so its established unquoted case-folding semantics\n * do not change.\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 * Quotes a validated column name using PostgreSQL's historic case semantics.\n *\n * PostgreSQL folds every unquoted identifier to lowercase. The CRUD API has\n * always accepted mixed-case inputs while rendering them unquoted, so quoting\n * the caller's spelling directly would silently change which physical column\n * is addressed. Validate the existing plain-identifier contract first, then\n * lowercase before quoting: `mixedCase` still addresses `mixedcase`, while a\n * reserved word such as `end` is no longer parsed as SQL syntax.\n *\n * Explicit double-delimited input preserves its physical spelling.\n *\n * @param columnName - Plain or explicitly delimited column name for PostgreSQL\n * @returns A double-quoted identifier, folding only undelimited input\n * @throws Error if the column name is outside the CRUD identifier contract\n */\nexport function quotePostgresColumnName(columnName: string): string {\n validateColumnName(columnName);\n return renderIdentifier(columnName, 'postgres', { quoteIdentifiers: true });\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 SQL identifier quotes\n * @param quote - Identifier delimiter (double quote, or SQLite backtick)\n * @returns The identifier with embedded delimiter characters doubled\n * @throws Error if the identifier is empty or contains a NUL byte\n */\nexport function escapeQuotedIdentifier(\n identifier: string,\n quote: '\"' | '`' = '\"',\n): 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(quote, quote + quote);\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\n/** Numeric SQL tokens accepted by the original WHERE/aggregate character grammar.\n * This is a bounded compatibility exception, never a general expression channel.\n */\nexport function isLegacyNumericSqlToken(value: string): boolean {\n return (\n typeof value === 'string' &&\n /^(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[0-9][0-9_]*(?:\\.[0-9_]*)?|\\.[0-9][0-9_]*)(?:[eE][0-9][0-9_]*)?)$/.test(\n value,\n )\n );\n}\n\n/** Additive policy for standalone builders; adapters always request quote-all. */\nexport interface IdentifierOptions {\n quoteIdentifiers?: boolean;\n}\n\n/** Parse identifiers, never SQL. Dots outside double quotes delimit qualifiers. */\nexport function identifierParts(\n identifier: string,\n): Array<{ name: string; exact: boolean }> {\n if (\n typeof identifier !== 'string' ||\n !identifier ||\n identifier.includes('\\0')\n ) {\n throw new Error(`Invalid SQL identifier: ${identifier}`);\n }\n const parts: Array<{ name: string; exact: boolean }> = [];\n let position = 0;\n while (position < identifier.length) {\n const rest = identifier.slice(position);\n const match = rest.startsWith('\"')\n ? /^\"((?:[^\"]|\"\")+)\"(?=\\.|$)/.exec(rest)\n : /^([A-Za-z0-9_]+)(?=\\.|$)/.exec(rest);\n if (!match) throw new Error(`Invalid SQL identifier: ${identifier}`);\n const exact = rest.startsWith('\"');\n parts.push({\n name: exact ? match[1].replaceAll('\"\"', '\"') : match[1],\n exact,\n });\n position += match[0].length;\n if (position < identifier.length) {\n position += 1;\n if (position === identifier.length)\n throw new Error(`Invalid SQL identifier: ${identifier}`);\n }\n }\n return parts;\n}\n\nfunction isColumnIdentifier(identifier: string): boolean {\n try {\n const parts = identifierParts(identifier);\n return (\n parts.length === 1 &&\n (parts[0].exact || /^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier))\n );\n } catch {\n return false;\n }\n}\n\n/** Quote a physical name without interpreting delimiters or dots. */\nexport function quoteLiteralIdentifier(identifier: string): string {\n return quotePhysicalIdentifier(identifier, '\"');\n}\n\n/** SQLite identifiers must not fall back to double-quoted string literals. */\nexport function quoteSqliteLiteralIdentifier(identifier: string): string {\n return quotePhysicalIdentifier(identifier, '`');\n}\n\nfunction quotePhysicalIdentifier(identifier: string, quote: '\"' | '`'): string {\n if (typeof identifier !== 'string')\n throw new Error(`Invalid SQL identifier: ${identifier}`);\n return `${quote}${escapeQuotedIdentifier(identifier, quote)}${quote}`;\n}\n\n/** SQLite CRUD column (one validated identifier). */\nexport function quoteSqliteColumnName(column: string): string {\n validateColumnName(column);\n return renderIdentifier(column, 'sqlite', { quoteIdentifiers: true });\n}\n\n/** DuckDB/JSON CRUD column, or an already-resolved literal physical name. */\nexport function quoteDuckDBColumnName(column: string, literal = false): string {\n if (literal) return quoteLiteralIdentifier(column);\n validateColumnName(column);\n return renderIdentifier(column, 'duckdb', { quoteIdentifiers: true });\n}\n\n/** Shared rendering for qualified WHERE/aggregate identifiers. */\nexport function renderIdentifier(\n identifier: string,\n dialect?: 'sqlite' | 'postgres' | 'duckdb' | 'json',\n options: IdentifierOptions = {},\n): string {\n return identifierParts(identifier)\n .map(({ name, exact }) => {\n if (\n !options.quoteIdentifiers &&\n !exact &&\n !IDENTIFIER_KEYWORDS.has(name.toLowerCase())\n )\n return name;\n const physical =\n dialect === 'postgres' && !exact ? name.toLowerCase() : name;\n return dialect === 'sqlite'\n ? quoteSqliteLiteralIdentifier(physical)\n : quoteLiteralIdentifier(physical);\n })\n .join('.');\n}\n\n/** Previously raw index terms may be expressions or ordered SQL, not just names. */\nexport function renderIndexTerm(\n term: string,\n dialect?: DatabaseDialect,\n options: IdentifierOptions = {},\n): string {\n // Classify syntax before rendering: do not hide errors thrown by the renderer.\n const component = '(?:[A-Za-z_][A-Za-z0-9_]*|\"(?:[^\"]|\"\")+\")';\n const plain = new RegExp(`^${component}(?:\\\\.${component})*$`);\n return typeof term === 'string' && plain.test(term)\n ? renderIdentifier(term, dialect, options)\n : term;\n}\n\n/** DDL names historically accepted SQLite's alternate identifier delimiters.\n * Normalize names only here; strict CRUD/WHERE keep their existing input syntax.\n */\nexport function renderSchemaIdentifier(\n identifier: string,\n dialect?: DatabaseDialect,\n options: IdentifierOptions = {},\n): string {\n if (typeof identifier !== 'string')\n throw new Error(`Invalid SQL identifier: ${identifier}`);\n const parts: string[] = [];\n let position = 0;\n while (position < identifier.length) {\n const match =\n /^(?:([A-Za-z0-9_]+)|\"((?:[^\"]|\"\")+)\"|`((?:[^`]|``)+)`|\\[([^\\]]+)\\]|'((?:[^']|'')+)')(?=\\.|$)/.exec(\n identifier.slice(position),\n );\n if (!match) throw new Error(`Invalid SQL identifier: ${identifier}`);\n if (match[1] !== undefined) parts.push(match[1]);\n else {\n const name =\n match[2] !== undefined\n ? match[2].replaceAll('\"\"', '\"')\n : match[3] !== undefined\n ? match[3].replaceAll('``', '`')\n : match[4] !== undefined\n ? match[4]\n : match[5].replaceAll(\"''\", \"'\");\n parts.push(quoteLiteralIdentifier(name));\n }\n position += match[0].length;\n if (position < identifier.length) {\n position += 1;\n if (position === identifier.length)\n throw new Error(`Invalid SQL identifier: ${identifier}`);\n }\n }\n return renderIdentifier(parts.join('.'), dialect, options);\n}\n\n/** FK lists contain identifiers, with commas outside explicit quotes only. */\nexport function renderIdentifierList(\n list: string,\n dialect?: DatabaseDialect,\n options: IdentifierOptions = {},\n): string {\n if (typeof list !== 'string')\n throw new Error(`Invalid SQL identifier list: ${list}`);\n const parts: string[] = [];\n let closingQuote: string | undefined;\n let start = 0;\n for (let index = 0; index < list.length; index += 1) {\n const char = list[index];\n if (closingQuote) {\n if (char === closingQuote) {\n if (closingQuote !== ']' && list[index + 1] === closingQuote)\n index += 1;\n else closingQuote = undefined;\n }\n } else if (char === '\"' || char === \"'\" || char === '`' || char === '[') {\n closingQuote = char === '[' ? ']' : char;\n } else if (char === ',') {\n parts.push(list.slice(start, index));\n start = index + 1;\n }\n }\n parts.push(list.slice(start));\n return parts\n .map((part) => {\n const name = part.trim();\n const offset = part.indexOf(name);\n return (\n part.slice(0, offset) +\n renderSchemaIdentifier(name, dialect, options) +\n part.slice(offset + name.length)\n );\n })\n .join(',');\n}\n\n// SQLite official 147-keyword list (sqlite.org/lang_keywords.html), plus reserved\n// pg_get_keywords() (PGlite 0.5.8) and duckdb_keywords() (DuckDB 1.4.3).\nconst IDENTIFIER_KEYWORDS = new Set(\n 'abort action add after all alter always analyse analyze and any array as asc asymmetric attach autoincrement before begin between both by cascade case cast check collate column commit conflict constraint create cross current current_catalog current_date current_role current_time current_timestamp current_user database default deferrable deferred delete desc describe detach distinct do drop each else end escape except exclude exclusive exists explain fail false fetch filter first following for foreign from full generated glob grant group groups having if ignore immediate in index indexed initially inner insert instead intersect into is isnull join key lambda last lateral leading left like limit localtime localtimestamp match materialized natural no not nothing notnull null nulls of offset on only or order others outer over partition pivot pivot_longer pivot_wider placing plan pragma preceding primary qualify query raise range recursive references regexp reindex release rename replace restrict returning right rollback row rows savepoint select session_user set show some summarize symmetric system_user table temp temporary then ties to trailing transaction trigger true unbounded union unique unpivot update user using vacuum values variadic view virtual when where window with without'.split(\n ' ',\n ),\n);\n","/**\n * Shared SQL utilities that work in both browser and Node.js environments\n */\n\nimport { DatabaseError } from '@happyvertical/utils';\nimport {\n type IdentifierOptions,\n isLegacyNumericSqlToken,\n renderIdentifier,\n} from './alter-utils.js';\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 connectionInvalidated?: boolean;\n};\n\nconst DRIVER_ERROR_FIELDS = [\n 'code',\n 'detail',\n 'hint',\n 'severity',\n 'errno',\n 'connectionInvalidated',\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 contains: 'CONTAINS',\n in: 'IN',\n 'not in': 'NOT IN',\n} as const;\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`, `contains`, `in`, `not in`. Any other trailing token is\n * treated as part of the expression and `=` is appended, so\n * `raw('name ILIKE')` silently emits `name ILIKE = $1`, which the database then\n * rejects. Fold an unsupported operator into the expression instead:\n * `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 = [\n 'not in',\n 'contains',\n 'like',\n 'in',\n '!=',\n '>=',\n '<=',\n '>',\n '<',\n '=',\n ];\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 options: IdentifierOptions = {},\n): { sql: string; values: any[] } => {\n const { key, isRaw } = unwrapRawKey(fullKey);\n const parsed = parseConditionKey(key);\n const operator = parsed.operator;\n let field = parsed.field;\n if (!isRaw && !isLegacyNumericSqlToken(field)) {\n try {\n field = renderIdentifier(field, adapterType, options);\n } catch (error) {\n if (\n !(error instanceof Error) ||\n !error.message.startsWith('Invalid SQL identifier:')\n )\n throw error;\n throw new Error(\n `${error.message}. Condition keys must be plain identifiers; wrap developer-authored SQL expressions in raw().`,\n );\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 (sqlOperator === 'CONTAINS') {\n if (!adapterType) {\n throw new Error(\n 'CONTAINS requires an adapter type so buildWhere can preserve case-sensitive semantics',\n );\n }\n if (typeof value !== 'string') {\n throw new Error('CONTAINS requires a string value');\n }\n\n const placeholder = `$${currIndex.value++}`;\n const containsFunction = adapterType === 'sqlite' ? 'instr' : 'strpos';\n sql = `${containsFunction}(${field}, ${placeholder}) > 0`;\n values.push(value);\n } else 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 sqlOperator === 'LIKE' ? \" ESCAPE '\\\\'\" : ''\n }`;\n } else {\n sql = `${field} ${sqlOperator} $${currIndex.value++}${\n sqlOperator === 'LIKE' ? \" ESCAPE '\\\\'\" : ''\n }`;\n }\n values.push(value.toISOString());\n } else {\n sql = `${field} ${sqlOperator} $${currIndex.value++}${\n sqlOperator === 'LIKE' ? \" ESCAPE '\\\\'\" : ''\n }`;\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 and `contains`\n * 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 * - Required for `contains`, whose case-sensitive literal substring SQL is\n * emitted with adapter-specific functions.\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 pattern; backslash escapes `%` / `_`\n * 'notes contains': '100% off' // literal, case-sensitive substring\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 with an explicit backslash escape character\n * - Case-sensitive literal substring matching with `contains`\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 options: IdentifierOptions = {},\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(\n fullKey,\n value,\n currIndex,\n adapterType,\n options,\n );\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(\n fullKey,\n value,\n currIndex,\n adapterType,\n options,\n );\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/** Adapter-owned WHERE policy: quote every identifier component. */\nexport const buildAdapterWhere: typeof buildWhere = (\n where,\n startIndex,\n adapterType,\n) => buildWhere(where, startIndex, adapterType, { quoteIdentifiers: true });\n\n/**\n * Rewrites executable positional parameters while preserving SQL text inside\n * literals, identifiers and comments. Extracted from the PostgreSQL adapter's\n * existing question-mark lexer so native SQLite and PostgreSQL use one policy.\n * SQLite's bracket/backtick identifiers are enabled only for that dialect:\n * PostgreSQL brackets can instead contain executable array subscript binds.\n */\nexport function rewriteSqlParameters(\n sql: string,\n dialect: 'postgres' | 'sqlite',\n replace: (token: string, index?: number) => string,\n): string {\n let output = '';\n let position = 0;\n const copyQuoted = (quote: string, escaped = false) => {\n output += sql[position++];\n while (position < sql.length) {\n const char = sql[position++];\n output += char;\n if (escaped && char === '\\\\' && position < sql.length) {\n output += sql[position++];\n } else if (char === quote) {\n if (quote !== ']' && sql[position] === quote) {\n output += sql[position++];\n } else break;\n }\n }\n };\n const copyUntil = (end: string) => {\n const endIndex = sql.indexOf(end, position + end.length);\n const after = endIndex < 0 ? sql.length : endIndex + end.length;\n output += sql.slice(position, after);\n position = after;\n };\n while (position < sql.length) {\n const char = sql[position];\n const next = sql[position + 1];\n if (\n dialect === 'postgres' &&\n (char === 'E' || char === 'e') &&\n next === \"'\"\n ) {\n output += char;\n position += 1;\n copyQuoted(\"'\", true);\n continue;\n }\n if (\n char === \"'\" ||\n char === '\"' ||\n (dialect === 'sqlite' && char === '`')\n ) {\n copyQuoted(char);\n continue;\n }\n if (dialect === 'sqlite' && char === '[') {\n copyQuoted(']');\n continue;\n }\n if (char === '-' && next === '-') {\n const endIndex = sql.slice(position).search(/[\\r\\n]/);\n const after = endIndex < 0 ? sql.length : position + endIndex + 1;\n output += sql.slice(position, after);\n position = after;\n continue;\n }\n if (char === '/' && next === '*') {\n if (dialect === 'sqlite') copyUntil('*/');\n else {\n const start = position;\n position += 2;\n let depth = 1;\n while (position < sql.length && depth > 0) {\n const pair = sql.slice(position, position + 2);\n if (pair === '/*') {\n depth += 1;\n position += 2;\n } else if (pair === '*/') {\n depth -= 1;\n position += 2;\n } else position += 1;\n }\n output += sql.slice(start, position);\n }\n continue;\n }\n // Both dialects allow $ within an undelimited identifier. Its suffix must\n // not be reinterpreted as a bind (for example, legacy raw foo$1).\n if (char === '$' && !/[\\w$\\u0080-\\uFFFF]/.test(sql[position - 1] ?? '')) {\n if (dialect === 'postgres') {\n const tag = sql.slice(position).match(/^\\$[A-Za-z_]\\w*\\$|^\\$\\$/);\n if (tag) {\n copyUntil(tag[0]);\n continue;\n }\n }\n const numbered = /^\\$(\\d+)/.exec(sql.slice(position));\n if (numbered) {\n output += replace(numbered[0], Number(numbered[1]));\n position += numbered[0].length;\n continue;\n }\n }\n if (char === '?' && next !== '|' && next !== '&') {\n output += replace('?');\n position += 1;\n continue;\n }\n output += char;\n position += 1;\n }\n return output;\n}\n","import {\n renderIdentifierList,\n renderIndexTerm,\n renderSchemaIdentifier,\n} from './shared/alter-utils.js';\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(\n `DROP TABLE IF EXISTS ${renderSchemaIdentifier(tableName)}`,\n );\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 = `${renderSchemaIdentifier(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 (${renderIdentifierList(fk.column)}) REFERENCES ${renderSchemaIdentifier(fk.referencesTable)}(${renderIdentifierList(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 ${renderSchemaIdentifier(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 ${renderSchemaIdentifier(index.name)} ON ${renderSchemaIdentifier(tableName)} (${index.columns.map((column) => renderIndexTerm(column)).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 ${renderSchemaIdentifier(trigger.name)} ${trigger.when} ${trigger.event} ON ${renderSchemaIdentifier(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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,2BACd,OACA,QACA,SACQ;CACR,MAAM,QAAkB,CACtB,uBAAuB,OAAO,MAAM,SAAS,EAAE,kBAAkB,KAAK,CAAC,GACvE,OAAO,IACT;CAGA,IAAI,OAAO,YACT,MAAM,KAAK,aAAa;CAI1B,IAAI,OAAO,SACT,MAAM,KAAK,UAAU;CAIvB,IAAI,OAAO,QACT,MAAM,KAAK,QAAQ;CAIrB,IAAI,OAAO,iBAAiB,KAAA,GAAW;EACrC,MAAM,gBAAgB,sBACpB,OAAO,MACP,OAAO,YACT;EACA,MAAM,KAAK,WAAW,eAAe;CACvC;CAGA,IAAI,OAAO,OACT,MAAM,KAAK,UAAU,OAAO,MAAM,EAAE;CAItC,IAAI,OAAO,YAAY;EACrB,MAAM,KAAK,OAAO;EAClB,MAAM,UAAU,CACd,cAAc,uBAAuB,GAAG,OAAO,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GAAG,OAAO,EAAE,cAAc,GAC9B,CAAC,GAAG,MAAM,GACd,CACF;EACF;EAEA,OAAO;CACT;;;;CAKA,oBAA4B,OAAwC;EAClE,MAAM,WAAqB,CAAC;EAC5B,MAAM,0BAAU,IAAI,IAAY;EAChC,MAAM,2BAAW,IAAI,IAAY;EAEjC,MAAM,SAAS,SAAiB;GAC9B,IAAI,SAAS,IAAI,IAAI,GACnB,MAAM,IAAI,MAAM,0CAA0C,MAAM;GAElE,IAAI,QAAQ,IAAI,IAAI,GAAG;GAEvB,SAAS,IAAI,IAAI;GACjB,MAAM,eAAe,MAAM,IAAI,IAAI,KAAK,CAAC;GAEzC,KAAK,MAAM,OAAO,cAChB,IAAI,MAAM,IAAI,GAAG,GACf,MAAM,GAAG;GAIb,SAAS,OAAO,IAAI;GACpB,QAAQ,IAAI,IAAI;GAChB,SAAS,KAAK,IAAI;EACpB;EAEA,KAAK,MAAM,QAAQ,MAAM,KAAK,GAC5B,IAAI,CAAC,QAAQ,IAAI,IAAI,GACnB,MAAM,IAAI;EAId,OAAO;CACT;;;;CAKA,iBAAyB,YAAoB,SAA0B;EACrE,OACE,KAAK,mBAAmB,IAAI,UAAU,KACtC,KAAK,eAAe,IAAI,UAAU,MAAM;CAE5C;;;;CAKA,sBAA8B,YAAoB,SAAuB;EACvE,KAAK,mBAAmB,IAAI,UAAU;EACtC,KAAK,eAAe,IAAI,YAAY,OAAO;CAC7C;;;;CAKA,QAAc;EACZ,KAAK,mBAAmB,MAAM;EAC9B,KAAK,eAAe,MAAM;EAC1B,sBAAsB,mBAAmB,MAAM;CACjD;AACF"}
@@ -1,4 +1,4 @@
1
- import { l as ConnectionCache } from "./postgres-dialect-DIy5f5YR.js";
1
+ import { l as ConnectionCache } from "./postgres-dialect-CaNhva-C.js";
2
2
  //#region src/shared/sqlite-connection-cache.ts
3
3
  var sqliteConnectionCache = new ConnectionCache();
4
4
  var sqliteCacheGroups = /* @__PURE__ */ new Map();
@@ -67,4 +67,4 @@ async function getCachedSqliteDatabase(path, options, create) {
67
67
  //#endregion
68
68
  export { getCachedSqliteDatabase as t };
69
69
 
70
- //# sourceMappingURL=sqlite-connection-cache-C_7rVisQ.js.map
70
+ //# sourceMappingURL=sqlite-connection-cache-BycfrYfi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-connection-cache-C_7rVisQ.js","names":[],"sources":["../../src/shared/sqlite-connection-cache.ts"],"sourcesContent":["import { ConnectionCache } from './connection-cache';\nimport type { DatabaseInterface, DatabaseOptions } from './types';\n\nexport type SqliteAdapterPath = 'libsql' | 'native' | 'secure';\n\nconst sqliteConnectionCache = new ConnectionCache<DatabaseInterface>();\ntype SqliteCacheGroup = {\n barrier?: Promise<void>;\n failure?: unknown;\n hasFailure: boolean;\n};\nconst sqliteCacheGroups = new Map<string, SqliteCacheGroup>();\n\nconst cacheKey = (dbid: string, path: SqliteAdapterPath) =>\n `sqlite:${path}:${dbid}`;\n\nasync function closeSqliteDatabase(db: DatabaseInterface): Promise<void> {\n await db.close?.();\n}\n\nasync function clearSqliteCacheGroup(dbid: string): Promise<void> {\n const group = sqliteCacheGroups.get(dbid) ?? { hasFailure: false };\n sqliteCacheGroups.set(dbid, group);\n const previous = group.barrier;\n const barrier = (previous?.catch(() => {}) ?? Promise.resolve()).then(\n async () => {\n const results = await Promise.allSettled([\n sqliteConnectionCache.evict(\n cacheKey(dbid, 'libsql'),\n closeSqliteDatabase,\n ),\n sqliteConnectionCache.evict(\n cacheKey(dbid, 'native'),\n closeSqliteDatabase,\n ),\n sqliteConnectionCache.evict(\n cacheKey(dbid, 'secure'),\n closeSqliteDatabase,\n ),\n ]);\n const failures = results.filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n );\n if (failures.length) {\n group.failure =\n failures.length === 1\n ? failures[0].reason\n : new AggregateError(\n failures.map((failure) => failure.reason),\n 'Multiple SQLite adapter paths failed to clear',\n );\n group.hasFailure = true;\n throw group.failure;\n }\n group.failure = undefined;\n group.hasFailure = false;\n },\n );\n group.barrier = barrier;\n try {\n await barrier;\n } finally {\n if (group.barrier === barrier) {\n group.barrier = undefined;\n if (!group.hasFailure) sqliteCacheGroups.delete(dbid);\n }\n }\n}\n\nasync function awaitSqliteCacheGroup(dbid: string): Promise<void> {\n const group = sqliteCacheGroups.get(dbid);\n if (!group) return;\n if (group.barrier) await group.barrier;\n if (group.hasFailure) throw group.failure;\n}\n\nexport async function getCachedSqliteDatabase(\n path: SqliteAdapterPath,\n options: DatabaseOptions,\n create: () => Promise<DatabaseInterface>,\n): Promise<DatabaseInterface> {\n const { dbid } = options;\n if (dbid && options.clearCache) {\n await clearSqliteCacheGroup(dbid);\n } else if (dbid) {\n await awaitSqliteCacheGroup(dbid);\n }\n\n return sqliteConnectionCache.getOrCreate(\n dbid ? cacheKey(dbid, path) : undefined,\n { ...options, clearCache: false },\n async () => {\n const db = await create();\n const originalClose = db.close?.bind(db);\n let closePromise: Promise<void> | undefined;\n db.close = async () => {\n if (!closePromise) {\n closePromise = originalClose?.() ?? Promise.resolve();\n }\n try {\n await closePromise;\n sqliteConnectionCache.forget(db);\n } catch (error) {\n closePromise = undefined;\n throw error;\n }\n };\n // Secure SQLite exposes a guarded public client.close() seam. Route it\n // through the same cache-aware close boundary so a direct client close\n // cannot leave a closed adapter cached under an explicit dbid.\n if ((db.client as any)?.transactionReservation === 'exclusive') {\n (db.client as any).close = db.close;\n }\n return db;\n },\n closeSqliteDatabase,\n async (db) =>\n path !== 'libsql' || (db.client as { closed?: boolean })?.closed !== true,\n );\n}\n"],"mappings":";;AAKA,IAAM,wBAAwB,IAAI,gBAAmC;AAMrE,IAAM,oCAAoB,IAAI,IAA8B;AAE5D,IAAM,YAAY,MAAc,SAC9B,UAAU,KAAK,GAAG;AAEpB,eAAe,oBAAoB,IAAsC;CACvE,MAAM,GAAG,QAAQ;AACnB;AAEA,eAAe,sBAAsB,MAA6B;CAChE,MAAM,QAAQ,kBAAkB,IAAI,IAAI,KAAK,EAAE,YAAY,MAAM;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AO;EACxB,MAAM,gBAAgB,GAAG,OAAO,KAAK,EAAE;EACvC,IAAI;EACJ,GAAG,QAAQ,YAAY;GACrB,IAAI,CAAC,cACH,eAAe,gBAAgB,KAAK,QAAQ,QAAQ;GAEtD,IAAI;IACF,MAAM;IACN,sBAAsB,OAAO,EAAE;GACjC,SAAS,OAAO;IACd,eAAe,KAAA;IACf,MAAM;GACR;EACF;EAIA,IAAK,GAAG,QAAgB,2BAA2B,aACjD,GAAI,OAAe,QAAQ,GAAG;EAEhC,OAAO;CACT,GACA,qBACA,OAAO,OACL,SAAS,YAAa,GAAG,QAAiC,WAAW,IACzE;AACF"}
1
+ {"version":3,"file":"sqlite-connection-cache-BycfrYfi.js","names":[],"sources":["../../src/shared/sqlite-connection-cache.ts"],"sourcesContent":["import { ConnectionCache } from './connection-cache';\nimport type { DatabaseInterface, DatabaseOptions } from './types';\n\nexport type SqliteAdapterPath = 'libsql' | 'native' | 'secure';\n\nconst sqliteConnectionCache = new ConnectionCache<DatabaseInterface>();\ntype SqliteCacheGroup = {\n barrier?: Promise<void>;\n failure?: unknown;\n hasFailure: boolean;\n};\nconst sqliteCacheGroups = new Map<string, SqliteCacheGroup>();\n\nconst cacheKey = (dbid: string, path: SqliteAdapterPath) =>\n `sqlite:${path}:${dbid}`;\n\nasync function closeSqliteDatabase(db: DatabaseInterface): Promise<void> {\n await db.close?.();\n}\n\nasync function clearSqliteCacheGroup(dbid: string): Promise<void> {\n const group = sqliteCacheGroups.get(dbid) ?? { hasFailure: false };\n sqliteCacheGroups.set(dbid, group);\n const previous = group.barrier;\n const barrier = (previous?.catch(() => {}) ?? Promise.resolve()).then(\n async () => {\n const results = await Promise.allSettled([\n sqliteConnectionCache.evict(\n cacheKey(dbid, 'libsql'),\n closeSqliteDatabase,\n ),\n sqliteConnectionCache.evict(\n cacheKey(dbid, 'native'),\n closeSqliteDatabase,\n ),\n sqliteConnectionCache.evict(\n cacheKey(dbid, 'secure'),\n closeSqliteDatabase,\n ),\n ]);\n const failures = results.filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n );\n if (failures.length) {\n group.failure =\n failures.length === 1\n ? failures[0].reason\n : new AggregateError(\n failures.map((failure) => failure.reason),\n 'Multiple SQLite adapter paths failed to clear',\n );\n group.hasFailure = true;\n throw group.failure;\n }\n group.failure = undefined;\n group.hasFailure = false;\n },\n );\n group.barrier = barrier;\n try {\n await barrier;\n } finally {\n if (group.barrier === barrier) {\n group.barrier = undefined;\n if (!group.hasFailure) sqliteCacheGroups.delete(dbid);\n }\n }\n}\n\nasync function awaitSqliteCacheGroup(dbid: string): Promise<void> {\n const group = sqliteCacheGroups.get(dbid);\n if (!group) return;\n if (group.barrier) await group.barrier;\n if (group.hasFailure) throw group.failure;\n}\n\nexport async function getCachedSqliteDatabase(\n path: SqliteAdapterPath,\n options: DatabaseOptions,\n create: () => Promise<DatabaseInterface>,\n): Promise<DatabaseInterface> {\n const { dbid } = options;\n if (dbid && options.clearCache) {\n await clearSqliteCacheGroup(dbid);\n } else if (dbid) {\n await awaitSqliteCacheGroup(dbid);\n }\n\n return sqliteConnectionCache.getOrCreate(\n dbid ? cacheKey(dbid, path) : undefined,\n { ...options, clearCache: false },\n async () => {\n const db = await create();\n const originalClose = db.close?.bind(db);\n let closePromise: Promise<void> | undefined;\n db.close = async () => {\n if (!closePromise) {\n closePromise = originalClose?.() ?? Promise.resolve();\n }\n try {\n await closePromise;\n sqliteConnectionCache.forget(db);\n } catch (error) {\n closePromise = undefined;\n throw error;\n }\n };\n // Secure SQLite exposes a guarded public client.close() seam. Route it\n // through the same cache-aware close boundary so a direct client close\n // cannot leave a closed adapter cached under an explicit dbid.\n if ((db.client as any)?.transactionReservation === 'exclusive') {\n (db.client as any).close = db.close;\n }\n return db;\n },\n closeSqliteDatabase,\n async (db) =>\n path !== 'libsql' || (db.client as { closed?: boolean })?.closed !== true,\n );\n}\n"],"mappings":";;AAKA,IAAM,wBAAwB,IAAI,gBAAmC;AAMrE,IAAM,oCAAo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AAQ,QAAQ,YAClB,MAAM,sBAAsB,IAAI;MAC3B,IAAI,MACT,MAAM,sBAAsB,IAAI;CAGlC,OAAO,sBAAsB,YAC3B,OAAO,SAAS,MAAM,IAAI,IAAI,KAAA,GAC9B;EAAE,GAAG;EAAS,YAAY;CAAM,GAChC,YAAY;EACV,MAAM,KAAK,MAAM,OAAO;EACxB,MAAM,gBAAgB,GAAG,OAAO,KAAK,EAAE;EACvC,IAAI;EACJ,GAAG,QAAQ,YAAY;GACrB,IAAI,CAAC,cACH,eAAe,gBAAgB,KAAK,QAAQ,QAAQ;GAEtD,IAAI;IACF,MAAM;IACN,sBAAsB,OAAO,EAAE;GACjC,SAAS,OAAO;IACd,eAAe,KAAA;IACf,MAAM;GACR;EACF;EAIA,IAAK,GAAG,QAAgB,2BAA2B,aACjD,GAAI,OAAe,QAAQ,GAAG;EAEhC,OAAO;CACT,GACA,qBACA,OAAO,OACL,SAAS,YAAa,GAAG,QAAiC,WAAW,IACzE;AACF"}
@@ -1,8 +1,8 @@
1
- import { o as resolveSchemas } from "./query-i6IIkNhF.js";
2
- import { c as wrapDatabaseError, n as buildWhere, o as resolveInsertColumns, r as formatDbError, t as DatabaseSchemaManager } from "./schema-manager-tfASrb_b.js";
3
- import { _ as validateColumnNames, c as createTransactionLock, d as validateDatabaseCacheOptions, g as validateColumnName, h as generateCreateIndexStatement, m as generateAddColumnStatement, v as validateIndexName, y as validateTableName } from "./postgres-dialect-DIy5f5YR.js";
1
+ import { C as validateColumnNames, E as validateTableName, S as validateColumnName, T as validatePlainColumnName, f as generateAddColumnStatement, i as formatDbError, n as buildAdapterWhere, p as generateCreateIndexStatement, s as resolveInsertColumns, t as DatabaseSchemaManager, u as wrapDatabaseError, w as validateIndexName, y as quoteSqliteColumnName } from "./schema-manager-psLzQ2yh.js";
2
+ import { o as resolveSchemas } from "./query-Dz0TZ0pY.js";
3
+ import { c as createTransactionLock, d as validateDatabaseCacheOptions } from "./postgres-dialect-CaNhva-C.js";
4
4
  import { t as redactDatabaseUrl } from "./redact-database-url-CfMDvSdy.js";
5
- import { t as getCachedSqliteDatabase } from "./sqlite-connection-cache-C_7rVisQ.js";
5
+ import { t as getCachedSqliteDatabase } from "./sqlite-connection-cache-BycfrYfi.js";
6
6
  import { DatabaseError } from "@happyvertical/utils";
7
7
  import { execFile } from "node:child_process";
8
8
  import { lstat, open, unlink } from "node:fs/promises";
@@ -1439,7 +1439,7 @@ async function getDatabase(options = {}) {
1439
1439
  windowsCustody: secureOptions.windowsCustody
1440
1440
  })));
1441
1441
  }
1442
- if (hasNativeSqliteCapabilities(options)) return (await import("./sqlite-native-DngobJtv.js")).getNativeSqliteDatabase(options);
1442
+ if (hasNativeSqliteCapabilities(options)) return (await import("./sqlite-native-CZGNm9zh.js")).getNativeSqliteDatabase(options);
1443
1443
  return getCachedSqliteDatabase("libsql", options, () => createDatabase(options, url));
1444
1444
  }
1445
1445
  async function createDatabase(options, url, clientFactory = () => createLibSQLClient(options)) {
@@ -1530,9 +1530,9 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1530
1530
  const keys = Object.keys(serializedData);
1531
1531
  const values = Object.values(serializedData);
1532
1532
  const placeholders = keys.map(() => "?").join(", ");
1533
- const updateSet = keys.map((key) => `${key} = excluded.${key}`).join(", ");
1534
- const conflict = conflictColumns.join(", ");
1535
- const sql = `INSERT INTO ${table} (${keys.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${conflict}) DO UPDATE SET ${updateSet}`;
1533
+ const updateSet = keys.map((key) => `${quoteSqliteColumnName(key)} = excluded.${quoteSqliteColumnName(key)}`).join(", ");
1534
+ const conflict = conflictColumns.map(quoteSqliteColumnName).join(", ");
1535
+ const sql = `INSERT INTO ${table} (${keys.map((key) => quoteSqliteColumnName(key)).join(", ")}) VALUES (${placeholders}) ON CONFLICT(${conflict}) DO UPDATE SET ${updateSet}`;
1536
1536
  return {
1537
1537
  operation: "upsert",
1538
1538
  affected: (await currentExecutor().execute({
@@ -1544,8 +1544,8 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1544
1544
  const executeNullAwareUpsertAttempt = async (executor, table, conflictColumns, serializedData) => {
1545
1545
  const keys = Object.keys(serializedData);
1546
1546
  const values = Object.values(serializedData);
1547
- const updateSet = keys.map((key) => `${key} = ?`).join(", ");
1548
- const whereClause = conflictColumns.map((col) => `${col} IS ?`).join(" AND ");
1547
+ const updateSet = keys.map((key) => `${quoteSqliteColumnName(key)} = ?`).join(", ");
1548
+ const whereClause = conflictColumns.map((col) => `${quoteSqliteColumnName(col)} IS ?`).join(" AND ");
1549
1549
  const whereValues = conflictColumns.map((col) => serializedData[col]);
1550
1550
  const updateSql = `UPDATE ${table} SET ${updateSet} WHERE ${whereClause}`;
1551
1551
  const updateResult = await executor.execute({
@@ -1557,7 +1557,7 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1557
1557
  affected: updateResult.rowsAffected
1558
1558
  };
1559
1559
  const placeholders = keys.map(() => "?").join(", ");
1560
- const insertSql = `INSERT INTO ${table} (${keys.join(", ")}) VALUES (${placeholders})`;
1560
+ const insertSql = `INSERT INTO ${table} (${keys.map((key) => quoteSqliteColumnName(key)).join(", ")}) VALUES (${placeholders})`;
1561
1561
  return {
1562
1562
  operation: "upsert",
1563
1563
  affected: (await executor.execute({
@@ -1644,14 +1644,14 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1644
1644
  const keys = resolveInsertColumns(table, serializedRecords);
1645
1645
  validateColumnNames(keys);
1646
1646
  const placeholders = serializedRecords.map(() => `(${keys.map(() => "?").join(", ")})`).join(", ");
1647
- sql = `INSERT INTO ${table} (${keys.join(", ")}) VALUES ${placeholders}`;
1647
+ sql = `INSERT INTO ${table} (${keys.map((key) => quoteSqliteColumnName(key)).join(", ")}) VALUES ${placeholders}`;
1648
1648
  values = serializedRecords.flatMap((record) => keys.map((key) => record[key]));
1649
1649
  } else {
1650
1650
  const serializedData = serializeRecord(data);
1651
1651
  const keys = Object.keys(serializedData);
1652
1652
  validateColumnNames(keys);
1653
1653
  const placeholders = keys.map(() => "?").join(", ");
1654
- sql = `INSERT INTO ${table} (${keys.join(", ")}) VALUES (${placeholders})`;
1654
+ sql = `INSERT INTO ${table} (${keys.map((key) => quoteSqliteColumnName(key)).join(", ")}) VALUES (${placeholders})`;
1655
1655
  values = Object.values(serializedData);
1656
1656
  }
1657
1657
  try {
@@ -1681,7 +1681,7 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1681
1681
  */
1682
1682
  const get = async (table, where) => {
1683
1683
  validateTableName(table);
1684
- const { sql: whereClause, values } = buildWhere(where, 1, "sqlite");
1684
+ const { sql: whereClause, values } = buildAdapterWhere(where, 1, "sqlite");
1685
1685
  if (!whereClause) throw new DatabaseError("GET requires at least one WHERE condition to prevent returning an arbitrary record", { table });
1686
1686
  const sql = `SELECT * FROM ${table} ${whereClause}`;
1687
1687
  try {
@@ -1708,7 +1708,7 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1708
1708
  */
1709
1709
  const list = async (table, where) => {
1710
1710
  validateTableName(table);
1711
- const { sql: whereClause, values } = buildWhere(where, 1, "sqlite");
1711
+ const { sql: whereClause, values } = buildAdapterWhere(where, 1, "sqlite");
1712
1712
  const sql = `SELECT * FROM ${table} ${whereClause}`;
1713
1713
  try {
1714
1714
  return (await currentExecutor().execute({
@@ -1739,8 +1739,8 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1739
1739
  const keys = Object.keys(serializedData);
1740
1740
  validateColumnNames(keys);
1741
1741
  const values = Object.values(serializedData);
1742
- const setClause = keys.map((key, i) => `${key} = $${i + 1}`).join(", ");
1743
- const { sql: whereClause, values: whereValues } = buildWhere(where, values.length + 1, "sqlite");
1742
+ const setClause = keys.map((key, i) => `${quoteSqliteColumnName(key)} = $${i + 1}`).join(", ");
1743
+ const { sql: whereClause, values: whereValues } = buildAdapterWhere(where, values.length + 1, "sqlite");
1744
1744
  if (!whereClause) throw new DatabaseError("UPDATE requires at least one WHERE condition to prevent accidental update of all records", { table });
1745
1745
  const sql = `UPDATE ${table} SET ${setClause} ${whereClause}`;
1746
1746
  try {
@@ -1834,7 +1834,7 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1834
1834
  const deleteRecords = async (table, where) => {
1835
1835
  validateTableName(table);
1836
1836
  if (Object.keys(where).length === 0) throw new DatabaseError("DELETE requires at least one WHERE condition to prevent accidental deletion of all records", { table });
1837
- const { sql: whereClause, values } = buildWhere(where, 1, "sqlite");
1837
+ const { sql: whereClause, values } = buildAdapterWhere(where, 1, "sqlite");
1838
1838
  try {
1839
1839
  await currentExecutor().execute({
1840
1840
  sql: `DELETE FROM ${table} ${whereClause}`,
@@ -1867,7 +1867,7 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
1867
1867
  sql: `SELECT COUNT(*) as count FROM ${table}`,
1868
1868
  args: []
1869
1869
  })).rows[0]?.count);
1870
- const { sql: whereClause, values } = buildWhere(where, 1, "sqlite");
1870
+ const { sql: whereClause, values } = buildAdapterWhere(where, 1, "sqlite");
1871
1871
  return toSafeSqliteCount((await currentExecutor().execute({
1872
1872
  sql: `SELECT COUNT(*) as count FROM ${table} ${whereClause}`,
1873
1873
  args: values
@@ -2670,10 +2670,10 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
2670
2670
  addIndex: async (table, index) => {
2671
2671
  validateTableName(table);
2672
2672
  validateIndexName(index.name);
2673
- for (const col of index.columns) validateColumnName(col);
2673
+ for (const col of index.columns) validatePlainColumnName(col);
2674
2674
  let sql;
2675
2675
  try {
2676
- sql = generateCreateIndexStatement(table, index);
2676
+ sql = generateCreateIndexStatement(table, index, "sqlite");
2677
2677
  await currentExecutor().execute({
2678
2678
  sql,
2679
2679
  args: []
@@ -2860,4 +2860,4 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
2860
2860
  //#endregion
2861
2861
  export { getDatabase };
2862
2862
 
2863
- //# sourceMappingURL=sqlite-BdM-nAQD.js.map
2863
+ //# sourceMappingURL=sqlite-nNhv0FMq.js.map