@happyvertical/sql 0.112.0 → 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.
- package/AGENT.md +65 -3
- package/README.md +146 -19
- package/dist/aggregate-expression.d.ts +77 -3
- package/dist/aggregate-expression.d.ts.map +1 -1
- package/dist/aggregate.d.ts +3 -2
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/chunks/{duckdb-CpeXdf0i.js → duckdb-DCV4JFWK.js} +23 -52
- package/dist/chunks/duckdb-DCV4JFWK.js.map +1 -0
- package/dist/chunks/{postgres-dialect-DIy5f5YR.js → postgres-dialect-CaNhva-C.js} +28 -328
- package/dist/chunks/postgres-dialect-CaNhva-C.js.map +1 -0
- package/dist/chunks/query-Dz0TZ0pY.js +970 -0
- package/dist/chunks/query-Dz0TZ0pY.js.map +1 -0
- package/dist/chunks/{schema-manager-tfASrb_b.js → schema-manager-psLzQ2yh.js} +471 -18
- package/dist/chunks/schema-manager-psLzQ2yh.js.map +1 -0
- package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js → sqlite-connection-cache-BycfrYfi.js} +2 -2
- package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js.map → sqlite-connection-cache-BycfrYfi.js.map} +1 -1
- package/dist/chunks/{sqlite-BdM-nAQD.js → sqlite-nNhv0FMq.js} +22 -22
- package/dist/chunks/sqlite-nNhv0FMq.js.map +1 -0
- package/dist/chunks/{sqlite-native-DngobJtv.js → sqlite-native-CZGNm9zh.js} +40 -37
- package/dist/chunks/sqlite-native-CZGNm9zh.js.map +1 -0
- package/dist/doctor.d.ts.map +1 -1
- package/dist/duckdb.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -77
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts.map +1 -1
- package/dist/pglite.js +2 -2
- package/dist/query.d.ts +3 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +3 -3
- package/dist/schema-manager.d.ts.map +1 -1
- package/dist/shared/alter-utils.d.ts +43 -7
- package/dist/shared/alter-utils.d.ts.map +1 -1
- package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
- package/dist/shared/postgres-dialect.d.ts.map +1 -1
- package/dist/shared/types.d.ts +1 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/dist/shared/utils.d.ts +12 -1
- package/dist/shared/utils.d.ts.map +1 -1
- package/dist/sqlite-native.d.ts.map +1 -1
- package/dist/sqlite.d.ts.map +1 -1
- package/metadata.json +4 -4
- package/package.json +4 -4
- package/dist/chunks/duckdb-CpeXdf0i.js.map +0 -1
- package/dist/chunks/postgres-dialect-DIy5f5YR.js.map +0 -1
- package/dist/chunks/query-i6IIkNhF.js +0 -564
- package/dist/chunks/query-i6IIkNhF.js.map +0 -1
- package/dist/chunks/schema-manager-tfASrb_b.js.map +0 -1
- package/dist/chunks/sqlite-BdM-nAQD.js.map +0 -1
- package/dist/chunks/sqlite-native-DngobJtv.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duckdb-DCV4JFWK.js","names":[],"sources":["../../src/duckdb.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, extname, join } from 'node:path';\nimport { DatabaseError } from '@happyvertical/utils';\nimport { DatabaseSchemaManager } from './schema-manager';\nimport {\n escapeStringLiteral,\n generateAddColumnStatement,\n generateCreateIndexStatement,\n quoteDuckDBColumnName,\n validateColumnName,\n validateColumnNames,\n validateIndexName,\n validatePlainColumnName,\n validateTableName,\n} from './shared/alter-utils';\nimport { validateDatabaseCacheOptions } from './shared/connection-cache';\nimport {\n createDuckDBResourceCloser,\n throwWithDuckDBCleanup,\n} from './shared/duckdb-resources';\nimport { convertUniqueIndexesToInlineConstraints } from './shared/duckdb-schema-utils';\nimport { serializeDuckDBStatements } from './shared/duckdb-statement-queue';\nimport { redactDatabaseUrl } from './shared/redact-database-url';\nimport { createTransactionLock } from './shared/transaction-lock';\nimport type {\n ColumnDefinition,\n ColumnDefinitionWithName,\n DatabaseInterface,\n DuckDBOptions,\n IndexDefinition,\n QueryResult,\n SchemaInitializationOptions,\n TableInterface,\n TableSchemaInfo,\n TransactionHandle,\n UpsertOptions,\n} from './shared/types';\nimport { NestedTransactionError, resolveSchemas } from './shared/types';\nimport {\n buildAdapterWhere as buildWhere,\n formatDbError,\n resolveInsertColumns,\n wrapDatabaseError,\n} from './shared/utils';\n\n/**\n * Creates tables from provided schema definitions\n *\n * DuckDB has a known limitation (issue #12684) where ON CONFLICT clauses\n * fail with UNIQUE INDEX but work with inline UNIQUE constraints.\n * This function converts UNIQUE indexes to inline constraints for compatibility.\n *\n * @param connection - DuckDB connection\n * @param schemas - Schema definitions to create\n */\nasync function createTablesFromSchemas(\n connection: any,\n schemas: Record<string, import('./shared/types').SchemaProvider>,\n): Promise<void> {\n for (const [tableName, schema] of Object.entries(schemas)) {\n try {\n // Check if table already exists\n const result = await connection.runAndReadAll(\n `SELECT name FROM sqlite_master WHERE type='table' AND name='${escapeStringLiteral(tableName)}'`,\n );\n const rows = result.getRowObjects();\n\n if (rows.length > 0) {\n console.log(`[duckdb] Table ${tableName} already exists, skipping`);\n continue;\n }\n\n console.log(`[duckdb] Creating table ${tableName} from provided schema`);\n\n // Convert UNIQUE indexes to inline UNIQUE constraints for DuckDB compatibility\n // DuckDB's ON CONFLICT requires inline constraints, not separate indexes\n const transformed = convertUniqueIndexesToInlineConstraints(\n schema.ddl,\n schema.indexes,\n );\n\n // Create table from transformed DDL\n await connection.run(transformed.ddl);\n\n // Create remaining indexes (non-UNIQUE indexes only)\n // UNIQUE indexes have been converted to inline constraints\n if (transformed.indexes && transformed.indexes.length > 0) {\n for (const indexSQL of transformed.indexes) {\n try {\n await connection.run(indexSQL);\n } catch (error) {\n console.warn(\n `[duckdb] Failed to create index for ${tableName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n // Create triggers (if supported)\n if (schema.triggers && schema.triggers.length > 0) {\n for (const triggerSQL of schema.triggers) {\n try {\n await connection.run(triggerSQL);\n } catch (error) {\n console.warn(\n `[duckdb] Failed to create trigger for ${tableName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n } catch (error) {\n throw new DatabaseError(\n `Failed to create table ${tableName} from schema`,\n {\n tableName,\n schema,\n originalError: error instanceof Error ? error.message : String(error),\n },\n );\n }\n }\n}\n\n/**\n * Resolves a DuckDB URL, handling :memory: variants to prevent file leakage.\n *\n * DuckDB interprets any string as a file path unless it's exactly ':memory:'.\n * URLs like ':memory:12345' create files named ':memory:12345' in the working directory.\n *\n * This function:\n * - Returns ':memory:' unchanged (pure in-memory database)\n * - Converts ':memory:*' patterns to temp files in os.tmpdir()\n * - Returns other URLs unchanged (file paths, etc.)\n *\n * @param url - The database URL to resolve\n * @returns The resolved URL safe for DuckDB\n */\nfunction resolveDuckDBUrl(url: string): string {\n // Pure in-memory: use as-is\n if (url === ':memory:') {\n return url;\n }\n\n // Pattern: :memory: followed by anything (e.g., :memory:12345-0.5678)\n // These would create files in CWD - redirect to temp directory instead\n if (url.startsWith(':memory:')) {\n const suffix = url.slice(':memory:'.length);\n const tempPath = join(tmpdir(), `duckdb-memory-${suffix}.db`);\n return tempPath;\n }\n\n // Other URLs (file paths, etc.): use as-is\n return url;\n}\n\n/**\n * Creates a DuckDB connection instance\n *\n * @param options - DuckDB connection options\n * @returns Promise resolving to a DuckDB connection\n */\nasync function createDuckDBConnection(options: DuckDBOptions) {\n const {\n url = ':memory:',\n dataDir = './data',\n autoRegisterJSON = true,\n } = options;\n const schemas = resolveSchemas(options.schemas) ?? {};\n\n // Resolve URL to prevent file leakage from :memory:* patterns\n const resolvedUrl = resolveDuckDBUrl(url);\n\n let instance: Awaited<ReturnType<any>> | undefined;\n let connection: any;\n try {\n // Dynamic import to avoid bundling\n const duckdbModule = '@duckdb/node-api';\n const { DuckDBInstance } = await import(/* @vite-ignore */ duckdbModule);\n\n // Create DuckDB instance with resolved URL\n instance = await DuckDBInstance.create(resolvedUrl);\n // One connection serves every call on this handle; queue its statements.\n connection = serializeDuckDBStatements(await instance.connect());\n\n // Create tables from provided schemas first\n if (schemas && Object.keys(schemas).length > 0) {\n await createTablesFromSchemas(connection, schemas);\n }\n\n // Auto-register JSON files if enabled\n if (autoRegisterJSON && dataDir) {\n await registerJSONFiles(connection, dataDir);\n }\n\n return { connection, instance };\n } catch (error) {\n const errorMessage = redactDatabaseUrl(\n error instanceof Error ? error.message : String(error),\n );\n const databaseError = new DatabaseError(\n `Failed to create DuckDB connection: ${errorMessage}`,\n {\n url: redactDatabaseUrl(url),\n originalError: errorMessage,\n },\n );\n return throwWithDuckDBCleanup(\n databaseError,\n createDuckDBResourceCloser(connection, instance),\n );\n }\n}\n\n/**\n * Scans the data directory and registers JSON files as queryable tables\n *\n * @param connection - DuckDB connection\n * @param dataDir - Directory containing JSON files\n */\nasync function registerJSONFiles(connection: any, dataDir: string) {\n try {\n const files = await readdir(dataDir);\n const jsonFiles = files.filter(\n (file) => extname(file).toLowerCase() === '.json',\n );\n\n for (const file of jsonFiles) {\n const filePath = join(dataDir, file);\n const tableName = basename(file, '.json');\n\n // Create view that reads from JSON file\n // DuckDB automatically infers schema with ISO date/timestamp parsing\n // Both halves come from a file in the data directory: the view name from\n // its basename, the path from its location. Anyone who can drop a file\n // there would otherwise get DDL execution at getDatabase() time.\n validateTableName(tableName);\n await connection.run(\n `CREATE OR REPLACE VIEW ${tableName} AS SELECT * FROM read_json('${escapeStringLiteral(filePath)}', auto_detect=true, format='auto', timestampformat='iso', dateformat='iso')`,\n );\n }\n } catch (error) {\n // If directory doesn't exist, that's okay - user might not have JSON files yet\n if ((error as any).code !== 'ENOENT') {\n throw new DatabaseError(`Failed to register JSON files from ${dataDir}`, {\n dataDir,\n originalError: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n\n/**\n * Converts DuckDB-specific type representations to JavaScript types\n *\n * Handles two cases:\n * 1. JavaScript BigInt values → converted to numbers\n * 2. DuckDB timestamp objects ({ micros: number }) → converted to Date objects\n *\n * DuckDB represents TIMESTAMP values as objects with a single property\n * called 'micros' containing microseconds since Unix epoch. This function\n * converts them to JavaScript Date objects for proper serialization.\n *\n * @param obj - Object that may contain BigInt or timestamp values\n * @returns Object with DuckDB types converted to JavaScript types\n */\nfunction convertBigInts(obj: any): any {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj === 'bigint') return Number(obj);\n\n // Handle DuckDB timestamp objects: { micros: number | bigint }\n // Convert to JavaScript Date for proper serialization\n // Fixes issue #314: DuckDB returns dates as { micros } objects\n if (\n typeof obj === 'object' &&\n !Array.isArray(obj) &&\n 'micros' in obj &&\n Object.keys(obj).length === 1 &&\n (typeof obj.micros === 'number' || typeof obj.micros === 'bigint')\n ) {\n // Convert microseconds to milliseconds for Date constructor\n // DuckDB stores timestamps as microseconds since Unix epoch\n // Handle both number and bigint types (DuckDB can return either)\n const micros =\n typeof obj.micros === 'bigint' ? Number(obj.micros) : obj.micros;\n const milliseconds = micros / 1000;\n return new Date(milliseconds);\n }\n\n if (Array.isArray(obj)) return obj.map(convertBigInts);\n if (typeof obj === 'object') {\n const result: any = {};\n for (const key in obj) {\n result[key] = convertBigInts(obj[key]);\n }\n return result;\n }\n return obj;\n}\n\n/**\n * Creates a DuckDB database adapter\n *\n * @param options - DuckDB connection options\n * @returns Database interface for DuckDB\n */\nexport async function getDatabase(\n options: DuckDBOptions = {},\n): Promise<DatabaseInterface> {\n validateDatabaseCacheOptions(options);\n const { connection, instance } = await createDuckDBConnection(options);\n const writeStrategy = options.writeStrategy || 'none';\n const dataDir = options.dataDir || './data';\n // Use resolved URL to reflect actual database location\n const url = resolveDuckDBUrl(options.url || ':memory:');\n\n // One lock per connection. This adapter creates a fresh DuckDB instance and\n // connection per call and caches nothing, so the lock's scope is exactly the\n // connection it was created alongside.\n const connectionLock = createTransactionLock(\n 'duckdb',\n options.transactionQueueTimeout,\n );\n const closeResources = createDuckDBResourceCloser(connection, instance);\n\n /**\n * Inserts one or more records into a table\n *\n * @param table - Table name\n * @param data - Single record or array of records to insert\n * @returns Promise resolving to operation result\n * @throws Error if the insert operation fails\n */\n const insert = async (\n table: string,\n data: Record<string, any> | Record<string, any>[],\n ): Promise<QueryResult> => {\n validateTableName(table);\n const records = Array.isArray(data) ? data : [data];\n\n if (records.length === 0) {\n return { operation: 'insert', affected: 0 };\n }\n\n const keys = resolveInsertColumns(table, records);\n validateColumnNames(keys);\n const values: any[] = [];\n let paramIdx = 1;\n\n // Build placeholders with proper type casting for DuckDB\n const placeholders = records\n .map((record) => {\n const rowPlaceholders = keys.map((key) => {\n const value = record[key];\n\n if (value === null || value === undefined) {\n return 'NULL';\n } else if (value === '' && typeof value === 'string') {\n // CAST empty strings to TEXT to prevent DuckDB ANY type inference\n values.push(value);\n return `CAST($${paramIdx++} AS TEXT)`;\n } else if (value instanceof Date) {\n // Convert Date objects to ISO strings for DuckDB\n values.push(value.toISOString());\n return `$${paramIdx++}`;\n } else if (Array.isArray(value)) {\n // CAST arrays to JSON to prevent DuckDB ANY type inference\n values.push(JSON.stringify(value));\n return `CAST($${paramIdx++} AS JSON)`;\n } else if (\n typeof value === 'object' &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n // CAST plain objects to JSON to prevent DuckDB ANY type inference\n values.push(JSON.stringify(value));\n return `CAST($${paramIdx++} AS JSON)`;\n } else {\n // Direct parameter binding for other values\n values.push(value);\n return `$${paramIdx++}`;\n }\n });\n return `(${rowPlaceholders.join(', ')})`;\n })\n .join(', ');\n\n const sql = `INSERT INTO ${table} (${keys.map((key) => quoteDuckDBColumnName(key)).join(', ')}) VALUES ${placeholders}`;\n\n try {\n await connection.run(sql, values);\n const affected = records.length;\n\n // Handle write-back strategy\n if (writeStrategy === 'immediate') {\n await exportTableToJSON(connection, table, dataDir);\n }\n\n return { operation: 'insert', affected };\n } catch (e) {\n throw new DatabaseError('Failed to insert records into table', {\n table,\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Retrieves a single record matching the where criteria\n *\n * @param table - Table name\n * @param where - Criteria to match records\n * @returns Promise resolving to matching record or null if not found\n * @throws Error if the query fails\n */\n const get = async (\n table: string,\n where: Record<string, any>,\n ): Promise<Record<string, any> | null> => {\n validateTableName(table);\n const { sql: whereClause, values } = buildWhere(where, 1, 'duckdb');\n const sql = `SELECT * FROM ${table} ${whereClause} LIMIT 1`;\n\n try {\n const reader = await connection.runAndReadAll(sql, values);\n const rows = reader.getRowObjects();\n return rows.length > 0 ? convertBigInts(rows[0]) : null;\n } catch (e) {\n throw new DatabaseError('Failed to retrieve record from table', {\n table,\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Retrieves multiple records matching the where criteria\n *\n * @param table - Table name\n * @param where - Criteria to match records\n * @returns Promise resolving to array of matching records\n * @throws Error if the query fails\n */\n const list = async (\n table: string,\n where: Record<string, any>,\n ): Promise<Record<string, any>[]> => {\n validateTableName(table);\n const { sql: whereClause, values } = buildWhere(where, 1, 'duckdb');\n const sql = `SELECT * FROM ${table} ${whereClause}`;\n\n try {\n const reader = await connection.runAndReadAll(sql, values);\n return convertBigInts(reader.getRowObjects());\n } catch (e) {\n throw new DatabaseError('Failed to list records from table', {\n table,\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Updates records matching the where criteria\n *\n * @param table - Table name\n * @param where - Criteria to match records to update\n * @param data - New data to set\n * @returns Promise resolving to operation result\n * @throws Error if the update operation fails\n */\n const update = async (\n table: string,\n where: Record<string, any>,\n data: Record<string, any>,\n ): Promise<QueryResult> => {\n validateTableName(table);\n const keys = Object.keys(data);\n validateColumnNames(keys);\n const setClause = keys\n .map((key, idx) => `${quoteDuckDBColumnName(key)} = $${idx + 1}`)\n .join(', ');\n const { sql: whereClause, values: whereValues } = buildWhere(\n where,\n keys.length + 1,\n 'duckdb',\n );\n\n const sql = `UPDATE ${table} SET ${setClause} ${whereClause}`;\n // Read values through the validated key list rather than a second\n // enumeration of `data`, so a hostile Proxy cannot return values that\n // disagree in order or membership with the `keys` driving `setClause`.\n const values = [...keys.map((key) => data[key]), ...whereValues];\n\n try {\n await connection.run(sql, values);\n\n // Handle write-back strategy\n if (writeStrategy === 'immediate') {\n await exportTableToJSON(connection, table, dataDir);\n }\n\n // DuckDB doesn't return rowsAffected in the same way, estimate from where clause\n return { operation: 'update', affected: 1 };\n } catch (e) {\n throw new DatabaseError('Failed to update records in table', {\n table,\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n const buildDuckDBValueExpression = (\n value: any,\n values: any[],\n paramIdx: { value: number },\n ): string => {\n if (value === null || value === undefined) {\n return 'NULL';\n }\n if (value === '' && typeof value === 'string') {\n values.push(value);\n return `CAST($${paramIdx.value++} AS TEXT)`;\n }\n if (value instanceof Date) {\n values.push(value.toISOString());\n return `$${paramIdx.value++}`;\n }\n if (Array.isArray(value)) {\n values.push(JSON.stringify(value));\n return `CAST($${paramIdx.value++} AS JSON)`;\n }\n if (\n typeof value === 'object' &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n values.push(JSON.stringify(value));\n return `CAST($${paramIdx.value++} AS JSON)`;\n }\n\n values.push(value);\n return `$${paramIdx.value++}`;\n };\n\n const executeNullAwareDuckDBUpsert = async (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n ): Promise<QueryResult> => {\n const conflictWhere = Object.fromEntries(\n conflictColumns.map((col) => [\n quoteDuckDBColumnName(col, true),\n data[col],\n ]),\n );\n const existing = await get(table, conflictWhere);\n\n if (!existing) {\n return insert(\n table,\n Object.fromEntries(\n Object.entries(data).map(([key, value]) => [\n quoteDuckDBColumnName(key, true),\n value,\n ]),\n ),\n );\n }\n\n const keys = Object.keys(data);\n const updateKeys = keys.filter((key) => !conflictColumns.includes(key));\n if (updateKeys.length === 0) {\n return { operation: 'upsert', affected: 1 };\n }\n const values: any[] = [];\n const paramIdx = { value: 1 };\n const assignments = updateKeys.map((key) => {\n const valueExpr = buildDuckDBValueExpression(data[key], values, paramIdx);\n return `${quoteDuckDBColumnName(key, true)} = ${valueExpr}`;\n });\n const { sql: whereClause, values: whereValues } = buildWhere(\n conflictWhere,\n paramIdx.value,\n 'duckdb',\n );\n const sql = `UPDATE ${table} SET ${assignments.join(', ')} ${whereClause}`;\n\n try {\n await connection.run(sql, [...values, ...whereValues]);\n\n if (writeStrategy === 'immediate') {\n await exportTableToJSON(connection, table, dataDir);\n }\n\n return { operation: 'upsert', affected: 1 };\n } catch (e) {\n throw new DatabaseError('Failed to upsert record into table', {\n table,\n sql,\n values: [...values, ...whereValues],\n conflictColumns,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Inserts a record or updates it if it already exists (UPSERT)\n *\n * @param table - Table name\n * @param conflictColumns - Columns that define the uniqueness constraint\n * @param data - Data to insert or update\n * @returns Promise resolving to operation result\n * @throws Error if the upsert operation fails\n */\n const upsert = async (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n options?: UpsertOptions,\n ): Promise<QueryResult> => {\n validateTableName(table);\n // Snapshot the record once. Every read below — the presence check, the\n // column list, the value list, and the null-aware branch — must see the\n // same keys and values, or a hostile object could present one shape to the\n // checks and another to the interpolated `keys`. A plain-object copy cannot\n // observe how many times it is read.\n const record = { ...data };\n // Coerce the conflict columns to primitive strings once, for the same\n // reason as `record`. These are not validated (they are quoted, so names\n // that need quotes keep working), only escaped — and `escapeQuotedIdentifier`\n // must run on a primitive. Coercing here also pins the value the presence\n // check below sees to the value the `ON CONFLICT` list escapes, so a crafted\n // object cannot read as `id` for the check and as unescaped SQL for the SQL.\n const conflictCols = conflictColumns.map((col) => String(col));\n // Conflict and record keys remain literal physical names, including dots,\n // spaces and quote characters. The NULL-aware branch delimits those names\n // before passing them to the qualified WHERE renderer.\n // Validate that all conflict columns are present in the data\n const missingColumns = conflictCols.filter((col) => !(col in record));\n\n if (missingColumns.length > 0) {\n throw new DatabaseError('Conflict columns missing from data', {\n table,\n conflictColumns: conflictCols,\n missingColumns,\n availableColumns: Object.keys(record),\n hint: 'All columns specified in ON CONFLICT must be present in the data being inserted. Undefined values should be replaced with null or an appropriate default.',\n });\n }\n\n if (\n !options?.nullsDistinct &&\n conflictCols.some((col) => record[col] === null)\n ) {\n return executeNullAwareDuckDBUpsert(table, conflictCols, record);\n }\n\n const keys = Object.keys(record);\n const dataValues = Object.values(record);\n const updateKeys = keys.filter((key) => !conflictCols.includes(key));\n\n // Build placeholders and values with proper type handling for DuckDB\n // DuckDB cannot infer types from empty strings or certain values, so we need explicit CAST\n const placeholders: string[] = [];\n const values: any[] = [];\n let paramIdx = 1;\n\n for (const value of dataValues) {\n if (value === null || value === undefined) {\n // DuckDB requires explicit NULL for null/undefined values\n placeholders.push('NULL');\n } else if (value === '' && typeof value === 'string') {\n // CAST empty strings to TEXT to prevent DuckDB ANY type inference\n placeholders.push(`CAST($${paramIdx} AS TEXT)`);\n values.push(value);\n paramIdx++;\n } else if (value instanceof Date) {\n // Convert Date objects to ISO strings for DuckDB\n placeholders.push(`$${paramIdx}`);\n values.push(value.toISOString());\n paramIdx++;\n } else if (Array.isArray(value)) {\n // CAST arrays to JSON to prevent DuckDB ANY type inference\n // DuckDB cannot infer array element types from empty arrays or mixed types\n placeholders.push(`CAST($${paramIdx} AS JSON)`);\n values.push(JSON.stringify(value));\n paramIdx++;\n } else if (\n typeof value === 'object' &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n // CAST plain objects to JSON to prevent DuckDB ANY type inference\n // Only applies to plain objects (not class instances)\n placeholders.push(`CAST($${paramIdx} AS JSON)`);\n values.push(JSON.stringify(value));\n paramIdx++;\n } else {\n // Direct parameter binding for other values\n placeholders.push(`$${paramIdx}`);\n values.push(value);\n paramIdx++;\n }\n }\n\n const updateIndex = { value: paramIdx };\n const quotedUpdateSetParts = updateKeys.map(\n (key) =>\n `${quoteDuckDBColumnName(key, true)} = ${buildDuckDBValueExpression(record[key], values, updateIndex)}`,\n );\n const conflict = conflictCols\n .map((col) => quoteDuckDBColumnName(col, true))\n .join(', ');\n const quotedKeys = keys\n .map((key) => quoteDuckDBColumnName(key, true))\n .join(', ');\n\n const conflictAction =\n quotedUpdateSetParts.length > 0\n ? `DO UPDATE SET ${quotedUpdateSetParts.join(', ')}`\n : 'DO NOTHING';\n const sql = `INSERT INTO ${table} (${quotedKeys}) VALUES (${placeholders.join(', ')}) ON CONFLICT(${conflict}) ${conflictAction}`;\n\n try {\n await connection.run(sql, values);\n\n // Handle write-back strategy\n if (writeStrategy === 'immediate') {\n await exportTableToJSON(connection, table, dataDir);\n }\n\n return { operation: 'upsert', affected: 1 };\n } catch (e) {\n throw new DatabaseError('Failed to upsert record into table', {\n table,\n sql,\n values,\n conflictColumns: conflictCols,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Gets a record matching the where criteria or inserts it if not found\n *\n * @param table - Table name\n * @param where - Criteria to match existing record\n * @param data - Data to insert if no record found\n * @returns Promise resolving to the record (either retrieved or newly inserted)\n * @throws Error if the operation fails\n */\n const getOrInsert = async (\n table: string,\n where: Record<string, any>,\n data: Record<string, any>,\n ): Promise<Record<string, any>> => {\n const result = await get(table, where);\n if (result) return result;\n\n await insert(table, data);\n const inserted = await get(table, where);\n\n if (!inserted) {\n throw new DatabaseError('Failed to insert and retrieve record', {\n table,\n where,\n data,\n });\n }\n\n return inserted;\n };\n\n /**\n * Deletes records from a table matching the where criteria\n *\n * @param table - Table name\n * @param where - Criteria to match records for deletion\n * @returns Promise resolving to operation result with count of deleted rows\n * @throws Error if the delete operation fails\n */\n const deleteRecords = async (\n table: string,\n where: Record<string, any>,\n ): Promise<QueryResult> => {\n validateTableName(table);\n\n const keys = Object.keys(where);\n if (keys.length === 0) {\n throw new DatabaseError(\n 'DELETE requires at least one WHERE condition to prevent accidental deletion of all records',\n { table },\n );\n }\n\n const { sql: whereClause, values } = buildWhere(where, 1, 'duckdb');\n const sql = `DELETE FROM ${table} ${whereClause}`;\n\n try {\n await connection.run(sql, values);\n\n // Handle write-back strategy\n if (writeStrategy === 'immediate') {\n await exportTableToJSON(connection, table, dataDir);\n }\n\n return { operation: 'delete', affected: 1 };\n } catch (e) {\n throw new DatabaseError('Failed to delete records from table', {\n table,\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Counts records in a table matching the where criteria\n *\n * @param table - Table name\n * @param where - Criteria to match records (optional, counts all if omitted)\n * @returns Promise resolving to count of matching records\n * @throws Error if the count operation fails\n */\n const count = async (\n table: string,\n where?: Record<string, any>,\n ): Promise<number> => {\n validateTableName(table);\n\n try {\n if (!where || Object.keys(where).length === 0) {\n // Count all records\n const result = await connection.runAndReadAll(\n `SELECT COUNT(*) as count FROM ${table}`,\n );\n const rows = result.getRowObjects();\n return Number(rows[0]?.count) || 0;\n }\n\n // Count with conditions\n const { sql: whereClause, values } = buildWhere(where, 1, 'duckdb');\n const sql = `SELECT COUNT(*) as count FROM ${table} ${whereClause}`;\n\n const result = await connection.runAndReadAll(sql, values);\n const rows = result.getRowObjects();\n\n return Number(rows[0]?.count) || 0;\n } catch (e) {\n throw new DatabaseError('Failed to count records in table', {\n table,\n where,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Checks if a table exists in the database\n *\n * @param tableName - Name of the table to check\n * @returns Promise resolving to boolean indicating if the table exists\n */\n const tableExists = async (tableName: string): Promise<boolean> => {\n // The name is interpolated into a statement, and this engine executes every\n // statement in the string it is given, so an unvalidated name here is a\n // DDL/DML sink rather than a read oracle — the `catch` below swallows the\n // error, not the execution. Validation runs outside the try for that\n // reason: a rejected identifier must be reported, not reported as `false`.\n validateTableName(tableName);\n try {\n // Try to query the table - simpler and works for both tables and views\n await connection.runAndReadAll(`SELECT * FROM ${tableName} LIMIT 1`);\n return true;\n } catch {\n return false;\n }\n };\n\n /**\n * Exports a table to a JSON file (for write-back strategies)\n *\n * @param connection - DuckDB connection\n * @param table - Table name\n * @param dataDir - Directory to write JSON file\n */\n const exportTableToJSON = async (\n connection: any,\n table: string,\n dataDir: string,\n ): Promise<void> => {\n // Every caller-facing path into this function takes a table name, and it is\n // interpolated into a COPY statement and into the target file path.\n // Unvalidated, `exportTable('t TO $$/etc/x$$; DROP ...; --')` both writes a\n // file outside the data directory and runs the trailing statements.\n // Validate at this choke point so the internal callers that pass\n // catalog-derived names are covered too.\n validateTableName(table);\n\n const filePath = join(dataDir, `${table}.json`);\n await connection.run(\n `COPY (SELECT * FROM ${table}) TO '${escapeStringLiteral(filePath)}' (FORMAT JSON, ARRAY true)`,\n );\n };\n\n /**\n * Manual export method for 'manual' write strategy\n *\n * @param table - Table name to export\n * @returns Promise that resolves when export completes\n */\n const exportTable = async (table: string): Promise<void> => {\n if (writeStrategy === 'none') {\n throw new DatabaseError(\n 'Cannot export table: write strategy is set to none',\n { table, writeStrategy },\n );\n }\n await exportTableToJSON(connection, table, dataDir);\n };\n\n /**\n * Creates a table-specific interface for simplified table operations\n *\n * @param tableName - Table name\n * @returns TableInterface for the specified table\n */\n const table = (tableName: string): TableInterface => ({\n insert: (data) => insert(tableName, data),\n get: (where) => get(tableName, where),\n list: (where) => list(tableName, where),\n });\n\n /**\n * Parses a tagged template literal into a SQL query and values\n *\n * @param strings - Template strings\n * @param vars - Variables to interpolate into the query\n * @returns Object with SQL query and values array\n */\n const parseTemplate = (strings: TemplateStringsArray, ...vars: any[]) => {\n let sql = strings[0];\n const values = [];\n for (let i = 0; i < vars.length; i++) {\n values.push(vars[i]);\n sql += `$${i + 1}${strings[i + 1]}`;\n }\n return { sql, values };\n };\n\n /**\n * Executes a SQL query using template literals and returns multiple rows\n *\n * @param strings - Template strings\n * @param vars - Variables to interpolate into the query\n * @returns Promise resolving to array of result records\n * @throws Error if the query fails\n */\n const many = async (\n strings: TemplateStringsArray,\n ...vars: any[]\n ): Promise<Record<string, any>[]> => {\n const { sql, values } = parseTemplate(strings, ...vars);\n try {\n const reader = await connection.runAndReadAll(sql, values);\n return convertBigInts(reader.getRowObjects());\n } catch (e) {\n throw new DatabaseError('Failed to execute many query', {\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Executes a SQL query using template literals and returns a single row\n *\n * @param strings - Template strings\n * @param vars - Variables to interpolate into the query\n * @returns Promise resolving to a single result record or null\n * @throws Error if the query fails\n */\n const single = async (\n strings: TemplateStringsArray,\n ...vars: any[]\n ): Promise<Record<string, any> | null> => {\n const { sql, values } = parseTemplate(strings, ...vars);\n try {\n const reader = await connection.runAndReadAll(sql, values);\n const rows = reader.getRowObjects();\n return rows[0] ? convertBigInts(rows[0]) : null;\n } catch (e) {\n throw new DatabaseError('Failed to execute single query', {\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Executes a SQL query using template literals and returns a single value\n *\n * @param strings - Template strings\n * @param vars - Variables to interpolate into the query\n * @returns Promise resolving to a single value (first column of first row)\n * @throws Error if the query fails\n */\n const pluck = async (\n strings: TemplateStringsArray,\n ...vars: any[]\n ): Promise<any> => {\n const { sql, values } = parseTemplate(strings, ...vars);\n try {\n const reader = await connection.runAndReadAll(sql, values);\n const rows = reader.getRowObjects();\n if (rows.length === 0) return null;\n const firstRow = rows[0];\n const firstKey = Object.keys(firstRow)[0];\n return convertBigInts(firstRow[firstKey]);\n } catch (e) {\n throw new DatabaseError('Failed to execute pluck query', {\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Executes a SQL query using template literals without returning results\n *\n * @param strings - Template strings\n * @param vars - Variables to interpolate into the query\n * @returns Promise that resolves when the query completes\n * @throws Error if the query fails\n */\n const execute = async (\n strings: TemplateStringsArray,\n ...vars: any[]\n ): Promise<void> => {\n const { sql, values } = parseTemplate(strings, ...vars);\n try {\n await connection.run(sql, values);\n } catch (e) {\n throw new DatabaseError('Failed to execute query', {\n sql,\n values,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * Executes a raw SQL query with parameterized values\n *\n * @param str - SQL query string\n * @param values - Variables to use as parameters\n * @returns Promise resolving to query result with rows and metadata\n * @throws Error if the query fails\n */\n const query = async (str: string, ...values: any[]) => {\n const sql = str;\n const args = Array.isArray(values[0]) ? values[0] : values;\n\n try {\n const reader = await connection.runAndReadAll(sql, args);\n const rows = convertBigInts(reader.getRowObjects());\n\n return {\n command: sql.split(' ')[0].toUpperCase(),\n rowCount: rows.length,\n oid: null,\n fields:\n rows.length > 0\n ? Object.keys(rows[0]).map((name) => ({\n name,\n tableID: 0,\n columnID: 0,\n dataTypeID: 0,\n dataTypeSize: -1,\n dataTypeModifier: -1,\n format: 'text',\n }))\n : [],\n rows,\n };\n } catch (e) {\n throw wrapDatabaseError('Failed to execute raw query', e, {\n sql,\n args,\n });\n }\n };\n\n // Shorthand aliases for query methods\n const oo = many; // (o)bjective-(o)bjects: returns multiple rows\n const oO = single; // (o)bjective-(O)bject: returns a single row\n const ox = pluck; // (o)bjective-(x): returns a single value\n const xx = execute; // e(x)ecute-e(x)ecute: executes without returning\n\n /**\n * Synchronizes database schema with provided SQL DDL\n *\n * DuckDB requires UNIQUE constraints to be defined **inline** in CREATE TABLE\n * statements for ON CONFLICT clauses to work. This method automatically\n * transforms UNIQUE indexes to inline constraints before executing the schema.\n *\n * @param schema - SQL schema definition with CREATE TABLE and CREATE INDEX statements\n * @returns Promise that resolves when schema is synchronized\n */\n const syncSchema = async (schema: string): Promise<void> => {\n const statements = schema\n .trim()\n .split(';')\n .filter((stmt) => stmt.trim() !== '');\n\n const createTableStatements: string[] = [];\n const indexStatements: string[] = [];\n\n // Separate CREATE TABLE from CREATE INDEX statements\n for (const stmt of statements) {\n const trimmed = stmt.trim();\n if (!trimmed) continue;\n\n if (\n trimmed.startsWith('CREATE INDEX') ||\n trimmed.startsWith('CREATE UNIQUE INDEX')\n ) {\n indexStatements.push(trimmed);\n } else if (trimmed.startsWith('CREATE TABLE')) {\n createTableStatements.push(trimmed);\n }\n }\n\n // Process each CREATE TABLE statement\n for (const ddl of createTableStatements) {\n // Transform UNIQUE indexes to inline constraints for DuckDB compatibility\n const { ddl: transformedDDL, indexes: remainingIndexes } =\n convertUniqueIndexesToInlineConstraints(ddl, indexStatements);\n\n // Execute transformed DDL\n try {\n await connection.run(transformedDDL);\n } catch (e) {\n console.error('Schema sync error (CREATE TABLE):', e);\n }\n\n // Execute remaining (non-UNIQUE) indexes for this table\n for (const indexSQL of remainingIndexes) {\n try {\n await connection.run(indexSQL);\n } catch (e) {\n console.error('Schema sync error (CREATE INDEX):', e);\n }\n }\n }\n };\n\n /**\n * Initialize database schemas from JSON manifest\n * Supports dependency resolution and schema overrides\n *\n * @param options - Schema initialization options\n * @returns Promise that resolves when schemas are initialized\n */\n const initializeSchemas = async (\n options: SchemaInitializationOptions,\n ): Promise<void> => {\n const schemaManager = new DatabaseSchemaManager();\n const currentDb: DatabaseInterface = {\n url,\n client: connection,\n query,\n insert,\n update,\n upsert,\n get,\n list,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n tableExists,\n many,\n single,\n pluck,\n execute,\n oo,\n oO,\n ox,\n xx,\n syncSchema,\n };\n\n await schemaManager.initializeSchemas(currentDb, options);\n };\n\n /**\n * Retrieves the schema information for a table\n *\n * @param table - Table name\n * @returns Promise resolving to table schema info or null if table doesn't exist\n * @throws Error if the query fails\n */\n const getTableSchema = async (\n table: string,\n ): Promise<TableSchemaInfo | null> => {\n validateTableName(table);\n\n try {\n // Check if table exists\n const exists = await tableExists(table);\n if (!exists) {\n return null;\n }\n\n // Get column information from information_schema\n const columnRows = await many`\n SELECT\n column_name,\n data_type,\n is_nullable,\n column_default\n FROM information_schema.columns\n WHERE table_name = ${table}\n ORDER BY ordinal_position\n `;\n\n // Get primary key columns from DuckDB system tables\n const pkRows = await many`\n SELECT column_name\n FROM duckdb_constraints() con\n JOIN duckdb_columns() cols\n ON con.table_oid = cols.table_oid\n WHERE con.table_name = ${table}\n AND con.constraint_type = 'PRIMARY KEY'\n AND cols.column_name = ANY(con.constraint_column_names)\n `;\n\n const pkColumns = new Set(pkRows.map((row) => row.column_name));\n\n const columns: Record<string, ColumnDefinition> = {};\n for (const row of columnRows) {\n const colName = row.column_name as string;\n columns[colName] = {\n type: row.data_type as string,\n primaryKey: pkColumns.has(colName),\n notNull: row.is_nullable === 'NO',\n defaultValue: row.column_default,\n };\n }\n\n // Get index information from duckdb_indexes()\n const indexRows = await many`\n SELECT\n index_name,\n sql\n FROM duckdb_indexes()\n WHERE table_name = ${table}\n AND NOT is_primary\n `;\n\n const indexes: IndexDefinition[] = [];\n for (const row of indexRows) {\n const indexName = row.index_name as string;\n const indexDef = (row.sql as string) || '';\n\n // Parse column names from index definition\n const colMatch = indexDef.match(/\\(([^)]+)\\)/);\n const indexColumns = colMatch\n ? colMatch[1].split(',').map((col) => col.trim())\n : [];\n\n const isUnique = indexDef.toUpperCase().includes('UNIQUE');\n\n indexes.push({\n name: indexName,\n columns: indexColumns,\n unique: isUnique,\n });\n }\n\n // Get foreign key information\n const fkRows = await many`\n SELECT\n constraint_column_names,\n constraint_column_indexes,\n constraint_text\n FROM duckdb_constraints()\n WHERE table_name = ${table}\n AND constraint_type = 'FOREIGN KEY'\n `;\n\n const foreignKeys: Array<{\n column: string;\n referencesTable: string;\n referencesColumn: string;\n onDelete?: string;\n onUpdate?: string;\n }> = [];\n\n for (const fkRow of fkRows) {\n // Parse foreign key constraint text to extract referenced table and column\n const fkText = (fkRow.constraint_text as string) || '';\n const referencesMatch = fkText.match(\n /REFERENCES\\s+(\\w+)\\s*\\(([^)]+)\\)/i,\n );\n\n if (\n referencesMatch &&\n Array.isArray(fkRow.constraint_column_names) &&\n fkRow.constraint_column_names.length > 0\n ) {\n const columnName = fkRow.constraint_column_names[0];\n const referencedTable = referencesMatch[1];\n const referencedColumn = referencesMatch[2].trim();\n\n const onDeleteMatch = fkText.match(/ON DELETE\\s+(\\w+)/i);\n const onUpdateMatch = fkText.match(/ON UPDATE\\s+(\\w+)/i);\n\n foreignKeys.push({\n column: columnName,\n referencesTable: referencedTable,\n referencesColumn: referencedColumn,\n onDelete: onDeleteMatch ? onDeleteMatch[1] : undefined,\n onUpdate: onUpdateMatch ? onUpdateMatch[1] : undefined,\n });\n }\n }\n\n return {\n tableName: table,\n columns,\n indexes,\n foreignKeys,\n };\n } catch (e) {\n throw new DatabaseError('Failed to retrieve table schema', {\n table,\n originalError: formatDbError(e),\n });\n }\n };\n\n /**\n * ALTER TABLE operations for schema evolution\n */\n const alterTable = {\n /**\n * Adds a new column to an existing table\n *\n * @param table - Table name\n * @param column - Column definition with name\n * @returns Promise that resolves when column is added\n * @throws Error if the alter operation fails\n */\n addColumn: async (\n table: string,\n column: ColumnDefinitionWithName,\n ): Promise<void> => {\n validateTableName(table);\n validateColumnName(column.name);\n\n let sql: string | undefined;\n try {\n sql = generateAddColumnStatement(table, column, 'duckdb');\n await connection.run(sql);\n } catch (e) {\n throw wrapDatabaseError('Failed to add column to table', e, {\n table,\n column: column.name,\n ...(sql ? { sql } : {}),\n });\n }\n },\n\n /**\n * Adds a new index to an existing table\n *\n * @param table - Table name\n * @param index - Index definition\n * @returns Promise that resolves when index is created\n * @throws Error if the create index operation fails\n */\n addIndex: async (table: string, index: IndexDefinition): Promise<void> => {\n validateTableName(table);\n validateIndexName(index.name);\n\n for (const col of index.columns) {\n validatePlainColumnName(col);\n }\n\n let sql: string | undefined;\n try {\n sql = generateCreateIndexStatement(table, index, 'duckdb');\n await connection.run(sql);\n } catch (e) {\n throw wrapDatabaseError('Failed to create index on table', e, {\n table,\n index: index.name,\n ...(sql ? { sql } : {}),\n });\n }\n },\n };\n\n /**\n * Executes a callback within a database transaction\n * Automatically commits on success or rolls back on error\n *\n * @param callback - Function to execute within transaction\n * @returns Promise resolving to callback result\n */\n const transaction = async <T>(\n callback: (tx: DatabaseInterface) => Promise<T>,\n ): Promise<T> =>\n // Held across the whole BEGIN … COMMIT/ROLLBACK span. Without it two\n // overlapping calls raced on the one connection: the second BEGIN threw,\n // its catch ran ROLLBACK, and that rollback ended the *first* transaction\n // — half of its writes durable, half lost, and its promise rejected, so\n // the caller was told nothing had happened.\n connectionLock.run(async () => {\n try {\n await connection.run('BEGIN TRANSACTION');\n\n const result = await callback(createTransactionScope());\n await connection.run('COMMIT');\n return result;\n } catch (error) {\n // A failing ROLLBACK must not replace the caller's error: DuckDB reports\n // \"cannot rollback - no transaction is active\" whenever the transaction\n // is already gone, which says nothing about what actually failed.\n try {\n await connection.run('ROLLBACK');\n } catch {\n // Nothing left to roll back.\n }\n throw error;\n }\n });\n\n /**\n * Builds the transaction-scoped interface handed to a transaction callback.\n *\n * The only difference from the top-level interface is `transaction`, which\n * refuses to nest. DuckDB has no SAVEPOINT, so there is no way to re-enter\n * the transaction already in progress; re-exposing the top-level\n * `transaction` (the previous behaviour) sent the nested call into a second\n * BEGIN on the same connection, which throws and then rolls back the\n * *enclosing* transaction, silently discarding its work.\n */\n const createTransactionScope = (): DatabaseInterface => {\n const txDb: DatabaseInterface = {\n url,\n client: connection,\n insert,\n get,\n list,\n update,\n upsert,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n many,\n single,\n pluck,\n execute,\n query,\n oo,\n oO,\n ox,\n xx,\n tableExists,\n syncSchema,\n transaction: async () => {\n throw new NestedTransactionError(\n 'Nested transactions are not supported by this adapter because its engine has no SAVEPOINT. Pass the existing transaction to the callee instead of opening a new one.',\n { adapter: 'duckdb' },\n );\n },\n };\n\n return txDb;\n };\n\n /**\n * Begins a new transaction and returns a handle for manual control\n *\n * Unlike transaction(), this gives you explicit control over commit/rollback.\n * Ideal for test isolation where you want to rollback after each test.\n *\n * @returns Promise resolving to a TransactionHandle\n */\n const beginTransaction = async (): Promise<TransactionHandle> => {\n // The handle owns the connection until the caller ends it, so the lock is\n // held across the gap rather than around a single call. A handle that is\n // never committed or rolled back therefore blocks every later transaction\n // until the queue timeout reports it.\n const releaseConnection = await connectionLock.acquire();\n try {\n await connection.run('BEGIN TRANSACTION');\n } catch (error) {\n // No transaction was opened, so there is no handle to end it and nothing\n // left to release the connection.\n releaseConnection();\n throw error;\n }\n\n let active = true;\n\n // COMMIT and ROLLBACK can both throw, and the transaction is over either\n // way, so the connection goes back before the error is rethrown.\n const end = async (command: 'COMMIT' | 'ROLLBACK'): Promise<void> => {\n if (!active) {\n throw new DatabaseError('Transaction already ended', {});\n }\n try {\n await connection.run(command);\n } catch (error) {\n // COMMIT can fail and leave the transaction *open* — SQLite documents\n // exactly that for SQLITE_BUSY. Releasing the connection then would hand\n // the next queued caller a connection still inside a transaction: its\n // BEGIN would throw, and its catch would ROLLBACK, discarding this\n // transaction's work. So normalize before releasing, the way the pooled\n // adapter's discardTxClient does.\n try {\n await connection.run('ROLLBACK');\n } catch {\n // Already gone; nothing left to normalize.\n }\n throw error;\n } finally {\n active = false;\n releaseConnection();\n }\n };\n\n const commit = (): Promise<void> => end('COMMIT');\n\n const rollback = (): Promise<void> => end('ROLLBACK');\n\n const isActive = (): boolean => active;\n\n // Create a transaction-scoped database interface with commit/rollback.\n // The handle is inside a transaction for the same reason a callback\n // scope is, so it gets the same non-nesting `transaction`.\n const txHandle: TransactionHandle = {\n ...createTransactionScope(),\n commit,\n rollback,\n isActive,\n };\n\n return txHandle;\n };\n\n return {\n url,\n requiresSchemaCheck: true,\n client: connection,\n query,\n insert,\n update,\n upsert,\n get,\n list,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n tableExists,\n many,\n single,\n pluck,\n execute,\n oo,\n oO,\n ox,\n xx,\n syncSchema,\n initializeSchemas,\n transaction,\n beginTransaction,\n getTableSchema,\n alterTable,\n close: async () => {\n await closeResources();\n },\n // DuckDB-specific export method\n exportTable,\n } as DatabaseInterface & { exportTable: (table: string) => Promise<void> };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwDA,eAAe,wBACb,YACA,SACe;CACf,KAAK,MAAM,CAAC,WAAW,WAAW,OAAO,QAAQ,OAAO,GACtD,IAAI;EAOF,KAFa,MAHQ,WAAW,cAC9B,+DAA+D,oBAAoB,SAAS,EAAE,EAChG,EAAA,CACoB,cAEhB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AAM,WAAW,IAAI,mBAAmB;EAC1C,SAAS,OAAO;GAGd,kBAAkB;GAClB,MAAM;EACR;EAEA,IAAI,SAAS;EAIb,MAAM,MAAM,OAAO,YAAkD;GACnE,IAAI,CAAC,QACH,MAAM,IAAI,cAAc,6BAA6B,CAAC,CAAC;GAEzD,IAAI;IACF,MAAM,WAAW,IAAI,OAAO;GAC9B,SAAS,OAAO;IAOd,IAAI;KACF,MAAM,WAAW,IAAI,UAAU;IACjC,QAAQ,CAER;IACA,MAAM;GACR,UAAU;IACR,SAAS;IACT,kBAAkB;GACpB;EACF;EAEA,MAAM,eAA8B,IAAI,QAAQ;EAEhD,MAAM,iBAAgC,IAAI,UAAU;EAEpD,MAAM,iBAA0B;EAYhC,OAAO;GANL,GAAG,uBAAuB;GAC1B;GACA;GACA;EAGK;CACT;CAEA,OAAO;EACL;EACA,qBAAqB;EACrB,QAAQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO,YAAY;GACjB,MAAM,eAAe;EACvB;EAEA;CACF;AACF"}
|
|
@@ -1,227 +1,5 @@
|
|
|
1
|
-
import { c as
|
|
1
|
+
import { C as validateColumnNames, E as validateTableName, S as validateColumnName, T as validatePlainColumnName, _ as quoteLiteralIdentifier, c as rewriteSqlParameters, f as generateAddColumnStatement, i as formatDbError, n as buildAdapterWhere, p as generateCreateIndexStatement, s as resolveInsertColumns, u as wrapDatabaseError, v as quotePostgresColumnName, w as validateIndexName, x as renderIdentifier } from "./schema-manager-psLzQ2yh.js";
|
|
2
2
|
import { DatabaseError } from "@happyvertical/utils";
|
|
3
|
-
//#region src/shared/alter-utils.ts
|
|
4
|
-
/**
|
|
5
|
-
* Generates an ALTER TABLE ADD COLUMN statement
|
|
6
|
-
*
|
|
7
|
-
* @param table - Table name
|
|
8
|
-
* @param column - Column definition with name
|
|
9
|
-
* @param dialect - Database dialect
|
|
10
|
-
* @returns SQL statement string
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* ```typescript
|
|
14
|
-
* const sql = generateAddColumnStatement('users', {
|
|
15
|
-
* name: 'email',
|
|
16
|
-
* type: 'TEXT',
|
|
17
|
-
* unique: true,
|
|
18
|
-
* notNull: false
|
|
19
|
-
* }, 'sqlite');
|
|
20
|
-
* // Returns: "ALTER TABLE users ADD COLUMN email TEXT UNIQUE"
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
function generateAddColumnStatement(table, column, _dialect) {
|
|
24
|
-
const parts = [column.name, column.type];
|
|
25
|
-
if (column.primaryKey) parts.push("PRIMARY KEY");
|
|
26
|
-
if (column.notNull) parts.push("NOT NULL");
|
|
27
|
-
if (column.unique) parts.push("UNIQUE");
|
|
28
|
-
if (column.defaultValue !== void 0) {
|
|
29
|
-
const defaultClause = generateDefaultClause(column.type, column.defaultValue);
|
|
30
|
-
parts.push(`DEFAULT ${defaultClause}`);
|
|
31
|
-
}
|
|
32
|
-
if (column.check) parts.push(`CHECK (${column.check})`);
|
|
33
|
-
if (column.foreignKey) {
|
|
34
|
-
const fk = column.foreignKey;
|
|
35
|
-
const fkParts = [`REFERENCES ${fk.table}(${fk.column})`];
|
|
36
|
-
if (fk.onDelete) fkParts.push(`ON DELETE ${fk.onDelete}`);
|
|
37
|
-
if (fk.onUpdate) fkParts.push(`ON UPDATE ${fk.onUpdate}`);
|
|
38
|
-
parts.push(fkParts.join(" "));
|
|
39
|
-
}
|
|
40
|
-
return `ALTER TABLE ${table} ADD COLUMN ${parts.join(" ")}`;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Generates a DEFAULT clause for a column definition
|
|
44
|
-
*
|
|
45
|
-
* Handles proper formatting and escaping of default values based on column type.
|
|
46
|
-
*
|
|
47
|
-
* @param columnType - SQL column type (TEXT, INTEGER, BOOLEAN, etc.)
|
|
48
|
-
* @param defaultValue - Default value to format
|
|
49
|
-
* @returns Formatted default value string
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```typescript
|
|
53
|
-
* generateDefaultClause('TEXT', 'hello'); // Returns: "'hello'"
|
|
54
|
-
* generateDefaultClause('INTEGER', 42); // Returns: "42"
|
|
55
|
-
* generateDefaultClause('BOOLEAN', true); // Returns: "true"
|
|
56
|
-
* generateDefaultClause('TEXT', null); // Returns: "NULL"
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
|
-
function generateDefaultClause(columnType, defaultValue) {
|
|
60
|
-
if (defaultValue === null) return "NULL";
|
|
61
|
-
const typeUpper = columnType.toUpperCase();
|
|
62
|
-
if (typeUpper.includes("TEXT") || typeUpper.includes("CHAR") || typeUpper.includes("VARCHAR") || typeUpper.includes("STRING")) {
|
|
63
|
-
if (defaultValue === "") return "''";
|
|
64
|
-
return `'${String(defaultValue).replace(/'/g, "''")}'`;
|
|
65
|
-
}
|
|
66
|
-
if (typeUpper.includes("BOOL")) return defaultValue ? "true" : "false";
|
|
67
|
-
if (typeUpper.includes("INT") || typeUpper.includes("REAL") || typeUpper.includes("FLOAT") || typeUpper.includes("DOUBLE") || typeUpper.includes("NUMERIC") || typeUpper.includes("DECIMAL")) return String(defaultValue);
|
|
68
|
-
if (typeUpper.includes("JSON")) {
|
|
69
|
-
if (typeof defaultValue === "string") return `'${defaultValue.replace(/'/g, "''")}'`;
|
|
70
|
-
return `'${JSON.stringify(defaultValue).replace(/'/g, "''")}'`;
|
|
71
|
-
}
|
|
72
|
-
if (typeUpper.includes("DATE") || typeUpper.includes("TIME") || typeUpper.includes("TIMESTAMP")) {
|
|
73
|
-
if (defaultValue instanceof Date) return `'${defaultValue.toISOString()}'`;
|
|
74
|
-
return `'${String(defaultValue).replace(/'/g, "''")}'`;
|
|
75
|
-
}
|
|
76
|
-
if (typeof defaultValue === "string") return `'${defaultValue.replace(/'/g, "''")}'`;
|
|
77
|
-
return String(defaultValue);
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Generates a CREATE INDEX statement
|
|
81
|
-
*
|
|
82
|
-
* @param table - Table name
|
|
83
|
-
* @param index - Index definition
|
|
84
|
-
* @returns SQL CREATE INDEX statement
|
|
85
|
-
*
|
|
86
|
-
* @example
|
|
87
|
-
* ```typescript
|
|
88
|
-
* const sql = generateCreateIndexStatement('users', {
|
|
89
|
-
* name: 'idx_users_email',
|
|
90
|
-
* columns: ['email'],
|
|
91
|
-
* unique: true
|
|
92
|
-
* });
|
|
93
|
-
* // Returns: "CREATE UNIQUE INDEX idx_users_email ON users (email)"
|
|
94
|
-
* ```
|
|
95
|
-
*/
|
|
96
|
-
function generateCreateIndexStatement(table, index) {
|
|
97
|
-
const parts = ["CREATE"];
|
|
98
|
-
if (index.unique) parts.push("UNIQUE");
|
|
99
|
-
parts.push("INDEX");
|
|
100
|
-
parts.push(index.name);
|
|
101
|
-
parts.push(`ON ${table}`);
|
|
102
|
-
const columns = index.columns.join(", ");
|
|
103
|
-
parts.push(`(${columns})`);
|
|
104
|
-
if (index.where) parts.push(`WHERE ${index.where}`);
|
|
105
|
-
return parts.join(" ");
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Validates a table name to prevent SQL injection
|
|
109
|
-
*
|
|
110
|
-
* The argument must be a primitive string. `RegExp.prototype.test` coerces its
|
|
111
|
-
* argument with `toString`, so an object whose `toString` returns a valid name
|
|
112
|
-
* on the call the validator makes and a different one on the call the caller's
|
|
113
|
-
* `${table}` interpolation makes would pass here and then reach SQL. Rejecting
|
|
114
|
-
* non-strings up front closes that gap: the value validated is the value
|
|
115
|
-
* interpolated, because a primitive string cannot observe how many times it is
|
|
116
|
-
* read.
|
|
117
|
-
*
|
|
118
|
-
* @param tableName - Table name to validate
|
|
119
|
-
* @throws Error if the value is not a string or contains invalid characters
|
|
120
|
-
*/
|
|
121
|
-
function validateTableName(tableName) {
|
|
122
|
-
if (typeof tableName !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) throw new Error(`Invalid table name: ${tableName}. Table names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`);
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Validates a column name to prevent SQL injection
|
|
126
|
-
*
|
|
127
|
-
* Rejects non-strings for the same reason as {@link validateTableName}: a value
|
|
128
|
-
* whose `toString` differs between the validation read and the interpolation
|
|
129
|
-
* read would otherwise slip a different identifier into SQL than the one
|
|
130
|
-
* checked here.
|
|
131
|
-
*
|
|
132
|
-
* @param columnName - Column name to validate
|
|
133
|
-
* @throws Error if the value is not a string or contains invalid characters
|
|
134
|
-
*/
|
|
135
|
-
function validateColumnName(columnName) {
|
|
136
|
-
if (typeof columnName !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(columnName)) throw new Error(`Invalid column name: ${columnName}. Column names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`);
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* Validates every identifier in a column list to prevent SQL injection
|
|
140
|
-
*
|
|
141
|
-
* Column names reaching the CRUD methods come from `Object.keys(data)` and the
|
|
142
|
-
* caller's `conflictColumns`, both of which are interpolated into SQL. The
|
|
143
|
-
* accepted shape has no character that can end an identifier. Adapters may
|
|
144
|
-
* render a validated name bare, or quote it under an adapter-specific contract.
|
|
145
|
-
* PostgreSQL upsert uses {@link quotePostgresColumnName}, which canonicalizes
|
|
146
|
-
* the name before quoting so its established unquoted case-folding semantics
|
|
147
|
-
* do not change.
|
|
148
|
-
*
|
|
149
|
-
* @param columnNames - Column names to validate
|
|
150
|
-
* @throws Error if any column name contains invalid characters
|
|
151
|
-
*/
|
|
152
|
-
function validateColumnNames(columnNames) {
|
|
153
|
-
for (const columnName of columnNames) validateColumnName(columnName);
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Quotes a validated column name using PostgreSQL's historic case semantics.
|
|
157
|
-
*
|
|
158
|
-
* PostgreSQL folds every unquoted identifier to lowercase. The CRUD API has
|
|
159
|
-
* always accepted mixed-case inputs while rendering them unquoted, so quoting
|
|
160
|
-
* the caller's spelling directly would silently change which physical column
|
|
161
|
-
* is addressed. Validate the existing plain-identifier contract first, then
|
|
162
|
-
* lowercase before quoting: `mixedCase` still addresses `mixedcase`, while a
|
|
163
|
-
* reserved word such as `end` is no longer parsed as SQL syntax.
|
|
164
|
-
*
|
|
165
|
-
* @param columnName - Plain column name to render for PostgreSQL
|
|
166
|
-
* @returns A lowercase, double-quoted PostgreSQL identifier
|
|
167
|
-
* @throws Error if the column name is outside the CRUD identifier contract
|
|
168
|
-
*/
|
|
169
|
-
function quotePostgresColumnName(columnName) {
|
|
170
|
-
validateColumnName(columnName);
|
|
171
|
-
return `"${columnName.toLowerCase()}"`;
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Escapes an identifier for interpolation inside double quotes
|
|
175
|
-
*
|
|
176
|
-
* For the positions that already quote the identifier — the DuckDB and JSON
|
|
177
|
-
* upsert statements, which quote to match their schema generator — quoting is
|
|
178
|
-
* what makes the identifier safe, so the only thing that has to be handled is
|
|
179
|
-
* a quote character inside the name. Doubling it is the SQL escape.
|
|
180
|
-
*
|
|
181
|
-
* This is deliberately more permissive than {@link validateColumnName}: those
|
|
182
|
-
* adapters accept column names that are not plain identifiers (`Full Name`,
|
|
183
|
-
* `user-id`, `2024_total`), which matters most for the JSON adapter, whose
|
|
184
|
-
* columns come straight from the keys of whatever JSON it was pointed at.
|
|
185
|
-
* Rejecting them would break working code to fix an injection that quoting
|
|
186
|
-
* already prevents.
|
|
187
|
-
*
|
|
188
|
-
* @param identifier - Identifier to place inside double quotes
|
|
189
|
-
* @returns The identifier with embedded quotes doubled
|
|
190
|
-
* @throws Error if the identifier is empty or contains a NUL byte
|
|
191
|
-
*/
|
|
192
|
-
function escapeQuotedIdentifier(identifier) {
|
|
193
|
-
const value = String(identifier);
|
|
194
|
-
if (value.length === 0 || value.includes("\0")) throw new Error(`Invalid column name: ${JSON.stringify(value)}. Column names must be non-empty and must not contain a NUL byte.`);
|
|
195
|
-
return value.replaceAll("\"", "\"\"");
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Escapes a value for interpolation inside a single-quoted SQL string literal
|
|
199
|
-
*
|
|
200
|
-
* The DuckDB-backed adapters read JSON through `read_json_auto('<path>')`, and
|
|
201
|
-
* a file path is not something an identifier validator can check — paths
|
|
202
|
-
* legitimately contain spaces, dots and, on Linux and macOS, quotes. Doubling
|
|
203
|
-
* the quote is the SQL escape, and it is what keeps a file named `x'.json`
|
|
204
|
-
* from ending the literal and starting a statement.
|
|
205
|
-
*
|
|
206
|
-
* @param value - Value to place inside single quotes
|
|
207
|
-
* @returns The value with embedded single quotes doubled
|
|
208
|
-
* @throws Error if the value contains a NUL byte
|
|
209
|
-
*/
|
|
210
|
-
function escapeStringLiteral(value) {
|
|
211
|
-
const text = String(value);
|
|
212
|
-
if (text.includes("\0")) throw new Error(`Invalid SQL string literal: ${JSON.stringify(text)}. Values must not contain a NUL byte.`);
|
|
213
|
-
return text.replaceAll("'", "''");
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Validates an index name to prevent SQL injection
|
|
217
|
-
*
|
|
218
|
-
* @param indexName - Index name to validate
|
|
219
|
-
* @throws Error if index name contains invalid characters
|
|
220
|
-
*/
|
|
221
|
-
function validateIndexName(indexName) {
|
|
222
|
-
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.`);
|
|
223
|
-
}
|
|
224
|
-
//#endregion
|
|
225
3
|
//#region src/shared/connection-cache.ts
|
|
226
4
|
var CACHED_VALIDATION_CAPABILITY = Symbol.for("@happyvertical/sql/connection-cache-cached-validation/v1");
|
|
227
5
|
/** Race-safe async resource cache used by database adapters. */
|
|
@@ -645,10 +423,10 @@ function vectorOperator(metric) {
|
|
|
645
423
|
}
|
|
646
424
|
function getMaxPostgresParameterIndex(sql) {
|
|
647
425
|
let maxIndex = 0;
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
}
|
|
426
|
+
rewriteSqlParameters(sql, "postgres", (token, index) => {
|
|
427
|
+
if (index !== void 0 && Number.isSafeInteger(index) && index > maxIndex) maxIndex = index;
|
|
428
|
+
return token;
|
|
429
|
+
});
|
|
652
430
|
return maxIndex;
|
|
653
431
|
}
|
|
654
432
|
function usesSingleArrayParameter(sql) {
|
|
@@ -666,91 +444,13 @@ function normalizeRawQueryValues(sql, values) {
|
|
|
666
444
|
return values;
|
|
667
445
|
}
|
|
668
446
|
function rewriteQuestionMarkPlaceholders(sql) {
|
|
669
|
-
let output = "";
|
|
670
447
|
let count = 0;
|
|
671
|
-
let index = 0;
|
|
672
|
-
const copyQuoted = (quote, escaped = false) => {
|
|
673
|
-
output += quote;
|
|
674
|
-
index += 1;
|
|
675
|
-
while (index < sql.length) {
|
|
676
|
-
const char = sql[index];
|
|
677
|
-
output += char;
|
|
678
|
-
index += 1;
|
|
679
|
-
if (escaped && char === "\\" && index < sql.length) {
|
|
680
|
-
output += sql[index];
|
|
681
|
-
index += 1;
|
|
682
|
-
continue;
|
|
683
|
-
}
|
|
684
|
-
if (char === quote) {
|
|
685
|
-
if (sql[index] === quote) {
|
|
686
|
-
output += sql[index];
|
|
687
|
-
index += 1;
|
|
688
|
-
continue;
|
|
689
|
-
}
|
|
690
|
-
break;
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
};
|
|
694
|
-
const copyUntil = (end) => {
|
|
695
|
-
const endIndex = sql.indexOf(end, index + end.length);
|
|
696
|
-
if (endIndex === -1) {
|
|
697
|
-
output += sql.slice(index);
|
|
698
|
-
index = sql.length;
|
|
699
|
-
return;
|
|
700
|
-
}
|
|
701
|
-
output += sql.slice(index, endIndex + end.length);
|
|
702
|
-
index = endIndex + end.length;
|
|
703
|
-
};
|
|
704
|
-
while (index < sql.length) {
|
|
705
|
-
const char = sql[index];
|
|
706
|
-
const next = sql[index + 1];
|
|
707
|
-
if ((char === "E" || char === "e") && next === "'") {
|
|
708
|
-
output += char;
|
|
709
|
-
index += 1;
|
|
710
|
-
copyQuoted("'", true);
|
|
711
|
-
continue;
|
|
712
|
-
}
|
|
713
|
-
if (char === "'") {
|
|
714
|
-
copyQuoted("'");
|
|
715
|
-
continue;
|
|
716
|
-
}
|
|
717
|
-
if (char === "\"") {
|
|
718
|
-
copyQuoted("\"");
|
|
719
|
-
continue;
|
|
720
|
-
}
|
|
721
|
-
if (char === "-" && next === "-") {
|
|
722
|
-
const endIndex = sql.indexOf("\n", index + 2);
|
|
723
|
-
if (endIndex === -1) {
|
|
724
|
-
output += sql.slice(index);
|
|
725
|
-
index = sql.length;
|
|
726
|
-
} else {
|
|
727
|
-
output += sql.slice(index, endIndex + 1);
|
|
728
|
-
index = endIndex + 1;
|
|
729
|
-
}
|
|
730
|
-
continue;
|
|
731
|
-
}
|
|
732
|
-
if (char === "/" && next === "*") {
|
|
733
|
-
copyUntil("*/");
|
|
734
|
-
continue;
|
|
735
|
-
}
|
|
736
|
-
if (char === "$") {
|
|
737
|
-
const tag = sql.slice(index).match(/^\$[A-Za-z_][\w$]*\$|^\$\$/);
|
|
738
|
-
if (tag) {
|
|
739
|
-
copyUntil(tag[0]);
|
|
740
|
-
continue;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
if (char === "?" && next !== "|" && next !== "&") {
|
|
744
|
-
count += 1;
|
|
745
|
-
output += `$${count}`;
|
|
746
|
-
index += 1;
|
|
747
|
-
continue;
|
|
748
|
-
}
|
|
749
|
-
output += char;
|
|
750
|
-
index += 1;
|
|
751
|
-
}
|
|
752
448
|
return {
|
|
753
|
-
sql:
|
|
449
|
+
sql: rewriteSqlParameters(sql, "postgres", (token, index) => {
|
|
450
|
+
if (index !== void 0) return token;
|
|
451
|
+
count += 1;
|
|
452
|
+
return `$${count}`;
|
|
453
|
+
}),
|
|
754
454
|
count
|
|
755
455
|
};
|
|
756
456
|
}
|
|
@@ -843,7 +543,7 @@ function createVectorCapabilities(pool) {
|
|
|
843
543
|
validateColumnName(column);
|
|
844
544
|
try {
|
|
845
545
|
await pool.query("CREATE EXTENSION IF NOT EXISTS vector");
|
|
846
|
-
await pool.query(`ALTER TABLE
|
|
546
|
+
await pool.query(`ALTER TABLE ${quoteLiteralIdentifier(table)} ADD COLUMN IF NOT EXISTS ${renderIdentifier(column, void 0, { quoteIdentifiers: true })} vector(${dimensions})`);
|
|
847
547
|
} catch (e) {
|
|
848
548
|
throw new DatabaseError("Failed to ensure vector column", {
|
|
849
549
|
table,
|
|
@@ -873,7 +573,7 @@ function createVectorCapabilities(pool) {
|
|
|
873
573
|
const opsClass = vectorOpsClass(metric);
|
|
874
574
|
const indexName = `idx_${table}_${column}_${metric}_${indexType}`;
|
|
875
575
|
try {
|
|
876
|
-
await pool.query(`CREATE INDEX IF NOT EXISTS
|
|
576
|
+
await pool.query(`CREATE INDEX IF NOT EXISTS ${quoteLiteralIdentifier(indexName)} ON ${quoteLiteralIdentifier(table)} USING ${indexType} (${renderIdentifier(column, void 0, { quoteIdentifiers: true })} ${opsClass})`);
|
|
877
577
|
} catch (e) {
|
|
878
578
|
throw new DatabaseError("Failed to ensure vector index", {
|
|
879
579
|
table,
|
|
@@ -889,10 +589,10 @@ function createVectorCapabilities(pool) {
|
|
|
889
589
|
const keys = Object.keys(where);
|
|
890
590
|
validateColumnNames(keys);
|
|
891
591
|
const values = Object.values(where);
|
|
892
|
-
const conditions = keys.map((key, i) =>
|
|
592
|
+
const conditions = keys.map((key, i) => `${renderIdentifier(key, void 0, { quoteIdentifiers: true })} IS NOT DISTINCT FROM $${i + 1}`).join(" AND ");
|
|
893
593
|
const vectorParam = `$${values.length + 1}`;
|
|
894
594
|
try {
|
|
895
|
-
await pool.query(`UPDATE
|
|
595
|
+
await pool.query(`UPDATE ${quoteLiteralIdentifier(table)} SET ${renderIdentifier(column, void 0, { quoteIdentifiers: true })} = ${vectorParam}::vector WHERE ${conditions}`, [...values, toVectorLiteral(embedding)]);
|
|
896
596
|
} catch (e) {
|
|
897
597
|
throw new DatabaseError("Failed to upsert vector", {
|
|
898
598
|
table,
|
|
@@ -909,14 +609,14 @@ function createVectorCapabilities(pool) {
|
|
|
909
609
|
const limit = options?.limit || 10;
|
|
910
610
|
const op = vectorOperator(metric);
|
|
911
611
|
const queryParams = [toVectorLiteral(embedding)];
|
|
912
|
-
let whereClause =
|
|
612
|
+
let whereClause = `${renderIdentifier(column, void 0, { quoteIdentifiers: true })} IS NOT NULL`;
|
|
913
613
|
if (options?.where) {
|
|
914
614
|
whereClause += ` AND (${options.where})`;
|
|
915
615
|
if (options.params) queryParams.push(...options.params);
|
|
916
616
|
}
|
|
917
617
|
const limitParam = `$${queryParams.length + 1}`;
|
|
918
618
|
queryParams.push(limit);
|
|
919
|
-
const sql = `SELECT *, (
|
|
619
|
+
const sql = `SELECT *, (${renderIdentifier(column, void 0, { quoteIdentifiers: true })} ${op} $1::vector) AS distance FROM ${quoteLiteralIdentifier(table)} WHERE ${whereClause} ORDER BY ${renderIdentifier(column, void 0, { quoteIdentifiers: true })} ${op} $1::vector LIMIT ${limitParam}`;
|
|
920
620
|
try {
|
|
921
621
|
return (await pool.query(sql, queryParams)).rows.map((row) => ({
|
|
922
622
|
...row,
|
|
@@ -1224,7 +924,7 @@ function createPostgresDialect(host) {
|
|
|
1224
924
|
const keys = resolveInsertColumns(table, serializedRecords);
|
|
1225
925
|
validateColumnNames(keys);
|
|
1226
926
|
const placeholders = serializedRecords.map((_, i) => `(${keys.map((_, j) => `$${i * keys.length + j + 1}`).join(", ")})`).join(", ");
|
|
1227
|
-
const query = `INSERT INTO ${table} (${keys.join(", ")}) VALUES ${placeholders}`;
|
|
927
|
+
const query = `INSERT INTO ${table} (${keys.map((key) => quotePostgresColumnName(key)).join(", ")}) VALUES ${placeholders}`;
|
|
1228
928
|
const values = serializedRecords.flatMap((row) => keys.map((key) => row[key]));
|
|
1229
929
|
return {
|
|
1230
930
|
operation: "insert",
|
|
@@ -1236,7 +936,7 @@ function createPostgresDialect(host) {
|
|
|
1236
936
|
validateColumnNames(keys);
|
|
1237
937
|
const values = Object.values(serializedData);
|
|
1238
938
|
const placeholders = keys.map((_, i) => `$${i + 1}`).join(", ");
|
|
1239
|
-
const query = `INSERT INTO ${table} (${keys.join(", ")}) VALUES (${placeholders})`;
|
|
939
|
+
const query = `INSERT INTO ${table} (${keys.map((key) => quotePostgresColumnName(key)).join(", ")}) VALUES (${placeholders})`;
|
|
1240
940
|
return {
|
|
1241
941
|
operation: "insert",
|
|
1242
942
|
affected: (await executor.query(query, values)).rowCount ?? 0
|
|
@@ -1251,7 +951,7 @@ function createPostgresDialect(host) {
|
|
|
1251
951
|
*/
|
|
1252
952
|
const get = async (table, where) => {
|
|
1253
953
|
validateTableName(table);
|
|
1254
|
-
const { sql: whereClause, values } =
|
|
954
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "postgres");
|
|
1255
955
|
if (!whereClause) throw new DatabaseError("GET requires at least one WHERE condition to prevent returning an arbitrary record", { table });
|
|
1256
956
|
const query = `SELECT * FROM ${table} ${whereClause}`;
|
|
1257
957
|
try {
|
|
@@ -1274,7 +974,7 @@ function createPostgresDialect(host) {
|
|
|
1274
974
|
*/
|
|
1275
975
|
const list = async (table, where) => {
|
|
1276
976
|
validateTableName(table);
|
|
1277
|
-
const { sql: whereClause, values } =
|
|
977
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "postgres");
|
|
1278
978
|
const query = `SELECT * FROM ${table} ${whereClause}`;
|
|
1279
979
|
try {
|
|
1280
980
|
return (await executor.query(query, values)).rows;
|
|
@@ -1301,8 +1001,8 @@ function createPostgresDialect(host) {
|
|
|
1301
1001
|
const keys = Object.keys(serializedData);
|
|
1302
1002
|
validateColumnNames(keys);
|
|
1303
1003
|
const values = Object.values(serializedData);
|
|
1304
|
-
const setClause = keys.map((key, i) => `${key} = $${i + 1}`).join(", ");
|
|
1305
|
-
const { sql: whereClause, values: whereValues } =
|
|
1004
|
+
const setClause = keys.map((key, i) => `${quotePostgresColumnName(key)} = $${i + 1}`).join(", ");
|
|
1005
|
+
const { sql: whereClause, values: whereValues } = buildAdapterWhere(where, values.length + 1, "postgres");
|
|
1306
1006
|
if (!whereClause) throw new DatabaseError("UPDATE requires at least one WHERE condition to prevent accidental update of all records", { table });
|
|
1307
1007
|
const sql = `UPDATE ${table} SET ${setClause} ${whereClause}`;
|
|
1308
1008
|
try {
|
|
@@ -1376,7 +1076,7 @@ function createPostgresDialect(host) {
|
|
|
1376
1076
|
const deleteRecords = async (table, where) => {
|
|
1377
1077
|
validateTableName(table);
|
|
1378
1078
|
if (Object.keys(where).length === 0) throw new DatabaseError("DELETE requires at least one WHERE condition to prevent accidental deletion of all records", { table });
|
|
1379
|
-
const { sql: whereClause, values } =
|
|
1079
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "postgres");
|
|
1380
1080
|
try {
|
|
1381
1081
|
return {
|
|
1382
1082
|
operation: "delete",
|
|
@@ -1405,7 +1105,7 @@ function createPostgresDialect(host) {
|
|
|
1405
1105
|
const result = await executor.query(`SELECT COUNT(*) as count FROM ${table}`);
|
|
1406
1106
|
return Number(result.rows[0]?.count) || 0;
|
|
1407
1107
|
}
|
|
1408
|
-
const { sql: whereClause, values } =
|
|
1108
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "postgres");
|
|
1409
1109
|
const result = await executor.query(`SELECT COUNT(*) as count FROM ${table} ${whereClause}`, values);
|
|
1410
1110
|
return Number(result.rows[0]?.count) || 0;
|
|
1411
1111
|
} catch (e) {
|
|
@@ -1935,10 +1635,10 @@ function createAlterTable(client) {
|
|
|
1935
1635
|
addIndex: async (table, index) => {
|
|
1936
1636
|
validateTableName(table);
|
|
1937
1637
|
validateIndexName(index.name);
|
|
1938
|
-
for (const col of index.columns)
|
|
1638
|
+
for (const col of index.columns) validatePlainColumnName(col);
|
|
1939
1639
|
let sql;
|
|
1940
1640
|
try {
|
|
1941
|
-
sql = generateCreateIndexStatement(table, index);
|
|
1641
|
+
sql = generateCreateIndexStatement(table, index, "postgres");
|
|
1942
1642
|
await client.query(sql);
|
|
1943
1643
|
} catch (e) {
|
|
1944
1644
|
throw wrapDatabaseError("Failed to create index on table", e, {
|
|
@@ -1951,6 +1651,6 @@ function createAlterTable(client) {
|
|
|
1951
1651
|
};
|
|
1952
1652
|
}
|
|
1953
1653
|
//#endregion
|
|
1954
|
-
export {
|
|
1654
|
+
export { createVectorCapabilities as a, createTransactionLock as c, validateDatabaseCacheOptions as d, createTransactionErrorTracker as i, ConnectionCache as l, createGetTableSchema as n, normalizePostgresRawQuery as o, createPostgresDialect as r, DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS as s, createAlterTable as t, enableCachedValidation as u };
|
|
1955
1655
|
|
|
1956
|
-
//# sourceMappingURL=postgres-dialect-
|
|
1656
|
+
//# sourceMappingURL=postgres-dialect-CaNhva-C.js.map
|