@happyvertical/sql 0.116.0 → 0.116.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,12 @@
1
1
  import { E as validateColumnNames, a as buildAdapterWhere, b as quoteLiteralIdentifier, i as DatabaseSchemaManager, l as raw, m as escapeStringLiteral, n as ReopenNotSupportedError, o as buildWhere, p as wrapDatabaseError, r as resolveSchemas, s as formatDbError, t as NestedTransactionError, u as resolveInsertColumns, y as quoteDuckDBColumnName } from "./chunks/types-DihIt7ez.js";
2
2
  import { a as convertUniqueIndexesToInlineConstraints, c as buildAggregate, i as validateColumnName, l as ExpressionError, n as syncSchema, r as tableExists, s as bucketExpr, t as escapeSqlValue, u as renderExpression } from "./chunks/query-DFAYXNk-.js";
3
3
  import { a as dropPostgresDatabase, c as postgresEnvFromUrl, i as databaseNameFromUrl, l as redactDatabaseUrl, n as assertCanImportDatabase, o as dumpPostgresDatabase, r as createPostgresDatabase, s as isLocalDatabaseUrl, t as assertCanExportDatabase, u as restorePostgresDatabase } from "./chunks/postgres-cli-DzZcXSIG.js";
4
- import { a as normalizePostgresRawQuery, c as refuseReopen, d as validateDatabaseCacheOptions, i as createVectorCapabilities, l as ConnectionCache, n as createPostgresDialect, r as createTransactionErrorTracker, s as createTransactionLock, t as createAlterTable, u as enableCachedValidation } from "./chunks/postgres-dialect-CevaHPBb.js";
4
+ import { a as enableCachedValidation, i as ConnectionCache, n as createTransactionLock, r as refuseReopen } from "./chunks/transaction-lock-BX2GJ4ei.js";
5
5
  import { n as createDuckDBResourceCloser, r as throwWithDuckDBCleanup, t as serializeDuckDBStatements } from "./chunks/duckdb-statement-queue-BJ6-PQRr.js";
6
6
  import { t as redactDatabaseUrl$1 } from "./chunks/redact-database-url-CfMDvSdy.js";
7
7
  import { DatabaseError, loadEnvConfig } from "@happyvertical/utils";
8
8
  import { mkdir, readdir, stat } from "node:fs/promises";
9
9
  import { basename, extname, join } from "node:path";
10
- import { AsyncLocalStorage } from "node:async_hooks";
11
- import { webcrypto } from "node:crypto";
12
- import { DatabaseError as DatabaseError$1, Pool } from "pg";
13
10
  //#region \0rolldown/runtime.js
14
11
  var __defProp = Object.defineProperty;
15
12
  var __exportAll = (all, no_symbols) => {
@@ -192,7 +189,7 @@ function countValueFromRow(value) {
192
189
  //#region src/json.ts
193
190
  var json_exports = /* @__PURE__ */ __exportAll({
194
191
  clearConnectionCache: () => clearConnectionCache,
195
- getDatabase: () => getDatabase$2
192
+ getDatabase: () => getDatabase$1
196
193
  });
197
194
  var reopenOptions = refuseReopen("json", "every connection keeps its own in-memory copy of the files, so concurrent writers lose updates");
198
195
  /**
@@ -760,7 +757,7 @@ function validateTableName(table) {
760
757
  * @param options - JSON database options
761
758
  * @returns Database interface for JSON files
762
759
  */
763
- async function getDatabase$2(options) {
760
+ async function getDatabase$1(options) {
764
761
  const cacheKey = options.dbid || `json:${options.url}:${options.writeStrategy || "immediate"}:${options.autoRegister !== false}`;
765
762
  return memoryConnectionCache.getOrCreate(cacheKey, options, () => createTrackedJSONDatabase(options), closeJSONDatabase, isCachedJSONDatabaseFresh);
766
763
  }
@@ -1749,610 +1746,6 @@ async function createJSONDatabase(options) {
1749
1746
  })();
1750
1747
  }
1751
1748
  //#endregion
1752
- //#region src/postgres.ts
1753
- var postgres_exports = /* @__PURE__ */ __exportAll({
1754
- clearPostgresConnectionCache: () => clearPostgresConnectionCache,
1755
- getDatabase: () => getDatabase$1
1756
- });
1757
- /** Default pool size of a reopened PostgreSQL connection. */
1758
- var REOPEN_POOL_MAX = 5;
1759
- var MAX_TIMER_DELAY_MILLIS = 2147483647;
1760
- globalThis.__haveSqlPostgresConnectionCache ??= new ConnectionCache();
1761
- var connectionCache = globalThis.__haveSqlPostgresConnectionCache;
1762
- /**
1763
- * Returns the process-local cache identity HMAC key, generating it on first
1764
- * use. Generating it at import would leave a WebCrypto key job in flight in
1765
- * every isolate that loads the package, and Node aborts the whole process when
1766
- * a worker thread is terminated while such a job completes (#1518).
1767
- *
1768
- * Concurrent first callers share one pending promise. The promise lives on
1769
- * `globalThis` so every copy of this module in an isolate derives the same
1770
- * cache identities. A rejected generation is dropped so the next call retries.
1771
- */
1772
- function getPostgresCacheHmacKey() {
1773
- const existing = globalThis.__haveSqlPostgresCacheHmacKey;
1774
- if (existing) return existing;
1775
- let pending;
1776
- try {
1777
- pending = webcrypto.subtle.generateKey({
1778
- name: "HMAC",
1779
- hash: "SHA-256"
1780
- }, false, ["sign"]);
1781
- } catch (error) {
1782
- pending = Promise.reject(error);
1783
- }
1784
- globalThis.__haveSqlPostgresCacheHmacKey = pending;
1785
- pending.catch(() => {
1786
- if (globalThis.__haveSqlPostgresCacheHmacKey === pending) globalThis.__haveSqlPostgresCacheHmacKey = void 0;
1787
- });
1788
- return pending;
1789
- }
1790
- /**
1791
- * Clears the PostgreSQL connection cache.
1792
- * Useful for test isolation and reconnection scenarios.
1793
- */
1794
- async function clearPostgresConnectionCache() {
1795
- await connectionCache.clear(closePostgresDatabase);
1796
- }
1797
- async function closePostgresDatabase(db) {
1798
- if (db.close) {
1799
- await db.close();
1800
- return;
1801
- }
1802
- await db.client.end();
1803
- }
1804
- function resolvePostgresConfig(options) {
1805
- const preferred = (option, environment) => option !== void 0 ? option : environment;
1806
- const envPort = process.env.HAVE_SQL_PORT;
1807
- const primary = {
1808
- url: preferred(options.url, process.env.HAVE_SQL_URL),
1809
- database: preferred(options.database, process.env.HAVE_SQL_DATABASE),
1810
- host: preferred(options.host, process.env.HAVE_SQL_HOST),
1811
- user: preferred(options.user, process.env.HAVE_SQL_USER),
1812
- password: preferred(options.password, process.env.HAVE_SQL_PASSWORD),
1813
- port: preferred(options.port, envPort === void 0 ? void 0 : Number(envPort))
1814
- };
1815
- const useLegacy = !primary.url && !primary.host && !primary.database && !primary.user;
1816
- const legacy = (value, environment) => value !== void 0 || !useLegacy ? value : environment;
1817
- const legacyPort = process.env.SQLOO_PORT;
1818
- const port = legacy(primary.port, legacyPort === void 0 ? void 0 : Number(legacyPort)) ?? 5432;
1819
- const max = options.max ?? 20;
1820
- const { connectionTimeoutMillis, idleTimeoutMillis } = options;
1821
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("PostgreSQL port must be an integer between 1 and 65535");
1822
- if (!Number.isInteger(max) || max < 1) throw new Error("PostgreSQL pool max must be a positive integer");
1823
- if (connectionTimeoutMillis !== void 0 && (!Number.isInteger(connectionTimeoutMillis) || connectionTimeoutMillis < 0 || connectionTimeoutMillis > MAX_TIMER_DELAY_MILLIS)) throw new Error(`PostgreSQL pool connectionTimeoutMillis must be an integer between 0 and ${MAX_TIMER_DELAY_MILLIS}`);
1824
- if (idleTimeoutMillis !== void 0 && (!Number.isInteger(idleTimeoutMillis) || idleTimeoutMillis < 0 || idleTimeoutMillis > MAX_TIMER_DELAY_MILLIS)) throw new Error(`PostgreSQL pool idleTimeoutMillis must be an integer between 0 and ${MAX_TIMER_DELAY_MILLIS}`);
1825
- return {
1826
- url: legacy(primary.url, process.env.SQLOO_URL),
1827
- database: legacy(primary.database, process.env.SQLOO_DATABASE),
1828
- host: legacy(primary.host, process.env.SQLOO_HOST),
1829
- user: legacy(primary.user, process.env.SQLOO_USER),
1830
- password: legacy(primary.password, process.env.SQLOO_PASSWORD),
1831
- port,
1832
- max,
1833
- connectionTimeoutMillis,
1834
- idleTimeoutMillis
1835
- };
1836
- }
1837
- async function derivePostgresConnectionCacheKey(options, effective) {
1838
- if (options.dbid) return options.dbid;
1839
- const identity = JSON.stringify({
1840
- url: effective.url ?? null,
1841
- host: effective.host ?? "localhost",
1842
- port: effective.port,
1843
- database: effective.database ?? null,
1844
- user: effective.user ?? null,
1845
- password: effective.password ?? null,
1846
- max: effective.max,
1847
- connectionTimeoutMillis: effective.connectionTimeoutMillis ?? null,
1848
- idleTimeoutMillis: effective.idleTimeoutMillis ?? null
1849
- });
1850
- const hmacKey = await getPostgresCacheHmacKey();
1851
- const signature = await webcrypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(`@happyvertical/sql:postgres-cache:v1\0${identity}`));
1852
- return `pg:hmac-sha256:v1:${Buffer.from(signature).toString("hex")}`;
1853
- }
1854
- /**
1855
- * Creates a PostgreSQL database adapter
1856
- *
1857
- * Loads configuration from environment variables with backward compatibility:
1858
- * - First checks HAVE_SQL_* environment variables (new standard)
1859
- * - Falls back to SQLOO_* environment variables (legacy)
1860
- * - User-provided options always take precedence
1861
- *
1862
- * Environment variables:
1863
- * - HAVE_SQL_URL / SQLOO_URL → Connection string (takes precedence)
1864
- * - HAVE_SQL_DATABASE / SQLOO_DATABASE → Database name
1865
- * - HAVE_SQL_HOST / SQLOO_HOST → Host (default: 'localhost')
1866
- * - HAVE_SQL_USER / SQLOO_USER → Username
1867
- * - HAVE_SQL_PASSWORD / SQLOO_PASSWORD → Password
1868
- * - HAVE_SQL_PORT / SQLOO_PORT → Port (default: 5432)
1869
- *
1870
- * @param options - PostgreSQL connection options
1871
- * @returns Database interface for PostgreSQL
1872
- */
1873
- async function getDatabase$1(options = {}) {
1874
- validateDatabaseCacheOptions(options);
1875
- const effective = resolvePostgresConfig(options);
1876
- const cacheKey = await derivePostgresConnectionCacheKey(options, effective);
1877
- return connectionCache.getOrCreate(cacheKey, options, () => createDatabase(effective), closePostgresDatabase);
1878
- }
1879
- /**
1880
- * Internal: creates the actual database connection and caches it.
1881
- */
1882
- async function createDatabase(config) {
1883
- const { database, host = "localhost", user, password, port = 5432 } = config;
1884
- const url = config.url || `postgresql://${user}${password ? `:${password}` : ""}@${host}:${port}/${database || "postgres"}`;
1885
- const reopenOptions = () => {
1886
- return {
1887
- ...Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0)),
1888
- type: "postgres",
1889
- cache: false,
1890
- max: Math.min(config.max, REOPEN_POOL_MAX)
1891
- };
1892
- };
1893
- const { max: poolMax, connectionTimeoutMillis, idleTimeoutMillis } = config;
1894
- const pool = new Pool(config.url ? {
1895
- connectionString: config.url,
1896
- max: poolMax,
1897
- connectionTimeoutMillis,
1898
- idleTimeoutMillis
1899
- } : {
1900
- host,
1901
- user,
1902
- password,
1903
- port,
1904
- database,
1905
- max: poolMax,
1906
- connectionTimeoutMillis,
1907
- idleTimeoutMillis
1908
- });
1909
- pool.on("error", (error) => {
1910
- console.warn("Warning: PostgreSQL pool client error (connection discarded):", error instanceof Error ? error.message : String(error));
1911
- });
1912
- const originalEnd = pool.end.bind(pool);
1913
- let db;
1914
- let endPromise;
1915
- const evictFromCache = () => connectionCache.forget(db);
1916
- pool.end = (callback) => {
1917
- if (!endPromise) {
1918
- evictFromCache();
1919
- endPromise = originalEnd();
1920
- }
1921
- if (callback) {
1922
- endPromise.then(() => callback(), (error) => callback(error instanceof Error ? error : new Error(String(error))));
1923
- return;
1924
- }
1925
- return endPromise;
1926
- };
1927
- const client = pool;
1928
- /**
1929
- * Absorbs 'error' events for the clients currently checked out for a
1930
- * transaction, keyed by client so the listener can be removed on release.
1931
- */
1932
- const txErrorAbsorbers = /* @__PURE__ */ new WeakMap();
1933
- const releasedTxClients = /* @__PURE__ */ new WeakSet();
1934
- /**
1935
- * Checks out a pooled client for a transaction.
1936
- *
1937
- * pg-pool drops its own idle 'error' listener while a client is checked out,
1938
- * so a backend that dies mid-transaction would emit an unhandled 'error' and
1939
- * terminate the process. Absorb it here — the failure still reaches the
1940
- * caller as a rejected query — and drop the listener again on release so
1941
- * repeated checkouts of the same client cannot accumulate them.
1942
- */
1943
- const acquireTxClient = async () => {
1944
- const txClient = await client.connect();
1945
- releasedTxClients.delete(txClient);
1946
- const absorb = () => {};
1947
- txClient.on("error", absorb);
1948
- txErrorAbsorbers.set(txClient, absorb);
1949
- return txClient;
1950
- };
1951
- /**
1952
- * Returns a transaction client to the pool exactly once.
1953
- *
1954
- * Every teardown path must run this, including the ones reached by a throwing
1955
- * COMMIT or ROLLBACK — a client that is never released stays checked out for
1956
- * the life of the process, and enough of them exhaust the pool. Releasing
1957
- * twice throws, so the released clients are tracked rather than assumed.
1958
- *
1959
- * @param txClient - The pooled client backing a transaction
1960
- * @param destroy - Destroy the connection instead of reusing it, for when the
1961
- * transaction state could not be cleaned up
1962
- */
1963
- const releaseTxClient = (txClient, destroy = false) => {
1964
- if (releasedTxClients.has(txClient)) return;
1965
- releasedTxClients.add(txClient);
1966
- const absorb = txErrorAbsorbers.get(txClient);
1967
- if (absorb) {
1968
- txClient.off("error", absorb);
1969
- txErrorAbsorbers.delete(txClient);
1970
- }
1971
- txClient.release(destroy || void 0);
1972
- };
1973
- /**
1974
- * Rolls back a failed transaction and returns its client to the pool.
1975
- *
1976
- * The connection may still be inside a transaction, so ROLLBACK is attempted
1977
- * to normalize it. If that works the connection is clean and worth reusing;
1978
- * if it does not, the state is unknown and the connection is destroyed rather
1979
- * than handed to unrelated code later.
1980
- *
1981
- * @returns The rollback failure, if the connection could not be normalized
1982
- */
1983
- const discardTxClient = async (txClient) => {
1984
- try {
1985
- await txClient.query("ROLLBACK");
1986
- releaseTxClient(txClient);
1987
- return;
1988
- } catch (rollbackError) {
1989
- releaseTxClient(txClient, true);
1990
- return rollbackError;
1991
- }
1992
- };
1993
- /**
1994
- * Keeps the first PostgreSQL statement failure attached to a transaction.
1995
- *
1996
- * PostgreSQL reports every later statement in an aborted transaction as
1997
- * 25P02. Replacing the first failure with that generic state error hides the
1998
- * actionable code and diagnostics from callers. The scoped executor instead
1999
- * rethrows the first failure whenever PostgreSQL reports 25P02, and exposes
2000
- * the recorded failure so a swallowed statement error cannot make COMMIT's
2001
- * implicit rollback look successful.
2002
- */
2003
- const createTransactionExecutor = (txClient) => {
2004
- const tracker = createTransactionErrorTracker((error) => error instanceof DatabaseError$1);
2005
- const { pending, preserve: preserveFirstError } = tracker;
2006
- return {
2007
- client: new Proxy(txClient, { get(target, property) {
2008
- if (property === "query") return (...args) => {
2009
- const query = args[0];
2010
- const callbackIndex = typeof args.at(-1) === "function" ? args.length - 1 : -1;
2011
- if (typeof query === "object" && query !== null && "submit" in query && typeof query.submit === "function") {
2012
- if (!("handleError" in query) || typeof query.handleError !== "function" || !("handleReadyForQuery" in query) || typeof query.handleReadyForQuery !== "function") return Reflect.apply(target.query, target, args);
2013
- const handleError = query.handleError;
2014
- const handleReadyForQuery = query.handleReadyForQuery;
2015
- let complete;
2016
- const completion = new Promise((resolve) => {
2017
- complete = resolve;
2018
- });
2019
- let completed = false;
2020
- const finish = () => {
2021
- if (completed) return;
2022
- completed = true;
2023
- query.handleError = handleError;
2024
- query.handleReadyForQuery = handleReadyForQuery;
2025
- pending.delete(completion);
2026
- complete();
2027
- };
2028
- pending.add(completion);
2029
- query.handleError = function(...handlerArgs) {
2030
- const error = preserveFirstError(handlerArgs[0]);
2031
- try {
2032
- return Reflect.apply(handleError, this, [error, ...handlerArgs.slice(1)]);
2033
- } finally {
2034
- finish();
2035
- }
2036
- };
2037
- query.handleReadyForQuery = function(...handlerArgs) {
2038
- try {
2039
- const result = Reflect.apply(handleReadyForQuery, this, handlerArgs);
2040
- tracker.confirm(query);
2041
- return result;
2042
- } finally {
2043
- finish();
2044
- }
2045
- };
2046
- try {
2047
- return Reflect.apply(target.query, target, args);
2048
- } catch (error) {
2049
- finish();
2050
- throw preserveFirstError(error);
2051
- }
2052
- }
2053
- if (callbackIndex !== -1) {
2054
- const callback = args[callbackIndex];
2055
- let complete;
2056
- const completion = new Promise((resolve) => {
2057
- complete = resolve;
2058
- });
2059
- pending.add(completion);
2060
- args[callbackIndex] = (error, result) => {
2061
- const callbackError = error === null || error === void 0 ? error : preserveFirstError(error);
2062
- if (callbackError === null || callbackError === void 0) tracker.confirm(query);
2063
- pending.delete(completion);
2064
- complete();
2065
- callback(callbackError, result);
2066
- };
2067
- try {
2068
- return Reflect.apply(target.query, target, args);
2069
- } catch (error) {
2070
- pending.delete(completion);
2071
- complete();
2072
- throw preserveFirstError(error);
2073
- }
2074
- }
2075
- const result = Reflect.apply(target.query, target, args);
2076
- if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") return tracker.track(Promise.resolve(result), query);
2077
- if (typeof result === "object" && result !== null && "once" in result && typeof result.once === "function") {
2078
- let complete;
2079
- const completion = new Promise((resolve) => {
2080
- complete = resolve;
2081
- });
2082
- const finish = () => {
2083
- pending.delete(completion);
2084
- complete();
2085
- };
2086
- pending.add(completion);
2087
- result.once("error", (error) => {
2088
- preserveFirstError(error);
2089
- finish();
2090
- });
2091
- result.once("end", () => {
2092
- tracker.confirm(query);
2093
- finish();
2094
- });
2095
- result.once("close", finish);
2096
- }
2097
- return result;
2098
- };
2099
- return Reflect.get(target, property, target);
2100
- } }),
2101
- executor: { query: (sql, values) => tracker.track(txClient.query(sql, values), sql) },
2102
- clearError: tracker.clearError,
2103
- drain: tracker.drain,
2104
- getError: tracker.getError,
2105
- getUnconfirmedError: tracker.getUnconfirmedError
2106
- };
2107
- };
2108
- const assertCommitted = (result, transactionState) => {
2109
- if (result.command === "COMMIT") return;
2110
- const queryError = transactionState?.getError() ?? transactionState?.getUnconfirmedError();
2111
- if (queryError !== void 0) throw queryError;
2112
- throw new DatabaseError("PostgreSQL rolled back the transaction at commit", { command: result.command });
2113
- };
2114
- const { serializeRecord, createClientMethods, createNestedTransaction } = createPostgresDialect({
2115
- client,
2116
- probeExecutor: () => client,
2117
- runInTransaction: async (work) => {
2118
- const txClient = await acquireTxClient();
2119
- try {
2120
- await txClient.query("BEGIN");
2121
- const result = await work(txClient);
2122
- const commitResult = await txClient.query("COMMIT");
2123
- assertCommitted(commitResult);
2124
- releaseTxClient(txClient);
2125
- return result;
2126
- } catch (error) {
2127
- const rollbackError = await discardTxClient(txClient);
2128
- if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
2129
- throw error;
2130
- }
2131
- }
2132
- });
2133
- const { insert, get, list, update, upsert, getOrInsert, delete: deleteRecords, count, table, many, single, pluck, execute, query, oo, oO, ox, xx, tableExists, getTableSchema, syncSchema } = createClientMethods(client, false, serializeRecord);
2134
- const alterTable = createAlterTable(client);
2135
- /**
2136
- * Acquire a pinned connection from the pool for session-scoped state such as
2137
- * `pg_advisory_lock`. Every query on the returned handle runs on the same
2138
- * client until {@link SessionHandle.release} drops the connection (which
2139
- * frees any session locks it held). The connection is held for the handle's
2140
- * lifetime, so hold one session per process, not per operation.
2141
- */
2142
- const acquireSession = async () => {
2143
- const sessionClient = await pool.connect();
2144
- let released = false;
2145
- let lost = false;
2146
- sessionClient.on("error", () => {
2147
- lost = true;
2148
- });
2149
- return {
2150
- query: async (sql, ...values) => {
2151
- if (released) throw new DatabaseError("Session has been released", {});
2152
- if (lost) throw new DatabaseError("Session connection was lost", {});
2153
- const normalized = normalizePostgresRawQuery(sql, values);
2154
- try {
2155
- const result = await sessionClient.query(normalized.sql, normalized.values);
2156
- return {
2157
- rows: result.rows,
2158
- rowCount: result.rowCount ?? 0
2159
- };
2160
- } catch (e) {
2161
- throw wrapDatabaseError("Failed to execute session query", e, {
2162
- sql: normalized.sql,
2163
- values: normalized.values
2164
- });
2165
- }
2166
- },
2167
- isActive: () => !released && !lost,
2168
- release: async () => {
2169
- if (released) return;
2170
- released = true;
2171
- if (!lost) {
2172
- try {
2173
- await sessionClient.query("ROLLBACK");
2174
- } catch {}
2175
- try {
2176
- await sessionClient.query("SELECT pg_advisory_unlock_all()");
2177
- } catch {}
2178
- }
2179
- sessionClient.release(true);
2180
- }
2181
- };
2182
- };
2183
- /**
2184
- * Executes a callback within a database transaction
2185
- * Automatically commits on success or rolls back on error
2186
- *
2187
- * @param callback - Function to execute within transaction
2188
- * @returns Promise resolving to callback result
2189
- */
2190
- const transaction = async (callback) => {
2191
- const txClient = await acquireTxClient();
2192
- let nestedTransaction;
2193
- const transactionState = createTransactionExecutor(txClient);
2194
- try {
2195
- await txClient.query("BEGIN");
2196
- let txDb;
2197
- nestedTransaction = createNestedTransaction(transactionState.executor, () => txDb, transactionState.clearError, new AsyncLocalStorage());
2198
- txDb = {
2199
- url,
2200
- engine: "postgres",
2201
- reopenOptions,
2202
- client: transactionState.client,
2203
- ...createClientMethods(transactionState.executor, true, serializeRecord, transactionState.clearError),
2204
- transaction: nestedTransaction
2205
- };
2206
- const result = await callback(txDb);
2207
- await nestedTransaction.drain();
2208
- await transactionState.drain();
2209
- const statementError = transactionState.getError();
2210
- if (statementError !== void 0) throw statementError;
2211
- const commitResult = await txClient.query("COMMIT");
2212
- assertCommitted(commitResult, transactionState);
2213
- releaseTxClient(txClient);
2214
- return result;
2215
- } catch (error) {
2216
- await nestedTransaction?.drain();
2217
- await transactionState.drain();
2218
- const rollbackError = await discardTxClient(txClient);
2219
- if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
2220
- throw error;
2221
- }
2222
- };
2223
- /**
2224
- * Begins a new transaction and returns a handle for manual control
2225
- *
2226
- * Unlike transaction(), this gives you explicit control over commit/rollback.
2227
- * Ideal for test isolation where you want to rollback after each test.
2228
- *
2229
- * @returns Promise resolving to a TransactionHandle
2230
- */
2231
- const beginTransaction = async () => {
2232
- const txClient = await acquireTxClient();
2233
- try {
2234
- await txClient.query("BEGIN");
2235
- } catch (error) {
2236
- releaseTxClient(txClient, true);
2237
- throw error;
2238
- }
2239
- let active = true;
2240
- let nestedTransaction;
2241
- const transactionState = createTransactionExecutor(txClient);
2242
- const end = async (command) => {
2243
- if (!active) throw new DatabaseError("Transaction already ended", {});
2244
- try {
2245
- await nestedTransaction?.drain();
2246
- await transactionState.drain();
2247
- const statementError = transactionState.getError();
2248
- if (command === "COMMIT" && statementError !== void 0) throw statementError;
2249
- const result = await txClient.query(command);
2250
- if (command === "COMMIT") assertCommitted(result, transactionState);
2251
- active = false;
2252
- releaseTxClient(txClient);
2253
- } catch (error) {
2254
- active = false;
2255
- const rollbackError = await discardTxClient(txClient);
2256
- if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
2257
- throw error;
2258
- }
2259
- };
2260
- const commit = () => end("COMMIT");
2261
- const rollback = () => end("ROLLBACK");
2262
- const isActive = () => active;
2263
- let txHandle;
2264
- nestedTransaction = createNestedTransaction(transactionState.executor, () => txHandle, transactionState.clearError, new AsyncLocalStorage());
2265
- txHandle = {
2266
- url,
2267
- engine: "postgres",
2268
- reopenOptions,
2269
- client: transactionState.client,
2270
- ...createClientMethods(transactionState.executor, true, serializeRecord, transactionState.clearError),
2271
- transaction: nestedTransaction,
2272
- commit,
2273
- rollback,
2274
- isActive
2275
- };
2276
- return txHandle;
2277
- };
2278
- /**
2279
- * Initialize database schemas from JSON manifest
2280
- * Supports dependency resolution and schema overrides
2281
- *
2282
- * @param options - Schema initialization options
2283
- * @returns Promise that resolves when schemas are initialized
2284
- */
2285
- const initializeSchemas = async (options) => {
2286
- const schemaManager = new DatabaseSchemaManager();
2287
- const currentDb = {
2288
- url,
2289
- engine: "postgres",
2290
- reopenOptions,
2291
- client,
2292
- insert,
2293
- update,
2294
- upsert,
2295
- get,
2296
- getOrInsert,
2297
- delete: deleteRecords,
2298
- count,
2299
- list,
2300
- table,
2301
- many,
2302
- single,
2303
- pluck,
2304
- execute,
2305
- query,
2306
- oo,
2307
- oO,
2308
- ox,
2309
- xx,
2310
- tableExists,
2311
- getTableSchema,
2312
- syncSchema,
2313
- transaction
2314
- };
2315
- await schemaManager.initializeSchemas(currentDb, options);
2316
- };
2317
- db = {
2318
- url,
2319
- engine: "postgres",
2320
- reopenOptions,
2321
- client,
2322
- insert,
2323
- update,
2324
- upsert,
2325
- get,
2326
- getOrInsert,
2327
- delete: deleteRecords,
2328
- count,
2329
- list,
2330
- table,
2331
- many,
2332
- single,
2333
- pluck,
2334
- execute,
2335
- query,
2336
- oo,
2337
- oO,
2338
- ox,
2339
- xx,
2340
- tableExists,
2341
- syncSchema,
2342
- initializeSchemas,
2343
- transaction,
2344
- beginTransaction,
2345
- acquireSession,
2346
- getTableSchema,
2347
- alterTable,
2348
- vector: createVectorCapabilities(pool),
2349
- close: async () => {
2350
- await pool.end();
2351
- }
2352
- };
2353
- return db;
2354
- }
2355
- //#endregion
2356
1749
  //#region src/index.ts
2357
1750
  /**
2358
1751
  * Checks if the provided value is a database instance rather than configuration options
@@ -2412,13 +1805,23 @@ async function getDatabase(options = {}) {
2412
1805
  }
2413
1806
  }));
2414
1807
  if (!options.type && (options.url?.startsWith("file:") || options.url === ":memory:")) options.type = "sqlite";
2415
- if (options.type === "postgres") return (await Promise.resolve().then(() => postgres_exports)).getDatabase(options);
1808
+ if (options.type === "postgres") return (await import("./chunks/postgres-dbGVT9aR.js")).getDatabase(options);
2416
1809
  if (options.type === "pglite") return (await import("./pglite.js")).getDatabase(options);
2417
- if (options.type === "sqlite") return (await import("./chunks/sqlite-4D5RuZT0.js")).getDatabase(options);
2418
- if (options.type === "duckdb") return (await import("./chunks/duckdb-_d9aSOht.js")).getDatabase(options);
1810
+ if (options.type === "sqlite") return (await import("./chunks/sqlite-DQXS8fAo.js")).getDatabase(options);
1811
+ if (options.type === "duckdb") return (await import("./chunks/duckdb-ddmnqn5l.js")).getDatabase(options);
2419
1812
  if (options.type === "json") return (await Promise.resolve().then(() => json_exports)).getDatabase(options);
2420
1813
  throw new Error("Invalid database type");
2421
1814
  }
1815
+ /**
1816
+ * Clears the PostgreSQL connection cache.
1817
+ * Useful for test isolation and reconnection scenarios.
1818
+ *
1819
+ * The PostgreSQL adapter (and its `pg` driver) loads on first call, so the
1820
+ * root entry does not pull the driver in for callers that never use it.
1821
+ */
1822
+ async function clearPostgresConnectionCache() {
1823
+ await (await import("./chunks/postgres-dbGVT9aR.js")).clearPostgresConnectionCache();
1824
+ }
2422
1825
  var src_default = {
2423
1826
  getDatabase,
2424
1827
  syncSchema,