@happyvertical/sql 0.116.0 → 0.116.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +33 -14
  2. package/dist/chunks/{duckdb-_d9aSOht.js → duckdb-KwkNHwu2.js} +18 -14
  3. package/dist/chunks/duckdb-KwkNHwu2.js.map +1 -0
  4. package/dist/chunks/postgres-DPYxHPpn.js +610 -0
  5. package/dist/chunks/postgres-DPYxHPpn.js.map +1 -0
  6. package/dist/chunks/{postgres-dialect-CevaHPBb.js → postgres-dialect-CL4kFDM0.js} +13 -420
  7. package/dist/chunks/postgres-dialect-CL4kFDM0.js.map +1 -0
  8. package/dist/chunks/{query-DFAYXNk-.js → query-BXjIqpxx.js} +2 -2
  9. package/dist/chunks/{query-DFAYXNk-.js.map → query-BXjIqpxx.js.map} +1 -1
  10. package/dist/chunks/{sqlite-4D5RuZT0.js → sqlite-B_nn3rHX.js} +18 -14
  11. package/dist/chunks/sqlite-B_nn3rHX.js.map +1 -0
  12. package/dist/chunks/{sqlite-engine-BLAv3Esk.js → sqlite-engine-Bai741Ho.js} +3 -3
  13. package/dist/chunks/{sqlite-engine-BLAv3Esk.js.map → sqlite-engine-Bai741Ho.js.map} +1 -1
  14. package/dist/chunks/{sqlite-native-Bqs856IC.js → sqlite-native-BC8jcbGo.js} +22 -14
  15. package/dist/chunks/sqlite-native-BC8jcbGo.js.map +1 -0
  16. package/dist/chunks/transaction-lock-BaXakB9D.js +415 -0
  17. package/dist/chunks/transaction-lock-BaXakB9D.js.map +1 -0
  18. package/dist/chunks/{types-DihIt7ez.js → types-B5zTs-6A.js} +13 -2
  19. package/dist/chunks/types-B5zTs-6A.js.map +1 -0
  20. package/dist/doctor.d.ts +4 -2
  21. package/dist/doctor.d.ts.map +1 -1
  22. package/dist/duckdb.d.ts.map +1 -1
  23. package/dist/index.d.ts +8 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +20 -617
  26. package/dist/index.js.map +1 -1
  27. package/dist/json.d.ts.map +1 -1
  28. package/dist/pglite.js +3 -2
  29. package/dist/pglite.js.map +1 -1
  30. package/dist/query.js +2 -2
  31. package/dist/shared/alter-utils.d.ts +9 -0
  32. package/dist/shared/alter-utils.d.ts.map +1 -1
  33. package/dist/shared/postgres-dialect.d.ts +3 -3
  34. package/dist/shared/postgres-dialect.d.ts.map +1 -1
  35. package/dist/shared/types.d.ts +39 -6
  36. package/dist/shared/types.d.ts.map +1 -1
  37. package/dist/sqlite-native.d.ts.map +1 -1
  38. package/dist/sqlite.d.ts.map +1 -1
  39. package/package.json +3 -3
  40. package/dist/chunks/duckdb-_d9aSOht.js.map +0 -1
  41. package/dist/chunks/postgres-dialect-CevaHPBb.js.map +0 -1
  42. package/dist/chunks/sqlite-4D5RuZT0.js.map +0 -1
  43. package/dist/chunks/sqlite-native-Bqs856IC.js.map +0 -1
  44. package/dist/chunks/types-DihIt7ez.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-DPYxHPpn.js","names":[],"sources":["../../src/postgres.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { webcrypto } from 'node:crypto';\nimport { DatabaseError } from '@happyvertical/utils';\nimport {\n DatabaseError as PgDatabaseError,\n type QueryResult as PgQueryResult,\n Pool,\n type PoolClient,\n} from 'pg';\nimport { DatabaseSchemaManager } from './schema-manager';\nimport {\n ConnectionCache,\n validateDatabaseCacheOptions,\n} from './shared/connection-cache';\nimport {\n createAlterTable,\n createPostgresDialect,\n createTransactionErrorTracker,\n createVectorCapabilities,\n type NestedScope,\n normalizePostgresRawQuery,\n type PostgresQueryExecutor,\n} from './shared/postgres-dialect';\nimport type {\n DatabaseCacheOptions,\n DatabaseInterface,\n ReopenOptions,\n SchemaInitializationOptions,\n SessionHandle,\n TransactionHandle,\n} from './shared/types';\nimport { wrapDatabaseError } from './shared/utils';\n\n/** Default pool size of a reopened PostgreSQL connection. */\nconst REOPEN_POOL_MAX = 5;\n\nconst MAX_TIMER_DELAY_MILLIS = 2_147_483_647;\n\n/**\n * Configuration options for PostgreSQL database connections\n */\nexport interface PostgresOptions extends DatabaseCacheOptions {\n /**\n * Connection URL for PostgreSQL\n */\n url?: string;\n\n /**\n * Database name\n */\n database?: string;\n\n /**\n * Database server hostname\n */\n host?: string;\n\n /**\n * Username for authentication\n */\n user?: string;\n\n /**\n * Password for authentication\n */\n password?: string;\n\n /**\n * Port number for the PostgreSQL server\n */\n port?: number;\n\n /**\n * Opaque caller-owned cache identity for connection pooling.\n * If provided, the same dbid returns the same cached connection.\n * When omitted, a keyed digest is derived from effective connection and pool\n * options, including credentials, without retaining them in readable keys.\n */\n dbid?: string;\n\n /**\n * Maximum number of connections in the pool.\n * Defaults to 20. The pg library defaults to 10, which is too low\n * for applications with many SMRT collections.\n */\n max?: number;\n\n /**\n * Maximum time to wait for a pool connection, in milliseconds.\n * Must not exceed Node.js's maximum timer delay of 2,147,483,647.\n * Set to 0 to wait indefinitely. When omitted, pg's default is used.\n */\n connectionTimeoutMillis?: number;\n\n /**\n * Maximum time an idle client remains in the pool, in milliseconds.\n * Must not exceed Node.js's maximum timer delay of 2,147,483,647.\n * Set to 0 to retain idle clients. When omitted, pg's default is used.\n */\n idleTimeoutMillis?: number;\n\n /**\n * Schema definitions for tables.\n * Accepts a record or a lazy function (see SchemasOption).\n *\n * **Postgres ignores this option** — tables are managed by migrations.\n * The option exists so callers can pass schemas uniformly to all adapters\n * without knowing the adapter type. Only JSON/DuckDB adapters resolve it.\n */\n schemas?: import('./shared/types').SchemasOption;\n}\n\n/**\n * Module-level cache for PostgreSQL connections.\n * Keyed by dbid (or derived from connection URL).\n * Prevents creating multiple pg.Pool instances for the same database.\n */\ndeclare global {\n // A non-extractable process-local HMAC key keeps password-bearing cache\n // identities resistant to offline guessing even if cache keys are inspected.\n // eslint-disable-next-line no-var\n var __haveSqlPostgresCacheHmacKey: Promise<CryptoKey> | undefined;\n // eslint-disable-next-line no-var\n var __haveSqlPostgresConnectionCache:\n | ConnectionCache<DatabaseInterface>\n | undefined;\n}\n\nglobalThis.__haveSqlPostgresConnectionCache ??=\n new ConnectionCache<DatabaseInterface>();\nconst connectionCache = globalThis.__haveSqlPostgresConnectionCache;\n\n/**\n * Returns the process-local cache identity HMAC key, generating it on first\n * use. Generating it at import would leave a WebCrypto key job in flight in\n * every isolate that loads the package, and Node aborts the whole process when\n * a worker thread is terminated while such a job completes (#1518).\n *\n * Concurrent first callers share one pending promise. The promise lives on\n * `globalThis` so every copy of this module in an isolate derives the same\n * cache identities. A rejected generation is dropped so the next call retries.\n */\nfunction getPostgresCacheHmacKey(): Promise<CryptoKey> {\n const existing = globalThis.__haveSqlPostgresCacheHmacKey;\n if (existing) {\n return existing;\n }\n let pending: Promise<CryptoKey>;\n try {\n pending = webcrypto.subtle.generateKey(\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n ) as Promise<CryptoKey>;\n } catch (error) {\n pending = Promise.reject(error);\n }\n globalThis.__haveSqlPostgresCacheHmacKey = pending;\n pending.catch(() => {\n if (globalThis.__haveSqlPostgresCacheHmacKey === pending) {\n globalThis.__haveSqlPostgresCacheHmacKey = undefined;\n }\n });\n return pending;\n}\n\n/**\n * Clears the PostgreSQL connection cache.\n * Useful for test isolation and reconnection scenarios.\n */\nexport async function clearPostgresConnectionCache(): Promise<void> {\n await connectionCache.clear(closePostgresDatabase);\n}\n\nasync function closePostgresDatabase(db: DatabaseInterface): Promise<void> {\n if (db.close) {\n await db.close();\n return;\n }\n await db.client.end();\n}\n\ntype EffectivePostgresConfig = {\n url?: string;\n database?: string;\n host?: string;\n user?: string;\n password?: string;\n port: number;\n max: number;\n connectionTimeoutMillis?: number;\n idleTimeoutMillis?: number;\n};\n\nfunction resolvePostgresConfig(\n options: PostgresOptions,\n): EffectivePostgresConfig {\n const preferred = <T>(option: T | undefined, environment: T | undefined) =>\n option !== undefined ? option : environment;\n const envPort = process.env.HAVE_SQL_PORT;\n const primary = {\n url: preferred(options.url, process.env.HAVE_SQL_URL),\n database: preferred(options.database, process.env.HAVE_SQL_DATABASE),\n host: preferred(options.host, process.env.HAVE_SQL_HOST),\n user: preferred(options.user, process.env.HAVE_SQL_USER),\n password: preferred(options.password, process.env.HAVE_SQL_PASSWORD),\n port: preferred(\n options.port,\n envPort === undefined ? undefined : Number(envPort),\n ),\n };\n const useLegacy =\n !primary.url && !primary.host && !primary.database && !primary.user;\n const legacy = <T>(value: T | undefined, environment: T | undefined) =>\n value !== undefined || !useLegacy ? value : environment;\n const legacyPort = process.env.SQLOO_PORT;\n\n const port =\n legacy(\n primary.port,\n legacyPort === undefined ? undefined : Number(legacyPort),\n ) ?? 5432;\n const max = options.max ?? 20;\n const { connectionTimeoutMillis, idleTimeoutMillis } = options;\n if (!Number.isInteger(port) || port < 1 || port > 65_535) {\n throw new Error('PostgreSQL port must be an integer between 1 and 65535');\n }\n if (!Number.isInteger(max) || max < 1) {\n throw new Error('PostgreSQL pool max must be a positive integer');\n }\n if (\n connectionTimeoutMillis !== undefined &&\n (!Number.isInteger(connectionTimeoutMillis) ||\n connectionTimeoutMillis < 0 ||\n connectionTimeoutMillis > MAX_TIMER_DELAY_MILLIS)\n ) {\n throw new Error(\n `PostgreSQL pool connectionTimeoutMillis must be an integer between 0 and ${MAX_TIMER_DELAY_MILLIS}`,\n );\n }\n if (\n idleTimeoutMillis !== undefined &&\n (!Number.isInteger(idleTimeoutMillis) ||\n idleTimeoutMillis < 0 ||\n idleTimeoutMillis > MAX_TIMER_DELAY_MILLIS)\n ) {\n throw new Error(\n `PostgreSQL pool idleTimeoutMillis must be an integer between 0 and ${MAX_TIMER_DELAY_MILLIS}`,\n );\n }\n\n return {\n url: legacy(primary.url, process.env.SQLOO_URL),\n database: legacy(primary.database, process.env.SQLOO_DATABASE),\n host: legacy(primary.host, process.env.SQLOO_HOST),\n user: legacy(primary.user, process.env.SQLOO_USER),\n password: legacy(primary.password, process.env.SQLOO_PASSWORD),\n port,\n max,\n connectionTimeoutMillis,\n idleTimeoutMillis,\n };\n}\n\nasync function derivePostgresConnectionCacheKey(\n options: PostgresOptions,\n effective: EffectivePostgresConfig,\n): Promise<string | undefined> {\n if (options.dbid) {\n return options.dbid;\n }\n\n const identity = JSON.stringify({\n url: effective.url ?? null,\n host: effective.host ?? 'localhost',\n port: effective.port,\n database: effective.database ?? null,\n user: effective.user ?? null,\n password: effective.password ?? null,\n max: effective.max,\n connectionTimeoutMillis: effective.connectionTimeoutMillis ?? null,\n idleTimeoutMillis: effective.idleTimeoutMillis ?? null,\n });\n const hmacKey = await getPostgresCacheHmacKey();\n const signature = await webcrypto.subtle.sign(\n 'HMAC',\n hmacKey,\n new TextEncoder().encode(\n `@happyvertical/sql:postgres-cache:v1\\0${identity}`,\n ),\n );\n return `pg:hmac-sha256:v1:${Buffer.from(signature).toString('hex')}`;\n}\n\n/** @internal Exported for adversarial identity tests. */\nexport async function getPostgresConnectionCacheKey(\n options: PostgresOptions,\n): Promise<string | undefined> {\n validateDatabaseCacheOptions(options);\n return derivePostgresConnectionCacheKey(\n options,\n resolvePostgresConfig(options),\n );\n}\n\n/**\n * Creates a PostgreSQL database adapter\n *\n * Loads configuration from environment variables with backward compatibility:\n * - First checks HAVE_SQL_* environment variables (new standard)\n * - Falls back to SQLOO_* environment variables (legacy)\n * - User-provided options always take precedence\n *\n * Environment variables:\n * - HAVE_SQL_URL / SQLOO_URL → Connection string (takes precedence)\n * - HAVE_SQL_DATABASE / SQLOO_DATABASE → Database name\n * - HAVE_SQL_HOST / SQLOO_HOST → Host (default: 'localhost')\n * - HAVE_SQL_USER / SQLOO_USER → Username\n * - HAVE_SQL_PASSWORD / SQLOO_PASSWORD → Password\n * - HAVE_SQL_PORT / SQLOO_PORT → Port (default: 5432)\n *\n * @param options - PostgreSQL connection options\n * @returns Database interface for PostgreSQL\n */\nexport async function getDatabase(\n options: PostgresOptions = {},\n): Promise<DatabaseInterface> {\n validateDatabaseCacheOptions(options);\n const effective = resolvePostgresConfig(options);\n const cacheKey = await derivePostgresConnectionCacheKey(options, effective);\n return connectionCache.getOrCreate(\n cacheKey,\n options,\n () => createDatabase(effective),\n closePostgresDatabase,\n );\n}\n\n/**\n * Internal: creates the actual database connection and caches it.\n */\nasync function createDatabase(\n config: EffectivePostgresConfig,\n): Promise<DatabaseInterface> {\n // Apply defaults\n const { database, host = 'localhost', user, password, port = 5432 } = config;\n\n // Construct url if not provided (for DatabaseInterface requirement)\n const url: string =\n (config.url as string) ||\n `postgresql://${user}${password ? `:${password}` : ''}@${host}:${port}/${database || 'postgres'}`;\n\n // Another thread can open its own pool against the same server, so the\n // effective options are the reopen options. They may carry credentials.\n const reopenOptions = (): ReopenOptions => {\n const reopened: PostgresOptions & { type: 'postgres' } = {\n ...(Object.fromEntries(\n Object.entries(config).filter(([, value]) => value !== undefined),\n ) as PostgresOptions),\n type: 'postgres',\n // An equal configuration would otherwise return this cached pool.\n cache: false,\n // Every reopen is a pool of its own. Keep it small by default; a caller\n // who needs more overrides `max` on the returned options.\n max: Math.min(config.max, REOPEN_POOL_MAX),\n };\n return reopened;\n };\n\n // Create a connection pool with explicit max to prevent exhaustion.\n // pg defaults to 10 which is too low for SMRT apps that sync 30+ table\n // schemas on startup. Default to 20 but allow callers to override.\n const { max: poolMax, connectionTimeoutMillis, idleTimeoutMillis } = config;\n const pool = new Pool(\n config.url\n ? {\n connectionString: config.url as string,\n max: poolMax,\n connectionTimeoutMillis,\n idleTimeoutMillis,\n }\n : {\n host: host as string,\n user: user as string,\n password: password as string,\n port: port as number,\n database: database as string,\n max: poolMax,\n connectionTimeoutMillis,\n idleTimeoutMillis,\n },\n );\n\n // An idle pooled client that loses its backend (restart, failover, proxy\n // idle timeout, TCP reset) emits 'error' on the pool. Without a listener Node\n // treats that as an unhandled 'error' event and terminates the process, so\n // routine database maintenance would crash every consumer of this adapter.\n // pg has already removed the client from the pool by this point; absorb the\n // event and let the pool carry on with its remaining connections.\n pool.on('error', (error) => {\n console.warn(\n 'Warning: PostgreSQL pool client error (connection discarded):',\n error instanceof Error ? error.message : String(error),\n );\n });\n\n // Wrap pool.end() to evict from cache so stale pools are never returned.\n // This fixes the \"Cannot use a pool after calling end on the pool\" error\n // when tests or shutdown code calls db.client.end() and subsequent calls\n // to getDatabase() would otherwise return the ended pool.\n const originalEnd = pool.end.bind(pool);\n let db: DatabaseInterface;\n let endPromise: Promise<void> | undefined;\n const evictFromCache = () => connectionCache.forget(db);\n (pool as any).end = (callback?: (error?: Error) => void) => {\n if (!endPromise) {\n evictFromCache();\n endPromise = originalEnd();\n }\n if (callback) {\n endPromise.then(\n () => callback(),\n (error) =>\n callback(error instanceof Error ? error : new Error(String(error))),\n );\n return;\n }\n return endPromise;\n };\n\n const client = pool;\n\n /**\n * Absorbs 'error' events for the clients currently checked out for a\n * transaction, keyed by client so the listener can be removed on release.\n */\n const txErrorAbsorbers = new WeakMap<PoolClient, () => void>();\n const releasedTxClients = new WeakSet<PoolClient>();\n\n /**\n * Checks out a pooled client for a transaction.\n *\n * pg-pool drops its own idle 'error' listener while a client is checked out,\n * so a backend that dies mid-transaction would emit an unhandled 'error' and\n * terminate the process. Absorb it here — the failure still reaches the\n * caller as a rejected query — and drop the listener again on release so\n * repeated checkouts of the same client cannot accumulate them.\n */\n const acquireTxClient = async (): Promise<PoolClient> => {\n const txClient = await client.connect();\n // The pool hands back the same client objects, so the release guard has to\n // be reset per checkout — otherwise every reuse after the first would be\n // treated as already released and stay checked out forever.\n releasedTxClients.delete(txClient);\n const absorb = () => {};\n txClient.on('error', absorb);\n txErrorAbsorbers.set(txClient, absorb);\n return txClient;\n };\n\n /**\n * Returns a transaction client to the pool exactly once.\n *\n * Every teardown path must run this, including the ones reached by a throwing\n * COMMIT or ROLLBACK — a client that is never released stays checked out for\n * the life of the process, and enough of them exhaust the pool. Releasing\n * twice throws, so the released clients are tracked rather than assumed.\n *\n * @param txClient - The pooled client backing a transaction\n * @param destroy - Destroy the connection instead of reusing it, for when the\n * transaction state could not be cleaned up\n */\n const releaseTxClient = (txClient: PoolClient, destroy = false): void => {\n if (releasedTxClients.has(txClient)) return;\n releasedTxClients.add(txClient);\n const absorb = txErrorAbsorbers.get(txClient);\n if (absorb) {\n txClient.off('error', absorb);\n txErrorAbsorbers.delete(txClient);\n }\n txClient.release(destroy || undefined);\n };\n\n /**\n * Rolls back a failed transaction and returns its client to the pool.\n *\n * The connection may still be inside a transaction, so ROLLBACK is attempted\n * to normalize it. If that works the connection is clean and worth reusing;\n * if it does not, the state is unknown and the connection is destroyed rather\n * than handed to unrelated code later.\n *\n * @returns The rollback failure, if the connection could not be normalized\n */\n const discardTxClient = async (txClient: PoolClient): Promise<unknown> => {\n try {\n await txClient.query('ROLLBACK');\n releaseTxClient(txClient);\n return undefined;\n } catch (rollbackError) {\n releaseTxClient(txClient, true);\n return rollbackError;\n }\n };\n\n /**\n * Keeps the first PostgreSQL statement failure attached to a transaction.\n *\n * PostgreSQL reports every later statement in an aborted transaction as\n * 25P02. Replacing the first failure with that generic state error hides the\n * actionable code and diagnostics from callers. The scoped executor instead\n * rethrows the first failure whenever PostgreSQL reports 25P02, and exposes\n * the recorded failure so a swallowed statement error cannot make COMMIT's\n * implicit rollback look successful.\n */\n const createTransactionExecutor = (txClient: PoolClient) => {\n const tracker = createTransactionErrorTracker(\n (error) => error instanceof PgDatabaseError,\n );\n const { pending, preserve: preserveFirstError } = tracker;\n\n const executor: PostgresQueryExecutor = {\n query: (sql, values) => tracker.track(txClient.query(sql, values), sql),\n };\n\n const client = new Proxy(txClient, {\n get(target, property) {\n if (property === 'query') {\n return (...args: any[]) => {\n const query = args[0];\n const callbackIndex =\n typeof args.at(-1) === 'function' ? args.length - 1 : -1;\n const submittable =\n typeof query === 'object' &&\n query !== null &&\n 'submit' in query &&\n typeof query.submit === 'function';\n\n if (submittable) {\n if (\n !('handleError' in query) ||\n typeof query.handleError !== 'function' ||\n !('handleReadyForQuery' in query) ||\n typeof query.handleReadyForQuery !== 'function'\n ) {\n return Reflect.apply(target.query, target, args);\n }\n\n const handleError = query.handleError;\n const handleReadyForQuery = query.handleReadyForQuery;\n let complete!: () => void;\n const completion = new Promise<void>((resolve) => {\n complete = resolve;\n });\n let completed = false;\n const finish = () => {\n if (completed) return;\n completed = true;\n query.handleError = handleError;\n query.handleReadyForQuery = handleReadyForQuery;\n pending.delete(completion);\n complete();\n };\n pending.add(completion);\n query.handleError = function (...handlerArgs: unknown[]) {\n const error = preserveFirstError(handlerArgs[0]);\n try {\n return Reflect.apply(handleError, this, [\n error,\n ...handlerArgs.slice(1),\n ]);\n } finally {\n finish();\n }\n };\n query.handleReadyForQuery = function (...handlerArgs: unknown[]) {\n try {\n const result = Reflect.apply(\n handleReadyForQuery,\n this,\n handlerArgs,\n );\n tracker.confirm(query);\n return result;\n } finally {\n finish();\n }\n };\n try {\n return Reflect.apply(target.query, target, args);\n } catch (error) {\n finish();\n throw preserveFirstError(error);\n }\n }\n\n if (callbackIndex !== -1) {\n const callback = args[callbackIndex];\n let complete!: () => void;\n const completion = new Promise<void>((resolve) => {\n complete = resolve;\n });\n pending.add(completion);\n args[callbackIndex] = (error: unknown, result: unknown) => {\n const callbackError =\n error === null || error === undefined\n ? error\n : preserveFirstError(error);\n if (callbackError === null || callbackError === undefined) {\n tracker.confirm(query);\n }\n pending.delete(completion);\n complete();\n callback(callbackError, result);\n };\n try {\n return Reflect.apply(target.query, target, args);\n } catch (error) {\n pending.delete(completion);\n complete();\n throw preserveFirstError(error);\n }\n }\n\n const result = Reflect.apply(target.query, target, args);\n if (\n typeof result === 'object' &&\n result !== null &&\n 'then' in result &&\n typeof result.then === 'function'\n ) {\n return tracker.track(Promise.resolve(result), query);\n }\n if (\n typeof result === 'object' &&\n result !== null &&\n 'once' in result &&\n typeof result.once === 'function'\n ) {\n let complete!: () => void;\n const completion = new Promise<void>((resolve) => {\n complete = resolve;\n });\n const finish = () => {\n pending.delete(completion);\n complete();\n };\n pending.add(completion);\n result.once('error', (error: unknown) => {\n preserveFirstError(error);\n finish();\n });\n result.once('end', () => {\n tracker.confirm(query);\n finish();\n });\n result.once('close', finish);\n }\n return result;\n };\n }\n return Reflect.get(target, property, target);\n },\n });\n\n return {\n client,\n executor,\n clearError: tracker.clearError,\n drain: tracker.drain,\n getError: tracker.getError,\n getUnconfirmedError: tracker.getUnconfirmedError,\n };\n };\n\n const assertCommitted = (\n result: PgQueryResult,\n transactionState?: ReturnType<typeof createTransactionExecutor>,\n ): void => {\n if (result.command === 'COMMIT') return;\n\n const queryError =\n transactionState?.getError() ?? transactionState?.getUnconfirmedError();\n if (queryError !== undefined) throw queryError;\n\n throw new DatabaseError(\n 'PostgreSQL rolled back the transaction at commit',\n {\n command: result.command,\n },\n );\n };\n\n const dialect = createPostgresDialect({\n client,\n // Pooled: a probe on its own connection cannot abort the caller's\n // transaction.\n probeExecutor: () => client,\n runInTransaction: async (work) => {\n const txClient = await acquireTxClient();\n\n try {\n await txClient.query('BEGIN');\n const result = await work(txClient);\n const commitResult = await txClient.query('COMMIT');\n assertCommitted(commitResult);\n releaseTxClient(txClient);\n return result;\n } catch (error) {\n const rollbackError = await discardTxClient(txClient);\n if (rollbackError !== undefined && error instanceof Error) {\n error.cause ??= rollbackError;\n }\n throw error;\n }\n },\n });\n const { serializeRecord, createClientMethods, createNestedTransaction } =\n dialect;\n\n const {\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 getTableSchema,\n syncSchema,\n } = createClientMethods(client, false, serializeRecord);\n const alterTable = createAlterTable(client);\n\n /**\n * Acquire a pinned connection from the pool for session-scoped state such as\n * `pg_advisory_lock`. Every query on the returned handle runs on the same\n * client until {@link SessionHandle.release} drops the connection (which\n * frees any session locks it held). The connection is held for the handle's\n * lifetime, so hold one session per process, not per operation.\n */\n const acquireSession = async (): Promise<SessionHandle> => {\n const sessionClient = await pool.connect();\n let released = false;\n let lost = false;\n\n // pg-pool removes its idle 'error' listener when a client is checked out.\n // A session is pinned for the process lifetime and mostly idle between\n // queries, so a backend disconnect/failover would emit 'error' on a\n // listener-less client and crash the process. Absorb it and mark the\n // session dead instead; the next query()/isActive() surfaces it.\n sessionClient.on('error', () => {\n lost = true;\n });\n\n return {\n query: async (sql: string, ...values: any[]) => {\n if (released) {\n throw new DatabaseError('Session has been released', {});\n }\n if (lost) {\n throw new DatabaseError('Session connection was lost', {});\n }\n const normalized = normalizePostgresRawQuery(sql, values);\n try {\n const result = await sessionClient.query(\n normalized.sql,\n normalized.values,\n );\n return {\n rows: result.rows,\n rowCount: result.rowCount ?? 0,\n };\n } catch (e) {\n throw wrapDatabaseError('Failed to execute session query', e, {\n sql: normalized.sql,\n values: normalized.values,\n });\n }\n },\n isActive: () => !released && !lost,\n release: async () => {\n if (released) return;\n released = true;\n // Free session advisory locks before tearing down so the contract\n // \"after release() the locks are gone\" holds deterministically — the\n // destroy below is async (TCP teardown) and resolves later. Skip on a\n // lost connection (nothing to talk to; backend exit frees them anyway).\n if (!lost) {\n try {\n // A caller that left the connection in an aborted transaction\n // (BEGIN, a failed statement, then release) would make\n // pg_advisory_unlock_all() error with \"current transaction is\n // aborted\". Roll back first (a no-op when no transaction is open)\n // so the unlock runs and the deterministic-release contract holds.\n await sessionClient.query('ROLLBACK');\n } catch {\n // No open transaction, or already gone — proceed to unlock.\n }\n try {\n await sessionClient.query('SELECT pg_advisory_unlock_all()');\n } catch {\n // Best-effort; the destroy below frees locks at backend exit.\n }\n }\n // Destroy the physical connection rather than returning it to the pool.\n // Returning it would NOT clear residual session state, which could then\n // leak onto a connection later handed to unrelated code.\n sessionClient.release(true);\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 // Get a client from the pool for the transaction\n const txClient = await acquireTxClient();\n\n let nestedTransaction:\n | ReturnType<typeof createNestedTransaction>\n | undefined;\n const transactionState = createTransactionExecutor(txClient);\n try {\n await txClient.query('BEGIN');\n\n // Create a transaction-scoped database interface\n let txDb!: DatabaseInterface;\n nestedTransaction = createNestedTransaction(\n transactionState.executor,\n () => txDb,\n transactionState.clearError,\n new AsyncLocalStorage<NestedScope>(),\n );\n txDb = {\n url,\n engine: 'postgres',\n reopenOptions,\n client: transactionState.client,\n ...createClientMethods(\n transactionState.executor,\n true,\n serializeRecord,\n transactionState.clearError,\n ),\n transaction: nestedTransaction,\n };\n\n const result = await callback(txDb);\n await nestedTransaction.drain();\n await transactionState.drain();\n const statementError = transactionState.getError();\n if (statementError !== undefined) {\n throw statementError;\n }\n const commitResult = await txClient.query('COMMIT');\n assertCommitted(commitResult, transactionState);\n releaseTxClient(txClient);\n return result;\n } catch (error) {\n // Promise.all may reject before queued nested scopes finish. Do not\n // release this client until their savepoint work has drained.\n await nestedTransaction?.drain();\n await transactionState.drain();\n // Never let a failing ROLLBACK replace the caller's error. On a dead\n // connection the rollback throws \"Connection terminated unexpectedly\",\n // which would otherwise be the only thing the caller ever sees.\n const rollbackError = await discardTxClient(txClient);\n if (rollbackError !== undefined && error instanceof Error) {\n error.cause ??= rollbackError;\n }\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 // Get a client from the pool for the transaction\n const txClient = await acquireTxClient();\n try {\n await txClient.query('BEGIN');\n } catch (error) {\n // BEGIN failed, so there is no transaction for the caller to end and no\n // handle to release the client — return it here or it is stranded.\n releaseTxClient(txClient, true);\n throw error;\n }\n\n let active = true;\n let nestedTransaction:\n | ReturnType<typeof createNestedTransaction>\n | undefined;\n const transactionState = createTransactionExecutor(txClient);\n\n // COMMIT and ROLLBACK both throw in ordinary operation — deferred\n // constraint violations, serialization failures, a connection lost at\n // commit time. The transaction is over either way, so end it and return the\n // client before rethrowing; leaving it checked out would strand a pooled\n // connection permanently and eventually deadlock the pool.\n const end = async (command: 'COMMIT' | 'ROLLBACK'): Promise<void> => {\n if (!active) {\n throw new DatabaseError('Transaction already ended', {});\n }\n try {\n await nestedTransaction?.drain();\n await transactionState.drain();\n const statementError = transactionState.getError();\n if (command === 'COMMIT' && statementError !== undefined) {\n throw statementError;\n }\n const result = await txClient.query(command);\n if (command === 'COMMIT') assertCommitted(result, transactionState);\n active = false;\n releaseTxClient(txClient);\n } catch (error) {\n active = false;\n const rollbackError = await discardTxClient(txClient);\n if (rollbackError !== undefined && error instanceof Error) {\n error.cause ??= rollbackError;\n }\n throw error;\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 let txHandle!: TransactionHandle;\n nestedTransaction = createNestedTransaction(\n transactionState.executor,\n () => txHandle,\n transactionState.clearError,\n new AsyncLocalStorage<NestedScope>(),\n );\n txHandle = {\n url,\n engine: 'postgres',\n reopenOptions,\n client: transactionState.client,\n ...createClientMethods(\n transactionState.executor,\n true,\n serializeRecord,\n transactionState.clearError,\n ),\n transaction: nestedTransaction,\n commit,\n rollback,\n isActive,\n };\n\n return txHandle;\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 engine: 'postgres',\n reopenOptions,\n client,\n insert,\n update,\n upsert,\n get,\n getOrInsert,\n delete: deleteRecords,\n count,\n list,\n table,\n many,\n single,\n pluck,\n execute,\n query,\n oo,\n oO,\n ox,\n xx,\n tableExists,\n getTableSchema,\n syncSchema,\n transaction,\n };\n\n await schemaManager.initializeSchemas(currentDb, options);\n };\n\n db = {\n url,\n engine: 'postgres',\n reopenOptions,\n client,\n insert,\n update,\n upsert,\n get,\n getOrInsert,\n delete: deleteRecords,\n count,\n list,\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 initializeSchemas,\n transaction,\n beginTransaction,\n acquireSession,\n getTableSchema,\n alterTable,\n vector: createVectorCapabilities(pool),\n close: async () => {\n await pool.end();\n },\n };\n\n return db;\n}\n"],"mappings":";;;;;;;;;AAkCA,IAAM,kBAAkB;AAExB,IAAM,yBAAyB;AA4F/B,WAAW,qCACT,IAAI,gBAAmC;AACzC,IAAM,kBAAkB,WAAW;;;;;;;;;;;AAYnC,SAAS,0BAA8C;CACrD,MAAM,WAAW,WAAW;CAC5B,IAAI,UACF,OAAO;CAET,IAAI;CACJ,IAAI;EACF,UAAU,UAAU,OAAO,YACzB;GAAE,MAAM;GAAQ,MAAM;EAAU,GAChC,OACA,CAAC,MAAM,CACT;CACF,SAAS,OAAO;EACd,UAAU,QAAQ,OAAO,KAAK;CAChC;CACA,WAAW,gCAAgC;CAC3C,QAAQ,YAAY;EAClB,IAAI,WAAW,kCAAkC,SAC/C,WAAW,gCAAgC,KAAA;CAE/C,CAAC;CACD,OAAO;AACT;;;;;AAMA,eAAsB,+BAA8C;CAClE,MAAM,gBAAgB,MAAM,qBAAqB;AACnD;AAEA,eAAe,sBAAsB,IAAsC;CACzE,IAAI,GAAG,OAAO;EACZ,MAAM,GAAG,MAAM;EACf;CACF;CACA,MAAM,GAAG,OAAO,IAAI;AACtB;AAcA,SAAS,sBACP,SACyB;CACzB,MAAM,aAAgB,QAAuB,gBAC3C,WAAW,KAAA,IAAY,SAAS;CAClC,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,UAAU;EACd,KAAK,UAAU,QAAQ,KAAK,QAAQ,IAAI,YAAY;EACpD,UAA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gBAAgB,QAAQ;GAC1B,SAAS,OAAO;IACd,SAAS;IACT,MAAM,gBAAgB,MAAM,gBAAgB,QAAQ;IACpD,IAAI,kBAAkB,KAAA,KAAa,iBAAiB,OAClD,MAAM,UAAU;IAElB,MAAM;GACR;EACF;EAEA,MAAM,eAA8B,IAAI,QAAQ;EAEhD,MAAM,iBAAgC,IAAI,UAAU;EAEpD,MAAM,iBAA0B;EAGhC,IAAI;EACJ,oBAAoB,wBAClB,iBAAiB,gBACX,UACN,iBAAiB,YACjB,IAAI,kBAA+B,CACrC;EACA,WAAW;GACT;GACA,QAAQ;GACR;GACA,QAAQ,iBAAiB;GACzB,GAAG,oBACD,iBAAiB,UACjB,MACA,iBACA,iBAAiB,UACnB;GACA,aAAa;GACb;GACA;GACA;EACF;EAEA,OAAO;CACT;;;;;;;;CASA,MAAM,oBAAoB,OACxB,YACkB;EAClB,MAAM,gBAAgB,IAAI,sBAAsB;EAChD,MAAM,YAA+B;GACnC;GACA,QAAQ;GACR;GACA;GACA;GACA;GACA;GACA;GACA;GACA,QAAQ;GACR;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EAEA,MAAM,cAAc,kBAAkB,WAAW,OAAO;CAC1D;CAEA,KAAK;EACH;EACA,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;EACA;EACA;EACA,QAAQ,yBAAyB,IAAI;EACrC,OAAO,YAAY;GACjB,MAAM,KAAK,IAAI;EACjB;CACF;CAEA,OAAO;AACT"}
@@ -1,415 +1,5 @@
1
- import { D as validateIndexName, E as validateColumnNames, O as validatePlainColumnName, T as validateColumnName, a as buildAdapterWhere, b as quoteLiteralIdentifier, d as rewriteSqlParameters, g as generateCreateIndexStatement, h as generateAddColumnStatement, k as validateTableName, n as ReopenNotSupportedError, p as wrapDatabaseError, s as formatDbError, u as resolveInsertColumns, w as renderIdentifier, x as quotePostgresColumnName } from "./types-DihIt7ez.js";
1
+ import { A as validateTableName, D as validateColumnNames, E as validateColumnName, O as validateIndexName, S as quotePostgresColumnName, T as renderIdentifier, _ as generateCreateIndexStatement, a as buildAdapterWhere, d as rewriteSqlParameters, g as generateAddColumnStatement, k as validatePlainColumnName, m as assertIntrospectionTableName, p as wrapDatabaseError, s as formatDbError, u as resolveInsertColumns, x as quoteLiteralIdentifier } from "./types-B5zTs-6A.js";
2
2
  import { DatabaseError } from "@happyvertical/utils";
3
- //#region src/shared/connection-cache.ts
4
- var CACHED_VALIDATION_CAPABILITY = Symbol.for("@happyvertical/sql/connection-cache-cached-validation/v1");
5
- /** Race-safe async resource cache used by database adapters. */
6
- var ConnectionCache = class {
7
- [CACHED_VALIDATION_CAPABILITY] = true;
8
- #connections = /* @__PURE__ */ new Map();
9
- #pending = /* @__PURE__ */ new Map();
10
- #evictions = /* @__PURE__ */ new Map();
11
- #requests = /* @__PURE__ */ new Map();
12
- #clearing = /* @__PURE__ */ new Map();
13
- #failedClosures = /* @__PURE__ */ new Map();
14
- async getOrCreate(key, options, create, close, validateCached) {
15
- validateDatabaseCacheOptions(options);
16
- const request = key && options.cache !== false ? this.#registerRequest(key) : void 0;
17
- try {
18
- this.#throwIfCancelled(request);
19
- if (key && options.clearCache) {
20
- await this.evict(key, close);
21
- this.#throwIfCancelled(request);
22
- }
23
- if (key) this.#throwIfFailedClosure(key);
24
- if (!key || options.cache === false) return create();
25
- while (true) {
26
- if (this.#evictions.has(key)) {
27
- await this.#waitForEviction(key);
28
- this.#throwIfCancelled(request);
29
- }
30
- this.#throwIfFailedClosure(key);
31
- const cached = this.#connections.get(key);
32
- if (cached !== void 0) {
33
- if (!validateCached) return cached;
34
- const isValid = await validateCached(cached);
35
- this.#throwIfCancelled(request);
36
- if (isValid && this.#connections.get(key) === cached && !this.#evictions.has(key)) return cached;
37
- if (!isValid && this.#connections.get(key) === cached && !this.#evictions.has(key)) {
38
- await this.evict(key, close);
39
- this.#throwIfCancelled(request);
40
- }
41
- continue;
42
- }
43
- let pending = this.#pending.get(key);
44
- if (!pending) {
45
- this.#throwIfCancelled(request);
46
- pending = {
47
- invalidated: false,
48
- promise: create()
49
- };
50
- this.#pending.set(key, pending);
51
- }
52
- let connection;
53
- try {
54
- connection = await pending.promise;
55
- } catch (error) {
56
- if (this.#pending.get(key) === pending) this.#pending.delete(key);
57
- throw error;
58
- }
59
- if (pending.invalidated || this.#evictions.has(key)) {
60
- if (this.#evictions.has(key)) await this.#waitForEviction(key);
61
- this.#throwIfCancelled(request);
62
- if (pending.invalidated === "clear") throw this.#clearError();
63
- continue;
64
- }
65
- this.#throwIfCancelled(request);
66
- if (this.#pending.get(key) === pending) this.#pending.delete(key);
67
- this.#connections.set(key, connection);
68
- return connection;
69
- }
70
- } finally {
71
- if (request && key) this.#finishRequest(key, request);
72
- }
73
- }
74
- async evict(key, close, invalidation = "evict") {
75
- const previous = this.#evictions.get(key);
76
- const state = previous?.state ?? {
77
- invalidated: /* @__PURE__ */ new Set(),
78
- invalidation
79
- };
80
- if (invalidation === "clear") {
81
- state.invalidation = "clear";
82
- for (const pending of state.invalidated) pending.invalidated = "clear";
83
- }
84
- const eviction = (previous?.promise ?? Promise.resolve()).then(async () => {
85
- const resources = new Set(this.#failedClosures.get(key)?.resources ?? []);
86
- this.#failedClosures.delete(key);
87
- const cached = this.#connections.get(key);
88
- this.#connections.delete(key);
89
- if (cached) resources.add(cached);
90
- const pending = this.#pending.get(key);
91
- this.#pending.delete(key);
92
- if (pending) {
93
- state.invalidated.add(pending);
94
- pending.invalidated = state.invalidation;
95
- const initialized = await pending.promise.catch(() => void 0);
96
- if (initialized !== void 0) resources.add(initialized);
97
- }
98
- const closeResults = await Promise.allSettled([...resources].map(async (resource) => {
99
- await close(resource);
100
- return resource;
101
- }));
102
- const failures = closeResults.filter((result) => result.status === "rejected");
103
- if (failures.length) {
104
- const resourceList = [...resources];
105
- const failedResources = /* @__PURE__ */ new Set();
106
- closeResults.forEach((result, index) => {
107
- if (result.status === "rejected") failedResources.add(resourceList[index]);
108
- });
109
- const error = failures.length === 1 ? failures[0].reason : new AggregateError(failures.map((failure) => failure.reason), "Multiple database connections failed to close");
110
- this.#failedClosures.set(key, {
111
- error,
112
- resources: failedResources
113
- });
114
- throw error;
115
- }
116
- });
117
- const chain = {
118
- promise: eviction,
119
- state
120
- };
121
- this.#evictions.set(key, chain);
122
- try {
123
- await eviction;
124
- } finally {
125
- if (this.#evictions.get(key) === chain) this.#evictions.delete(key);
126
- }
127
- }
128
- async clear(close) {
129
- const keys = /* @__PURE__ */ new Set([
130
- ...this.#connections.keys(),
131
- ...this.#pending.keys(),
132
- ...this.#evictions.keys(),
133
- ...this.#requests.keys(),
134
- ...this.#clearing.keys(),
135
- ...this.#failedClosures.keys()
136
- ]);
137
- const failures = (await Promise.allSettled([...keys].map((key) => this.#clearKey(key, close)))).filter((result) => result.status === "rejected");
138
- if (failures.length === 1) throw failures[0].reason;
139
- if (failures.length > 1) throw new AggregateError(failures.map((failure) => failure.reason), "Multiple database connection cache entries failed to clear");
140
- }
141
- forget(connection) {
142
- for (const [key, cached] of this.#connections) if (cached === connection) this.#connections.delete(key);
143
- }
144
- /** @internal Test-only visibility; includes every retained namespace. */
145
- get size() {
146
- return this.#connections.size + this.#pending.size + this.#evictions.size + this.#requests.size + this.#clearing.size + this.#failedClosures.size;
147
- }
148
- async #clearKey(key, close) {
149
- this.#clearing.set(key, (this.#clearing.get(key) ?? 0) + 1);
150
- try {
151
- this.#cancelRequests(key);
152
- await this.evict(key, close, "clear");
153
- while (this.#requests.get(key)?.size) {
154
- this.#cancelRequests(key);
155
- await Promise.all([...this.#requests.get(key) ?? []].map((request) => request.done));
156
- }
157
- } finally {
158
- const remaining = (this.#clearing.get(key) ?? 1) - 1;
159
- if (remaining === 0) this.#clearing.delete(key);
160
- else this.#clearing.set(key, remaining);
161
- }
162
- }
163
- #cancelRequests(key) {
164
- for (const request of this.#requests.get(key) ?? []) request.cancelled = true;
165
- }
166
- #clearError() {
167
- return /* @__PURE__ */ new Error("Database connection initialization was cancelled by cache clear");
168
- }
169
- #finishRequest(key, request) {
170
- const requests = this.#requests.get(key);
171
- requests?.delete(request);
172
- if (requests?.size === 0) this.#requests.delete(key);
173
- request.finish();
174
- }
175
- #registerRequest(key) {
176
- let finish = () => {};
177
- const done = new Promise((resolve) => {
178
- finish = resolve;
179
- });
180
- const request = {
181
- cancelled: this.#clearing.has(key),
182
- done,
183
- finish
184
- };
185
- const requests = this.#requests.get(key) ?? /* @__PURE__ */ new Set();
186
- requests.add(request);
187
- this.#requests.set(key, requests);
188
- return request;
189
- }
190
- #throwIfCancelled(request) {
191
- if (request?.cancelled) throw this.#clearError();
192
- }
193
- #throwIfFailedClosure(key) {
194
- const failure = this.#failedClosures.get(key);
195
- if (failure) throw failure.error;
196
- }
197
- async #waitForEviction(key) {
198
- while (true) {
199
- const eviction = this.#evictions.get(key);
200
- if (!eviction) return;
201
- await eviction.promise;
202
- }
203
- }
204
- };
205
- /**
206
- * Adds cached-resource validation to a shared cache created by an older module.
207
- *
208
- * JSON connection caches live on `globalThis`, so a compatible older SDK copy
209
- * can create the shared object before this module loads. Mutating that object
210
- * preserves one cache for both module copies while upgrading its four-argument
211
- * `getOrCreate` method to the current validation contract.
212
- */
213
- function enableCachedValidation(cache) {
214
- if (cache[CACHED_VALIDATION_CAPABILITY]) return cache;
215
- const legacyGetOrCreate = cache.getOrCreate.bind(cache);
216
- const legacyClear = cache.clear.bind(cache);
217
- const locks = /* @__PURE__ */ new Map();
218
- let clearGeneration = 0;
219
- let activeClear;
220
- const runLocked = async (key, work) => {
221
- const previous = locks.get(key) ?? Promise.resolve();
222
- let release;
223
- const current = new Promise((resolve) => {
224
- release = resolve;
225
- });
226
- const chain = previous.then(() => current, () => current);
227
- locks.set(key, chain);
228
- await previous.catch(() => {});
229
- try {
230
- return await work();
231
- } finally {
232
- release();
233
- if (locks.get(key) === chain) locks.delete(key);
234
- }
235
- };
236
- Object.defineProperty(cache, "getOrCreate", {
237
- configurable: true,
238
- value: async (key, options, create, close, validateCached) => {
239
- if (!key || options.cache === false) return legacyGetOrCreate(key, options, create, close);
240
- const requestGeneration = clearGeneration;
241
- const throwIfCleared = () => {
242
- if (activeClear || requestGeneration !== clearGeneration) throw new Error("Database connection initialization was cancelled by cache clear");
243
- };
244
- return runLocked(key, async () => {
245
- throwIfCleared();
246
- let requestOptions = options;
247
- while (true) {
248
- throwIfCleared();
249
- const candidate = await legacyGetOrCreate(key, requestOptions, create, close);
250
- throwIfCleared();
251
- if (!validateCached) return candidate;
252
- const isValid = await validateCached(candidate);
253
- throwIfCleared();
254
- if (isValid) {
255
- const confirmed = await legacyGetOrCreate(key, {
256
- ...requestOptions,
257
- clearCache: false
258
- }, create, close);
259
- throwIfCleared();
260
- if (confirmed === candidate) return candidate;
261
- } else await cache.evict(key, close);
262
- requestOptions = {
263
- ...options,
264
- clearCache: false
265
- };
266
- }
267
- });
268
- },
269
- writable: true
270
- });
271
- Object.defineProperty(cache, "clear", {
272
- configurable: true,
273
- value: async (close) => {
274
- if (activeClear) return activeClear;
275
- clearGeneration += 1;
276
- const clearing = (async () => {
277
- let clearError;
278
- let clearFailed = false;
279
- try {
280
- await legacyClear(close);
281
- } catch (error) {
282
- clearFailed = true;
283
- clearError = error;
284
- }
285
- while (locks.size > 0) await Promise.allSettled([...locks.values()]);
286
- if (clearFailed) throw clearError;
287
- })();
288
- activeClear = clearing;
289
- try {
290
- await clearing;
291
- } finally {
292
- if (activeClear === clearing) activeClear = void 0;
293
- }
294
- },
295
- writable: true
296
- });
297
- Object.defineProperty(cache, CACHED_VALIDATION_CAPABILITY, {
298
- configurable: false,
299
- enumerable: false,
300
- value: true,
301
- writable: false
302
- });
303
- return cache;
304
- }
305
- function validateDatabaseCacheOptions(options) {
306
- if (options.dbid === "") throw new Error("Database cache dbid must be a non-empty string");
307
- }
308
- //#endregion
309
- //#region src/shared/reopen.ts
310
- /**
311
- * A `reopenOptions` for engines that allow one owner per database: it refuses
312
- * with {@link ReopenNotSupportedError}.
313
- */
314
- function refuseReopen(engine, reason) {
315
- return () => {
316
- throw new ReopenNotSupportedError(engine, reason);
317
- };
318
- }
319
- //#endregion
320
- //#region src/shared/transaction-lock.ts
321
- /**
322
- * How long a queued transaction waits for the connection before giving up.
323
- *
324
- * A transaction that legitimately runs longer than this will make the ones
325
- * behind it fail rather than stall indefinitely. Raise it with the adapter's
326
- * `transactionQueueTimeout` option if that is the wrong trade for a workload.
327
- */
328
- var DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS = 3e4;
329
- /**
330
- * Creates a lock that serializes transactions on one connection.
331
- *
332
- * SQLite, DuckDB and the JSON adapter each drive a single connection, and a
333
- * connection can only be in one transaction at a time. `transaction()` used to
334
- * issue `BEGIN` on that shared connection with no serialization and no record
335
- * of whether one was already open, so two overlapping calls corrupted each
336
- * other: the second `BEGIN` threw, its `catch` ran `ROLLBACK`, and that
337
- * rollback landed on the *first* transaction — committing part of its work,
338
- * discarding the rest, and rejecting its promise. Nesting was not required;
339
- * two concurrent requests were enough, which made it reachable from any server
340
- * handling more than one at a time.
341
- *
342
- * The lock spans the whole `BEGIN` … `COMMIT`/`ROLLBACK` sequence, so a queued
343
- * transaction starts only once the previous one has ended. It is a
344
- * promise-chain mutex, the same shape as the `withNullAwareUpsertLock` the
345
- * SQLite adapter already used for the narrower upsert case.
346
- *
347
- * Re-entrant calls must not come through here. A nested `tx.transaction()`
348
- * arrives via the transaction-scoped interface, which re-enters under a
349
- * `SAVEPOINT` (SQLite) or refuses (DuckDB, JSON) without ever reaching the
350
- * top-level `transaction()`; routing one here instead would make it wait on a
351
- * lock its own caller is holding.
352
- *
353
- * @param adapter - Adapter name, for the timeout error
354
- * @param timeoutMs - Ceiling on how long to wait for a turn
355
- */
356
- function createTransactionLock(adapter, timeoutMs = DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS) {
357
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new DatabaseError("transactionQueueTimeout must be a positive, finite number of milliseconds", {
358
- adapter,
359
- timeoutMs
360
- });
361
- let tail = Promise.resolve();
362
- let held = false;
363
- const acquire = async () => {
364
- const previous = tail;
365
- let release = () => {};
366
- const current = new Promise((resolve) => {
367
- release = resolve;
368
- });
369
- tail = previous.then(() => current, () => current);
370
- let timer;
371
- try {
372
- await new Promise((resolve, reject) => {
373
- timer = setTimeout(() => {
374
- reject(new DatabaseError(`Timed out after ${timeoutMs}ms waiting for the ${adapter} connection's current transaction to finish. This connection runs one transaction at a time. Usually one of: a beginTransaction() handle that was never committed or rolled back; a top-level db.* call that opens its own transaction being made inside a transaction callback, which waits on the connection its own caller holds (use the tx-scoped method instead); or simply more queued transactions than transactionQueueTimeout allows for.`, {
375
- adapter,
376
- timeoutMs
377
- }));
378
- }, timeoutMs);
379
- previous.then(resolve, resolve);
380
- });
381
- } catch (error) {
382
- release();
383
- throw error;
384
- } finally {
385
- if (timer) clearTimeout(timer);
386
- }
387
- let released = false;
388
- held = true;
389
- return () => {
390
- if (released) return;
391
- released = true;
392
- held = false;
393
- release();
394
- };
395
- };
396
- const run = async (work) => {
397
- const release = await acquire();
398
- try {
399
- return await work();
400
- } finally {
401
- release();
402
- }
403
- };
404
- return {
405
- acquire,
406
- get held() {
407
- return held;
408
- },
409
- run
410
- };
411
- }
412
- //#endregion
413
3
  //#region src/shared/postgres-dialect.ts
414
4
  /**
415
5
  * PostgreSQL dialect logic shared by every adapter that speaks to a Postgres
@@ -1505,9 +1095,10 @@ function createGetTableSchema(methods) {
1505
1095
  * @returns Promise resolving to table schema info or null if table doesn't exist
1506
1096
  * @throws Error if the query fails
1507
1097
  */
1508
- const getTableSchema = async (requested) => {
1098
+ const getTableSchema = async (requested, schemaOptions) => {
1099
+ assertIntrospectionTableName(requested);
1509
1100
  const relation = parseRelationName(requested);
1510
- if (relation.qualified === null) validateTableName(requested);
1101
+ const optedIn = !!schemaOptions?.includeGenerated || !!schemaOptions?.includeHidden;
1511
1102
  try {
1512
1103
  if (!await tableExists(requested)) return null;
1513
1104
  const resolved = await many`
@@ -1545,7 +1136,7 @@ function createGetTableSchema(methods) {
1545
1136
  AND tc.constraint_type = 'PRIMARY KEY'
1546
1137
  `;
1547
1138
  const pkColumns = new Set(pkRows.map((row) => row.column_name));
1548
- const generatedRows = await many`
1139
+ const generatedRows = optedIn ? await many`
1549
1140
  SELECT attribute.attname AS column_name
1550
1141
  FROM pg_catalog.pg_attribute AS attribute
1551
1142
  WHERE attribute.attrelid = COALESCE(
@@ -1555,18 +1146,20 @@ function createGetTableSchema(methods) {
1555
1146
  AND attribute.attnum > 0
1556
1147
  AND NOT attribute.attisdropped
1557
1148
  AND attribute.attgenerated::text <> ''
1558
- `;
1149
+ ` : [];
1559
1150
  const generatedColumns = new Set(generatedRows.map((row) => row.column_name));
1560
1151
  const columns = {};
1561
1152
  for (const row of columnRows) {
1562
1153
  const colName = row.column_name;
1563
1154
  columns[colName] = {
1564
- generated: generatedColumns.has(colName),
1565
- hidden: false,
1566
1155
  type: row.data_type,
1567
1156
  primaryKey: pkColumns.has(colName),
1568
1157
  notNull: row.is_nullable === "NO",
1569
- defaultValue: row.column_default
1158
+ defaultValue: row.column_default,
1159
+ ...optedIn ? {
1160
+ generated: generatedColumns.has(colName),
1161
+ hidden: false
1162
+ } : {}
1570
1163
  };
1571
1164
  }
1572
1165
  const indexRows = await many`
@@ -1690,6 +1283,6 @@ function createAlterTable(client) {
1690
1283
  };
1691
1284
  }
1692
1285
  //#endregion
1693
- export { normalizePostgresRawQuery as a, refuseReopen as c, validateDatabaseCacheOptions as d, createVectorCapabilities as i, ConnectionCache as l, createPostgresDialect as n, DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS as o, createTransactionErrorTracker as r, createTransactionLock as s, createAlterTable as t, enableCachedValidation as u };
1286
+ export { normalizePostgresRawQuery as a, createVectorCapabilities as i, createPostgresDialect as n, createTransactionErrorTracker as r, createAlterTable as t };
1694
1287
 
1695
- //# sourceMappingURL=postgres-dialect-CevaHPBb.js.map
1288
+ //# sourceMappingURL=postgres-dialect-CL4kFDM0.js.map