@happyvertical/sql 0.115.1 → 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.
Files changed (43) hide show
  1. package/README.md +38 -0
  2. package/dist/chunks/{duckdb-aMJ05d68.js → duckdb-ddmnqn5l.js} +9 -3
  3. package/dist/chunks/duckdb-ddmnqn5l.js.map +1 -0
  4. package/dist/chunks/postgres-dbGVT9aR.js +610 -0
  5. package/dist/chunks/postgres-dbGVT9aR.js.map +1 -0
  6. package/dist/chunks/{postgres-dialect-C8GwYO-9.js → postgres-dialect-uyqX-KB-.js} +76 -458
  7. package/dist/chunks/postgres-dialect-uyqX-KB-.js.map +1 -0
  8. package/dist/chunks/{query-CcLSVKOo.js → query-DFAYXNk-.js} +47 -2
  9. package/dist/chunks/{query-CcLSVKOo.js.map → query-DFAYXNk-.js.map} +1 -1
  10. package/dist/chunks/{sqlite-DAzuB3Hb.js → sqlite-DQXS8fAo.js} +12 -11
  11. package/dist/chunks/sqlite-DQXS8fAo.js.map +1 -0
  12. package/dist/chunks/{sqlite-engine-ByvkAlrK.js → sqlite-engine-DpcUbF-P.js} +2 -2
  13. package/dist/chunks/{sqlite-engine-ByvkAlrK.js.map → sqlite-engine-DpcUbF-P.js.map} +1 -1
  14. package/dist/chunks/{sqlite-native-Dj0hF4qn.js → sqlite-native-BJcrl8b4.js} +7 -5
  15. package/dist/chunks/sqlite-native-BJcrl8b4.js.map +1 -0
  16. package/dist/chunks/transaction-lock-BX2GJ4ei.js +415 -0
  17. package/dist/chunks/transaction-lock-BX2GJ4ei.js.map +1 -0
  18. package/dist/chunks/types-DihIt7ez.js.map +1 -1
  19. package/dist/doctor.d.ts +30 -5
  20. package/dist/doctor.d.ts.map +1 -1
  21. package/dist/duckdb.d.ts.map +1 -1
  22. package/dist/index.d.ts +8 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +67 -632
  25. package/dist/index.js.map +1 -1
  26. package/dist/pglite.d.ts.map +1 -1
  27. package/dist/pglite.js +4 -6
  28. package/dist/pglite.js.map +1 -1
  29. package/dist/postgres.d.ts.map +1 -1
  30. package/dist/query.js +1 -1
  31. package/dist/shared/duckdb-schema-utils.d.ts +13 -0
  32. package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
  33. package/dist/shared/postgres-dialect.d.ts +16 -1
  34. package/dist/shared/postgres-dialect.d.ts.map +1 -1
  35. package/dist/shared/types.d.ts +35 -4
  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 +2 -2
  40. package/dist/chunks/duckdb-aMJ05d68.js.map +0 -1
  41. package/dist/chunks/postgres-dialect-C8GwYO-9.js.map +0 -1
  42. package/dist/chunks/sqlite-DAzuB3Hb.js.map +0 -1
  43. package/dist/chunks/sqlite-native-Dj0hF4qn.js.map +0 -1
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
- import { a as convertUniqueIndexesToInlineConstraints, c as ExpressionError, i as validateColumnName, l as renderExpression, n as syncSchema, o as bucketExpr, r as tableExists, s as buildAggregate, t as escapeSqlValue } from "./chunks/query-CcLSVKOo.js";
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 createVectorCapabilities, c as createTransactionLock, d as enableCachedValidation, f as validateDatabaseCacheOptions, i as createTransactionErrorTracker, l as refuseReopen, n as createGetTableSchema, o as normalizePostgresRawQuery, r as createPostgresDialect, t as createAlterTable, u as ConnectionCache } from "./chunks/postgres-dialect-C8GwYO-9.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) => {
@@ -35,7 +32,7 @@ var __exportAll = (all, no_symbols) => {
35
32
  * package and on plain table/column names.
36
33
  *
37
34
  * **Postgres-only today.** The bundled check builders and
38
- * `listPublicTables` use Postgres syntax (`pg_tables`, `::int`/`::text`
35
+ * `listTables` use Postgres syntax (`pg_tables`, `::int`/`::text`
39
36
  * casts). The shape is portable in principle — `DoctorContext` carries a
40
37
  * generic `DatabaseInterface` so apps can add engine-aware checks — but
41
38
  * the out-of-the-box runner expects a Postgres connection. `runDoctor`
@@ -43,23 +40,53 @@ var __exportAll = (all, no_symbols) => {
43
40
  * mid-execution with a confusing `pg_tables`-doesn't-exist error.
44
41
  */
45
42
  /**
46
- * Execute every check against the public-schema tables of `db` and
47
- * partition the results by severity. Returns the aggregate; callers
48
- * format/exit as they see fit.
43
+ * Execute every check against the tables of `db` and partition the results by
44
+ * severity. Returns the aggregate; callers format/exit as they see fit.
49
45
  *
50
- * The current table set is enumerated once and shared across checks so
51
- * each check can cheaply decide whether its target tables exist.
46
+ * By default only the `public` schema is checked, exactly as before. Pass
47
+ * `schemas` or `allSchemas` to check others: each schema's table set is
48
+ * enumerated once and shared across that schema's checks, which run in a
49
+ * transaction with `search_path` set to the schema.
52
50
  */
53
51
  async function runDoctor(options) {
54
52
  assertPostgresAdapter(options.db);
55
- const tables = await listPublicTables(options.db);
56
53
  const issues = [];
57
- for (const check of options.checks) {
58
- const checkIssues = await check({
54
+ if (options.schemas === void 0 && !options.allSchemas) {
55
+ const tables = await listTables(options.db, "public");
56
+ for (const check of options.checks) issues.push(...await check({
59
57
  db: options.db,
60
- tables
61
- });
62
- issues.push(...checkIssues);
58
+ tables,
59
+ schema: "public"
60
+ }));
61
+ } else {
62
+ const schemas = options.allSchemas ? await listNonSystemSchemas(options.db) : [...new Set(typeof options.schemas === "string" ? [options.schemas] : options.schemas ?? [])];
63
+ if (!options.db.transaction) throw new Error("runDoctor with schemas requires a database that supports transactions.");
64
+ for (const schema of schemas) {
65
+ const schemaIssues = await options.db.transaction(async (tx) => {
66
+ const incoming = await tx.query("SELECT current_setting('search_path') AS search_path");
67
+ const previous = String(incoming.rows[0]?.search_path ?? "");
68
+ await tx.query(`SET LOCAL search_path TO ${quoteLiteralIdentifier(schema)}`);
69
+ try {
70
+ const tables = await listTables(tx, schema);
71
+ const found = [];
72
+ for (const check of options.checks) found.push(...await check({
73
+ db: tx,
74
+ tables,
75
+ schema
76
+ }));
77
+ return found;
78
+ } finally {
79
+ try {
80
+ await tx.query("SELECT set_config('search_path', $1, true)", previous);
81
+ } catch {}
82
+ }
83
+ });
84
+ for (const issue of schemaIssues) issues.push({
85
+ ...issue,
86
+ message: `[${schema}] ${issue.message}`,
87
+ schema
88
+ });
89
+ }
63
90
  }
64
91
  return {
65
92
  failures: issues.filter((issue) => issue.level === "fail"),
@@ -69,7 +96,7 @@ async function runDoctor(options) {
69
96
  }
70
97
  /**
71
98
  * Throw early if the supplied database isn't Postgres. The check builders
72
- * and `listPublicTables` use Postgres syntax; pointing them at SQLite or
99
+ * and `listTables` use Postgres syntax; pointing them at SQLite or
73
100
  * DuckDB would fail mid-execution with a confusing "table pg_tables does
74
101
  * not exist" error from the adapter. Fail fast with a useful message
75
102
  * instead.
@@ -144,10 +171,15 @@ function checkRelationship(spec) {
144
171
  }];
145
172
  };
146
173
  }
147
- async function listPublicTables(db) {
148
- const result = await db.query("SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename");
174
+ async function listTables(db, schema) {
175
+ const result = await db.query("SELECT tablename FROM pg_tables WHERE schemaname = $1 ORDER BY tablename", schema);
149
176
  return new Set(result.rows.map((row) => String(row.tablename ?? "")));
150
177
  }
178
+ async function listNonSystemSchemas(db) {
179
+ return (await db.query(`SELECT nspname FROM pg_namespace
180
+ WHERE nspname <> 'information_schema' AND nspname NOT LIKE 'pg\\_%'
181
+ ORDER BY nspname`)).rows.map((row) => String(row.nspname));
182
+ }
151
183
  function countValueFromRow(value) {
152
184
  if (typeof value === "string") return value;
153
185
  if (typeof value === "number" || typeof value === "bigint") return String(value);
@@ -157,7 +189,7 @@ function countValueFromRow(value) {
157
189
  //#region src/json.ts
158
190
  var json_exports = /* @__PURE__ */ __exportAll({
159
191
  clearConnectionCache: () => clearConnectionCache,
160
- getDatabase: () => getDatabase$2
192
+ getDatabase: () => getDatabase$1
161
193
  });
162
194
  var reopenOptions = refuseReopen("json", "every connection keeps its own in-memory copy of the files, so concurrent writers lose updates");
163
195
  /**
@@ -725,7 +757,7 @@ function validateTableName(table) {
725
757
  * @param options - JSON database options
726
758
  * @returns Database interface for JSON files
727
759
  */
728
- async function getDatabase$2(options) {
760
+ async function getDatabase$1(options) {
729
761
  const cacheKey = options.dbid || `json:${options.url}:${options.writeStrategy || "immediate"}:${options.autoRegister !== false}`;
730
762
  return memoryConnectionCache.getOrCreate(cacheKey, options, () => createTrackedJSONDatabase(options), closeJSONDatabase, isCachedJSONDatabaseFresh);
731
763
  }
@@ -1714,613 +1746,6 @@ async function createJSONDatabase(options) {
1714
1746
  })();
1715
1747
  }
1716
1748
  //#endregion
1717
- //#region src/postgres.ts
1718
- var postgres_exports = /* @__PURE__ */ __exportAll({
1719
- clearPostgresConnectionCache: () => clearPostgresConnectionCache,
1720
- getDatabase: () => getDatabase$1
1721
- });
1722
- /** Default pool size of a reopened PostgreSQL connection. */
1723
- var REOPEN_POOL_MAX = 5;
1724
- var MAX_TIMER_DELAY_MILLIS = 2147483647;
1725
- globalThis.__haveSqlPostgresConnectionCache ??= new ConnectionCache();
1726
- var connectionCache = globalThis.__haveSqlPostgresConnectionCache;
1727
- /**
1728
- * Returns the process-local cache identity HMAC key, generating it on first
1729
- * use. Generating it at import would leave a WebCrypto key job in flight in
1730
- * every isolate that loads the package, and Node aborts the whole process when
1731
- * a worker thread is terminated while such a job completes (#1518).
1732
- *
1733
- * Concurrent first callers share one pending promise. The promise lives on
1734
- * `globalThis` so every copy of this module in an isolate derives the same
1735
- * cache identities. A rejected generation is dropped so the next call retries.
1736
- */
1737
- function getPostgresCacheHmacKey() {
1738
- const existing = globalThis.__haveSqlPostgresCacheHmacKey;
1739
- if (existing) return existing;
1740
- let pending;
1741
- try {
1742
- pending = webcrypto.subtle.generateKey({
1743
- name: "HMAC",
1744
- hash: "SHA-256"
1745
- }, false, ["sign"]);
1746
- } catch (error) {
1747
- pending = Promise.reject(error);
1748
- }
1749
- globalThis.__haveSqlPostgresCacheHmacKey = pending;
1750
- pending.catch(() => {
1751
- if (globalThis.__haveSqlPostgresCacheHmacKey === pending) globalThis.__haveSqlPostgresCacheHmacKey = void 0;
1752
- });
1753
- return pending;
1754
- }
1755
- /**
1756
- * Clears the PostgreSQL connection cache.
1757
- * Useful for test isolation and reconnection scenarios.
1758
- */
1759
- async function clearPostgresConnectionCache() {
1760
- await connectionCache.clear(closePostgresDatabase);
1761
- }
1762
- async function closePostgresDatabase(db) {
1763
- if (db.close) {
1764
- await db.close();
1765
- return;
1766
- }
1767
- await db.client.end();
1768
- }
1769
- function resolvePostgresConfig(options) {
1770
- const preferred = (option, environment) => option !== void 0 ? option : environment;
1771
- const envPort = process.env.HAVE_SQL_PORT;
1772
- const primary = {
1773
- url: preferred(options.url, process.env.HAVE_SQL_URL),
1774
- database: preferred(options.database, process.env.HAVE_SQL_DATABASE),
1775
- host: preferred(options.host, process.env.HAVE_SQL_HOST),
1776
- user: preferred(options.user, process.env.HAVE_SQL_USER),
1777
- password: preferred(options.password, process.env.HAVE_SQL_PASSWORD),
1778
- port: preferred(options.port, envPort === void 0 ? void 0 : Number(envPort))
1779
- };
1780
- const useLegacy = !primary.url && !primary.host && !primary.database && !primary.user;
1781
- const legacy = (value, environment) => value !== void 0 || !useLegacy ? value : environment;
1782
- const legacyPort = process.env.SQLOO_PORT;
1783
- const port = legacy(primary.port, legacyPort === void 0 ? void 0 : Number(legacyPort)) ?? 5432;
1784
- const max = options.max ?? 20;
1785
- const { connectionTimeoutMillis, idleTimeoutMillis } = options;
1786
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("PostgreSQL port must be an integer between 1 and 65535");
1787
- if (!Number.isInteger(max) || max < 1) throw new Error("PostgreSQL pool max must be a positive integer");
1788
- 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}`);
1789
- 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}`);
1790
- return {
1791
- url: legacy(primary.url, process.env.SQLOO_URL),
1792
- database: legacy(primary.database, process.env.SQLOO_DATABASE),
1793
- host: legacy(primary.host, process.env.SQLOO_HOST),
1794
- user: legacy(primary.user, process.env.SQLOO_USER),
1795
- password: legacy(primary.password, process.env.SQLOO_PASSWORD),
1796
- port,
1797
- max,
1798
- connectionTimeoutMillis,
1799
- idleTimeoutMillis
1800
- };
1801
- }
1802
- async function derivePostgresConnectionCacheKey(options, effective) {
1803
- if (options.dbid) return options.dbid;
1804
- const identity = JSON.stringify({
1805
- url: effective.url ?? null,
1806
- host: effective.host ?? "localhost",
1807
- port: effective.port,
1808
- database: effective.database ?? null,
1809
- user: effective.user ?? null,
1810
- password: effective.password ?? null,
1811
- max: effective.max,
1812
- connectionTimeoutMillis: effective.connectionTimeoutMillis ?? null,
1813
- idleTimeoutMillis: effective.idleTimeoutMillis ?? null
1814
- });
1815
- const hmacKey = await getPostgresCacheHmacKey();
1816
- const signature = await webcrypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(`@happyvertical/sql:postgres-cache:v1\0${identity}`));
1817
- return `pg:hmac-sha256:v1:${Buffer.from(signature).toString("hex")}`;
1818
- }
1819
- /**
1820
- * Creates a PostgreSQL database adapter
1821
- *
1822
- * Loads configuration from environment variables with backward compatibility:
1823
- * - First checks HAVE_SQL_* environment variables (new standard)
1824
- * - Falls back to SQLOO_* environment variables (legacy)
1825
- * - User-provided options always take precedence
1826
- *
1827
- * Environment variables:
1828
- * - HAVE_SQL_URL / SQLOO_URL → Connection string (takes precedence)
1829
- * - HAVE_SQL_DATABASE / SQLOO_DATABASE → Database name
1830
- * - HAVE_SQL_HOST / SQLOO_HOST → Host (default: 'localhost')
1831
- * - HAVE_SQL_USER / SQLOO_USER → Username
1832
- * - HAVE_SQL_PASSWORD / SQLOO_PASSWORD → Password
1833
- * - HAVE_SQL_PORT / SQLOO_PORT → Port (default: 5432)
1834
- *
1835
- * @param options - PostgreSQL connection options
1836
- * @returns Database interface for PostgreSQL
1837
- */
1838
- async function getDatabase$1(options = {}) {
1839
- validateDatabaseCacheOptions(options);
1840
- const effective = resolvePostgresConfig(options);
1841
- const cacheKey = await derivePostgresConnectionCacheKey(options, effective);
1842
- return connectionCache.getOrCreate(cacheKey, options, () => createDatabase(effective), closePostgresDatabase);
1843
- }
1844
- /**
1845
- * Internal: creates the actual database connection and caches it.
1846
- */
1847
- async function createDatabase(config) {
1848
- const { database, host = "localhost", user, password, port = 5432 } = config;
1849
- const url = config.url || `postgresql://${user}${password ? `:${password}` : ""}@${host}:${port}/${database || "postgres"}`;
1850
- const reopenOptions = () => {
1851
- return {
1852
- ...Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0)),
1853
- type: "postgres",
1854
- cache: false,
1855
- max: Math.min(config.max, REOPEN_POOL_MAX)
1856
- };
1857
- };
1858
- const { max: poolMax, connectionTimeoutMillis, idleTimeoutMillis } = config;
1859
- const pool = new Pool(config.url ? {
1860
- connectionString: config.url,
1861
- max: poolMax,
1862
- connectionTimeoutMillis,
1863
- idleTimeoutMillis
1864
- } : {
1865
- host,
1866
- user,
1867
- password,
1868
- port,
1869
- database,
1870
- max: poolMax,
1871
- connectionTimeoutMillis,
1872
- idleTimeoutMillis
1873
- });
1874
- pool.on("error", (error) => {
1875
- console.warn("Warning: PostgreSQL pool client error (connection discarded):", error instanceof Error ? error.message : String(error));
1876
- });
1877
- const originalEnd = pool.end.bind(pool);
1878
- let db;
1879
- let endPromise;
1880
- const evictFromCache = () => connectionCache.forget(db);
1881
- pool.end = (callback) => {
1882
- if (!endPromise) {
1883
- evictFromCache();
1884
- endPromise = originalEnd();
1885
- }
1886
- if (callback) {
1887
- endPromise.then(() => callback(), (error) => callback(error instanceof Error ? error : new Error(String(error))));
1888
- return;
1889
- }
1890
- return endPromise;
1891
- };
1892
- const client = pool;
1893
- /**
1894
- * Absorbs 'error' events for the clients currently checked out for a
1895
- * transaction, keyed by client so the listener can be removed on release.
1896
- */
1897
- const txErrorAbsorbers = /* @__PURE__ */ new WeakMap();
1898
- const releasedTxClients = /* @__PURE__ */ new WeakSet();
1899
- /**
1900
- * Checks out a pooled client for a transaction.
1901
- *
1902
- * pg-pool drops its own idle 'error' listener while a client is checked out,
1903
- * so a backend that dies mid-transaction would emit an unhandled 'error' and
1904
- * terminate the process. Absorb it here — the failure still reaches the
1905
- * caller as a rejected query — and drop the listener again on release so
1906
- * repeated checkouts of the same client cannot accumulate them.
1907
- */
1908
- const acquireTxClient = async () => {
1909
- const txClient = await client.connect();
1910
- releasedTxClients.delete(txClient);
1911
- const absorb = () => {};
1912
- txClient.on("error", absorb);
1913
- txErrorAbsorbers.set(txClient, absorb);
1914
- return txClient;
1915
- };
1916
- /**
1917
- * Returns a transaction client to the pool exactly once.
1918
- *
1919
- * Every teardown path must run this, including the ones reached by a throwing
1920
- * COMMIT or ROLLBACK — a client that is never released stays checked out for
1921
- * the life of the process, and enough of them exhaust the pool. Releasing
1922
- * twice throws, so the released clients are tracked rather than assumed.
1923
- *
1924
- * @param txClient - The pooled client backing a transaction
1925
- * @param destroy - Destroy the connection instead of reusing it, for when the
1926
- * transaction state could not be cleaned up
1927
- */
1928
- const releaseTxClient = (txClient, destroy = false) => {
1929
- if (releasedTxClients.has(txClient)) return;
1930
- releasedTxClients.add(txClient);
1931
- const absorb = txErrorAbsorbers.get(txClient);
1932
- if (absorb) {
1933
- txClient.off("error", absorb);
1934
- txErrorAbsorbers.delete(txClient);
1935
- }
1936
- txClient.release(destroy || void 0);
1937
- };
1938
- /**
1939
- * Rolls back a failed transaction and returns its client to the pool.
1940
- *
1941
- * The connection may still be inside a transaction, so ROLLBACK is attempted
1942
- * to normalize it. If that works the connection is clean and worth reusing;
1943
- * if it does not, the state is unknown and the connection is destroyed rather
1944
- * than handed to unrelated code later.
1945
- *
1946
- * @returns The rollback failure, if the connection could not be normalized
1947
- */
1948
- const discardTxClient = async (txClient) => {
1949
- try {
1950
- await txClient.query("ROLLBACK");
1951
- releaseTxClient(txClient);
1952
- return;
1953
- } catch (rollbackError) {
1954
- releaseTxClient(txClient, true);
1955
- return rollbackError;
1956
- }
1957
- };
1958
- /**
1959
- * Keeps the first PostgreSQL statement failure attached to a transaction.
1960
- *
1961
- * PostgreSQL reports every later statement in an aborted transaction as
1962
- * 25P02. Replacing the first failure with that generic state error hides the
1963
- * actionable code and diagnostics from callers. The scoped executor instead
1964
- * rethrows the first failure whenever PostgreSQL reports 25P02, and exposes
1965
- * the recorded failure so a swallowed statement error cannot make COMMIT's
1966
- * implicit rollback look successful.
1967
- */
1968
- const createTransactionExecutor = (txClient) => {
1969
- const tracker = createTransactionErrorTracker((error) => error instanceof DatabaseError$1);
1970
- const { pending, preserve: preserveFirstError } = tracker;
1971
- return {
1972
- client: new Proxy(txClient, { get(target, property) {
1973
- if (property === "query") return (...args) => {
1974
- const query = args[0];
1975
- const callbackIndex = typeof args.at(-1) === "function" ? args.length - 1 : -1;
1976
- if (typeof query === "object" && query !== null && "submit" in query && typeof query.submit === "function") {
1977
- if (!("handleError" in query) || typeof query.handleError !== "function" || !("handleReadyForQuery" in query) || typeof query.handleReadyForQuery !== "function") return Reflect.apply(target.query, target, args);
1978
- const handleError = query.handleError;
1979
- const handleReadyForQuery = query.handleReadyForQuery;
1980
- let complete;
1981
- const completion = new Promise((resolve) => {
1982
- complete = resolve;
1983
- });
1984
- let completed = false;
1985
- const finish = () => {
1986
- if (completed) return;
1987
- completed = true;
1988
- query.handleError = handleError;
1989
- query.handleReadyForQuery = handleReadyForQuery;
1990
- pending.delete(completion);
1991
- complete();
1992
- };
1993
- pending.add(completion);
1994
- query.handleError = function(...handlerArgs) {
1995
- const error = preserveFirstError(handlerArgs[0]);
1996
- try {
1997
- return Reflect.apply(handleError, this, [error, ...handlerArgs.slice(1)]);
1998
- } finally {
1999
- finish();
2000
- }
2001
- };
2002
- query.handleReadyForQuery = function(...handlerArgs) {
2003
- try {
2004
- const result = Reflect.apply(handleReadyForQuery, this, handlerArgs);
2005
- tracker.confirm(query);
2006
- return result;
2007
- } finally {
2008
- finish();
2009
- }
2010
- };
2011
- try {
2012
- return Reflect.apply(target.query, target, args);
2013
- } catch (error) {
2014
- finish();
2015
- throw preserveFirstError(error);
2016
- }
2017
- }
2018
- if (callbackIndex !== -1) {
2019
- const callback = args[callbackIndex];
2020
- let complete;
2021
- const completion = new Promise((resolve) => {
2022
- complete = resolve;
2023
- });
2024
- pending.add(completion);
2025
- args[callbackIndex] = (error, result) => {
2026
- const callbackError = error === null || error === void 0 ? error : preserveFirstError(error);
2027
- if (callbackError === null || callbackError === void 0) tracker.confirm(query);
2028
- pending.delete(completion);
2029
- complete();
2030
- callback(callbackError, result);
2031
- };
2032
- try {
2033
- return Reflect.apply(target.query, target, args);
2034
- } catch (error) {
2035
- pending.delete(completion);
2036
- complete();
2037
- throw preserveFirstError(error);
2038
- }
2039
- }
2040
- const result = Reflect.apply(target.query, target, args);
2041
- if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") return tracker.track(Promise.resolve(result), query);
2042
- if (typeof result === "object" && result !== null && "once" in result && typeof result.once === "function") {
2043
- let complete;
2044
- const completion = new Promise((resolve) => {
2045
- complete = resolve;
2046
- });
2047
- const finish = () => {
2048
- pending.delete(completion);
2049
- complete();
2050
- };
2051
- pending.add(completion);
2052
- result.once("error", (error) => {
2053
- preserveFirstError(error);
2054
- finish();
2055
- });
2056
- result.once("end", () => {
2057
- tracker.confirm(query);
2058
- finish();
2059
- });
2060
- result.once("close", finish);
2061
- }
2062
- return result;
2063
- };
2064
- return Reflect.get(target, property, target);
2065
- } }),
2066
- executor: { query: (sql, values) => tracker.track(txClient.query(sql, values), sql) },
2067
- clearError: tracker.clearError,
2068
- drain: tracker.drain,
2069
- getError: tracker.getError,
2070
- getUnconfirmedError: tracker.getUnconfirmedError
2071
- };
2072
- };
2073
- const assertCommitted = (result, transactionState) => {
2074
- if (result.command === "COMMIT") return;
2075
- const queryError = transactionState?.getError() ?? transactionState?.getUnconfirmedError();
2076
- if (queryError !== void 0) throw queryError;
2077
- throw new DatabaseError("PostgreSQL rolled back the transaction at commit", { command: result.command });
2078
- };
2079
- const { serializeRecord, createClientMethods, createNestedTransaction } = createPostgresDialect({
2080
- client,
2081
- probeExecutor: () => client,
2082
- runInTransaction: async (work) => {
2083
- const txClient = await acquireTxClient();
2084
- try {
2085
- await txClient.query("BEGIN");
2086
- const result = await work(txClient);
2087
- const commitResult = await txClient.query("COMMIT");
2088
- assertCommitted(commitResult);
2089
- releaseTxClient(txClient);
2090
- return result;
2091
- } catch (error) {
2092
- const rollbackError = await discardTxClient(txClient);
2093
- if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
2094
- throw error;
2095
- }
2096
- }
2097
- });
2098
- const { insert, get, list, update, upsert, getOrInsert, delete: deleteRecords, count, table, many, single, pluck, execute, query, oo, oO, ox, xx, tableExists, syncSchema } = createClientMethods(client, false, serializeRecord);
2099
- const getTableSchema = createGetTableSchema({
2100
- many,
2101
- tableExists
2102
- });
2103
- const alterTable = createAlterTable(client);
2104
- /**
2105
- * Acquire a pinned connection from the pool for session-scoped state such as
2106
- * `pg_advisory_lock`. Every query on the returned handle runs on the same
2107
- * client until {@link SessionHandle.release} drops the connection (which
2108
- * frees any session locks it held). The connection is held for the handle's
2109
- * lifetime, so hold one session per process, not per operation.
2110
- */
2111
- const acquireSession = async () => {
2112
- const sessionClient = await pool.connect();
2113
- let released = false;
2114
- let lost = false;
2115
- sessionClient.on("error", () => {
2116
- lost = true;
2117
- });
2118
- return {
2119
- query: async (sql, ...values) => {
2120
- if (released) throw new DatabaseError("Session has been released", {});
2121
- if (lost) throw new DatabaseError("Session connection was lost", {});
2122
- const normalized = normalizePostgresRawQuery(sql, values);
2123
- try {
2124
- const result = await sessionClient.query(normalized.sql, normalized.values);
2125
- return {
2126
- rows: result.rows,
2127
- rowCount: result.rowCount ?? 0
2128
- };
2129
- } catch (e) {
2130
- throw wrapDatabaseError("Failed to execute session query", e, {
2131
- sql: normalized.sql,
2132
- values: normalized.values
2133
- });
2134
- }
2135
- },
2136
- isActive: () => !released && !lost,
2137
- release: async () => {
2138
- if (released) return;
2139
- released = true;
2140
- if (!lost) {
2141
- try {
2142
- await sessionClient.query("ROLLBACK");
2143
- } catch {}
2144
- try {
2145
- await sessionClient.query("SELECT pg_advisory_unlock_all()");
2146
- } catch {}
2147
- }
2148
- sessionClient.release(true);
2149
- }
2150
- };
2151
- };
2152
- /**
2153
- * Executes a callback within a database transaction
2154
- * Automatically commits on success or rolls back on error
2155
- *
2156
- * @param callback - Function to execute within transaction
2157
- * @returns Promise resolving to callback result
2158
- */
2159
- const transaction = async (callback) => {
2160
- const txClient = await acquireTxClient();
2161
- let nestedTransaction;
2162
- const transactionState = createTransactionExecutor(txClient);
2163
- try {
2164
- await txClient.query("BEGIN");
2165
- let txDb;
2166
- nestedTransaction = createNestedTransaction(transactionState.executor, () => txDb, transactionState.clearError, new AsyncLocalStorage());
2167
- txDb = {
2168
- url,
2169
- engine: "postgres",
2170
- reopenOptions,
2171
- client: transactionState.client,
2172
- ...createClientMethods(transactionState.executor, true, serializeRecord, transactionState.clearError),
2173
- transaction: nestedTransaction
2174
- };
2175
- const result = await callback(txDb);
2176
- await nestedTransaction.drain();
2177
- await transactionState.drain();
2178
- const statementError = transactionState.getError();
2179
- if (statementError !== void 0) throw statementError;
2180
- const commitResult = await txClient.query("COMMIT");
2181
- assertCommitted(commitResult, transactionState);
2182
- releaseTxClient(txClient);
2183
- return result;
2184
- } catch (error) {
2185
- await nestedTransaction?.drain();
2186
- await transactionState.drain();
2187
- const rollbackError = await discardTxClient(txClient);
2188
- if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
2189
- throw error;
2190
- }
2191
- };
2192
- /**
2193
- * Begins a new transaction and returns a handle for manual control
2194
- *
2195
- * Unlike transaction(), this gives you explicit control over commit/rollback.
2196
- * Ideal for test isolation where you want to rollback after each test.
2197
- *
2198
- * @returns Promise resolving to a TransactionHandle
2199
- */
2200
- const beginTransaction = async () => {
2201
- const txClient = await acquireTxClient();
2202
- try {
2203
- await txClient.query("BEGIN");
2204
- } catch (error) {
2205
- releaseTxClient(txClient, true);
2206
- throw error;
2207
- }
2208
- let active = true;
2209
- let nestedTransaction;
2210
- const transactionState = createTransactionExecutor(txClient);
2211
- const end = async (command) => {
2212
- if (!active) throw new DatabaseError("Transaction already ended", {});
2213
- try {
2214
- await nestedTransaction?.drain();
2215
- await transactionState.drain();
2216
- const statementError = transactionState.getError();
2217
- if (command === "COMMIT" && statementError !== void 0) throw statementError;
2218
- const result = await txClient.query(command);
2219
- if (command === "COMMIT") assertCommitted(result, transactionState);
2220
- active = false;
2221
- releaseTxClient(txClient);
2222
- } catch (error) {
2223
- active = false;
2224
- const rollbackError = await discardTxClient(txClient);
2225
- if (rollbackError !== void 0 && error instanceof Error) error.cause ??= rollbackError;
2226
- throw error;
2227
- }
2228
- };
2229
- const commit = () => end("COMMIT");
2230
- const rollback = () => end("ROLLBACK");
2231
- const isActive = () => active;
2232
- let txHandle;
2233
- nestedTransaction = createNestedTransaction(transactionState.executor, () => txHandle, transactionState.clearError, new AsyncLocalStorage());
2234
- txHandle = {
2235
- url,
2236
- engine: "postgres",
2237
- reopenOptions,
2238
- client: transactionState.client,
2239
- ...createClientMethods(transactionState.executor, true, serializeRecord, transactionState.clearError),
2240
- transaction: nestedTransaction,
2241
- commit,
2242
- rollback,
2243
- isActive
2244
- };
2245
- return txHandle;
2246
- };
2247
- /**
2248
- * Initialize database schemas from JSON manifest
2249
- * Supports dependency resolution and schema overrides
2250
- *
2251
- * @param options - Schema initialization options
2252
- * @returns Promise that resolves when schemas are initialized
2253
- */
2254
- const initializeSchemas = async (options) => {
2255
- const schemaManager = new DatabaseSchemaManager();
2256
- const currentDb = {
2257
- url,
2258
- engine: "postgres",
2259
- reopenOptions,
2260
- client,
2261
- insert,
2262
- update,
2263
- upsert,
2264
- get,
2265
- getOrInsert,
2266
- delete: deleteRecords,
2267
- count,
2268
- list,
2269
- table,
2270
- many,
2271
- single,
2272
- pluck,
2273
- execute,
2274
- query,
2275
- oo,
2276
- oO,
2277
- ox,
2278
- xx,
2279
- tableExists,
2280
- syncSchema,
2281
- transaction
2282
- };
2283
- await schemaManager.initializeSchemas(currentDb, options);
2284
- };
2285
- db = {
2286
- url,
2287
- engine: "postgres",
2288
- reopenOptions,
2289
- client,
2290
- insert,
2291
- update,
2292
- upsert,
2293
- get,
2294
- getOrInsert,
2295
- delete: deleteRecords,
2296
- count,
2297
- list,
2298
- table,
2299
- many,
2300
- single,
2301
- pluck,
2302
- execute,
2303
- query,
2304
- oo,
2305
- oO,
2306
- ox,
2307
- xx,
2308
- tableExists,
2309
- syncSchema,
2310
- initializeSchemas,
2311
- transaction,
2312
- beginTransaction,
2313
- acquireSession,
2314
- getTableSchema,
2315
- alterTable,
2316
- vector: createVectorCapabilities(pool),
2317
- close: async () => {
2318
- await pool.end();
2319
- }
2320
- };
2321
- return db;
2322
- }
2323
- //#endregion
2324
1749
  //#region src/index.ts
2325
1750
  /**
2326
1751
  * Checks if the provided value is a database instance rather than configuration options
@@ -2380,13 +1805,23 @@ async function getDatabase(options = {}) {
2380
1805
  }
2381
1806
  }));
2382
1807
  if (!options.type && (options.url?.startsWith("file:") || options.url === ":memory:")) options.type = "sqlite";
2383
- 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);
2384
1809
  if (options.type === "pglite") return (await import("./pglite.js")).getDatabase(options);
2385
- if (options.type === "sqlite") return (await import("./chunks/sqlite-DAzuB3Hb.js")).getDatabase(options);
2386
- if (options.type === "duckdb") return (await import("./chunks/duckdb-aMJ05d68.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);
2387
1812
  if (options.type === "json") return (await Promise.resolve().then(() => json_exports)).getDatabase(options);
2388
1813
  throw new Error("Invalid database type");
2389
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
+ }
2390
1825
  var src_default = {
2391
1826
  getDatabase,
2392
1827
  syncSchema,