@dbsp/cli 4.0.0 → 5.0.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.
@@ -3,9 +3,7 @@ import {
3
3
  canGenerateCreateIndex,
4
4
  generateCreateIndex
5
5
  } from "@dbsp/adapter-pgsql";
6
- import {
7
- validateSchemaIndexOptions
8
- } from "@dbsp/core";
6
+ import { validateSchemaIndexOptions } from "@dbsp/core/internal";
9
7
 
10
8
  // src/utils/db-utils.ts
11
9
  async function createDbConnection(connectionUrl) {
@@ -368,7 +366,7 @@ function generateSchemaFileWithDiagnostics(model, options = {}) {
368
366
  }
369
367
  lines.push(`import { ${coreImports.join(", ")} } from '@dbsp/core';`);
370
368
  if (options.dbCasing && options.dbCasing !== "preserve") {
371
- lines.push("import { createPgsqlAdapter } from '@dbsp/adapter-pgsql';");
369
+ lines.push("import { createPgAdapter } from '@dbsp/adapter-pgsql';");
372
370
  }
373
371
  lines.push("");
374
372
  lines.push("export const dbSchema = schema({");
@@ -398,7 +396,7 @@ function generateSchemaFileWithDiagnostics(model, options = {}) {
398
396
  lines.push(" * const orm = createOrm({");
399
397
  lines.push(" * model: dbSchema.model,");
400
398
  lines.push(
401
- ` * adapter: createPgsqlAdapter(pool, { dbCasing: '${options.dbCasing}' }),`
399
+ ` * adapter: createPgAdapter(pool, { dbCasing: '${options.dbCasing}' }),`
402
400
  );
403
401
  lines.push(" * });");
404
402
  lines.push(" * ```");
@@ -417,4 +415,4 @@ export {
417
415
  redactDbUrl,
418
416
  generateSchemaFileWithDiagnostics
419
417
  };
420
- //# sourceMappingURL=chunk-MFQPE7CY.js.map
418
+ //# sourceMappingURL=chunk-L6JD7UEM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generators/schema-codegen.ts","../src/utils/db-utils.ts"],"sourcesContent":["/**\n * CLI-DDL: Schema Codegen Module\n *\n * Generates TypeScript schema files from IntrospectedModelIR.\n * Used by `dbsp introspect` to create dbsp.schema.ts from a database.\n */\n\nimport {\n\tcanGenerateCreateIndex,\n\tgenerateCreateIndex,\n} from '@dbsp/adapter-pgsql';\nimport type { ModelIR, TableIR } from '@dbsp/core';\nimport { validateSchemaIndexOptions } from '@dbsp/core/internal';\nimport type { IndexIR } from '@dbsp/types';\nimport { redactDbUrl } from '../utils/db-utils.js';\n\n/**\n * Convert a snake_case string to camelCase.\n * @example 'author_id' → 'authorId'\n */\nfunction snakeToCamelCase(name: string): string {\n\treturn name.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/**\n * Options for schema code generation.\n */\nexport interface SchemaCodegenOptions {\n\t/** Source database URL (for comment header) */\n\treadonly sourceUrl?: string;\n\t/** Include original DB types as comments */\n\treadonly includeDbTypeComments?: boolean;\n\t/** Receive diagnostics as they are collected, including model warnings. */\n\treadonly onWarning?: (message: string) => void;\n\t/** Timestamp of introspection */\n\treadonly introspectedAt?: Date;\n\t/**\n\t * Database column casing convention.\n\t * When set to 'snake_case', column names are converted to camelCase\n\t * and a `dbCasing: 'snake_case'` comment is added to the generated code.\n\t * @default 'preserve'\n\t */\n\treadonly dbCasing?: 'snake_case' | 'camelCase' | 'preserve';\n}\n\nexport type SchemaCodegenDiagnosticsOptions = SchemaCodegenOptions;\n\nexport interface SchemaCodegenResult {\n\treadonly code: string;\n\treadonly warnings: readonly string[];\n}\n\n/**\n * Serialize a column default value to valid TypeScript source code.\n *\n * CODEX-11/CODEX-14: String(value) produced \"[object Object]\" for SQL-expression\n * defaults like { sql: 'now()' }, and single-quote wrapping without escape broke\n * strings containing quotes, backslashes, or newlines.\n *\n * Rules:\n * - null/undefined → 'null'\n * - number | boolean → unquoted literal (String(value))\n * - string → singleQuoteEscape (escapes \\, ', \\n, \\r, \\t — produces single-quoted TS literal)\n * - { sql: '...' } shape → `{ sql: ${JSON.stringify(sqlExpr)} }`\n * - anything else → throws (unrecognized shape; prevents silent [object Object])\n */\n\n/**\n * Wrap a string value in single quotes for TypeScript source output,\n * escaping any single quotes and backslashes contained in the value.\n *\n * Examples:\n * 'hello' → \"'hello'\"\n * \"O'Brien\" → \"'O\\\\'Brien'\"\n * 'C:\\\\Users' → \"'C:\\\\\\\\Users'\"\n */\nfunction singleQuoteEscape(s: string): string {\n\treturn `'${s\n\t\t.replace(/\\\\/g, '\\\\\\\\')\n\t\t.replace(/'/g, \"\\\\'\")\n\t\t.replace(/\\n/g, '\\\\n')\n\t\t.replace(/\\r/g, '\\\\r')\n\t\t.replace(/\\t/g, '\\\\t')}'`;\n}\n\n/**\n * Neutralize text that must remain inside generated block comments.\n *\n * Catalog-derived values are otherwise capable of closing `/* ... *\\/` comments\n * and turning the rest of the generated file into executable TypeScript.\n */\nfunction blockCommentText(s: string): string {\n\treturn s\n\t\t.replace(/\\*\\//g, '* /')\n\t\t.replace(/\\n/g, '\\\\n')\n\t\t.replace(/\\r/g, '\\\\r')\n\t\t.replace(/\\t/g, '\\\\t');\n}\n\n/**\n * Return the key suitable for use as a TypeScript object key.\n * Valid JS identifiers can be used bare; anything else is single-quote-wrapped.\n * A valid JS identifier starts with a letter, underscore, or $, followed by\n * letters, digits, underscores, or $.\n */\nfunction quoteKey(name: string): string {\n\tif (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n\t\treturn name;\n\t}\n\t// F3: Delegate to singleQuoteEscape() which also handles \\n, \\r, \\t.\n\t// The previous inline chain only escaped \\\\ and ' — identifiers containing\n\t// newlines, CR, or tabs would have produced invalid TypeScript output.\n\treturn singleQuoteEscape(name);\n}\n\nfunction emitDefault(d: unknown): string {\n\tif (d === null || d === undefined) return 'null';\n\tif (typeof d === 'number' || typeof d === 'boolean') return String(d);\n\tif (typeof d === 'string') return singleQuoteEscape(d);\n\tif (\n\t\ttypeof d === 'object' &&\n\t\t'sql' in d &&\n\t\ttypeof (d as { sql: unknown }).sql === 'string'\n\t) {\n\t\treturn `{ sql: ${singleQuoteEscape((d as { sql: string }).sql)} }`;\n\t}\n\tthrow new Error(\n\t\t`[schema-codegen] Unrecognized default shape: ${JSON.stringify(d)}`,\n\t);\n}\n\n/**\n * Generate column definition object code.\n */\nfunction generateColumnCode(\n\tcolumn: TableIR['columns'][number],\n\tisPrimaryKey: boolean,\n\tfkInfo:\n\t\t| {\n\t\t\t\ttable: string;\n\t\t\t\tcolumn?: string;\n\t\t\t\tnullable?: boolean;\n\t\t\t\tunique?: boolean;\n\t\t\t\tonDelete?: string;\n\t\t\t\tonUpdate?: string;\n\t\t\t\tisSelfRef?: boolean;\n\t\t }\n\t\t| undefined,\n\toptions: SchemaCodegenOptions,\n): string {\n\t// CODEX-13: FK + PK overlap — a column can be both FK and PK (e.g. shared-PK 1:1).\n\t// We must preserve isPrimaryKey even when fkInfo is present.\n\tif (fkInfo) {\n\t\treturn generateRefCode(column, fkInfo, isPrimaryKey, options);\n\t}\n\n\t// Check if we can use short form (just 'type' string)\n\tconst canUseShortForm =\n\t\t!isPrimaryKey &&\n\t\t!column.nullable &&\n\t\tcolumn.default === undefined &&\n\t\t!column.unique;\n\n\tif (canUseShortForm) {\n\t\t// Short form: 'type'\n\t\tlet code = singleQuoteEscape(column.type);\n\t\tif (options.includeDbTypeComments && column.originalDbType) {\n\t\t\tcode += ` /* from: ${blockCommentText(column.originalDbType)} */`;\n\t\t}\n\t\treturn code;\n\t}\n\n\t// Long form: { type, primaryKey?, nullable?, default?, unique? }\n\tconst props: string[] = [];\n\tprops.push(`type: ${singleQuoteEscape(column.type)}`);\n\n\tif (isPrimaryKey) {\n\t\tprops.push('primaryKey: true');\n\t}\n\n\tif (column.nullable) {\n\t\tprops.push('nullable: true');\n\t}\n\n\tif (column.default !== undefined) {\n\t\tprops.push(`default: ${emitDefault(column.default)}`);\n\t}\n\n\tif (column.unique) {\n\t\tprops.push('unique: true');\n\t}\n\n\tlet code = `{ ${props.join(', ')} }`;\n\n\tif (options.includeDbTypeComments && column.originalDbType) {\n\t\tcode += ` /* from: ${blockCommentText(column.originalDbType)} */`;\n\t}\n\n\treturn code;\n}\n\n/**\n * Generate ref() call for a foreign key column.\n * ARCH-005: Use ref() instead of references: { table, column }\n */\nfunction generateRefCode(\n\tcolumn: TableIR['columns'][number],\n\tfkInfo: {\n\t\ttable: string;\n\t\tcolumn?: string;\n\t\tnullable?: boolean;\n\t\tunique?: boolean;\n\t\tonDelete?: string;\n\t\tonUpdate?: string;\n\t\tisSelfRef?: boolean;\n\t},\n\tisPrimaryKey: boolean,\n\toptions: SchemaCodegenOptions,\n): string {\n\tconst refOptions: string[] = [];\n\n\t// C2: emit references option for non-PK FK target columns.\n\t// Now that buildRefColumn plumbs options.references into ModelIR,\n\t// emitting ref('table', { references: ['col'] }) round-trips correctly.\n\t// L1-followup-4: apply snake→camel transform to the target column name when\n\t// dbCasing='snake_case' so the generated references array round-trips correctly.\n\tif (fkInfo.column) {\n\t\tconst refColName =\n\t\t\toptions.dbCasing === 'snake_case'\n\t\t\t\t? snakeToCamelCase(fkInfo.column)\n\t\t\t\t: fkInfo.column;\n\t\trefOptions.push(`references: [${singleQuoteEscape(refColName)}]`);\n\t}\n\n\t// CODEX-13: FK column that is also PK — emit isPrimaryKey inside ref() options\n\tif (isPrimaryKey) {\n\t\trefOptions.push('isPrimaryKey: true');\n\t}\n\n\t// Nullable FK\n\tif (fkInfo.nullable || column.nullable) {\n\t\trefOptions.push('nullable: true');\n\t}\n\n\t// Unique FK → hasOne (1:1 relation)\n\tif (fkInfo.unique || column.unique) {\n\t\trefOptions.push('unique: true');\n\t}\n\n\t// onDelete action\n\tif (fkInfo.onDelete && fkInfo.onDelete !== 'NO ACTION') {\n\t\trefOptions.push(`onDelete: ${singleQuoteEscape(fkInfo.onDelete)}`);\n\t}\n\n\t// CODEX-12: onUpdate action\n\tif (fkInfo.onUpdate && fkInfo.onUpdate !== 'NO ACTION') {\n\t\trefOptions.push(`onUpdate: ${singleQuoteEscape(fkInfo.onUpdate)}`);\n\t}\n\n\t// Self-referential FK needs roles\n\tif (fkInfo.isSelfRef) {\n\t\t// Infer role names from column name\n\t\t// e.g., 'parentId' → parent: 'parent', children: 'children'\n\t\tconst baseName = column.name.replace(/_?[iI]d$/, '');\n\t\tconst childrenName = baseName === 'parent' ? 'children' : `${baseName}s`;\n\t\trefOptions.push(\n\t\t\t`roles: { parent: ${singleQuoteEscape(baseName)}, children: ${singleQuoteEscape(childrenName)} }`,\n\t\t);\n\t}\n\n\t// Build the ref() call — table name converted if dbCasing applies.\n\t// Route through singleQuoteEscape so a table name containing a single quote,\n\t// backslash, or newline produces valid TypeScript instead of a syntax error.\n\tconst refTable =\n\t\toptions.dbCasing === 'snake_case'\n\t\t\t? snakeToCamelCase(fkInfo.table)\n\t\t\t: fkInfo.table;\n\tlet code: string;\n\tif (refOptions.length === 0) {\n\t\tcode = `ref(${singleQuoteEscape(refTable)})`;\n\t} else {\n\t\tcode = `ref(${singleQuoteEscape(refTable)}, { ${refOptions.join(', ')} })`;\n\t}\n\n\t// Add comment for original DB type if requested\n\tif (options.includeDbTypeComments && column.originalDbType) {\n\t\tcode += ` /* from: ${blockCommentText(column.originalDbType)} */`;\n\t}\n\n\treturn code;\n}\n\n/**\n * Generate table definition code.\n */\nfunction generateTableCode(\n\ttable: TableIR,\n\toptions: SchemaCodegenOptions,\n): string {\n\t// ARCH-005: Build FK info map with extended properties\n\tconst fkMap = new Map<\n\t\tstring,\n\t\t{\n\t\t\ttable: string;\n\t\t\tcolumn?: string;\n\t\t\tnullable?: boolean;\n\t\t\tunique?: boolean;\n\t\t\tonDelete?: string;\n\t\t\tonUpdate?: string;\n\t\t\tisSelfRef?: boolean;\n\t\t}\n\t>();\n\n\tfor (const fk of table.foreignKeys) {\n\t\tconst localCol = fk.columns[0];\n\t\tconst refCol = fk.references.columns[0];\n\t\tif (\n\t\t\tfk.columns.length === 1 &&\n\t\t\tfk.references.columns.length === 1 &&\n\t\t\tfk.references.schema === undefined &&\n\t\t\tlocalCol &&\n\t\t\trefCol\n\t\t) {\n\t\t\t// Find the column to check nullable/unique\n\t\t\t// FK column names may be snake_case (from raw SQL) while column.name\n\t\t\t// is camelCase (when CamelCasePlugin is active)\n\t\t\tconst colDef = table.columns.find(\n\t\t\t\t(c) => c.name === localCol || c.name === snakeToCamelCase(localCol),\n\t\t\t);\n\n\t\t\tconst entry: {\n\t\t\t\ttable: string;\n\t\t\t\tcolumn?: string;\n\t\t\t\tnullable?: boolean;\n\t\t\t\tunique?: boolean;\n\t\t\t\tonDelete?: string;\n\t\t\t\tonUpdate?: string;\n\t\t\t\tisSelfRef?: boolean;\n\t\t\t} = {\n\t\t\t\ttable: fk.references.table,\n\t\t\t\tisSelfRef:\n\t\t\t\t\tfk.references.schema === undefined &&\n\t\t\t\t\tfk.references.table === table.name,\n\t\t\t};\n\n\t\t\t// Only include column if not 'id' (the default)\n\t\t\tif (refCol !== 'id') {\n\t\t\t\tentry.column = refCol;\n\t\t\t}\n\n\t\t\t// Include nullable if true\n\t\t\tif (colDef?.nullable) {\n\t\t\t\tentry.nullable = true;\n\t\t\t}\n\n\t\t\t// Include unique if true\n\t\t\tif (colDef?.unique) {\n\t\t\t\tentry.unique = true;\n\t\t\t}\n\n\t\t\t// Include onDelete if not the default\n\t\t\tif (fk.onDelete && fk.onDelete !== 'NO ACTION') {\n\t\t\t\tentry.onDelete = fk.onDelete;\n\t\t\t}\n\n\t\t\t// CODEX-12: Include onUpdate if not the default\n\t\t\tif (fk.onUpdate && fk.onUpdate !== 'NO ACTION') {\n\t\t\t\tentry.onUpdate = fk.onUpdate;\n\t\t\t}\n\n\t\t\t// Store under both snake_case and camelCase keys so fkMap.get(col.name) works\n\t\t\t// regardless of naming convention\n\t\t\tfkMap.set(localCol, entry);\n\t\t\tconst camelCol = snakeToCamelCase(localCol);\n\t\t\tif (camelCol !== localCol) {\n\t\t\t\tfkMap.set(camelCol, entry);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst shouldCamelCase = options.dbCasing === 'snake_case';\n\n\tconst columnLines = table.columns.map((col) => {\n\t\tconst isPrimaryKey = table.primaryKey\n\t\t\t? typeof table.primaryKey === 'string'\n\t\t\t\t? col.name === table.primaryKey\n\t\t\t\t: table.primaryKey.includes(col.name)\n\t\t\t: false;\n\t\tconst fkInfo = fkMap.get(col.name);\n\t\tconst code = generateColumnCode(col, isPrimaryKey, fkInfo, options);\n\t\tconst rawColName = shouldCamelCase ? snakeToCamelCase(col.name) : col.name;\n\t\t// C7: quote the key if it's not a valid JS identifier (e.g. contains hyphens)\n\t\tconst colKey = quoteKey(rawColName);\n\t\treturn `\\t\\t${colKey}: ${code}`;\n\t});\n\n\tconst rawTableName = shouldCamelCase\n\t\t? snakeToCamelCase(table.name)\n\t\t: table.name;\n\t// C7: quote the table key if it's not a valid JS identifier\n\tconst tableKey = quoteKey(rawTableName);\n\treturn `\\t${tableKey}: {\\n${columnLines.join(',\\n')},\\n\\t}`;\n}\n\nfunction generatedName(name: string, options: SchemaCodegenOptions): string {\n\treturn options.dbCasing === 'snake_case' ? snakeToCamelCase(name) : name;\n}\n\nfunction stringArrayLiteral(values: readonly string[]): string {\n\treturn `[${values.map(singleQuoteEscape).join(', ')}]`;\n}\n\n/**\n * Emit a strict boolean literal. Interpolating the value itself would run a\n * foreign object's toString into the generated source, which is later imported.\n */\nfunction booleanLiteral(value: unknown): 'true' | 'false' {\n\treturn value === true ? 'true' : 'false';\n}\n\nfunction stringRecordLiteral(\n\tvalues: Readonly<Record<string, string>>,\n\tkeyName: (name: string) => string = (name) => name,\n): string {\n\tconst entries = Object.entries(values).map(\n\t\t([key, value]) =>\n\t\t\t`[${singleQuoteEscape(keyName(key))}]: ${singleQuoteEscape(value)}`,\n\t);\n\treturn `{ ${entries.join(', ')} }`;\n}\n\nfunction tableLevelForeignKeys(table: TableIR): TableIR['foreignKeys'] {\n\treturn table.foreignKeys.filter(\n\t\t(fk) =>\n\t\t\tfk.references.schema !== undefined ||\n\t\t\tfk.columns.length > 1 ||\n\t\t\tfk.references.columns.length > 1,\n\t);\n}\n\nfunction hasExpressions(idx: IndexIR): boolean {\n\treturn (idx.expressions?.length ?? 0) > 0;\n}\n\nfunction tableLevelIndexes(table: TableIR): readonly IndexIR[] {\n\treturn table.indexes.filter(\n\t\t(idx) => indexRepresentationWarning(table.name, idx) === undefined,\n\t);\n}\n\nfunction warningName(name: string | undefined): string {\n\treturn name === undefined ? '<unnamed>' : JSON.stringify(name);\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction indexRepresentationWarning(\n\ttableName: string,\n\tidx: IndexIR,\n): string | undefined {\n\tif (hasExpressions(idx)) {\n\t\treturn `Expression index ${warningName(idx.name)} on table ${warningName(tableName)} cannot be represented in the schema. It may be reported as destructive drift; list it in externalIndexes to keep it.`;\n\t}\n\tconst schemaWarning = schemaIndexRepresentationWarning(tableName, idx);\n\tconst ddlWarning = ddlIndexRepresentationWarning(tableName, idx);\n\treturn schemaWarning ?? ddlWarning;\n}\n\nfunction ddlIndexRepresentationWarning(\n\ttableName: string,\n\tidx: IndexIR,\n): string | undefined {\n\tif (canGenerateCreateIndex(tableName, idx, undefined)) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\tgenerateCreateIndex(tableName, idx, undefined);\n\t} catch (error) {\n\t\treturn `Index ${warningName(idx.name)} on table ${warningName(tableName)} cannot be represented in the schema because the DDL emitter rejected it: ${errorMessage(error)}. It may be reported as destructive drift; list it in externalIndexes to keep it.`;\n\t}\n\treturn undefined;\n}\n\nfunction schemaIndexRepresentationWarning(\n\ttableName: string,\n\tidx: IndexIR,\n): string | undefined {\n\ttry {\n\t\tvalidateSchemaIndexOptions(tableName, idx);\n\t} catch (error) {\n\t\treturn `Index ${warningName(idx.name)} on table ${warningName(tableName)} cannot be represented in the schema because schema() rejected it: ${errorMessage(error)}. It may be reported as destructive drift; list it in externalIndexes to keep it.`;\n\t}\n\treturn undefined;\n}\n\nfunction schemaCodegenWarnings(model: ModelIR): string[] {\n\tconst warnings: string[] = [];\n\tfor (const table of model.tables.values()) {\n\t\tfor (const idx of table.indexes) {\n\t\t\tconst warning = indexRepresentationWarning(table.name, idx);\n\t\t\tif (warning !== undefined) {\n\t\t\t\twarnings.push(warning);\n\t\t\t}\n\t\t}\n\t}\n\treturn warnings;\n}\n\nfunction modelWarnings(model: ModelIR): readonly string[] {\n\tconst warnings = (model as ModelIR & { readonly warnings?: unknown })\n\t\t.warnings;\n\treturn Array.isArray(warnings) && warnings.every((w) => typeof w === 'string')\n\t\t? warnings\n\t\t: [];\n}\n\nfunction generateIndexCode(\n\tidx: IndexIR,\n\toptions: SchemaCodegenOptions,\n): string {\n\tconst indexOptions = [\n\t\t`columns: ${stringArrayLiteral(idx.columns.map((col) => generatedName(col, options)))}`,\n\t];\n\tif (idx.unique !== undefined) {\n\t\tindexOptions.push(`unique: ${booleanLiteral(idx.unique)}`);\n\t}\n\tif (idx.name !== undefined) {\n\t\tindexOptions.push(`name: ${singleQuoteEscape(idx.name)}`);\n\t}\n\tif (idx.method !== undefined) {\n\t\tindexOptions.push(`method: ${singleQuoteEscape(idx.method)}`);\n\t}\n\tif (idx.where !== undefined) {\n\t\tindexOptions.push(`where: ${singleQuoteEscape(idx.where)}`);\n\t}\n\tif (idx.opclass !== undefined) {\n\t\tindexOptions.push(\n\t\t\t`opclass: ${stringRecordLiteral(idx.opclass, (key) => generatedName(key, options))}`,\n\t\t);\n\t}\n\tif (idx.with !== undefined) {\n\t\tindexOptions.push(`with: ${stringRecordLiteral(idx.with)}`);\n\t}\n\tif (idx.include !== undefined) {\n\t\tindexOptions.push(\n\t\t\t`include: ${stringArrayLiteral(idx.include.map((col) => generatedName(col, options)))}`,\n\t\t);\n\t}\n\tif (idx.nullsNotDistinct !== undefined) {\n\t\tindexOptions.push(\n\t\t\t`nullsNotDistinct: ${booleanLiteral(idx.nullsNotDistinct)}`,\n\t\t);\n\t}\n\treturn `\\t\\t\\t{ ${indexOptions.join(', ')} }`;\n}\n\nfunction generateTableConstraintCode(\n\tmodel: ModelIR,\n\toptions: SchemaCodegenOptions,\n): string | undefined {\n\tconst tableBlocks: string[] = [];\n\tfor (const table of model.tables.values()) {\n\t\tconst fks = tableLevelForeignKeys(table);\n\t\tconst indexes = tableLevelIndexes(table);\n\t\tif (fks.length === 0 && indexes.length === 0) continue;\n\t\tconst tableOptions: string[] = [];\n\t\tif (indexes.length > 0) {\n\t\t\tconst indexLines = indexes.map((idx) => generateIndexCode(idx, options));\n\t\t\ttableOptions.push(`\\t\\tindexes: [\\n${indexLines.join(',\\n')}\\n\\t\\t]`);\n\t\t}\n\t\tif (fks.length > 0) {\n\t\t\tconst fkLines = fks.map((fk) => {\n\t\t\t\tconst refOptions = [\n\t\t\t\t\t...(fk.references.schema !== undefined\n\t\t\t\t\t\t? [`schema: ${singleQuoteEscape(fk.references.schema)}`]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t`columns: ${stringArrayLiteral(fk.columns.map((col) => generatedName(col, options)))}`,\n\t\t\t\t\t`references: ${stringArrayLiteral(fk.references.columns.map((col) => generatedName(col, options)))}`,\n\t\t\t\t];\n\t\t\t\tif (fk.onDelete && fk.onDelete !== 'NO ACTION') {\n\t\t\t\t\trefOptions.push(`onDelete: ${singleQuoteEscape(fk.onDelete)}`);\n\t\t\t\t}\n\t\t\t\tif (fk.onUpdate && fk.onUpdate !== 'NO ACTION') {\n\t\t\t\t\trefOptions.push(`onUpdate: ${singleQuoteEscape(fk.onUpdate)}`);\n\t\t\t\t}\n\t\t\t\treturn `\\t\\t\\tref(${singleQuoteEscape(generatedName(fk.references.table, options))}, { ${refOptions.join(', ')} })`;\n\t\t\t});\n\t\t\ttableOptions.push(`\\t\\tforeignKeys: [\\n${fkLines.join(',\\n')}\\n\\t\\t]`);\n\t\t}\n\t\ttableBlocks.push(\n\t\t\t`\\t${quoteKey(generatedName(table.name, options))}: {\\n${tableOptions.join(',\\n')}\\n\\t}`,\n\t\t);\n\t}\n\tif (tableBlocks.length === 0) return undefined;\n\treturn `{\\n${tableBlocks.join(',\\n\\n')}\\n}`;\n}\n\n/**\n * Generate a TypeScript schema file from ModelIR and return diagnostics.\n *\n * @param model - The ModelIR (or IntrospectedModelIR) to generate from\n * @param options - Code generation options\n * @returns Generated source code and warnings\n */\nexport function generateSchemaFileWithDiagnostics(\n\tmodel: ModelIR,\n\toptions: SchemaCodegenDiagnosticsOptions = {},\n): SchemaCodegenResult {\n\tconst warnings = [...modelWarnings(model), ...schemaCodegenWarnings(model)];\n\tfor (const warning of warnings) {\n\t\toptions.onWarning?.(warning);\n\t}\n\n\tconst lines: string[] = [];\n\n\t// Header comment\n\tlines.push('/**');\n\tlines.push(' * Auto-generated by: dbsp introspect');\n\tif (options.sourceUrl) {\n\t\tconst redactedUrl = redactDbUrl(options.sourceUrl);\n\t\tlines.push(` * Source: ${blockCommentText(redactedUrl)}`);\n\t}\n\tif (options.introspectedAt) {\n\t\tlines.push(` * Generated: ${options.introspectedAt.toISOString()}`);\n\t}\n\tlines.push(' *');\n\tlines.push(' * Review before using in production.');\n\tlines.push(' */');\n\tlines.push('');\n\n\t// ARCH-005: Check if any table has FKs to determine imports\n\tconst hasForeignKeys = Array.from(model.tables.values()).some(\n\t\t(table) => table.foreignKeys.length > 0,\n\t);\n\n\t// Imports for the live schema() + ref() authoring API.\n\tconst coreImports = ['schema'];\n\tif (hasForeignKeys) {\n\t\tcoreImports.push('ref');\n\t}\n\tlines.push(`import { ${coreImports.join(', ')} } from '@dbsp/core';`);\n\tif (options.dbCasing && options.dbCasing !== 'preserve') {\n\t\tlines.push(\"import { createPgAdapter } from '@dbsp/adapter-pgsql';\");\n\t}\n\tlines.push('');\n\n\t// Schema definition.\n\tlines.push('export const dbSchema = schema({');\n\n\t// Generate each table\n\tconst tables = Array.from(model.tables.values());\n\tconst tableLines = tables.map((table) => generateTableCode(table, options));\n\tlines.push(tableLines.join(',\\n\\n'));\n\n\tconst tableConstraints = generateTableConstraintCode(model, options);\n\tif (tableConstraints) {\n\t\tlines.push(`}, ${tableConstraints});`);\n\t} else {\n\t\tlines.push('});');\n\t}\n\tlines.push('');\n\n\t// Add a default export so schema-loader can load generated files directly.\n\t// schema-loader accepts module.schema || module.default; the named dbSchema\n\t// export is the canonical API, but the default export allows `loadSchema()`\n\t// to round-trip without the caller knowing the internal export name.\n\tlines.push('export default dbSchema;');\n\tlines.push('');\n\n\t// Usage hint with dbCasing\n\tif (options.dbCasing && options.dbCasing !== 'preserve') {\n\t\tlines.push('/**');\n\t\tlines.push(\n\t\t\t` * Usage: columns above are camelCase; the database uses ${options.dbCasing}.`,\n\t\t);\n\t\tlines.push(\n\t\t\t' * Pass dbCasing to the adapter so it maps camelCase ↔ snake_case automatically.',\n\t\t);\n\t\tlines.push(' *');\n\t\tlines.push(' * @example');\n\t\tlines.push(' * ```typescript');\n\t\tlines.push(' * const orm = createOrm({');\n\t\tlines.push(' * model: dbSchema.model,');\n\t\tlines.push(\n\t\t\t` * adapter: createPgAdapter(pool, { dbCasing: '${options.dbCasing}' }),`,\n\t\t);\n\t\tlines.push(' * });');\n\t\tlines.push(' * ```');\n\t\tlines.push(' */');\n\t\tlines.push(`export const dbCasing = '${options.dbCasing}' as const;`);\n\t\tlines.push('');\n\t}\n\n\treturn {\n\t\tcode: lines.join('\\n'),\n\t\twarnings,\n\t};\n}\n","/**\n * Shared database utilities for CLI commands.\n *\n * E09: Extracted from verify.ts and introspect.ts to DRY up code.\n * E09b: Shared URL redaction for secure logging.\n */\n\n/**\n * Create a database connection pool.\n * pg is an optional peer dependency.\n *\n * @param connectionUrl - PostgreSQL connection URL\n * @returns Pool instance\n * @throws Error if pg is not installed\n */\nexport async function createDbConnection(connectionUrl: string) {\n\tlet pg: typeof import('pg').default;\n\ttry {\n\t\tconst mod = await import('pg');\n\t\tpg = mod.default;\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'pg is required for this command. Install it with: pnpm add pg',\n\t\t);\n\t}\n\n\tconst pool = new pg.Pool({\n\t\tconnectionString: connectionUrl,\n\t});\n\treturn { pool };\n}\n\n/**\n * Redact password from a database connection URL for safe logging.\n *\n * @param url - Database connection URL (e.g., postgres://user:pass@host/db)\n * @returns URL with password replaced by ***\n *\n * @example\n * redactDbUrl('postgres://user:secret@localhost/mydb')\n * // => 'postgres://user:***@localhost/mydb'\n */\nexport function redactDbUrl(url: string): string {\n\ttry {\n\t\tconst u = new URL(url);\n\t\tif (u.password) {\n\t\t\tu.password = '***';\n\t\t}\n\t\treturn u.toString();\n\t} catch {\n\t\t// Fall back to regex for non-standard or malformed URLs\n\t\treturn url.replace(/:[^:@]+@/, ':***@');\n\t}\n}\n"],"mappings":";AAOA;AAAA,EACC;AAAA,EACA;AAAA,OACM;AAEP,SAAS,kCAAkC;;;ACG3C,eAAsB,mBAAmB,eAAuB;AAC/D,MAAI;AACJ,MAAI;AACH,UAAM,MAAM,MAAM,OAAO,IAAI;AAC7B,SAAK,IAAI;AAAA,EACV,QAAQ;AACP,UAAM,IAAI;AAAA,MACT;AAAA,IACD;AAAA,EACD;AAEA,QAAM,OAAO,IAAI,GAAG,KAAK;AAAA,IACxB,kBAAkB;AAAA,EACnB,CAAC;AACD,SAAO,EAAE,KAAK;AACf;AAYO,SAAS,YAAY,KAAqB;AAChD,MAAI;AACH,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,QAAI,EAAE,UAAU;AACf,QAAE,WAAW;AAAA,IACd;AACA,WAAO,EAAE,SAAS;AAAA,EACnB,QAAQ;AAEP,WAAO,IAAI,QAAQ,YAAY,OAAO;AAAA,EACvC;AACD;;;ADjCA,SAAS,iBAAiB,MAAsB;AAC/C,SAAO,KAAK,QAAQ,aAAa,CAAC,GAAG,WAAmB,OAAO,YAAY,CAAC;AAC7E;AAsDA,SAAS,kBAAkB,GAAmB;AAC7C,SAAO,IAAI,EACT,QAAQ,OAAO,MAAM,EACrB,QAAQ,MAAM,KAAK,EACnB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,CAAC;AACxB;AAQA,SAAS,iBAAiB,GAAmB;AAC5C,SAAO,EACL,QAAQ,SAAS,KAA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rB;AAAA,EACD;AACD;","names":["code"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  generateSchemaFileWithDiagnostics
3
- } from "../chunk-MFQPE7CY.js";
3
+ } from "../chunk-L6JD7UEM.js";
4
4
  export {
5
5
  generateSchemaFileWithDiagnostics
6
6
  };
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  createDbConnection,
4
4
  generateSchemaFileWithDiagnostics,
5
5
  redactDbUrl
6
- } from "./chunk-MFQPE7CY.js";
6
+ } from "./chunk-L6JD7UEM.js";
7
7
  import {
8
8
  loadSchema,
9
9
  loadSchemaFromCwd
@@ -35,7 +35,7 @@ import {
35
35
  } from "@dbsp/adapter-pgsql";
36
36
  import {
37
37
  applyPgTransitionRun,
38
- comparePgsqlDeclaredAdoptionSchema as comparePgsqlDeclaredAdoptionSchema2,
38
+ comparePgDeclaredAdoptionSchema as comparePgDeclaredAdoptionSchema2,
39
39
  executeGeneratorPlan,
40
40
  lockPgJournalRun,
41
41
  modelForDeclaredAdoption as modelForDeclaredAdoption2
@@ -43,12 +43,12 @@ import {
43
43
  import {
44
44
  acquireExclusiveTransitionLease,
45
45
  acquireTransitionLease as acquireTransitionLease3,
46
+ mintDurablyLoadedRun,
46
47
  selectorMatchesResource,
47
48
  transitionPlanDigest as transitionPlanDigest2,
48
49
  validateNormalizedManagedStepManifest as validateNormalizedManagedStepManifest2
49
- } from "@dbsp/core";
50
- import { mintDurablyLoadedRun } from "@dbsp/core/internal";
51
- import { ledgerAddressKey, REFUSAL_VOCABULARY as REFUSAL_VOCABULARY2 } from "@dbsp/types";
50
+ } from "@dbsp/core/internal";
51
+ import { ledgerAddressKey, REFUSAL_VOCABULARY as REFUSAL_VOCABULARY2 } from "@dbsp/types/internal";
52
52
  import { Command as Command2 } from "commander";
53
53
 
54
54
  // src/utils/output.ts
@@ -67,10 +67,10 @@ import { randomUUID } from "crypto";
67
67
  import {
68
68
  assertDeclarableChangeKind,
69
69
  classifyGeneratedMutation,
70
- comparePgsqlDatabaseSchema,
70
+ comparePgDatabaseSchema,
71
+ createPgAdapter,
72
+ createPgGeneratedManagedStep,
71
73
  createPgPhysicalModel,
72
- createPgsqlAdapter,
73
- createPgsqlGeneratedManagedStep,
74
74
  createPgTransitionLessor,
75
75
  createPgTransitionRunPersister,
76
76
  generatedPostconditionForChange,
@@ -81,18 +81,18 @@ import {
81
81
  } from "@dbsp/adapter-pgsql";
82
82
  import {
83
83
  collectReferencedKeyRemovalConflicts,
84
- comparePgsqlDeclaredAdoptionSchema,
85
- createPgsqlDeclaredAdoptionStep,
84
+ comparePgDeclaredAdoptionSchema,
85
+ createPgDeclaredAdoptionStep,
86
86
  generateMigrationSQL as generateMigrationSQLForPhysicalDiff,
87
87
  modelForDeclaredAdoption,
88
- pgsqlDeclaredAdoptionDeclaration
88
+ pgDeclaredAdoptionDeclaration
89
89
  } from "@dbsp/adapter-pgsql/internal";
90
90
  import {
91
91
  acquireTransitionLease,
92
92
  canonicalJsonDigest,
93
93
  transitionPlanDigest,
94
94
  validateNormalizedManagedStepManifest
95
- } from "@dbsp/core";
95
+ } from "@dbsp/core/internal";
96
96
  function decodeGeneratorPlanMaterial(material) {
97
97
  if (material === null || typeof material !== "object" || Array.isArray(material) || !("kind" in material) || material.kind !== "schema-differ-generator")
98
98
  throw new Error("persisted generator material has an invalid kind");
@@ -382,8 +382,8 @@ async function runGeneratorPlan(input) {
382
382
  }
383
383
  const { pool } = await createDbConnection(input.db);
384
384
  try {
385
- const diff = await comparePgsqlDatabaseSchema(
386
- createPgsqlAdapter(pool),
385
+ const diff = await comparePgDatabaseSchema(
386
+ createPgAdapter(pool),
387
387
  physical,
388
388
  {
389
389
  // `apply --schema` owns one schema. Extensions are database-scoped,
@@ -424,7 +424,7 @@ async function runGeneratorPlan(input) {
424
424
  if (table.adopt !== true) continue;
425
425
  const physicalName = physicalTable(table.name);
426
426
  adoptionPhysicalNames.set(table.name, physicalName);
427
- const compared = await comparePgsqlDeclaredAdoptionSchema({
427
+ const compared = await comparePgDeclaredAdoptionSchema({
428
428
  executor: pool,
429
429
  model: modelForDeclaredAdoption(table),
430
430
  schema,
@@ -517,7 +517,7 @@ async function runGeneratorPlan(input) {
517
517
  details: `Adopt existing table "${physicalName}" after live shape match`,
518
518
  statements: [],
519
519
  adoption: {
520
- declaration: pgsqlDeclaredAdoptionDeclaration(table),
520
+ declaration: pgDeclaredAdoptionDeclaration(table),
521
521
  shape: table,
522
522
  catalogueIdentity: requiredAdoptionIdentity(
523
523
  adoptionIdentities,
@@ -558,7 +558,7 @@ async function runGeneratorPlan(input) {
558
558
  );
559
559
  ordinaryStepSources.push({
560
560
  change,
561
- step: createPgsqlGeneratedManagedStep({
561
+ step: createPgGeneratedManagedStep({
562
562
  change: {
563
563
  ...change,
564
564
  kind: "drop_foreign_key",
@@ -575,7 +575,7 @@ async function runGeneratorPlan(input) {
575
575
  });
576
576
  ordinaryStepSources.push({
577
577
  change,
578
- step: createPgsqlGeneratedManagedStep({
578
+ step: createPgGeneratedManagedStep({
579
579
  change: { ...change, kind: "add_foreign_key", destructive: false },
580
580
  database,
581
581
  schema,
@@ -589,7 +589,7 @@ async function runGeneratorPlan(input) {
589
589
  }
590
590
  ordinaryStepSources.push({
591
591
  change,
592
- step: createPgsqlGeneratedManagedStep({
592
+ step: createPgGeneratedManagedStep({
593
593
  change,
594
594
  database,
595
595
  schema,
@@ -655,7 +655,7 @@ async function runGeneratorPlan(input) {
655
655
  continue;
656
656
  }
657
657
  if (change.kind === "adopt_table" && change.adoption) {
658
- const adoptionStep = createPgsqlDeclaredAdoptionStep({
658
+ const adoptionStep = createPgDeclaredAdoptionStep({
659
659
  address: {
660
660
  scope: "schema",
661
661
  engine: "postgresql",
@@ -756,9 +756,9 @@ async function runGeneratorPlan(input) {
756
756
  // src/commands/plan.ts
757
757
  import {
758
758
  acquirePgTransitionClient,
759
+ createPgAdapter as createPgAdapter2,
759
760
  createPgExecutionContract,
760
761
  createPgPhysicalModel as createPgPhysicalModel2,
761
- createPgsqlAdapter as createPgsqlAdapter2,
762
762
  createPgTransitionLessor as createPgTransitionLessor2,
763
763
  createPgTransitionPack,
764
764
  createPgTransitionRunPersister as createPgTransitionRunPersister2,
@@ -784,7 +784,7 @@ import {
784
784
  createTransitionRunMetadata,
785
785
  declarationSetFromModel,
786
786
  validateDeclarationModel
787
- } from "@dbsp/core";
787
+ } from "@dbsp/core/internal";
788
788
  import { Command } from "commander";
789
789
  var planPhysicalPgTransitionRun = planPgTransitionRun;
790
790
  var PlanPersistenceIndeterminateError = class extends Error {
@@ -938,7 +938,7 @@ var defaultPlanDeps = {
938
938
  `PostgreSQL introspection target identity does not match the captured target: ${mismatch}`
939
939
  );
940
940
  }
941
- return await createPgsqlAdapter2(lease.client, {
941
+ return await createPgAdapter2(lease.client, {
942
942
  borrowedClient: true
943
943
  }).introspect(schema === void 0 ? {} : { schema });
944
944
  } finally {
@@ -1035,7 +1035,7 @@ async function runPlan(options, overrides) {
1035
1035
  if (overrides === void 0) {
1036
1036
  const lifecycle = await planPhysicalPgTransitionRun(
1037
1037
  physical,
1038
- async (client, schema) => createPgsqlAdapter2(client, {
1038
+ async (client, schema) => createPgAdapter2(client, {
1039
1039
  borrowedClient: true
1040
1040
  }).introspect(schema === void 0 ? {} : { schema }),
1041
1041
  pool,
@@ -1347,7 +1347,7 @@ var planCommand = new Command("plan").description("Prove and persist a transitio
1347
1347
 
1348
1348
  // src/commands/refusal-output.ts
1349
1349
  import { escapeDiagnosticText as escapeDiagnosticText2 } from "@dbsp/adapter-pgsql";
1350
- import { REFUSAL_VOCABULARY } from "@dbsp/types";
1350
+ import { REFUSAL_VOCABULARY } from "@dbsp/types/internal";
1351
1351
  function preAppendRefusalFor(code, input) {
1352
1352
  return {
1353
1353
  address: input.address,
@@ -2279,7 +2279,7 @@ async function runApplyInternal(runId, options, pool) {
2279
2279
  },
2280
2280
  verifyDeclaredAdoptionShape: async (executor, step) => {
2281
2281
  if (step.lifecycle?.kind !== "adoption") return false;
2282
- const compared = await comparePgsqlDeclaredAdoptionSchema2({
2282
+ const compared = await comparePgDeclaredAdoptionSchema2({
2283
2283
  // Outcome protocol provides its claimed pg session here. It is
2284
2284
  // intentionally not the outer pool held by runApply.
2285
2285
  executor,
@@ -2529,9 +2529,9 @@ var generateCommand = new Command3("generate").description("Generate code from s
2529
2529
  }
2530
2530
  let targetDialectCapabilities;
2531
2531
  if (options.postgresqlVersion !== void 0) {
2532
- const { derivePostgresqlCapabilitiesForVersion } = await import("@dbsp/adapter-pgsql");
2532
+ const { derivePgCapabilitiesForVersion } = await import("@dbsp/adapter-pgsql");
2533
2533
  try {
2534
- targetDialectCapabilities = derivePostgresqlCapabilitiesForVersion(
2534
+ targetDialectCapabilities = derivePgCapabilitiesForVersion(
2535
2535
  options.postgresqlVersion
2536
2536
  );
2537
2537
  } catch (error) {
@@ -2565,8 +2565,8 @@ var generateCommand = new Command3("generate").description("Generate code from s
2565
2565
  case "ddl": {
2566
2566
  const dbCasing = mapCasingToDbCasing(options.casing) ?? schema.dbCasing ?? "snake_case";
2567
2567
  const casingLabel = formatGenerateCasingLabel(dbCasing);
2568
- const { createPgPhysicalModel: createPgPhysicalModel6, createPgsqlCompileOnlyAdapter } = await import("@dbsp/adapter-pgsql");
2569
- const adapter = createPgsqlCompileOnlyAdapter({
2568
+ const { createPgPhysicalModel: createPgPhysicalModel6, createPgCompileOnlyAdapter } = await import("@dbsp/adapter-pgsql");
2569
+ const adapter = createPgCompileOnlyAdapter({
2570
2570
  dbCasing,
2571
2571
  ...options.schemaName ? { schemaName: options.schemaName } : {}
2572
2572
  });
@@ -2651,7 +2651,10 @@ import {
2651
2651
  readPgLedgerAddressChain as readPgLedgerAddressChain2,
2652
2652
  readPgLedgerMarker
2653
2653
  } from "@dbsp/adapter-pgsql";
2654
- import { acquireTransitionLease as acquireTransitionLease4, projectLedgerChain } from "@dbsp/core";
2654
+ import {
2655
+ acquireTransitionLease as acquireTransitionLease4,
2656
+ projectLedgerChain
2657
+ } from "@dbsp/core/internal";
2655
2658
  import {
2656
2659
  canonicalResourceParent
2657
2660
  } from "@dbsp/types";
@@ -3336,7 +3339,7 @@ import {
3336
3339
  escapeDiagnosticText as escapeDiagnosticText6,
3337
3340
  runPgReinitializePreflight
3338
3341
  } from "@dbsp/adapter-pgsql";
3339
- import { declarationSetFromModel as declarationSetFromModel2 } from "@dbsp/core";
3342
+ import { declarationSetFromModel as declarationSetFromModel2 } from "@dbsp/core/internal";
3340
3343
  import { Command as Command7 } from "commander";
3341
3344
  var defaultDeps = { createDbConnection, loadSchema };
3342
3345
  var nodeAdoptionFileSystem = {
@@ -3709,7 +3712,7 @@ import {
3709
3712
  loadVerifiedRecoveryJournal,
3710
3713
  transitionPlanDigest as transitionPlanDigest3,
3711
3714
  validateTransitionRelationalInvariants
3712
- } from "@dbsp/core";
3715
+ } from "@dbsp/core/internal";
3713
3716
  import { Command as Command9 } from "commander";
3714
3717
  var RECOVER_OUTCOME_CONTRACT = [
3715
3718
  ["completed", 0, "all attempted steps were durably reconciled"],
@@ -4018,7 +4021,7 @@ import {
4018
4021
  escapeDiagnosticText as escapeDiagnosticText8,
4019
4022
  releasePgManagedAddress
4020
4023
  } from "@dbsp/adapter-pgsql";
4021
- import { acquireTransitionLease as acquireTransitionLease5 } from "@dbsp/core";
4024
+ import { acquireTransitionLease as acquireTransitionLease5 } from "@dbsp/core/internal";
4022
4025
  import { Command as Command10 } from "commander";
4023
4026
  async function runRelease(selector, options) {
4024
4027
  const { pool } = await createDbConnection(options.db);
@@ -4181,7 +4184,7 @@ var replCommand = new Command11("repl").description("Launch interactive REPL for
4181
4184
  });
4182
4185
  return;
4183
4186
  }
4184
- const { startRepl } = await import("./repl-PIFVQAHC.js");
4187
+ const { startRepl } = await import("./repl-25H6N4K7.js");
4185
4188
  await startRepl({
4186
4189
  schema,
4187
4190
  schemaPath,
@@ -4212,9 +4215,9 @@ function mapReplCasingOption(casing) {
4212
4215
 
4213
4216
  // src/commands/verify.ts
4214
4217
  import {
4215
- comparePgsqlDatabaseSchema as comparePgsqlDatabaseSchema2,
4218
+ comparePgDatabaseSchema as comparePgDatabaseSchema2,
4219
+ createPgAdapter as createPgAdapter3,
4216
4220
  createPgPhysicalModel as createPgPhysicalModel5,
4217
- createPgsqlAdapter as createPgsqlAdapter3,
4218
4221
  escapeDiagnosticText as escapeDiagnosticText9
4219
4222
  } from "@dbsp/adapter-pgsql";
4220
4223
  import { Command as Command12 } from "commander";
@@ -4389,8 +4392,8 @@ var verifyCommand = new Command12("verify").description("Compare schema vs real
4389
4392
  });
4390
4393
  const { pool } = await createDbConnection(options.db);
4391
4394
  try {
4392
- const adapter = createPgsqlAdapter3(pool);
4393
- const diff = await comparePgsqlDatabaseSchema2(adapter, physical, {
4395
+ const adapter = createPgAdapter3(pool);
4396
+ const diff = await comparePgDatabaseSchema2(adapter, physical, {
4394
4397
  onExpressionCanonicalizationWarning: (warning) => console.warn(
4395
4398
  `\u26A0\uFE0F [${warning.kind} ${escapeDiagnosticText9(warning.table)}.${escapeDiagnosticText9(warning.name)}] ${warning.message}`
4396
4399
  )