@happyvertical/sql 0.74.10 → 0.75.0

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.
@@ -1,5 +1,5 @@
1
1
  import { DatabaseError } from "@happyvertical/utils";
2
- import { r as resolveSchemas, v as validateTableName, a as validateIndexName, b as validateColumnName, g as generateCreateIndexStatement, f as formatDbError, c as generateAddColumnStatement, D as DatabaseSchemaManager, d as buildWhere } from "./index-DrPgGVZz.js";
2
+ import { r as resolveSchemas, v as validateTableName, a as validateIndexName, b as validateColumnName, g as generateCreateIndexStatement, f as formatDbError, c as generateAddColumnStatement, D as DatabaseSchemaManager, d as buildWhere } from "./index-CzdYvRFp.js";
3
3
  const memoryConnectionCache = /* @__PURE__ */ new Map();
4
4
  const pendingConnections = /* @__PURE__ */ new Map();
5
5
  const NULL_AWARE_UPSERT_MAX_ATTEMPTS = 8;
@@ -128,7 +128,7 @@ async function getDatabase(options = {}) {
128
128
  options.dbid = generateDbId();
129
129
  }
130
130
  if (hasNativeSqliteCapabilities(options)) {
131
- const sqliteNative = await import("./sqlite-native-BdArMasZ.js");
131
+ const sqliteNative = await import("./sqlite-native-DqVPKNUu.js");
132
132
  return sqliteNative.getNativeSqliteDatabase(options);
133
133
  }
134
134
  if (options.dbid) {
@@ -934,4 +934,4 @@ async function getDatabase(options = {}) {
934
934
  export {
935
935
  getDatabase
936
936
  };
937
- //# sourceMappingURL=sqlite-Cxjsirpn.js.map
937
+ //# sourceMappingURL=sqlite-CPCNeJIH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-Cxjsirpn.js","sources":["../../src/sqlite.ts"],"sourcesContent":["import { DatabaseError } from '@happyvertical/utils';\nimport type { Client } from '@libsql/client';\nimport { DatabaseSchemaManager } from './schema-manager';\nimport {\n generateAddColumnStatement,\n generateCreateIndexStatement,\n validateColumnName,\n validateIndexName,\n validateTableName,\n} from './shared/alter-utils';\nimport type {\n ColumnDefinition,\n ColumnDefinitionWithName,\n DatabaseInterface,\n IndexDefinition,\n QueryResult,\n SchemaInitializationOptions,\n SqliteCapabilitiesOptions,\n TableInterface,\n TableSchemaInfo,\n TransactionHandle,\n UpsertOptions,\n} from './shared/types';\nimport { resolveSchemas } from './shared/types';\nimport { buildWhere, formatDbError } from './shared/utils';\n\n/**\n * Connection cache for in-memory databases with memoryId\n * Enables sharing of :memory: databases across multiple getDatabase() calls\n */\nconst memoryConnectionCache = new Map<string, DatabaseInterface>();\n\n/**\n * Pending connection promises to handle concurrent getDatabase() calls\n * Prevents creating duplicate connections when parallel calls happen\n */\nconst pendingConnections = new Map<string, Promise<DatabaseInterface>>();\nconst NULL_AWARE_UPSERT_MAX_ATTEMPTS = 8;\nconst NULL_AWARE_UPSERT_BASE_DELAY_MS = 25;\nconst nullAwareUpsertLocks = new Map<string, Promise<void>>();\n\ntype SqliteExecutor = Pick<Client, 'execute'>;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isRetriableSqliteTransactionError(error: unknown): boolean {\n const formatted = formatDbError(error).toLowerCase();\n return (\n formatted.includes('busy') ||\n formatted.includes('locked') ||\n formatted.includes('database is locked')\n );\n}\n\nasync function withNullAwareUpsertLock<T>(\n lockKey: string,\n callback: () => Promise<T>,\n): Promise<T> {\n const previous = nullAwareUpsertLocks.get(lockKey) ?? Promise.resolve();\n let release: () => void = () => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const next = previous.catch(() => {}).then(() => current);\n\n nullAwareUpsertLocks.set(lockKey, next);\n await previous.catch(() => {});\n\n try {\n return await callback();\n } finally {\n release();\n\n if (nullAwareUpsertLocks.get(lockKey) === next) {\n nullAwareUpsertLocks.delete(lockKey);\n }\n }\n}\n\n/**\n * Generates a unique identifier for in-memory databases\n * @returns A unique database identifier string\n */\nfunction generateDbId(): string {\n return `memory-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n\n/**\n * Creates a LibSQL client using the default client implementation\n * Supports in-memory databases and remote LibSQL URLs\n *\n * @param options - SQLite connection options\n * @returns Promise resolving to a LibSQL client instance\n */\nasync function createLibSQLClient(options: SqliteOptions): Promise<Client> {\n const { url = ':memory:', authToken, encryptionKey } = options;\n\n // Normalize URLs: add file:// prefix for local paths\n let libsqlUrl = url;\n if (\n url !== ':memory:' &&\n !url.startsWith('http://') &&\n !url.startsWith('https://') &&\n !url.startsWith('libsql://') &&\n !url.startsWith('file:')\n ) {\n // Local file path - resolve to absolute and add file:// prefix\n const { resolve } = await import('node:path');\n const absolutePath = resolve(url);\n // Use file:// format (file URL scheme with authority component omitted)\n libsqlUrl = `file://${absolutePath}`;\n }\n\n try {\n // Use explicit external import to avoid bundling\n const libsqlClient = '@libsql/client';\n const { createClient } = await import(/* @vite-ignore */ libsqlClient);\n return createClient({ url: libsqlUrl, authToken, encryptionKey });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n // Provide helpful error messages for common issues\n if (errorMessage?.includes('URL_SCHEME_NOT_SUPPORTED')) {\n throw new DatabaseError(\n `Unsupported URL scheme. Use ':memory:' for in-memory databases or 'libsql://' for remote LibSQL databases. Original: ${url}, Converted: ${libsqlUrl}`,\n { url: libsqlUrl, originalError: errorMessage },\n );\n }\n\n // Re-throw other errors with context\n throw new DatabaseError(`Failed to create LibSQL client: ${errorMessage}`, {\n url: libsqlUrl,\n originalError: errorMessage,\n });\n }\n}\n\n/**\n * Configuration options for SQLite database connections\n */\nexport interface SqliteOptions {\n /**\n * Connection URL for SQLite database\n * Supported schemes:\n * - ':memory:' for in-memory databases\n * - 'file:path/to/database.db' for local file databases\n * - 'libsql://...' for remote LibSQL/Turso databases\n */\n url?: string;\n\n /**\n * Authentication token for Turso/LibSQL remote connections\n */\n authToken?: string;\n\n /**\n * Encryption key for encrypted SQLite databases (LibSQL feature)\n */\n encryptionKey?: string;\n\n /**\n * Unique identifier for in-memory databases to enable connection sharing\n * When multiple getDatabase() calls use the same dbid, they receive\n * the same database connection instance.\n *\n * Auto-generated for :memory: databases if not provided.\n */\n dbid?: string;\n\n /**\n * Optional native SQLite capabilities for local development and testing.\n *\n * When any capability is enabled, the adapter uses the internal native\n * SQLite implementation instead of the LibSQL client path. Native\n * capabilities are only supported for local SQLite databases.\n */\n capabilities?: SqliteCapabilitiesOptions;\n\n /**\n * Schema definitions for tables.\n * Accepts a record or a lazy function (see SchemasOption).\n *\n * When provided, these schemas will be used for table creation.\n * Accepts a lazy function to defer schema building until needed.\n */\n schemas?: import('./shared/types').SchemasOption;\n}\n\nfunction hasNativeSqliteCapabilities(options: SqliteOptions): boolean {\n return Boolean(\n options.capabilities?.notifications || options.capabilities?.vector,\n );\n}\n\n/**\n * Creates tables from provided schema definitions\n *\n * @param client - LibSQL client\n * @param schemas - Schema definitions to create\n */\nasync function createTablesFromSchemas(\n client: 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 client.execute({\n sql: `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,\n args: [tableName],\n });\n\n if (result.rows.length > 0) {\n console.log(`[sqlite] Table ${tableName} already exists, skipping`);\n continue;\n }\n\n console.log(`[sqlite] Creating table ${tableName} from provided schema`);\n\n // Create table from DDL\n await client.execute(schema.ddl);\n\n // Create indexes\n if (schema.indexes && schema.indexes.length > 0) {\n for (const indexSQL of schema.indexes) {\n try {\n await client.execute(indexSQL);\n } catch (error) {\n console.warn(\n `[sqlite] 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 client.execute(triggerSQL);\n } catch (error) {\n console.warn(\n `[sqlite] Failed to create trigger for ${tableName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n } catch (error) {\n console.error(\n `[sqlite] Error creating table ${tableName}:`,\n error instanceof Error ? error.message : String(error),\n );\n console.error(`[sqlite] DDL was:`, schema.ddl?.substring(0, 200) + '...');\n throw new DatabaseError(\n `Failed to create table ${tableName} from schema: ${error instanceof Error ? error.message : String(error)}`,\n {\n tableName,\n schema,\n originalError: error instanceof Error ? error.message : String(error),\n },\n );\n }\n }\n}\n\n/**\n * Creates a SQLite database adapter\n *\n * @param options - SQLite connection options\n * @returns Database interface for SQLite\n */\nexport async function getDatabase(\n options: SqliteOptions = {},\n): Promise<DatabaseInterface> {\n const url = options.url || ':memory:';\n\n // Auto-generate dbid for :memory: databases if not provided\n // Mutate options object to ensure child objects reuse the same connection\n if (url === ':memory:' && !options.dbid) {\n options.dbid = generateDbId();\n }\n\n if (hasNativeSqliteCapabilities(options)) {\n const sqliteNative = await import('./sqlite-native.js');\n return sqliteNative.getNativeSqliteDatabase(options);\n }\n\n // Check if we have a cached connection for this dbid\n if (options.dbid) {\n const cached = memoryConnectionCache.get(options.dbid);\n if (cached) {\n return cached;\n }\n\n // Check if there's a pending connection for this dbid\n const pending = pendingConnections.get(options.dbid);\n if (pending) {\n return pending;\n }\n }\n\n // Create a new connection promise\n const connectionPromise = (async () => {\n const client = await createLibSQLClient(options);\n\n // Initialize tables from provided schemas (resolves lazy function if needed)\n const resolvedSchemas = resolveSchemas(options.schemas);\n if (resolvedSchemas && Object.keys(resolvedSchemas).length > 0) {\n await createTablesFromSchemas(client, resolvedSchemas);\n }\n\n /**\n * Serializes a value for SQLite storage\n * Converts objects and arrays to JSON strings\n * Converts Dates to ISO strings\n * Passes through primitives unchanged\n */\n const serializeValue = (value: any): any => {\n if (value === null || value === undefined) {\n return value;\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return value;\n };\n\n /**\n * Serializes all values in an object\n */\n const serializeRecord = (\n record: Record<string, any>,\n ): Record<string, any> => {\n const serialized: Record<string, any> = {};\n for (const [key, value] of Object.entries(record)) {\n // Skip undefined values - they cannot be passed to the database\n if (value === undefined) {\n continue;\n }\n serialized[key] = serializeValue(value);\n }\n return serialized;\n };\n\n const hasNullConflictValue = (\n conflictColumns: string[],\n data: Record<string, any>,\n ): boolean => conflictColumns.some((col) => data[col] === null);\n\n const buildNullAwareUpsertLockKey = (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n ): string => {\n const conflictValues = conflictColumns\n .map((col) => `${col}:${JSON.stringify(data[col])}`)\n .join('|');\n return `${url}:${table}:${conflictValues}`;\n };\n\n const validateUpsertConflictColumns = (\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): void => {\n const missingColumns = conflictColumns.filter(\n (col) => !(col in serializedData),\n );\n\n if (missingColumns.length > 0) {\n throw new DatabaseError('Conflict columns missing from data', {\n table,\n conflictColumns,\n missingColumns,\n availableColumns: Object.keys(serializedData),\n hint: 'All columns specified in ON CONFLICT must be present in the data being inserted. Undefined values are filtered out during serialization - consider using null or an empty string instead.',\n });\n }\n };\n\n const executeStandardUpsert = async (\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): Promise<QueryResult> => {\n const keys = Object.keys(serializedData);\n const values = Object.values(serializedData);\n const placeholders = keys.map(() => '?').join(', ');\n const updateSet = keys\n .map((key) => `${key} = excluded.${key}`)\n .join(', ');\n const conflict = conflictColumns.join(', ');\n const sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders}) ON CONFLICT(${conflict}) DO UPDATE SET ${updateSet}`;\n\n const result = await client.execute({ sql, args: values });\n return { operation: 'upsert', affected: result.rowsAffected };\n };\n\n const executeNullAwareUpsertAttempt = async (\n executor: SqliteExecutor,\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): Promise<QueryResult> => {\n const keys = Object.keys(serializedData);\n const values = Object.values(serializedData);\n const updateSet = keys.map((key) => `${key} = ?`).join(', ');\n const whereClause = conflictColumns\n .map((col) => `${col} IS ?`)\n .join(' AND ');\n const whereValues = conflictColumns.map((col) => serializedData[col]);\n\n const updateSql = `UPDATE ${table} SET ${updateSet} WHERE ${whereClause}`;\n const updateResult = await executor.execute({\n sql: updateSql,\n args: [...values, ...whereValues],\n });\n\n if ((updateResult.rowsAffected ?? 0) > 0) {\n return { operation: 'upsert', affected: updateResult.rowsAffected };\n }\n\n const placeholders = keys.map(() => '?').join(', ');\n const insertSql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders})`;\n const insertResult = await executor.execute({\n sql: insertSql,\n args: values,\n });\n\n return { operation: 'upsert', affected: insertResult.rowsAffected };\n };\n\n const executeNullAwareUpsertWithRetry = async (\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): Promise<QueryResult> => {\n if (url === ':memory:') {\n return executeNullAwareUpsertAttempt(\n client,\n table,\n conflictColumns,\n serializedData,\n );\n }\n\n let lastError: unknown;\n\n for (\n let attempt = 0;\n attempt < NULL_AWARE_UPSERT_MAX_ATTEMPTS;\n attempt++\n ) {\n let transaction: Awaited<ReturnType<Client['transaction']>> | undefined;\n\n try {\n transaction = await client.transaction('write');\n\n const result = await executeNullAwareUpsertAttempt(\n transaction,\n table,\n conflictColumns,\n serializedData,\n );\n\n await transaction.commit();\n return result;\n } catch (error) {\n lastError = error;\n\n if (transaction && !transaction.closed) {\n try {\n await transaction.rollback();\n } catch (_rollbackError) {\n // Preserve the original failure; rollback errors are secondary here.\n }\n }\n } finally {\n transaction?.close();\n }\n\n if (\n lastError &&\n attempt < NULL_AWARE_UPSERT_MAX_ATTEMPTS - 1 &&\n isRetriableSqliteTransactionError(lastError)\n ) {\n await delay(NULL_AWARE_UPSERT_BASE_DELAY_MS * 2 ** attempt);\n continue;\n }\n\n break;\n }\n\n throw lastError;\n };\n\n const executeUpsert = async (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n options: UpsertOptions | undefined,\n acquireTransaction: boolean,\n ): Promise<QueryResult> => {\n const serializedData = serializeRecord(data);\n validateUpsertConflictColumns(table, conflictColumns, serializedData);\n\n if (\n options?.nullsDistinct ||\n !hasNullConflictValue(conflictColumns, serializedData)\n ) {\n return executeStandardUpsert(table, conflictColumns, serializedData);\n }\n\n if (!acquireTransaction) {\n return executeNullAwareUpsertAttempt(\n client,\n table,\n conflictColumns,\n serializedData,\n );\n }\n\n return withNullAwareUpsertLock(\n buildNullAwareUpsertLockKey(table, conflictColumns, serializedData),\n () =>\n executeNullAwareUpsertWithRetry(\n table,\n conflictColumns,\n serializedData,\n ),\n );\n };\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 let sql: string;\n let values: any[];\n\n if (Array.isArray(data)) {\n // Serialize all records in the array\n const serializedRecords: Array<Record<string, any>> = data.map(\n (record) => serializeRecord(record),\n );\n const keys = Object.keys(serializedRecords[0]);\n const placeholders = serializedRecords\n .map(() => `(${keys.map(() => '?').join(', ')})`)\n .join(', ');\n sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES ${placeholders}`;\n // Flatten all values into a single array for batch insert\n const flattenedValues: any[] = [];\n for (const record of serializedRecords) {\n flattenedValues.push(...Object.values(record));\n }\n values = flattenedValues;\n } else {\n // Serialize the single record\n const serializedData = serializeRecord(data);\n const keys = Object.keys(serializedData);\n const placeholders = keys.map(() => '?').join(', ');\n sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders})`;\n values = Object.values(serializedData);\n }\n try {\n const result = await client.execute({ sql: sql, args: values });\n return { operation: 'insert', affected: result.rowsAffected };\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 const { sql: whereClause, values } = buildWhere(where, 1, 'sqlite');\n if (!whereClause) {\n throw new DatabaseError(\n 'GET requires at least one WHERE condition to prevent returning an arbitrary record',\n { table },\n );\n }\n\n const sql = `SELECT * FROM ${table} ${whereClause}`;\n try {\n const result = await client.execute({ sql: sql, args: values });\n return result.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 const { sql: whereClause, values } = buildWhere(where, 1, 'sqlite');\n const sql = `SELECT * FROM ${table} ${whereClause}`;\n try {\n const result = await client.execute({ sql, args: values });\n return result.rows;\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 // Serialize the data to update\n const serializedData = serializeRecord(data);\n const keys = Object.keys(serializedData);\n const values = Object.values(serializedData);\n const setClause = keys.map((key, i) => `${key} = $${i + 1}`).join(', ');\n const { sql: whereClause, values: whereValues } = buildWhere(\n where,\n values.length + 1,\n 'sqlite',\n );\n if (!whereClause) {\n throw new DatabaseError(\n 'UPDATE requires at least one WHERE condition to prevent accidental update of all records',\n { table },\n );\n }\n\n const sql = `UPDATE ${table} SET ${setClause} ${whereClause}`;\n try {\n const result = await client.execute({\n sql,\n args: [...values, ...whereValues],\n });\n return { operation: 'update', affected: result.rowsAffected };\n } catch (e) {\n throw new DatabaseError('Failed to update records in table', {\n table,\n sql,\n values: [...values, ...whereValues],\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 try {\n return await executeUpsert(table, conflictColumns, data, options, true);\n } catch (e) {\n if (\n e instanceof DatabaseError &&\n e.message === 'Conflict columns missing from data'\n ) {\n throw e;\n }\n\n throw new DatabaseError('Failed to upsert record into table', {\n table,\n values: data,\n conflictColumns,\n originalError: formatDbError(e),\n });\n }\n };\n\n const upsertInCurrentTransaction = async (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n options?: UpsertOptions,\n ): Promise<QueryResult> => {\n try {\n return await executeUpsert(\n table,\n conflictColumns,\n data,\n options,\n false,\n );\n } catch (e) {\n if (\n e instanceof DatabaseError &&\n e.message === 'Conflict columns missing from data'\n ) {\n throw e;\n }\n\n throw new DatabaseError('Failed to upsert record into table', {\n table,\n values: data,\n conflictColumns,\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 or if the record cannot be retrieved after insert\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 await insert(table, data);\n\n const inserted = await get(table, where);\n if (!inserted) {\n throw new DatabaseError('Failed to insert and retrieve record', {\n table,\n where,\n data,\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, 'sqlite');\n\n try {\n await client.execute({\n sql: `DELETE FROM ${table} ${whereClause}`,\n args: values,\n });\n\n // SQLite doesn't reliably return affected rows, so we can't provide an exact count\n return { operation: 'delete', affected: 1 };\n } catch (e) {\n throw new DatabaseError('Failed to delete records from table', {\n table,\n where,\n originalError: 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 pluck`SELECT COUNT(*) FROM ${table}`;\n return Number(result) || 0;\n }\n\n // Count with conditions\n const { sql: whereClause, values } = buildWhere(where, 1, 'sqlite');\n\n const result = await client.execute({\n sql: `SELECT COUNT(*) as count FROM ${table} ${whereClause}`,\n args: values,\n });\n\n return Number(result.rows[0]?.count) || 0;\n } catch (e) {\n throw new DatabaseError('Failed to count records in table', {\n table,\n where,\n originalError: 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 const tableExists =\n !!(await pluck`SELECT name FROM sqlite_master WHERE type='table' AND name=${tableName}`);\n return tableExists;\n };\n\n /**\n * Synchronizes database schema with provided SQL DDL\n * Creates tables if they don't exist and adds missing columns\n *\n * @param schema - SQL schema definition with CREATE TABLE statements\n * @returns Promise that resolves when schema is synchronized\n */\n const syncSchema = async (schema: string): Promise<void> => {\n console.log(\n '[sqlite.syncSchema] Starting schema sync for dbid:',\n options.dbid,\n );\n console.log('[sqlite.syncSchema] Schema length:', schema.length, 'chars');\n\n // List of SQL reserved keywords that need to stay quoted\n const reservedKeywords = new Set([\n 'references',\n 'order',\n 'group',\n 'table',\n 'index',\n 'select',\n 'from',\n 'where',\n 'join',\n 'left',\n 'right',\n 'inner',\n 'outer',\n 'on',\n 'as',\n 'and',\n 'or',\n 'not',\n 'like',\n 'in',\n 'between',\n 'case',\n 'when',\n 'then',\n 'else',\n 'end',\n 'union',\n 'distinct',\n 'having',\n 'limit',\n 'offset',\n 'default',\n 'check',\n 'unique',\n 'primary',\n 'foreign',\n 'key',\n 'constraint',\n 'cascade',\n ]);\n\n // Normalize whitespace and simplify CAST expressions\n let normalizedSchema = schema\n .replace(/\\s+/g, ' ') // Replace multiple whitespace with single space\n .replace(/DEFAULT CAST\\(([^)]+)\\s+AS\\s+\\w+\\)/gi, 'DEFAULT $1') // Simplify CAST in DEFAULT clauses\n .trim();\n\n // Remove quotes around identifiers EXCEPT for reserved keywords\n normalizedSchema = normalizedSchema.replace(\n /\"(\\w+)\"/g,\n (match, identifier) => {\n return reservedKeywords.has(identifier.toLowerCase())\n ? match\n : identifier;\n },\n );\n\n console.log('[sqlite.syncSchema] Normalized schema:', normalizedSchema);\n\n // Split into individual commands\n const commands = normalizedSchema\n .split(';')\n .map((cmd) => cmd.trim())\n .filter((cmd) => cmd.length > 0);\n\n console.log(\n '[sqlite.syncSchema] Found',\n commands.length,\n 'commands to process',\n );\n\n // Execute each command\n for (const command of commands) {\n try {\n console.log(\n '[sqlite.syncSchema] Executing:',\n `${command.substring(0, 50)}...`,\n );\n await client.execute(command);\n console.log('[sqlite.syncSchema] Successfully executed command');\n } catch (error) {\n console.error(\n '[sqlite.syncSchema] Failed to execute command:',\n command,\n );\n console.error('[sqlite.syncSchema] Error:', error);\n throw error;\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 try {\n await client.execute({ sql: 'BEGIN TRANSACTION', args: [] });\n\n // Create a transaction-scoped database interface\n // SQLite doesn't have separate transaction clients, so we reuse the same client\n const txDb: DatabaseInterface = {\n url,\n client,\n insert,\n get,\n list,\n update,\n upsert: upsertInCurrentTransaction,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n many,\n single,\n pluck,\n execute,\n query,\n oo: many,\n oO: single,\n ox: pluck,\n xx: execute,\n tableExists,\n syncSchema,\n transaction,\n };\n\n const result = await callback(txDb);\n await client.execute({ sql: 'COMMIT', args: [] });\n return result;\n } catch (error) {\n await client.execute({ sql: 'ROLLBACK', args: [] });\n throw error;\n }\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 await client.execute({ sql: 'BEGIN TRANSACTION', args: [] });\n\n let active = true;\n\n const commit = async (): Promise<void> => {\n if (!active) {\n throw new DatabaseError('Transaction already ended', {});\n }\n await client.execute({ sql: 'COMMIT', args: [] });\n active = false;\n };\n\n const rollback = async (): Promise<void> => {\n if (!active) {\n throw new DatabaseError('Transaction already ended', {});\n }\n await client.execute({ sql: 'ROLLBACK', args: [] });\n active = false;\n };\n\n const isActive = (): boolean => active;\n\n // Create a transaction-scoped database interface with commit/rollback\n const txHandle: TransactionHandle = {\n url,\n client,\n insert,\n get,\n list,\n update,\n upsert: upsertInCurrentTransaction,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n many,\n single,\n pluck,\n execute,\n query,\n oo: many,\n oO: single,\n ox: pluck,\n xx: execute,\n tableExists,\n syncSchema,\n transaction,\n commit,\n rollback,\n isActive,\n };\n\n return txHandle;\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 += `?${strings[i + 1]}`;\n }\n return { sql, values };\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 result = await client.execute({ sql, args: values });\n return result.rows[0]?.[Object.keys(result.rows[0])[0]] ?? null;\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 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 result = await client.execute({ sql, args: values });\n return result.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 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 result = await client.execute({ sql, args: values });\n return result.rows;\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 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 client.execute({ sql, args: 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 try {\n const result = await client.execute({ sql, args });\n return {\n command: sql.split(' ')[0].toUpperCase(),\n rowCount: result.rowsAffected ?? result.rows.length,\n oid: null,\n fields: Object.keys(result.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 rows: result.rows,\n };\n } catch (e) {\n throw new DatabaseError('Failed to execute raw query', {\n sql,\n args,\n originalError: formatDbError(e),\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; // (x)ecute-(x)ecute: executes without returning\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,\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 transaction,\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 pragma_table_info\n const columnRows =\n await many`SELECT * FROM pragma_table_info(${table})`;\n\n const columns: Record<string, ColumnDefinition> = {};\n for (const row of columnRows) {\n const colName = row.name as string;\n columns[colName] = {\n type: row.type as string,\n primaryKey: row.pk === 1,\n notNull: row.notnull === 1,\n defaultValue: row.dflt_value,\n };\n }\n\n // Get index information from sqlite_master\n const indexRows = await many`\n SELECT name, sql FROM sqlite_master\n WHERE type = 'index'\n AND tbl_name = ${table}\n AND name NOT LIKE 'sqlite_%'\n `;\n\n const indexes: IndexDefinition[] = [];\n for (const row of indexRows) {\n const indexName = row.name as string;\n\n // Get index columns from pragma_index_info\n const indexInfoRows =\n await many`SELECT * FROM pragma_index_info(${indexName})`;\n\n const indexColumns: string[] = [];\n for (const infoRow of indexInfoRows) {\n indexColumns.push(infoRow.name as string);\n }\n\n // Check if index is unique from pragma_index_list\n const indexListRow =\n await single`SELECT * FROM pragma_index_list(${table}) WHERE name = ${indexName}`;\n\n indexes.push({\n name: indexName,\n columns: indexColumns,\n unique: indexListRow?.unique === 1,\n });\n }\n\n // Get foreign key information from pragma_foreign_key_list\n const fkRows =\n await many`SELECT * FROM pragma_foreign_key_list(${table})`;\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 foreignKeys.push({\n column: fkRow.from as string,\n referencesTable: fkRow.table as string,\n referencesColumn: fkRow.to as string,\n onDelete: fkRow.on_delete as string | undefined,\n onUpdate: fkRow.on_update as string | undefined,\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 try {\n const sql = generateAddColumnStatement(table, column, 'sqlite');\n await client.execute({ sql, args: [] });\n } catch (e) {\n throw new DatabaseError('Failed to add column to table', {\n table,\n column: column.name,\n originalError: formatDbError(e),\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 (\n table: string,\n index: IndexDefinition,\n ): Promise<void> => {\n validateTableName(table);\n validateIndexName(index.name);\n\n for (const col of index.columns) {\n validateColumnName(col);\n }\n\n try {\n const sql = generateCreateIndexStatement(table, index);\n await client.execute({ sql, args: [] });\n } catch (e) {\n throw new DatabaseError('Failed to create index on table', {\n table,\n index: index.name,\n originalError: formatDbError(e),\n });\n }\n },\n };\n\n return {\n url,\n client,\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 };\n })();\n\n // Store the pending connection promise if dbid exists\n if (options.dbid) {\n pendingConnections.set(options.dbid, connectionPromise);\n }\n\n try {\n // Wait for the connection to be established\n const db = await connectionPromise;\n\n // Cache the connection for reuse if dbid exists\n if (options.dbid) {\n memoryConnectionCache.set(options.dbid, db);\n }\n\n return db;\n } finally {\n // Clean up pending connection promise\n if (options.dbid) {\n pendingConnections.delete(options.dbid);\n }\n }\n}\n"],"names":["table","transaction","options","result","tableExists"],"mappings":";;AA8BA,MAAM,4CAA4B,IAAA;AAMlC,MAAM,yCAAyB,IAAA;AAC/B,MAAM,iCAAiC;AACvC,MAAM,kCAAkC;AACxC,MAAM,2CAA2B,IAAA;AAIjC,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,kCAAkC,OAAyB;AAClE,QAAM,YAAY,cAAc,KAAK,EAAE,YAAA;AACvC,SACE,UAAU,SAAS,MAAM,KACzB,UAAU,SAAS,QAAQ,KAC3B,UAAU,SAAS,oBAAoB;AAE3C;AAEA,eAAe,wBACb,SACA,UACY;AACZ,QAAM,WAAW,qBAAqB,IAAI,OAAO,KAAK,QAAQ,QAAA;AAC9D,MAAI,UAAsB,MAAM;AAAA,EAAC;AACjC,QAAM,UAAU,IAAI,QAAc,CAAC,YAAY;AAC7C,cAAU;AAAA,EACZ,CAAC;AACD,QAAM,OAAO,SAAS,MAAM,MAAM;AAAA,EAAC,CAAC,EAAE,KAAK,MAAM,OAAO;AAExD,uBAAqB,IAAI,SAAS,IAAI;AACtC,QAAM,SAAS,MAAM,MAAM;AAAA,EAAC,CAAC;AAE7B,MAAI;AACF,WAAO,MAAM,SAAA;AAAA,EACf,UAAA;AACE,YAAA;AAEA,QAAI,qBAAqB,IAAI,OAAO,MAAM,MAAM;AAC9C,2BAAqB,OAAO,OAAO;AAAA,IACrC;AAAA,EACF;AACF;AAMA,SAAS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IAAA;AAAA,EAEJ,GAAA;AAGA,MAAI,QAAQ,MAAM;AAChB,uBAAmB,IAAI,QAAQ,MAAM,iBAAiB;AAAA,EACxD;AAEA,MAAI;AAEF,UAAM,KAAK,MAAM;AAGjB,QAAI,QAAQ,MAAM;AAChB,4BAAsB,IAAI,QAAQ,MAAM,EAAE;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,UAAA;AAEE,QAAI,QAAQ,MAAM;AAChB,yBAAmB,OAAO,QAAQ,IAAI;AAAA,IACxC;AAAA,EACF;AACF;"}
1
+ {"version":3,"file":"sqlite-CPCNeJIH.js","sources":["../../src/sqlite.ts"],"sourcesContent":["import { DatabaseError } from '@happyvertical/utils';\nimport type { Client } from '@libsql/client';\nimport { DatabaseSchemaManager } from './schema-manager';\nimport {\n generateAddColumnStatement,\n generateCreateIndexStatement,\n validateColumnName,\n validateIndexName,\n validateTableName,\n} from './shared/alter-utils';\nimport type {\n ColumnDefinition,\n ColumnDefinitionWithName,\n DatabaseInterface,\n IndexDefinition,\n QueryResult,\n SchemaInitializationOptions,\n SqliteCapabilitiesOptions,\n TableInterface,\n TableSchemaInfo,\n TransactionHandle,\n UpsertOptions,\n} from './shared/types';\nimport { resolveSchemas } from './shared/types';\nimport { buildWhere, formatDbError } from './shared/utils';\n\n/**\n * Connection cache for in-memory databases with memoryId\n * Enables sharing of :memory: databases across multiple getDatabase() calls\n */\nconst memoryConnectionCache = new Map<string, DatabaseInterface>();\n\n/**\n * Pending connection promises to handle concurrent getDatabase() calls\n * Prevents creating duplicate connections when parallel calls happen\n */\nconst pendingConnections = new Map<string, Promise<DatabaseInterface>>();\nconst NULL_AWARE_UPSERT_MAX_ATTEMPTS = 8;\nconst NULL_AWARE_UPSERT_BASE_DELAY_MS = 25;\nconst nullAwareUpsertLocks = new Map<string, Promise<void>>();\n\ntype SqliteExecutor = Pick<Client, 'execute'>;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isRetriableSqliteTransactionError(error: unknown): boolean {\n const formatted = formatDbError(error).toLowerCase();\n return (\n formatted.includes('busy') ||\n formatted.includes('locked') ||\n formatted.includes('database is locked')\n );\n}\n\nasync function withNullAwareUpsertLock<T>(\n lockKey: string,\n callback: () => Promise<T>,\n): Promise<T> {\n const previous = nullAwareUpsertLocks.get(lockKey) ?? Promise.resolve();\n let release: () => void = () => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const next = previous.catch(() => {}).then(() => current);\n\n nullAwareUpsertLocks.set(lockKey, next);\n await previous.catch(() => {});\n\n try {\n return await callback();\n } finally {\n release();\n\n if (nullAwareUpsertLocks.get(lockKey) === next) {\n nullAwareUpsertLocks.delete(lockKey);\n }\n }\n}\n\n/**\n * Generates a unique identifier for in-memory databases\n * @returns A unique database identifier string\n */\nfunction generateDbId(): string {\n return `memory-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n\n/**\n * Creates a LibSQL client using the default client implementation\n * Supports in-memory databases and remote LibSQL URLs\n *\n * @param options - SQLite connection options\n * @returns Promise resolving to a LibSQL client instance\n */\nasync function createLibSQLClient(options: SqliteOptions): Promise<Client> {\n const { url = ':memory:', authToken, encryptionKey } = options;\n\n // Normalize URLs: add file:// prefix for local paths\n let libsqlUrl = url;\n if (\n url !== ':memory:' &&\n !url.startsWith('http://') &&\n !url.startsWith('https://') &&\n !url.startsWith('libsql://') &&\n !url.startsWith('file:')\n ) {\n // Local file path - resolve to absolute and add file:// prefix\n const { resolve } = await import('node:path');\n const absolutePath = resolve(url);\n // Use file:// format (file URL scheme with authority component omitted)\n libsqlUrl = `file://${absolutePath}`;\n }\n\n try {\n // Use explicit external import to avoid bundling\n const libsqlClient = '@libsql/client';\n const { createClient } = await import(/* @vite-ignore */ libsqlClient);\n return createClient({ url: libsqlUrl, authToken, encryptionKey });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n // Provide helpful error messages for common issues\n if (errorMessage?.includes('URL_SCHEME_NOT_SUPPORTED')) {\n throw new DatabaseError(\n `Unsupported URL scheme. Use ':memory:' for in-memory databases or 'libsql://' for remote LibSQL databases. Original: ${url}, Converted: ${libsqlUrl}`,\n { url: libsqlUrl, originalError: errorMessage },\n );\n }\n\n // Re-throw other errors with context\n throw new DatabaseError(`Failed to create LibSQL client: ${errorMessage}`, {\n url: libsqlUrl,\n originalError: errorMessage,\n });\n }\n}\n\n/**\n * Configuration options for SQLite database connections\n */\nexport interface SqliteOptions {\n /**\n * Connection URL for SQLite database\n * Supported schemes:\n * - ':memory:' for in-memory databases\n * - 'file:path/to/database.db' for local file databases\n * - 'libsql://...' for remote LibSQL/Turso databases\n */\n url?: string;\n\n /**\n * Authentication token for Turso/LibSQL remote connections\n */\n authToken?: string;\n\n /**\n * Encryption key for encrypted SQLite databases (LibSQL feature)\n */\n encryptionKey?: string;\n\n /**\n * Unique identifier for in-memory databases to enable connection sharing\n * When multiple getDatabase() calls use the same dbid, they receive\n * the same database connection instance.\n *\n * Auto-generated for :memory: databases if not provided.\n */\n dbid?: string;\n\n /**\n * Optional native SQLite capabilities for local development and testing.\n *\n * When any capability is enabled, the adapter uses the internal native\n * SQLite implementation instead of the LibSQL client path. Native\n * capabilities are only supported for local SQLite databases.\n */\n capabilities?: SqliteCapabilitiesOptions;\n\n /**\n * Schema definitions for tables.\n * Accepts a record or a lazy function (see SchemasOption).\n *\n * When provided, these schemas will be used for table creation.\n * Accepts a lazy function to defer schema building until needed.\n */\n schemas?: import('./shared/types').SchemasOption;\n}\n\nfunction hasNativeSqliteCapabilities(options: SqliteOptions): boolean {\n return Boolean(\n options.capabilities?.notifications || options.capabilities?.vector,\n );\n}\n\n/**\n * Creates tables from provided schema definitions\n *\n * @param client - LibSQL client\n * @param schemas - Schema definitions to create\n */\nasync function createTablesFromSchemas(\n client: 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 client.execute({\n sql: `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,\n args: [tableName],\n });\n\n if (result.rows.length > 0) {\n console.log(`[sqlite] Table ${tableName} already exists, skipping`);\n continue;\n }\n\n console.log(`[sqlite] Creating table ${tableName} from provided schema`);\n\n // Create table from DDL\n await client.execute(schema.ddl);\n\n // Create indexes\n if (schema.indexes && schema.indexes.length > 0) {\n for (const indexSQL of schema.indexes) {\n try {\n await client.execute(indexSQL);\n } catch (error) {\n console.warn(\n `[sqlite] 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 client.execute(triggerSQL);\n } catch (error) {\n console.warn(\n `[sqlite] Failed to create trigger for ${tableName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n } catch (error) {\n console.error(\n `[sqlite] Error creating table ${tableName}:`,\n error instanceof Error ? error.message : String(error),\n );\n console.error(`[sqlite] DDL was:`, schema.ddl?.substring(0, 200) + '...');\n throw new DatabaseError(\n `Failed to create table ${tableName} from schema: ${error instanceof Error ? error.message : String(error)}`,\n {\n tableName,\n schema,\n originalError: error instanceof Error ? error.message : String(error),\n },\n );\n }\n }\n}\n\n/**\n * Creates a SQLite database adapter\n *\n * @param options - SQLite connection options\n * @returns Database interface for SQLite\n */\nexport async function getDatabase(\n options: SqliteOptions = {},\n): Promise<DatabaseInterface> {\n const url = options.url || ':memory:';\n\n // Auto-generate dbid for :memory: databases if not provided\n // Mutate options object to ensure child objects reuse the same connection\n if (url === ':memory:' && !options.dbid) {\n options.dbid = generateDbId();\n }\n\n if (hasNativeSqliteCapabilities(options)) {\n const sqliteNative = await import('./sqlite-native.js');\n return sqliteNative.getNativeSqliteDatabase(options);\n }\n\n // Check if we have a cached connection for this dbid\n if (options.dbid) {\n const cached = memoryConnectionCache.get(options.dbid);\n if (cached) {\n return cached;\n }\n\n // Check if there's a pending connection for this dbid\n const pending = pendingConnections.get(options.dbid);\n if (pending) {\n return pending;\n }\n }\n\n // Create a new connection promise\n const connectionPromise = (async () => {\n const client = await createLibSQLClient(options);\n\n // Initialize tables from provided schemas (resolves lazy function if needed)\n const resolvedSchemas = resolveSchemas(options.schemas);\n if (resolvedSchemas && Object.keys(resolvedSchemas).length > 0) {\n await createTablesFromSchemas(client, resolvedSchemas);\n }\n\n /**\n * Serializes a value for SQLite storage\n * Converts objects and arrays to JSON strings\n * Converts Dates to ISO strings\n * Passes through primitives unchanged\n */\n const serializeValue = (value: any): any => {\n if (value === null || value === undefined) {\n return value;\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return value;\n };\n\n /**\n * Serializes all values in an object\n */\n const serializeRecord = (\n record: Record<string, any>,\n ): Record<string, any> => {\n const serialized: Record<string, any> = {};\n for (const [key, value] of Object.entries(record)) {\n // Skip undefined values - they cannot be passed to the database\n if (value === undefined) {\n continue;\n }\n serialized[key] = serializeValue(value);\n }\n return serialized;\n };\n\n const hasNullConflictValue = (\n conflictColumns: string[],\n data: Record<string, any>,\n ): boolean => conflictColumns.some((col) => data[col] === null);\n\n const buildNullAwareUpsertLockKey = (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n ): string => {\n const conflictValues = conflictColumns\n .map((col) => `${col}:${JSON.stringify(data[col])}`)\n .join('|');\n return `${url}:${table}:${conflictValues}`;\n };\n\n const validateUpsertConflictColumns = (\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): void => {\n const missingColumns = conflictColumns.filter(\n (col) => !(col in serializedData),\n );\n\n if (missingColumns.length > 0) {\n throw new DatabaseError('Conflict columns missing from data', {\n table,\n conflictColumns,\n missingColumns,\n availableColumns: Object.keys(serializedData),\n hint: 'All columns specified in ON CONFLICT must be present in the data being inserted. Undefined values are filtered out during serialization - consider using null or an empty string instead.',\n });\n }\n };\n\n const executeStandardUpsert = async (\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): Promise<QueryResult> => {\n const keys = Object.keys(serializedData);\n const values = Object.values(serializedData);\n const placeholders = keys.map(() => '?').join(', ');\n const updateSet = keys\n .map((key) => `${key} = excluded.${key}`)\n .join(', ');\n const conflict = conflictColumns.join(', ');\n const sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders}) ON CONFLICT(${conflict}) DO UPDATE SET ${updateSet}`;\n\n const result = await client.execute({ sql, args: values });\n return { operation: 'upsert', affected: result.rowsAffected };\n };\n\n const executeNullAwareUpsertAttempt = async (\n executor: SqliteExecutor,\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): Promise<QueryResult> => {\n const keys = Object.keys(serializedData);\n const values = Object.values(serializedData);\n const updateSet = keys.map((key) => `${key} = ?`).join(', ');\n const whereClause = conflictColumns\n .map((col) => `${col} IS ?`)\n .join(' AND ');\n const whereValues = conflictColumns.map((col) => serializedData[col]);\n\n const updateSql = `UPDATE ${table} SET ${updateSet} WHERE ${whereClause}`;\n const updateResult = await executor.execute({\n sql: updateSql,\n args: [...values, ...whereValues],\n });\n\n if ((updateResult.rowsAffected ?? 0) > 0) {\n return { operation: 'upsert', affected: updateResult.rowsAffected };\n }\n\n const placeholders = keys.map(() => '?').join(', ');\n const insertSql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders})`;\n const insertResult = await executor.execute({\n sql: insertSql,\n args: values,\n });\n\n return { operation: 'upsert', affected: insertResult.rowsAffected };\n };\n\n const executeNullAwareUpsertWithRetry = async (\n table: string,\n conflictColumns: string[],\n serializedData: Record<string, any>,\n ): Promise<QueryResult> => {\n if (url === ':memory:') {\n return executeNullAwareUpsertAttempt(\n client,\n table,\n conflictColumns,\n serializedData,\n );\n }\n\n let lastError: unknown;\n\n for (\n let attempt = 0;\n attempt < NULL_AWARE_UPSERT_MAX_ATTEMPTS;\n attempt++\n ) {\n let transaction: Awaited<ReturnType<Client['transaction']>> | undefined;\n\n try {\n transaction = await client.transaction('write');\n\n const result = await executeNullAwareUpsertAttempt(\n transaction,\n table,\n conflictColumns,\n serializedData,\n );\n\n await transaction.commit();\n return result;\n } catch (error) {\n lastError = error;\n\n if (transaction && !transaction.closed) {\n try {\n await transaction.rollback();\n } catch (_rollbackError) {\n // Preserve the original failure; rollback errors are secondary here.\n }\n }\n } finally {\n transaction?.close();\n }\n\n if (\n lastError &&\n attempt < NULL_AWARE_UPSERT_MAX_ATTEMPTS - 1 &&\n isRetriableSqliteTransactionError(lastError)\n ) {\n await delay(NULL_AWARE_UPSERT_BASE_DELAY_MS * 2 ** attempt);\n continue;\n }\n\n break;\n }\n\n throw lastError;\n };\n\n const executeUpsert = async (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n options: UpsertOptions | undefined,\n acquireTransaction: boolean,\n ): Promise<QueryResult> => {\n const serializedData = serializeRecord(data);\n validateUpsertConflictColumns(table, conflictColumns, serializedData);\n\n if (\n options?.nullsDistinct ||\n !hasNullConflictValue(conflictColumns, serializedData)\n ) {\n return executeStandardUpsert(table, conflictColumns, serializedData);\n }\n\n if (!acquireTransaction) {\n return executeNullAwareUpsertAttempt(\n client,\n table,\n conflictColumns,\n serializedData,\n );\n }\n\n return withNullAwareUpsertLock(\n buildNullAwareUpsertLockKey(table, conflictColumns, serializedData),\n () =>\n executeNullAwareUpsertWithRetry(\n table,\n conflictColumns,\n serializedData,\n ),\n );\n };\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 let sql: string;\n let values: any[];\n\n if (Array.isArray(data)) {\n // Serialize all records in the array\n const serializedRecords: Array<Record<string, any>> = data.map(\n (record) => serializeRecord(record),\n );\n const keys = Object.keys(serializedRecords[0]);\n const placeholders = serializedRecords\n .map(() => `(${keys.map(() => '?').join(', ')})`)\n .join(', ');\n sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES ${placeholders}`;\n // Flatten all values into a single array for batch insert\n const flattenedValues: any[] = [];\n for (const record of serializedRecords) {\n flattenedValues.push(...Object.values(record));\n }\n values = flattenedValues;\n } else {\n // Serialize the single record\n const serializedData = serializeRecord(data);\n const keys = Object.keys(serializedData);\n const placeholders = keys.map(() => '?').join(', ');\n sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${placeholders})`;\n values = Object.values(serializedData);\n }\n try {\n const result = await client.execute({ sql: sql, args: values });\n return { operation: 'insert', affected: result.rowsAffected };\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 const { sql: whereClause, values } = buildWhere(where, 1, 'sqlite');\n if (!whereClause) {\n throw new DatabaseError(\n 'GET requires at least one WHERE condition to prevent returning an arbitrary record',\n { table },\n );\n }\n\n const sql = `SELECT * FROM ${table} ${whereClause}`;\n try {\n const result = await client.execute({ sql: sql, args: values });\n return result.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 const { sql: whereClause, values } = buildWhere(where, 1, 'sqlite');\n const sql = `SELECT * FROM ${table} ${whereClause}`;\n try {\n const result = await client.execute({ sql, args: values });\n return result.rows;\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 // Serialize the data to update\n const serializedData = serializeRecord(data);\n const keys = Object.keys(serializedData);\n const values = Object.values(serializedData);\n const setClause = keys.map((key, i) => `${key} = $${i + 1}`).join(', ');\n const { sql: whereClause, values: whereValues } = buildWhere(\n where,\n values.length + 1,\n 'sqlite',\n );\n if (!whereClause) {\n throw new DatabaseError(\n 'UPDATE requires at least one WHERE condition to prevent accidental update of all records',\n { table },\n );\n }\n\n const sql = `UPDATE ${table} SET ${setClause} ${whereClause}`;\n try {\n const result = await client.execute({\n sql,\n args: [...values, ...whereValues],\n });\n return { operation: 'update', affected: result.rowsAffected };\n } catch (e) {\n throw new DatabaseError('Failed to update records in table', {\n table,\n sql,\n values: [...values, ...whereValues],\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 try {\n return await executeUpsert(table, conflictColumns, data, options, true);\n } catch (e) {\n if (\n e instanceof DatabaseError &&\n e.message === 'Conflict columns missing from data'\n ) {\n throw e;\n }\n\n throw new DatabaseError('Failed to upsert record into table', {\n table,\n values: data,\n conflictColumns,\n originalError: formatDbError(e),\n });\n }\n };\n\n const upsertInCurrentTransaction = async (\n table: string,\n conflictColumns: string[],\n data: Record<string, any>,\n options?: UpsertOptions,\n ): Promise<QueryResult> => {\n try {\n return await executeUpsert(\n table,\n conflictColumns,\n data,\n options,\n false,\n );\n } catch (e) {\n if (\n e instanceof DatabaseError &&\n e.message === 'Conflict columns missing from data'\n ) {\n throw e;\n }\n\n throw new DatabaseError('Failed to upsert record into table', {\n table,\n values: data,\n conflictColumns,\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 or if the record cannot be retrieved after insert\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 await insert(table, data);\n\n const inserted = await get(table, where);\n if (!inserted) {\n throw new DatabaseError('Failed to insert and retrieve record', {\n table,\n where,\n data,\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, 'sqlite');\n\n try {\n await client.execute({\n sql: `DELETE FROM ${table} ${whereClause}`,\n args: values,\n });\n\n // SQLite doesn't reliably return affected rows, so we can't provide an exact count\n return { operation: 'delete', affected: 1 };\n } catch (e) {\n throw new DatabaseError('Failed to delete records from table', {\n table,\n where,\n originalError: 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 pluck`SELECT COUNT(*) FROM ${table}`;\n return Number(result) || 0;\n }\n\n // Count with conditions\n const { sql: whereClause, values } = buildWhere(where, 1, 'sqlite');\n\n const result = await client.execute({\n sql: `SELECT COUNT(*) as count FROM ${table} ${whereClause}`,\n args: values,\n });\n\n return Number(result.rows[0]?.count) || 0;\n } catch (e) {\n throw new DatabaseError('Failed to count records in table', {\n table,\n where,\n originalError: 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 const tableExists =\n !!(await pluck`SELECT name FROM sqlite_master WHERE type='table' AND name=${tableName}`);\n return tableExists;\n };\n\n /**\n * Synchronizes database schema with provided SQL DDL\n * Creates tables if they don't exist and adds missing columns\n *\n * @param schema - SQL schema definition with CREATE TABLE statements\n * @returns Promise that resolves when schema is synchronized\n */\n const syncSchema = async (schema: string): Promise<void> => {\n console.log(\n '[sqlite.syncSchema] Starting schema sync for dbid:',\n options.dbid,\n );\n console.log('[sqlite.syncSchema] Schema length:', schema.length, 'chars');\n\n // List of SQL reserved keywords that need to stay quoted\n const reservedKeywords = new Set([\n 'references',\n 'order',\n 'group',\n 'table',\n 'index',\n 'select',\n 'from',\n 'where',\n 'join',\n 'left',\n 'right',\n 'inner',\n 'outer',\n 'on',\n 'as',\n 'and',\n 'or',\n 'not',\n 'like',\n 'in',\n 'between',\n 'case',\n 'when',\n 'then',\n 'else',\n 'end',\n 'union',\n 'distinct',\n 'having',\n 'limit',\n 'offset',\n 'default',\n 'check',\n 'unique',\n 'primary',\n 'foreign',\n 'key',\n 'constraint',\n 'cascade',\n ]);\n\n // Normalize whitespace and simplify CAST expressions\n let normalizedSchema = schema\n .replace(/\\s+/g, ' ') // Replace multiple whitespace with single space\n .replace(/DEFAULT CAST\\(([^)]+)\\s+AS\\s+\\w+\\)/gi, 'DEFAULT $1') // Simplify CAST in DEFAULT clauses\n .trim();\n\n // Remove quotes around identifiers EXCEPT for reserved keywords\n normalizedSchema = normalizedSchema.replace(\n /\"(\\w+)\"/g,\n (match, identifier) => {\n return reservedKeywords.has(identifier.toLowerCase())\n ? match\n : identifier;\n },\n );\n\n console.log('[sqlite.syncSchema] Normalized schema:', normalizedSchema);\n\n // Split into individual commands\n const commands = normalizedSchema\n .split(';')\n .map((cmd) => cmd.trim())\n .filter((cmd) => cmd.length > 0);\n\n console.log(\n '[sqlite.syncSchema] Found',\n commands.length,\n 'commands to process',\n );\n\n // Execute each command\n for (const command of commands) {\n try {\n console.log(\n '[sqlite.syncSchema] Executing:',\n `${command.substring(0, 50)}...`,\n );\n await client.execute(command);\n console.log('[sqlite.syncSchema] Successfully executed command');\n } catch (error) {\n console.error(\n '[sqlite.syncSchema] Failed to execute command:',\n command,\n );\n console.error('[sqlite.syncSchema] Error:', error);\n throw error;\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 try {\n await client.execute({ sql: 'BEGIN TRANSACTION', args: [] });\n\n // Create a transaction-scoped database interface\n // SQLite doesn't have separate transaction clients, so we reuse the same client\n const txDb: DatabaseInterface = {\n url,\n client,\n insert,\n get,\n list,\n update,\n upsert: upsertInCurrentTransaction,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n many,\n single,\n pluck,\n execute,\n query,\n oo: many,\n oO: single,\n ox: pluck,\n xx: execute,\n tableExists,\n syncSchema,\n transaction,\n };\n\n const result = await callback(txDb);\n await client.execute({ sql: 'COMMIT', args: [] });\n return result;\n } catch (error) {\n await client.execute({ sql: 'ROLLBACK', args: [] });\n throw error;\n }\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 await client.execute({ sql: 'BEGIN TRANSACTION', args: [] });\n\n let active = true;\n\n const commit = async (): Promise<void> => {\n if (!active) {\n throw new DatabaseError('Transaction already ended', {});\n }\n await client.execute({ sql: 'COMMIT', args: [] });\n active = false;\n };\n\n const rollback = async (): Promise<void> => {\n if (!active) {\n throw new DatabaseError('Transaction already ended', {});\n }\n await client.execute({ sql: 'ROLLBACK', args: [] });\n active = false;\n };\n\n const isActive = (): boolean => active;\n\n // Create a transaction-scoped database interface with commit/rollback\n const txHandle: TransactionHandle = {\n url,\n client,\n insert,\n get,\n list,\n update,\n upsert: upsertInCurrentTransaction,\n getOrInsert,\n delete: deleteRecords,\n count,\n table,\n many,\n single,\n pluck,\n execute,\n query,\n oo: many,\n oO: single,\n ox: pluck,\n xx: execute,\n tableExists,\n syncSchema,\n transaction,\n commit,\n rollback,\n isActive,\n };\n\n return txHandle;\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 += `?${strings[i + 1]}`;\n }\n return { sql, values };\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 result = await client.execute({ sql, args: values });\n return result.rows[0]?.[Object.keys(result.rows[0])[0]] ?? null;\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 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 result = await client.execute({ sql, args: values });\n return result.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 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 result = await client.execute({ sql, args: values });\n return result.rows;\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 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 client.execute({ sql, args: 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 try {\n const result = await client.execute({ sql, args });\n return {\n command: sql.split(' ')[0].toUpperCase(),\n rowCount: result.rowsAffected ?? result.rows.length,\n oid: null,\n fields: Object.keys(result.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 rows: result.rows,\n };\n } catch (e) {\n throw new DatabaseError('Failed to execute raw query', {\n sql,\n args,\n originalError: formatDbError(e),\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; // (x)ecute-(x)ecute: executes without returning\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,\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 transaction,\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 pragma_table_info\n const columnRows =\n await many`SELECT * FROM pragma_table_info(${table})`;\n\n const columns: Record<string, ColumnDefinition> = {};\n for (const row of columnRows) {\n const colName = row.name as string;\n columns[colName] = {\n type: row.type as string,\n primaryKey: row.pk === 1,\n notNull: row.notnull === 1,\n defaultValue: row.dflt_value,\n };\n }\n\n // Get index information from sqlite_master\n const indexRows = await many`\n SELECT name, sql FROM sqlite_master\n WHERE type = 'index'\n AND tbl_name = ${table}\n AND name NOT LIKE 'sqlite_%'\n `;\n\n const indexes: IndexDefinition[] = [];\n for (const row of indexRows) {\n const indexName = row.name as string;\n\n // Get index columns from pragma_index_info\n const indexInfoRows =\n await many`SELECT * FROM pragma_index_info(${indexName})`;\n\n const indexColumns: string[] = [];\n for (const infoRow of indexInfoRows) {\n indexColumns.push(infoRow.name as string);\n }\n\n // Check if index is unique from pragma_index_list\n const indexListRow =\n await single`SELECT * FROM pragma_index_list(${table}) WHERE name = ${indexName}`;\n\n indexes.push({\n name: indexName,\n columns: indexColumns,\n unique: indexListRow?.unique === 1,\n });\n }\n\n // Get foreign key information from pragma_foreign_key_list\n const fkRows =\n await many`SELECT * FROM pragma_foreign_key_list(${table})`;\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 foreignKeys.push({\n column: fkRow.from as string,\n referencesTable: fkRow.table as string,\n referencesColumn: fkRow.to as string,\n onDelete: fkRow.on_delete as string | undefined,\n onUpdate: fkRow.on_update as string | undefined,\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 try {\n const sql = generateAddColumnStatement(table, column, 'sqlite');\n await client.execute({ sql, args: [] });\n } catch (e) {\n throw new DatabaseError('Failed to add column to table', {\n table,\n column: column.name,\n originalError: formatDbError(e),\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 (\n table: string,\n index: IndexDefinition,\n ): Promise<void> => {\n validateTableName(table);\n validateIndexName(index.name);\n\n for (const col of index.columns) {\n validateColumnName(col);\n }\n\n try {\n const sql = generateCreateIndexStatement(table, index);\n await client.execute({ sql, args: [] });\n } catch (e) {\n throw new DatabaseError('Failed to create index on table', {\n table,\n index: index.name,\n originalError: formatDbError(e),\n });\n }\n },\n };\n\n return {\n url,\n client,\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 };\n })();\n\n // Store the pending connection promise if dbid exists\n if (options.dbid) {\n pendingConnections.set(options.dbid, connectionPromise);\n }\n\n try {\n // Wait for the connection to be established\n const db = await connectionPromise;\n\n // Cache the connection for reuse if dbid exists\n if (options.dbid) {\n memoryConnectionCache.set(options.dbid, db);\n }\n\n return db;\n } finally {\n // Clean up pending connection promise\n if (options.dbid) {\n pendingConnections.delete(options.dbid);\n }\n }\n}\n"],"names":["table","transaction","options","result","tableExists"],"mappings":";;AA8BA,MAAM,4CAA4B,IAAA;AAMlC,MAAM,yCAAyB,IAAA;AAC/B,MAAM,iCAAiC;AACvC,MAAM,kCAAkC;AACxC,MAAM,2CAA2B,IAAA;AAIjC,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,kCAAkC,OAAyB;AAClE,QAAM,YAAY,cAAc,KAAK,EAAE,YAAA;AACvC,SACE,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AAEA,YAAI;AACF,gBAAM,MAAM,6BAA6BA,QAAO,KAAK;AACrD,gBAAM,OAAO,QAAQ,EAAE,KAAK,MAAM,CAAA,GAAI;AAAA,QACxC,SAAS,GAAG;AACV,gBAAM,IAAI,cAAc,mCAAmC;AAAA,YACzD,OAAAA;AAAAA,YACA,OAAO,MAAM;AAAA,YACb,eAAe,cAAc,CAAC;AAAA,UAAA,CAC/B;AAAA,QACH;AAAA,MACF;AAAA,IAAA;AAGF,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ,GAAA;AAGA,MAAI,QAAQ,MAAM;AAChB,uBAAmB,IAAI,QAAQ,MAAM,iBAAiB;AAAA,EACxD;AAEA,MAAI;AAEF,UAAM,KAAK,MAAM;AAGjB,QAAI,QAAQ,MAAM;AAChB,4BAAsB,IAAI,QAAQ,MAAM,EAAE;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,UAAA;AAEE,QAAI,QAAQ,MAAM;AAChB,yBAAmB,OAAO,QAAQ,IAAI;AAAA,IACxC;AAAA,EACF;AACF;"}
@@ -2,7 +2,7 @@ import { createRequire } from "node:module";
2
2
  import { resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { DatabaseError } from "@happyvertical/utils";
5
- import { f as formatDbError, v as validateTableName, D as DatabaseSchemaManager, a as validateIndexName, b as validateColumnName, g as generateCreateIndexStatement, c as generateAddColumnStatement, r as resolveSchemas, d as buildWhere } from "./index-DrPgGVZz.js";
5
+ import { f as formatDbError, v as validateTableName, D as DatabaseSchemaManager, a as validateIndexName, b as validateColumnName, g as generateCreateIndexStatement, c as generateAddColumnStatement, r as resolveSchemas, d as buildWhere } from "./index-CzdYvRFp.js";
6
6
  const nativeMemoryConnectionCache = /* @__PURE__ */ new Map();
7
7
  const nativePendingConnections = /* @__PURE__ */ new Map();
8
8
  const nativeNullAwareUpsertLocks = /* @__PURE__ */ new Map();
@@ -1126,4 +1126,4 @@ async function createNativeSqliteDatabase(options, url) {
1126
1126
  export {
1127
1127
  getNativeSqliteDatabase
1128
1128
  };
1129
- //# sourceMappingURL=sqlite-native-BdArMasZ.js.map
1129
+ //# sourceMappingURL=sqlite-native-DqVPKNUu.js.map