@happyvertical/sql 0.115.1 → 0.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +33 -0
  2. package/dist/chunks/{duckdb-aMJ05d68.js → duckdb-_d9aSOht.js} +9 -3
  3. package/dist/chunks/duckdb-_d9aSOht.js.map +1 -0
  4. package/dist/chunks/{postgres-dialect-C8GwYO-9.js → postgres-dialect-CevaHPBb.js} +75 -47
  5. package/dist/chunks/postgres-dialect-CevaHPBb.js.map +1 -0
  6. package/dist/chunks/{query-CcLSVKOo.js → query-DFAYXNk-.js} +47 -2
  7. package/dist/chunks/{query-CcLSVKOo.js.map → query-DFAYXNk-.js.map} +1 -1
  8. package/dist/chunks/{sqlite-DAzuB3Hb.js → sqlite-4D5RuZT0.js} +10 -6
  9. package/dist/chunks/sqlite-4D5RuZT0.js.map +1 -0
  10. package/dist/chunks/{sqlite-engine-ByvkAlrK.js → sqlite-engine-BLAv3Esk.js} +2 -2
  11. package/dist/chunks/{sqlite-engine-ByvkAlrK.js.map → sqlite-engine-BLAv3Esk.js.map} +1 -1
  12. package/dist/chunks/{sqlite-native-Dj0hF4qn.js → sqlite-native-Bqs856IC.js} +7 -5
  13. package/dist/chunks/sqlite-native-Bqs856IC.js.map +1 -0
  14. package/dist/chunks/types-DihIt7ez.js.map +1 -1
  15. package/dist/doctor.d.ts +30 -5
  16. package/dist/doctor.d.ts.map +1 -1
  17. package/dist/duckdb.d.ts.map +1 -1
  18. package/dist/index.js +56 -24
  19. package/dist/index.js.map +1 -1
  20. package/dist/pglite.d.ts.map +1 -1
  21. package/dist/pglite.js +3 -6
  22. package/dist/pglite.js.map +1 -1
  23. package/dist/postgres.d.ts.map +1 -1
  24. package/dist/query.js +1 -1
  25. package/dist/shared/duckdb-schema-utils.d.ts +13 -0
  26. package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
  27. package/dist/shared/postgres-dialect.d.ts +16 -1
  28. package/dist/shared/postgres-dialect.d.ts.map +1 -1
  29. package/dist/shared/types.d.ts +35 -4
  30. package/dist/shared/types.d.ts.map +1 -1
  31. package/dist/sqlite-native.d.ts.map +1 -1
  32. package/dist/sqlite.d.ts.map +1 -1
  33. package/package.json +2 -2
  34. package/dist/chunks/duckdb-aMJ05d68.js.map +0 -1
  35. package/dist/chunks/postgres-dialect-C8GwYO-9.js.map +0 -1
  36. package/dist/chunks/sqlite-DAzuB3Hb.js.map +0 -1
  37. package/dist/chunks/sqlite-native-Dj0hF4qn.js.map +0 -1
package/dist/doctor.d.ts CHANGED
@@ -3,15 +3,39 @@ export type DoctorLevel = 'fail' | 'warn';
3
3
  export interface DoctorIssue {
4
4
  level: DoctorLevel;
5
5
  message: string;
6
+ /**
7
+ * Schema the issue was found in. Set only when `schemas` or `allSchemas` was
8
+ * passed to {@link runDoctor}; the message is then prefixed `[schema] `.
9
+ */
10
+ schema?: string;
6
11
  }
7
12
  export interface DoctorContext {
8
13
  db: DatabaseInterface;
14
+ /** Names of the tables in the schema being checked. */
9
15
  tables: Set<string>;
16
+ /**
17
+ * Schema being checked. Table names in checks resolve against it: when
18
+ * `schemas` or `allSchemas` was passed, `db` is a transaction whose
19
+ * `search_path` is set to this schema alone.
20
+ */
21
+ schema: string;
10
22
  }
11
23
  export type DoctorCheck = (ctx: DoctorContext) => Promise<DoctorIssue[]>;
12
24
  export interface RunDoctorOptions {
13
25
  db: DatabaseInterface;
14
26
  checks: DoctorCheck[];
27
+ /**
28
+ * Schema, or list of schemas, to check. Every check runs once per schema,
29
+ * with unqualified table names resolving to that schema, so two schemas that
30
+ * each hold a table of the same name are checked separately. Defaults to
31
+ * `public`.
32
+ */
33
+ schemas?: string | readonly string[];
34
+ /**
35
+ * Check every non-system schema (everything except `information_schema` and
36
+ * `pg_*`) instead of `schemas`. Takes precedence over `schemas`.
37
+ */
38
+ allSchemas?: boolean;
15
39
  }
16
40
  export interface DoctorResult {
17
41
  failures: DoctorIssue[];
@@ -19,12 +43,13 @@ export interface DoctorResult {
19
43
  issues: DoctorIssue[];
20
44
  }
21
45
  /**
22
- * Execute every check against the public-schema tables of `db` and
23
- * partition the results by severity. Returns the aggregate; callers
24
- * format/exit as they see fit.
46
+ * Execute every check against the tables of `db` and partition the results by
47
+ * severity. Returns the aggregate; callers format/exit as they see fit.
25
48
  *
26
- * The current table set is enumerated once and shared across checks so
27
- * each check can cheaply decide whether its target tables exist.
49
+ * By default only the `public` schema is checked, exactly as before. Pass
50
+ * `schemas` or `allSchemas` to check others: each schema's table set is
51
+ * enumerated once and shared across that schema's checks, which run in a
52
+ * transaction with `search_path` set to the schema.
28
53
  */
29
54
  export declare function runDoctor(options: RunDoctorOptions): Promise<DoctorResult>;
30
55
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"doctor.d.ts","sourceRoot":"","sources":["../src/doctor.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAgB,CAAC;AAExD,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;AAE1C,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,WAAW,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,iBAAiB,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACrB;AAED,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,aAAa,KAAK,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;AAEzE,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,iBAAiB,CAAC;IACtB,MAAM,EAAE,WAAW,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,MAAM,EAAE,WAAW,EAAE,CAAC;CACvB;AAED;;;;;;;GAOG;AACH,wBAAsB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A0BA,OAAO,KAAK,EAGV,iBAAiB,EACjB,aAAa,EAQd,MAAM,mBAAgB,CAAC;AAuQxB;;;;;GAKG;AACH,wBAAsB,WAAW,CAC/B,OAAO,GAAE,aAAkB,GAC1B,OAAO,CAAC,iBAAiB,CAAC,CA4xC5B"}
1
+ {"version":3,"file":"duckdb.d.ts","sourceRoot":"","sources":["../src/duckdb.ts"],"names":[],"mappings":"AA6BA,OAAO,KAAK,EAEV,iBAAiB,EACjB,aAAa,EASd,MAAM,mBAAgB,CAAC;AAuQxB;;;;;GAKG;AACH,wBAAsB,WAAW,CAC/B,OAAO,GAAE,aAAkB,GAC1B,OAAO,CAAC,iBAAiB,CAAC,CAuyC5B"}
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
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 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";
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";
@@ -35,7 +35,7 @@ var __exportAll = (all, no_symbols) => {
35
35
  * package and on plain table/column names.
36
36
  *
37
37
  * **Postgres-only today.** The bundled check builders and
38
- * `listPublicTables` use Postgres syntax (`pg_tables`, `::int`/`::text`
38
+ * `listTables` use Postgres syntax (`pg_tables`, `::int`/`::text`
39
39
  * casts). The shape is portable in principle — `DoctorContext` carries a
40
40
  * generic `DatabaseInterface` so apps can add engine-aware checks — but
41
41
  * the out-of-the-box runner expects a Postgres connection. `runDoctor`
@@ -43,23 +43,53 @@ var __exportAll = (all, no_symbols) => {
43
43
  * mid-execution with a confusing `pg_tables`-doesn't-exist error.
44
44
  */
45
45
  /**
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.
46
+ * Execute every check against the tables of `db` and partition the results by
47
+ * severity. Returns the aggregate; callers format/exit as they see fit.
49
48
  *
50
- * The current table set is enumerated once and shared across checks so
51
- * each check can cheaply decide whether its target tables exist.
49
+ * By default only the `public` schema is checked, exactly as before. Pass
50
+ * `schemas` or `allSchemas` to check others: each schema's table set is
51
+ * enumerated once and shared across that schema's checks, which run in a
52
+ * transaction with `search_path` set to the schema.
52
53
  */
53
54
  async function runDoctor(options) {
54
55
  assertPostgresAdapter(options.db);
55
- const tables = await listPublicTables(options.db);
56
56
  const issues = [];
57
- for (const check of options.checks) {
58
- const checkIssues = await check({
57
+ if (options.schemas === void 0 && !options.allSchemas) {
58
+ const tables = await listTables(options.db, "public");
59
+ for (const check of options.checks) issues.push(...await check({
59
60
  db: options.db,
60
- tables
61
- });
62
- issues.push(...checkIssues);
61
+ tables,
62
+ schema: "public"
63
+ }));
64
+ } else {
65
+ const schemas = options.allSchemas ? await listNonSystemSchemas(options.db) : [...new Set(typeof options.schemas === "string" ? [options.schemas] : options.schemas ?? [])];
66
+ if (!options.db.transaction) throw new Error("runDoctor with schemas requires a database that supports transactions.");
67
+ for (const schema of schemas) {
68
+ const schemaIssues = await options.db.transaction(async (tx) => {
69
+ const incoming = await tx.query("SELECT current_setting('search_path') AS search_path");
70
+ const previous = String(incoming.rows[0]?.search_path ?? "");
71
+ await tx.query(`SET LOCAL search_path TO ${quoteLiteralIdentifier(schema)}`);
72
+ try {
73
+ const tables = await listTables(tx, schema);
74
+ const found = [];
75
+ for (const check of options.checks) found.push(...await check({
76
+ db: tx,
77
+ tables,
78
+ schema
79
+ }));
80
+ return found;
81
+ } finally {
82
+ try {
83
+ await tx.query("SELECT set_config('search_path', $1, true)", previous);
84
+ } catch {}
85
+ }
86
+ });
87
+ for (const issue of schemaIssues) issues.push({
88
+ ...issue,
89
+ message: `[${schema}] ${issue.message}`,
90
+ schema
91
+ });
92
+ }
63
93
  }
64
94
  return {
65
95
  failures: issues.filter((issue) => issue.level === "fail"),
@@ -69,7 +99,7 @@ async function runDoctor(options) {
69
99
  }
70
100
  /**
71
101
  * Throw early if the supplied database isn't Postgres. The check builders
72
- * and `listPublicTables` use Postgres syntax; pointing them at SQLite or
102
+ * and `listTables` use Postgres syntax; pointing them at SQLite or
73
103
  * DuckDB would fail mid-execution with a confusing "table pg_tables does
74
104
  * not exist" error from the adapter. Fail fast with a useful message
75
105
  * instead.
@@ -144,10 +174,15 @@ function checkRelationship(spec) {
144
174
  }];
145
175
  };
146
176
  }
147
- async function listPublicTables(db) {
148
- const result = await db.query("SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename");
177
+ async function listTables(db, schema) {
178
+ const result = await db.query("SELECT tablename FROM pg_tables WHERE schemaname = $1 ORDER BY tablename", schema);
149
179
  return new Set(result.rows.map((row) => String(row.tablename ?? "")));
150
180
  }
181
+ async function listNonSystemSchemas(db) {
182
+ return (await db.query(`SELECT nspname FROM pg_namespace
183
+ WHERE nspname <> 'information_schema' AND nspname NOT LIKE 'pg\\_%'
184
+ ORDER BY nspname`)).rows.map((row) => String(row.nspname));
185
+ }
151
186
  function countValueFromRow(value) {
152
187
  if (typeof value === "string") return value;
153
188
  if (typeof value === "number" || typeof value === "bigint") return String(value);
@@ -2095,11 +2130,7 @@ async function createDatabase(config) {
2095
2130
  }
2096
2131
  }
2097
2132
  });
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
- });
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);
2103
2134
  const alterTable = createAlterTable(client);
2104
2135
  /**
2105
2136
  * Acquire a pinned connection from the pool for session-scoped state such as
@@ -2277,6 +2308,7 @@ async function createDatabase(config) {
2277
2308
  ox,
2278
2309
  xx,
2279
2310
  tableExists,
2311
+ getTableSchema,
2280
2312
  syncSchema,
2281
2313
  transaction
2282
2314
  };
@@ -2382,8 +2414,8 @@ async function getDatabase(options = {}) {
2382
2414
  if (!options.type && (options.url?.startsWith("file:") || options.url === ":memory:")) options.type = "sqlite";
2383
2415
  if (options.type === "postgres") return (await Promise.resolve().then(() => postgres_exports)).getDatabase(options);
2384
2416
  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);
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);
2387
2419
  if (options.type === "json") return (await Promise.resolve().then(() => json_exports)).getDatabase(options);
2388
2420
  throw new Error("Invalid database type");
2389
2421
  }