@prisma-next/target-sqlite 0.11.0-dev.9 → 0.12.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.
- package/dist/codecs-BAlEiSeP.d.mts.map +1 -1
- package/dist/codecs-DVnHtVWW.mjs.map +1 -1
- package/dist/codecs.mjs.map +1 -1
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +5 -34
- package/dist/control.mjs.map +1 -1
- package/dist/default-normalizer-3Fccw7yw.mjs.map +1 -1
- package/dist/default-normalizer.d.mts.map +1 -1
- package/dist/descriptor-meta-CE2Kbn9b.mjs.map +1 -1
- package/dist/migration.d.mts.map +1 -1
- package/dist/migration.mjs.map +1 -1
- package/dist/native-type-normalizer-BlN5XfD-.mjs.map +1 -1
- package/dist/native-type-normalizer.d.mts.map +1 -1
- package/dist/op-factory-call-BnPhI25-.mjs.map +1 -1
- package/dist/op-factory-call.d.mts.map +1 -1
- package/dist/pack.d.mts.map +1 -1
- package/dist/{planner-B9-16QqD.mjs → planner-CEKTRydl.mjs} +2 -2
- package/dist/{planner-B9-16QqD.mjs.map → planner-CEKTRydl.mjs.map} +1 -1
- package/dist/planner-produced-sqlite-migration-CI9LdXPr.d.mts.map +1 -1
- package/dist/{planner-produced-sqlite-migration-BqzfeOFu.mjs → planner-produced-sqlite-migration-DCsg3RDZ.mjs} +3 -6
- package/dist/planner-produced-sqlite-migration-DCsg3RDZ.mjs.map +1 -0
- package/dist/planner-produced-sqlite-migration.mjs +1 -1
- package/dist/planner-target-details-Bm71XPKb.mjs.map +1 -1
- package/dist/planner-target-details-vhvZDWK1.d.mts.map +1 -1
- package/dist/planner.d.mts.map +1 -1
- package/dist/planner.mjs +1 -1
- package/dist/render-ops-CSRDT4YL.mjs.map +1 -1
- package/dist/render-ops.d.mts.map +1 -1
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs.map +1 -1
- package/dist/shared-qLsgTOZs.d.mts.map +1 -1
- package/dist/sql-utils-DhevMgef.mjs.map +1 -1
- package/dist/sql-utils.d.mts.map +1 -1
- package/dist/sqlite-migration-BBJktVVw.mjs.map +1 -1
- package/dist/sqlite-migration-DAb2NEX6.d.mts.map +1 -1
- package/dist/statement-builders-Dne-LkAV.mjs.map +1 -1
- package/dist/statement-builders.d.mts +1 -1
- package/dist/statement-builders.d.mts.map +1 -1
- package/dist/tables-DGRRJasz.mjs.map +1 -1
- package/package.json +29 -18
- package/src/core/migrations/planner-produced-sqlite-migration.ts +0 -2
- package/src/core/migrations/render-typescript.ts +1 -5
- package/src/core/migrations/runner.ts +11 -60
- package/src/core/migrations/statement-builders.ts +1 -1
- package/dist/planner-produced-sqlite-migration-BqzfeOFu.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tables-DGRRJasz.mjs","names":[],"sources":["../src/core/migrations/operations/shared.ts","../src/core/migrations/operations/columns.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operations/indexes.ts","../src/core/migrations/operations/tables.ts"],"sourcesContent":["import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ReferentialAction } from '@prisma-next/sql-contract/types';\nimport { quoteIdentifier } from '../../sql-utils';\nimport type { SqlitePlanTargetDetails } from '../planner-target-details';\n\nexport type Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport function step(description: string, sql: string): { description: string; sql: string } {\n return { description, sql };\n}\n\n/**\n * Flat, fully-resolved column shape consumed by `createTable`, `addColumn`,\n * and `recreateTable`. Codec / `typeRef` / default expansion happens at the\n * call-construction site (in the issue-planner / strategies) so the\n * operation factories deal only in pre-rendered SQL fragments — mirrors the\n * Postgres `ColumnSpec` pattern.\n *\n * - `typeSql` is the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * - `defaultSql` is the full `DEFAULT …` clause (or empty when there is no\n * default and when the column is rendered as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`, since SQLite forbids a default on an autoincrement PK).\n * - `inlineAutoincrementPrimaryKey` directs the renderer to emit\n * `INTEGER PRIMARY KEY AUTOINCREMENT` inline and to skip the table-level\n * primary-key constraint for this column. SQLite-specific: the column\n * becomes an alias for `rowid` only when this exact form is used.\n */\nexport interface SqliteColumnSpec {\n readonly name: string;\n readonly typeSql: string;\n readonly defaultSql: string;\n readonly nullable: boolean;\n readonly inlineAutoincrementPrimaryKey?: boolean;\n}\n\nexport interface SqlitePrimaryKeySpec {\n readonly columns: readonly string[];\n}\n\nexport interface SqliteUniqueSpec {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\nexport interface SqliteForeignKeySpec {\n readonly columns: readonly string[];\n readonly references: {\n readonly table: string;\n readonly columns: readonly string[];\n };\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n readonly constraint: boolean;\n}\n\n/**\n * Flat shape of a contract table for DDL emission. Used by both\n * `createTable` (additive) and `recreateTable` (widening/destructive).\n */\nexport interface SqliteTableSpec {\n readonly columns: readonly SqliteColumnSpec[];\n readonly primaryKey?: SqlitePrimaryKeySpec;\n readonly uniques?: readonly SqliteUniqueSpec[];\n readonly foreignKeys?: readonly SqliteForeignKeySpec[];\n}\n\n/**\n * Index recreation spec for `recreateTable`. Both declared indexes and\n * FK-backing indexes flatten to the same shape; the planner dedupes by\n * column-set before constructing the call.\n */\nexport interface SqliteIndexSpec {\n readonly name: string;\n readonly columns: readonly string[];\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\n/**\n * Renders a single column's inline DDL fragment within a `CREATE TABLE`\n * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite\n * treats `INTEGER PRIMARY KEY AUTOINCREMENT` as a special form that aliases\n * `rowid`, and the column must not carry a `DEFAULT` or repeat `NOT NULL`.\n */\nexport function renderColumnDefinition(column: SqliteColumnSpec): string {\n const parts: string[] = [quoteIdentifier(column.name), column.typeSql];\n if (column.inlineAutoincrementPrimaryKey) {\n parts.push('PRIMARY KEY AUTOINCREMENT');\n } else {\n if (column.defaultSql) parts.push(column.defaultSql);\n if (!column.nullable) parts.push('NOT NULL');\n }\n return parts.join(' ');\n}\n\n/**\n * Renders an inline FOREIGN KEY constraint clause for a `CREATE TABLE`\n * body. Returns the empty string when `constraint` is false (the FK is\n * tracked at the contract level for index-creation purposes only and must\n * not produce DDL).\n */\nexport function renderForeignKeyClause(fk: SqliteForeignKeySpec): string {\n if (!fk.constraint) return '';\n const name = fk.name ? `CONSTRAINT ${quoteIdentifier(fk.name)} ` : '';\n let sql = `${name}FOREIGN KEY (${fk.columns.map(quoteIdentifier).join(', ')}) REFERENCES ${quoteIdentifier(fk.references.table)} (${fk.references.columns.map(quoteIdentifier).join(', ')})`;\n if (fk.onDelete !== undefined) {\n sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[fk.onDelete]}`;\n }\n if (fk.onUpdate !== undefined) {\n sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[fk.onUpdate]}`;\n }\n return sql;\n}\n","import { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, type SqliteColumnSpec, step } from './shared';\n\nexport function addColumn(tableName: string, column: SqliteColumnSpec): Op {\n const parts = [\n `ALTER TABLE ${quoteIdentifier(tableName)}`,\n `ADD COLUMN ${quoteIdentifier(column.name)} ${column.typeSql}`,\n column.defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n const addSql = parts.join(' ');\n\n return {\n id: `column.${tableName}.${column.name}`,\n label: `Add column ${column.name} on ${tableName}`,\n summary: `Adds column ${column.name} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('column', column.name, tableName) },\n precheck: [\n step(\n `ensure column \"${column.name}\" is missing`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n execute: [step(`add column \"${column.name}\"`, addSql)],\n postcheck: [\n step(\n `verify column \"${column.name}\" exists`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n };\n}\n\nexport function dropColumn(tableName: string, columnName: string): Op {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} on ${tableName}`,\n summary: `Drops column ${columnName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('column', columnName, tableName) },\n precheck: [\n step(\n `ensure column \"${columnName}\" exists on \"${tableName}\"`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n execute: [\n step(\n `drop column \"${columnName}\" from \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${columnName}\" is gone from \"${tableName}\"`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n };\n}\n","/**\n * Low-level DDL fragment builders for SQLite migrations.\n *\n * These helpers consume `StorageColumn` (the contract shape, possibly with\n * `typeRef`) and produce string fragments. They are called once per column\n * at the call-construction boundary in `issue-planner.ts` / strategies to\n * build flat `SqliteColumnSpec`s; the operation factories themselves never\n * see `StorageColumn` or `storageTypes`.\n */\n\nimport {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n type StorageColumn,\n type StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\n\ntype SqliteColumnDefault = StorageColumn['default'];\n\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*$/',\n );\n }\n}\n\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * Resolves `typeRef` against `storageTypes` and validates the resulting\n * native type against a safe-identifier pattern.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType.toUpperCase();\n}\n\n/**\n * Renders the column's `DEFAULT …` clause. Returns the empty string when\n * there is no default, and also when the default is `autoincrement()` —\n * SQLite encodes that as `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the\n * column definition, not as a separate DEFAULT.\n */\nexport function buildColumnDefaultSql(columnDefault: SqliteColumnDefault | undefined): string {\n if (!columnDefault) return '';\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') return '';\n if (columnDefault.expression === 'now()') return \"DEFAULT (datetime('now'))\";\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n }\n}\n\nexport function renderDefaultLiteral(value: unknown): string {\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? '1' : '0';\n }\n if (value === null) {\n return 'NULL';\n }\n return `'${escapeLiteral(JSON.stringify(value))}'`;\n}\n\nexport function buildCreateIndexSql(\n tableName: string,\n indexName: string,\n columns: readonly string[],\n unique = false,\n): string {\n const uniqueKeyword = unique ? 'UNIQUE ' : '';\n return `CREATE ${uniqueKeyword}INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} (${columns.map(quoteIdentifier).join(', ')})`;\n}\n\nexport function buildDropIndexSql(indexName: string): string {\n return `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`;\n}\n\n/**\n * True when the column is rendered inline as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`. Requires the column's default to be `autoincrement()` and\n * the column to be the sole member of the table's primary key — anything\n * else falls back to a separate PRIMARY KEY constraint with a default\n * AUTOINCREMENT semantics expressed elsewhere.\n */\nexport function isInlineAutoincrementPrimaryKey(table: StorageTable, columnName: string): boolean {\n if (table.primaryKey?.columns.length !== 1) return false;\n if (table.primaryKey.columns[0] !== columnName) return false;\n const column = table.columns[columnName];\n return column?.default?.kind === 'function' && column.default.expression === 'autoincrement()';\n}\n\ntype ResolvedColumnTypeMetadata = Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>;\n\nfunction resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n throw new Error(\n `Storage type \"${column.typeRef}\" referenced by column is not defined in storage.types.`,\n );\n }\n if (isPostgresEnumStorageEntry(referencedType)) {\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: { values: referencedType.values } as Record<string, unknown>,\n };\n }\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral } from '../../sql-utils';\nimport { buildCreateIndexSql, buildDropIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, step } from './shared';\n\nexport function createIndex(tableName: string, indexName: string, columns: readonly string[]): Op {\n return {\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" is missing`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [\n step(`create index \"${indexName}\"`, buildCreateIndexSql(tableName, indexName, columns)),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n\nexport function dropIndex(tableName: string, indexName: string): Op {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops index ${indexName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [step(`drop index \"${indexName}\"`, buildDropIndexSql(indexName))],\n postcheck: [\n step(\n `verify index \"${indexName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n","import type { MigrationOperationClass } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { stripOuterParens } from '../../default-normalizer';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildCreateIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport {\n type Op,\n renderColumnDefinition,\n renderForeignKeyClause,\n type SqliteIndexSpec,\n type SqliteTableSpec,\n step,\n} from './shared';\n\n/**\n * Renders the body of a `CREATE TABLE <name> ( … )` statement from a flat\n * `SqliteTableSpec`. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` form is\n * inline on the column; the table-level PRIMARY KEY clause is emitted only\n * when no column carries `inlineAutoincrementPrimaryKey`.\n */\nfunction renderCreateTableSql(tableName: string, spec: SqliteTableSpec): string {\n const columnDefs = spec.columns.map(renderColumnDefinition);\n\n const constraintDefs: string[] = [];\n const hasInlinePk = spec.columns.some((c) => c.inlineAutoincrementPrimaryKey);\n if (spec.primaryKey && !hasInlinePk) {\n constraintDefs.push(`PRIMARY KEY (${spec.primaryKey.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const u of spec.uniques ?? []) {\n const name = u.name ? `CONSTRAINT ${quoteIdentifier(u.name)} ` : '';\n constraintDefs.push(`${name}UNIQUE (${u.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const fk of spec.foreignKeys ?? []) {\n const clause = renderForeignKeyClause(fk);\n if (clause) constraintDefs.push(clause);\n }\n\n const allDefs = [...columnDefs, ...constraintDefs];\n return `CREATE TABLE ${quoteIdentifier(tableName)} (\\n ${allDefs.join(',\\n ')}\\n)`;\n}\n\nexport function createTable(tableName: string, spec: SqliteTableSpec): Op {\n return {\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`create table \"${tableName}\"`, renderCreateTableSql(tableName, spec))],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport function dropTable(tableName: string): Op {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops table ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`drop table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`)],\n postcheck: [\n step(\n `verify table \"${tableName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport interface RecreateTableArgs {\n readonly tableName: string;\n /** New (post-recreate) shape of the table. Same flat spec as `createTable`. */\n readonly contractTable: SqliteTableSpec;\n /**\n * Names of columns that exist in the live (pre-recreate) schema. Used to\n * compute the `INSERT INTO temp ... SELECT ... FROM old` column list — only\n * shared columns are copied, so dropped columns are left behind and added\n * columns come from defaults.\n */\n readonly schemaColumnNames: readonly string[];\n /**\n * Indexes (declared + FK-backing, deduped by column-set) to recreate after\n * the table has been replaced. The planner pre-merges these.\n */\n readonly indexes: readonly SqliteIndexSpec[];\n /** Human-readable summary of the change, built by the planner from issues. */\n readonly summary: string;\n /**\n * Per-issue postcheck steps appended after the structural postchecks. The\n * planner pre-builds these via `buildRecreatePostchecks` so the call IR\n * carries flat, serializable data only — no `SchemaIssue` references.\n */\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly operationClass: MigrationOperationClass;\n}\n\nexport function recreateTable(args: RecreateTableArgs): Op {\n const {\n tableName,\n contractTable,\n schemaColumnNames,\n indexes,\n summary,\n postchecks,\n operationClass,\n } = args;\n const tempName = `_prisma_new_${tableName}`;\n const liveSet = new Set(schemaColumnNames);\n const sharedColumns = contractTable.columns.filter((c) => liveSet.has(c.name)).map((c) => c.name);\n const columnList = sharedColumns.map(quoteIdentifier).join(', ');\n\n const indexStatements = indexes.map((idx) => ({\n description: `recreate index \"${idx.name}\" on \"${tableName}\"`,\n sql: buildCreateIndexSql(tableName, idx.name, idx.columns),\n }));\n\n // If the contract retains no columns from the live table, an `INSERT INTO\n // tmp () SELECT FROM old` is invalid SQL — and would also be a no-op since\n // there's nothing to copy. Skip the copy step in that case; the new\n // (empty) table replaces the old one directly.\n const copyStep =\n sharedColumns.length > 0\n ? [\n step(\n `copy data from \"${tableName}\" to \"${tempName}\"`,\n `INSERT INTO ${quoteIdentifier(tempName)} (${columnList}) SELECT ${columnList} FROM ${quoteIdentifier(tableName)}`,\n ),\n ]\n : [];\n\n return {\n id: `recreateTable.${tableName}`,\n label: `Recreate table ${tableName}`,\n summary,\n operationClass,\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `ensure temp table \"${tempName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ],\n execute: [\n step(\n `create new table \"${tempName}\" with desired schema`,\n renderCreateTableSql(tempName, contractTable),\n ),\n ...copyStep,\n step(`drop old table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`),\n step(\n `rename \"${tempName}\" to \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tempName)} RENAME TO ${quoteIdentifier(tableName)}`,\n ),\n ...indexStatements,\n ],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `verify temp table \"${tempName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ...postchecks,\n ],\n };\n}\n\n/**\n * Build a one-line summary of a recreate-table operation from the schema\n * issues that triggered it. Lives next to `recreateTable` so the planner\n * (which has the issues) can produce the same description the factory\n * used to build inline. Keeping the formatting target-side keeps\n * `RecreateTableCall` issue-free at the IR layer.\n */\nexport function buildRecreateSummary(tableName: string, issues: readonly SchemaIssue[]): string {\n const messages = issues.map((i) => i.message).join('; ');\n return `Recreates table ${tableName} to apply schema changes: ${messages}`;\n}\n\nconst COLUMN_LEVEL_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'nullability_mismatch',\n 'default_mismatch',\n 'default_missing',\n 'extra_default',\n 'type_mismatch',\n]);\n\nconst PK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['primary_key_mismatch', 'extra_primary_key']);\n\nconst UNIQUE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'unique_constraint_mismatch',\n 'extra_unique_constraint',\n]);\n\nconst FK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['foreign_key_mismatch', 'extra_foreign_key']);\n\n/**\n * Returns the columns the contract expects as the table's primary key. Picks\n * up SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT` form when no\n * explicit `primaryKey` clause is set on the spec.\n */\nfunction expectedPrimaryKeyColumns(spec: SqliteTableSpec): readonly string[] {\n if (spec.primaryKey) return spec.primaryKey.columns;\n const inlinePk = spec.columns.find((c) => c.inlineAutoincrementPrimaryKey);\n return inlinePk ? [inlinePk.name] : [];\n}\n\nfunction quoteSqlList(values: readonly string[]): string {\n return values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n}\n\n/**\n * Per-issue postchecks verifying the recreated table's shape against the\n * contract spec. Column-level issues (`nullability_mismatch`,\n * `default_mismatch`, …) emit one targeted check each; constraint-level\n * issues (`primary_key_mismatch`, `unique_constraint_mismatch`,\n * `foreign_key_mismatch`, plus their `extra_*` siblings) emit one\n * `pragma_*`-driven check per declared constraint in the contract spec, so\n * a recreated table with the right columns but the wrong PK / unique / FK\n * shape fails the postcheck instead of passing silently. Exported so the\n * planner can pre-build the list at construction time and\n * `RecreateTableCall` doesn't have to carry `SchemaIssue` objects through\n * to render time.\n */\nexport function buildRecreatePostchecks(\n tableName: string,\n issues: readonly SchemaIssue[],\n spec: SqliteTableSpec,\n): Array<{ description: string; sql: string }> {\n const checks: Array<{ description: string; sql: string }> = [];\n const t = escapeLiteral(tableName);\n const byName = new Map(spec.columns.map((c) => [c.name, c]));\n\n for (const issue of issues) {\n if (issue.kind === 'enum_values_changed') continue;\n if (!COLUMN_LEVEL_ISSUE_KINDS.has(issue.kind)) continue;\n if (!issue.column) continue;\n const c = escapeLiteral(issue.column);\n if (issue.kind === 'nullability_mismatch') {\n // `expected` carries the contract's nullable flag as a string. We only\n // emit a postcheck when the value is recognized — anything else\n // (case-folded, numeric coding, etc.) is left to the structural\n // verifier so a typo here can't silently invert the meaning.\n let wantNotNull: boolean | undefined;\n if (issue.expected === 'false') wantNotNull = true;\n else if (issue.expected === 'true') wantNotNull = false;\n if (wantNotNull !== undefined) {\n checks.push({\n description: `verify \"${issue.column}\" nullability on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND \"notnull\" = ${wantNotNull ? 1 : 0}`,\n });\n }\n }\n if (issue.kind === 'default_mismatch' || issue.kind === 'default_missing') {\n const colSpec = byName.get(issue.column);\n const expectedRaw = colSpec?.defaultSql.startsWith('DEFAULT ')\n ? // SQLite's pragma_table_info.dflt_value strips outer parens for\n // expression defaults (per the SQLite docs), so `(datetime('now'))`\n // is stored as `datetime('now')`. Strip them here so the postcheck\n // matches.\n stripOuterParens(colSpec.defaultSql.slice('DEFAULT '.length))\n : null;\n if (expectedRaw) {\n checks.push({\n description: `verify \"${issue.column}\" default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value = '${escapeLiteral(expectedRaw)}'`,\n });\n }\n }\n if (issue.kind === 'type_mismatch') {\n const colSpec = byName.get(issue.column);\n if (colSpec) {\n checks.push({\n description: `verify \"${issue.column}\" type on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND LOWER(type) = '${escapeLiteral(colSpec.typeSql.toLowerCase())}'`,\n });\n }\n }\n if (issue.kind === 'extra_default') {\n checks.push({\n description: `verify \"${issue.column}\" has no default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value IS NULL`,\n });\n }\n }\n\n // Constraint-level issues — emit one postcheck per declared constraint in\n // the contract spec when *any* issue of that kind fires, since recreate\n // rebuilds the entire table at once.\n const hasPkIssue = issues.some((i) => PK_ISSUE_KINDS.has(i.kind));\n const hasUniqueIssue = issues.some((i) => UNIQUE_ISSUE_KINDS.has(i.kind));\n const hasFkIssue = issues.some((i) => FK_ISSUE_KINDS.has(i.kind));\n\n if (hasPkIssue) {\n const pkColumns = expectedPrimaryKeyColumns(spec);\n // Verify pragma_table_info reports exactly these columns as PK members\n // (count + named membership); zero columns expected ⇒ no PK at all.\n const colCount = pkColumns.length;\n if (colCount === 0) {\n checks.push({\n description: `verify \"${tableName}\" has no primary key`,\n sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = 0`,\n });\n } else {\n checks.push({\n description: `verify primary key on \"${tableName}\"`,\n sql:\n `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0 AND name IN (${quoteSqlList(pkColumns)})) = ${colCount}`,\n });\n }\n }\n\n if (hasUniqueIssue) {\n for (const u of spec.uniques ?? []) {\n const colCount = u.columns.length;\n const description = u.name\n ? `verify unique constraint \"${u.name}\" on \"${tableName}\"`\n : `verify unique constraint (${u.columns.join(', ')}) on \"${tableName}\"`;\n // Match any unique index whose covered columns are exactly the expected\n // set. Order is intentionally not checked — SQLite's unique-index\n // identity is column-set, not column-sequence.\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l` +\n ` WHERE l.\"unique\" = 1` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name)) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name) WHERE name IN (${quoteSqlList(u.columns)})) = ${colCount})`,\n });\n }\n }\n\n if (hasFkIssue) {\n for (const fk of spec.foreignKeys ?? []) {\n const refTable = escapeLiteral(fk.references.table);\n const colCount = fk.columns.length;\n // Build a `SUM(CASE WHEN (\"from\",\"to\") IN ((…)) …)` so the check works\n // for both single- and multi-column FKs without depending on FK row\n // ordering inside `pragma_foreign_key_list`.\n const tuples = fk.columns\n .map((from, i) => {\n const to = fk.references.columns[i] ?? from;\n return `('${escapeLiteral(from)}', '${escapeLiteral(to)}')`;\n })\n .join(', ');\n const description = `verify foreign key (${fk.columns.join(', ')}) → ${fk.references.table}(${fk.references.columns.join(', ')}) on \"${tableName}\"`;\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_foreign_key_list('${t}') f` +\n ` WHERE f.\"table\" = '${refTable}'` +\n ' GROUP BY f.id' +\n ` HAVING COUNT(*) = ${colCount}` +\n ` AND SUM(CASE WHEN (f.\"from\", f.\"to\") IN (${tuples}) THEN 1 ELSE 0 END) = ${colCount})`,\n });\n }\n }\n\n return checks;\n}\n"],"mappings":";;;;;AAOA,SAAgB,KAAK,aAAqB,KAAmD;CAC3F,OAAO;EAAE;EAAa;EAAK;;AAqE7B,MAAM,yBAA4D;CAChE,UAAU;CACV,UAAU;CACV,SAAS;CACT,SAA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AAC;IACxD,CACD,KAAK,KAAK;EACb,MAAM,cAAc,uBAAuB,GAAG,QAAQ,KAAK,KAAK,CAAC,MAAM,GAAG,WAAW,MAAM,GAAG,GAAG,WAAW,QAAQ,KAAK,KAAK,CAAC,QAAQ,UAAU;EACjJ,OAAO,KAAK;GACV;GACA,KACE,yDAAyD,EAAE,0BACpC,SAAS,oCAEV,SAAA,4CACuB,OAAO,yBAAyB,SAAS;GACzF,CAAC;;CAIN,OAAO"}
|
|
1
|
+
{"version":3,"file":"tables-DGRRJasz.mjs","names":[],"sources":["../src/core/migrations/operations/shared.ts","../src/core/migrations/operations/columns.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operations/indexes.ts","../src/core/migrations/operations/tables.ts"],"sourcesContent":["import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ReferentialAction } from '@prisma-next/sql-contract/types';\nimport { quoteIdentifier } from '../../sql-utils';\nimport type { SqlitePlanTargetDetails } from '../planner-target-details';\n\nexport type Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport function step(description: string, sql: string): { description: string; sql: string } {\n return { description, sql };\n}\n\n/**\n * Flat, fully-resolved column shape consumed by `createTable`, `addColumn`,\n * and `recreateTable`. Codec / `typeRef` / default expansion happens at the\n * call-construction site (in the issue-planner / strategies) so the\n * operation factories deal only in pre-rendered SQL fragments — mirrors the\n * Postgres `ColumnSpec` pattern.\n *\n * - `typeSql` is the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * - `defaultSql` is the full `DEFAULT …` clause (or empty when there is no\n * default and when the column is rendered as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`, since SQLite forbids a default on an autoincrement PK).\n * - `inlineAutoincrementPrimaryKey` directs the renderer to emit\n * `INTEGER PRIMARY KEY AUTOINCREMENT` inline and to skip the table-level\n * primary-key constraint for this column. SQLite-specific: the column\n * becomes an alias for `rowid` only when this exact form is used.\n */\nexport interface SqliteColumnSpec {\n readonly name: string;\n readonly typeSql: string;\n readonly defaultSql: string;\n readonly nullable: boolean;\n readonly inlineAutoincrementPrimaryKey?: boolean;\n}\n\nexport interface SqlitePrimaryKeySpec {\n readonly columns: readonly string[];\n}\n\nexport interface SqliteUniqueSpec {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\nexport interface SqliteForeignKeySpec {\n readonly columns: readonly string[];\n readonly references: {\n readonly table: string;\n readonly columns: readonly string[];\n };\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n readonly constraint: boolean;\n}\n\n/**\n * Flat shape of a contract table for DDL emission. Used by both\n * `createTable` (additive) and `recreateTable` (widening/destructive).\n */\nexport interface SqliteTableSpec {\n readonly columns: readonly SqliteColumnSpec[];\n readonly primaryKey?: SqlitePrimaryKeySpec;\n readonly uniques?: readonly SqliteUniqueSpec[];\n readonly foreignKeys?: readonly SqliteForeignKeySpec[];\n}\n\n/**\n * Index recreation spec for `recreateTable`. Both declared indexes and\n * FK-backing indexes flatten to the same shape; the planner dedupes by\n * column-set before constructing the call.\n */\nexport interface SqliteIndexSpec {\n readonly name: string;\n readonly columns: readonly string[];\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\n/**\n * Renders a single column's inline DDL fragment within a `CREATE TABLE`\n * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite\n * treats `INTEGER PRIMARY KEY AUTOINCREMENT` as a special form that aliases\n * `rowid`, and the column must not carry a `DEFAULT` or repeat `NOT NULL`.\n */\nexport function renderColumnDefinition(column: SqliteColumnSpec): string {\n const parts: string[] = [quoteIdentifier(column.name), column.typeSql];\n if (column.inlineAutoincrementPrimaryKey) {\n parts.push('PRIMARY KEY AUTOINCREMENT');\n } else {\n if (column.defaultSql) parts.push(column.defaultSql);\n if (!column.nullable) parts.push('NOT NULL');\n }\n return parts.join(' ');\n}\n\n/**\n * Renders an inline FOREIGN KEY constraint clause for a `CREATE TABLE`\n * body. Returns the empty string when `constraint` is false (the FK is\n * tracked at the contract level for index-creation purposes only and must\n * not produce DDL).\n */\nexport function renderForeignKeyClause(fk: SqliteForeignKeySpec): string {\n if (!fk.constraint) return '';\n const name = fk.name ? `CONSTRAINT ${quoteIdentifier(fk.name)} ` : '';\n let sql = `${name}FOREIGN KEY (${fk.columns.map(quoteIdentifier).join(', ')}) REFERENCES ${quoteIdentifier(fk.references.table)} (${fk.references.columns.map(quoteIdentifier).join(', ')})`;\n if (fk.onDelete !== undefined) {\n sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[fk.onDelete]}`;\n }\n if (fk.onUpdate !== undefined) {\n sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[fk.onUpdate]}`;\n }\n return sql;\n}\n","import { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, type SqliteColumnSpec, step } from './shared';\n\nexport function addColumn(tableName: string, column: SqliteColumnSpec): Op {\n const parts = [\n `ALTER TABLE ${quoteIdentifier(tableName)}`,\n `ADD COLUMN ${quoteIdentifier(column.name)} ${column.typeSql}`,\n column.defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n const addSql = parts.join(' ');\n\n return {\n id: `column.${tableName}.${column.name}`,\n label: `Add column ${column.name} on ${tableName}`,\n summary: `Adds column ${column.name} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('column', column.name, tableName) },\n precheck: [\n step(\n `ensure column \"${column.name}\" is missing`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n execute: [step(`add column \"${column.name}\"`, addSql)],\n postcheck: [\n step(\n `verify column \"${column.name}\" exists`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n };\n}\n\nexport function dropColumn(tableName: string, columnName: string): Op {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} on ${tableName}`,\n summary: `Drops column ${columnName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('column', columnName, tableName) },\n precheck: [\n step(\n `ensure column \"${columnName}\" exists on \"${tableName}\"`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n execute: [\n step(\n `drop column \"${columnName}\" from \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${columnName}\" is gone from \"${tableName}\"`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n };\n}\n","/**\n * Low-level DDL fragment builders for SQLite migrations.\n *\n * These helpers consume `StorageColumn` (the contract shape, possibly with\n * `typeRef`) and produce string fragments. They are called once per column\n * at the call-construction boundary in `issue-planner.ts` / strategies to\n * build flat `SqliteColumnSpec`s; the operation factories themselves never\n * see `StorageColumn` or `storageTypes`.\n */\n\nimport {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n type StorageColumn,\n type StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\n\ntype SqliteColumnDefault = StorageColumn['default'];\n\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*$/',\n );\n }\n}\n\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * Resolves `typeRef` against `storageTypes` and validates the resulting\n * native type against a safe-identifier pattern.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType.toUpperCase();\n}\n\n/**\n * Renders the column's `DEFAULT …` clause. Returns the empty string when\n * there is no default, and also when the default is `autoincrement()` —\n * SQLite encodes that as `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the\n * column definition, not as a separate DEFAULT.\n */\nexport function buildColumnDefaultSql(columnDefault: SqliteColumnDefault | undefined): string {\n if (!columnDefault) return '';\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') return '';\n if (columnDefault.expression === 'now()') return \"DEFAULT (datetime('now'))\";\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n }\n}\n\nexport function renderDefaultLiteral(value: unknown): string {\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? '1' : '0';\n }\n if (value === null) {\n return 'NULL';\n }\n return `'${escapeLiteral(JSON.stringify(value))}'`;\n}\n\nexport function buildCreateIndexSql(\n tableName: string,\n indexName: string,\n columns: readonly string[],\n unique = false,\n): string {\n const uniqueKeyword = unique ? 'UNIQUE ' : '';\n return `CREATE ${uniqueKeyword}INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} (${columns.map(quoteIdentifier).join(', ')})`;\n}\n\nexport function buildDropIndexSql(indexName: string): string {\n return `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`;\n}\n\n/**\n * True when the column is rendered inline as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`. Requires the column's default to be `autoincrement()` and\n * the column to be the sole member of the table's primary key — anything\n * else falls back to a separate PRIMARY KEY constraint with a default\n * AUTOINCREMENT semantics expressed elsewhere.\n */\nexport function isInlineAutoincrementPrimaryKey(table: StorageTable, columnName: string): boolean {\n if (table.primaryKey?.columns.length !== 1) return false;\n if (table.primaryKey.columns[0] !== columnName) return false;\n const column = table.columns[columnName];\n return column?.default?.kind === 'function' && column.default.expression === 'autoincrement()';\n}\n\ntype ResolvedColumnTypeMetadata = Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>;\n\nfunction resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n throw new Error(\n `Storage type \"${column.typeRef}\" referenced by column is not defined in storage.types.`,\n );\n }\n if (isPostgresEnumStorageEntry(referencedType)) {\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: { values: referencedType.values } as Record<string, unknown>,\n };\n }\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral } from '../../sql-utils';\nimport { buildCreateIndexSql, buildDropIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, step } from './shared';\n\nexport function createIndex(tableName: string, indexName: string, columns: readonly string[]): Op {\n return {\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" is missing`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [\n step(`create index \"${indexName}\"`, buildCreateIndexSql(tableName, indexName, columns)),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n\nexport function dropIndex(tableName: string, indexName: string): Op {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops index ${indexName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [step(`drop index \"${indexName}\"`, buildDropIndexSql(indexName))],\n postcheck: [\n step(\n `verify index \"${indexName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n","import type { MigrationOperationClass } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { stripOuterParens } from '../../default-normalizer';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildCreateIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport {\n type Op,\n renderColumnDefinition,\n renderForeignKeyClause,\n type SqliteIndexSpec,\n type SqliteTableSpec,\n step,\n} from './shared';\n\n/**\n * Renders the body of a `CREATE TABLE <name> ( … )` statement from a flat\n * `SqliteTableSpec`. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` form is\n * inline on the column; the table-level PRIMARY KEY clause is emitted only\n * when no column carries `inlineAutoincrementPrimaryKey`.\n */\nfunction renderCreateTableSql(tableName: string, spec: SqliteTableSpec): string {\n const columnDefs = spec.columns.map(renderColumnDefinition);\n\n const constraintDefs: string[] = [];\n const hasInlinePk = spec.columns.some((c) => c.inlineAutoincrementPrimaryKey);\n if (spec.primaryKey && !hasInlinePk) {\n constraintDefs.push(`PRIMARY KEY (${spec.primaryKey.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const u of spec.uniques ?? []) {\n const name = u.name ? `CONSTRAINT ${quoteIdentifier(u.name)} ` : '';\n constraintDefs.push(`${name}UNIQUE (${u.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const fk of spec.foreignKeys ?? []) {\n const clause = renderForeignKeyClause(fk);\n if (clause) constraintDefs.push(clause);\n }\n\n const allDefs = [...columnDefs, ...constraintDefs];\n return `CREATE TABLE ${quoteIdentifier(tableName)} (\\n ${allDefs.join(',\\n ')}\\n)`;\n}\n\nexport function createTable(tableName: string, spec: SqliteTableSpec): Op {\n return {\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`create table \"${tableName}\"`, renderCreateTableSql(tableName, spec))],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport function dropTable(tableName: string): Op {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops table ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`drop table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`)],\n postcheck: [\n step(\n `verify table \"${tableName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport interface RecreateTableArgs {\n readonly tableName: string;\n /** New (post-recreate) shape of the table. Same flat spec as `createTable`. */\n readonly contractTable: SqliteTableSpec;\n /**\n * Names of columns that exist in the live (pre-recreate) schema. Used to\n * compute the `INSERT INTO temp ... SELECT ... FROM old` column list — only\n * shared columns are copied, so dropped columns are left behind and added\n * columns come from defaults.\n */\n readonly schemaColumnNames: readonly string[];\n /**\n * Indexes (declared + FK-backing, deduped by column-set) to recreate after\n * the table has been replaced. The planner pre-merges these.\n */\n readonly indexes: readonly SqliteIndexSpec[];\n /** Human-readable summary of the change, built by the planner from issues. */\n readonly summary: string;\n /**\n * Per-issue postcheck steps appended after the structural postchecks. The\n * planner pre-builds these via `buildRecreatePostchecks` so the call IR\n * carries flat, serializable data only — no `SchemaIssue` references.\n */\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly operationClass: MigrationOperationClass;\n}\n\nexport function recreateTable(args: RecreateTableArgs): Op {\n const {\n tableName,\n contractTable,\n schemaColumnNames,\n indexes,\n summary,\n postchecks,\n operationClass,\n } = args;\n const tempName = `_prisma_new_${tableName}`;\n const liveSet = new Set(schemaColumnNames);\n const sharedColumns = contractTable.columns.filter((c) => liveSet.has(c.name)).map((c) => c.name);\n const columnList = sharedColumns.map(quoteIdentifier).join(', ');\n\n const indexStatements = indexes.map((idx) => ({\n description: `recreate index \"${idx.name}\" on \"${tableName}\"`,\n sql: buildCreateIndexSql(tableName, idx.name, idx.columns),\n }));\n\n // If the contract retains no columns from the live table, an `INSERT INTO\n // tmp () SELECT FROM old` is invalid SQL — and would also be a no-op since\n // there's nothing to copy. Skip the copy step in that case; the new\n // (empty) table replaces the old one directly.\n const copyStep =\n sharedColumns.length > 0\n ? [\n step(\n `copy data from \"${tableName}\" to \"${tempName}\"`,\n `INSERT INTO ${quoteIdentifier(tempName)} (${columnList}) SELECT ${columnList} FROM ${quoteIdentifier(tableName)}`,\n ),\n ]\n : [];\n\n return {\n id: `recreateTable.${tableName}`,\n label: `Recreate table ${tableName}`,\n summary,\n operationClass,\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `ensure temp table \"${tempName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ],\n execute: [\n step(\n `create new table \"${tempName}\" with desired schema`,\n renderCreateTableSql(tempName, contractTable),\n ),\n ...copyStep,\n step(`drop old table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`),\n step(\n `rename \"${tempName}\" to \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tempName)} RENAME TO ${quoteIdentifier(tableName)}`,\n ),\n ...indexStatements,\n ],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `verify temp table \"${tempName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ...postchecks,\n ],\n };\n}\n\n/**\n * Build a one-line summary of a recreate-table operation from the schema\n * issues that triggered it. Lives next to `recreateTable` so the planner\n * (which has the issues) can produce the same description the factory\n * used to build inline. Keeping the formatting target-side keeps\n * `RecreateTableCall` issue-free at the IR layer.\n */\nexport function buildRecreateSummary(tableName: string, issues: readonly SchemaIssue[]): string {\n const messages = issues.map((i) => i.message).join('; ');\n return `Recreates table ${tableName} to apply schema changes: ${messages}`;\n}\n\nconst COLUMN_LEVEL_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'nullability_mismatch',\n 'default_mismatch',\n 'default_missing',\n 'extra_default',\n 'type_mismatch',\n]);\n\nconst PK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['primary_key_mismatch', 'extra_primary_key']);\n\nconst UNIQUE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'unique_constraint_mismatch',\n 'extra_unique_constraint',\n]);\n\nconst FK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['foreign_key_mismatch', 'extra_foreign_key']);\n\n/**\n * Returns the columns the contract expects as the table's primary key. Picks\n * up SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT` form when no\n * explicit `primaryKey` clause is set on the spec.\n */\nfunction expectedPrimaryKeyColumns(spec: SqliteTableSpec): readonly string[] {\n if (spec.primaryKey) return spec.primaryKey.columns;\n const inlinePk = spec.columns.find((c) => c.inlineAutoincrementPrimaryKey);\n return inlinePk ? [inlinePk.name] : [];\n}\n\nfunction quoteSqlList(values: readonly string[]): string {\n return values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n}\n\n/**\n * Per-issue postchecks verifying the recreated table's shape against the\n * contract spec. Column-level issues (`nullability_mismatch`,\n * `default_mismatch`, …) emit one targeted check each; constraint-level\n * issues (`primary_key_mismatch`, `unique_constraint_mismatch`,\n * `foreign_key_mismatch`, plus their `extra_*` siblings) emit one\n * `pragma_*`-driven check per declared constraint in the contract spec, so\n * a recreated table with the right columns but the wrong PK / unique / FK\n * shape fails the postcheck instead of passing silently. Exported so the\n * planner can pre-build the list at construction time and\n * `RecreateTableCall` doesn't have to carry `SchemaIssue` objects through\n * to render time.\n */\nexport function buildRecreatePostchecks(\n tableName: string,\n issues: readonly SchemaIssue[],\n spec: SqliteTableSpec,\n): Array<{ description: string; sql: string }> {\n const checks: Array<{ description: string; sql: string }> = [];\n const t = escapeLiteral(tableName);\n const byName = new Map(spec.columns.map((c) => [c.name, c]));\n\n for (const issue of issues) {\n if (issue.kind === 'enum_values_changed') continue;\n if (!COLUMN_LEVEL_ISSUE_KINDS.has(issue.kind)) continue;\n if (!issue.column) continue;\n const c = escapeLiteral(issue.column);\n if (issue.kind === 'nullability_mismatch') {\n // `expected` carries the contract's nullable flag as a string. We only\n // emit a postcheck when the value is recognized — anything else\n // (case-folded, numeric coding, etc.) is left to the structural\n // verifier so a typo here can't silently invert the meaning.\n let wantNotNull: boolean | undefined;\n if (issue.expected === 'false') wantNotNull = true;\n else if (issue.expected === 'true') wantNotNull = false;\n if (wantNotNull !== undefined) {\n checks.push({\n description: `verify \"${issue.column}\" nullability on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND \"notnull\" = ${wantNotNull ? 1 : 0}`,\n });\n }\n }\n if (issue.kind === 'default_mismatch' || issue.kind === 'default_missing') {\n const colSpec = byName.get(issue.column);\n const expectedRaw = colSpec?.defaultSql.startsWith('DEFAULT ')\n ? // SQLite's pragma_table_info.dflt_value strips outer parens for\n // expression defaults (per the SQLite docs), so `(datetime('now'))`\n // is stored as `datetime('now')`. Strip them here so the postcheck\n // matches.\n stripOuterParens(colSpec.defaultSql.slice('DEFAULT '.length))\n : null;\n if (expectedRaw) {\n checks.push({\n description: `verify \"${issue.column}\" default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value = '${escapeLiteral(expectedRaw)}'`,\n });\n }\n }\n if (issue.kind === 'type_mismatch') {\n const colSpec = byName.get(issue.column);\n if (colSpec) {\n checks.push({\n description: `verify \"${issue.column}\" type on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND LOWER(type) = '${escapeLiteral(colSpec.typeSql.toLowerCase())}'`,\n });\n }\n }\n if (issue.kind === 'extra_default') {\n checks.push({\n description: `verify \"${issue.column}\" has no default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value IS NULL`,\n });\n }\n }\n\n // Constraint-level issues — emit one postcheck per declared constraint in\n // the contract spec when *any* issue of that kind fires, since recreate\n // rebuilds the entire table at once.\n const hasPkIssue = issues.some((i) => PK_ISSUE_KINDS.has(i.kind));\n const hasUniqueIssue = issues.some((i) => UNIQUE_ISSUE_KINDS.has(i.kind));\n const hasFkIssue = issues.some((i) => FK_ISSUE_KINDS.has(i.kind));\n\n if (hasPkIssue) {\n const pkColumns = expectedPrimaryKeyColumns(spec);\n // Verify pragma_table_info reports exactly these columns as PK members\n // (count + named membership); zero columns expected ⇒ no PK at all.\n const colCount = pkColumns.length;\n if (colCount === 0) {\n checks.push({\n description: `verify \"${tableName}\" has no primary key`,\n sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = 0`,\n });\n } else {\n checks.push({\n description: `verify primary key on \"${tableName}\"`,\n sql:\n `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0 AND name IN (${quoteSqlList(pkColumns)})) = ${colCount}`,\n });\n }\n }\n\n if (hasUniqueIssue) {\n for (const u of spec.uniques ?? []) {\n const colCount = u.columns.length;\n const description = u.name\n ? `verify unique constraint \"${u.name}\" on \"${tableName}\"`\n : `verify unique constraint (${u.columns.join(', ')}) on \"${tableName}\"`;\n // Match any unique index whose covered columns are exactly the expected\n // set. Order is intentionally not checked — SQLite's unique-index\n // identity is column-set, not column-sequence.\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l` +\n ` WHERE l.\"unique\" = 1` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name)) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name) WHERE name IN (${quoteSqlList(u.columns)})) = ${colCount})`,\n });\n }\n }\n\n if (hasFkIssue) {\n for (const fk of spec.foreignKeys ?? []) {\n const refTable = escapeLiteral(fk.references.table);\n const colCount = fk.columns.length;\n // Build a `SUM(CASE WHEN (\"from\",\"to\") IN ((…)) …)` so the check works\n // for both single- and multi-column FKs without depending on FK row\n // ordering inside `pragma_foreign_key_list`.\n const tuples = fk.columns\n .map((from, i) => {\n const to = fk.references.columns[i] ?? from;\n return `('${escapeLiteral(from)}', '${escapeLiteral(to)}')`;\n })\n .join(', ');\n const description = `verify foreign key (${fk.columns.join(', ')}) → ${fk.references.table}(${fk.references.columns.join(', ')}) on \"${tableName}\"`;\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_foreign_key_list('${t}') f` +\n ` WHERE f.\"table\" = '${refTable}'` +\n ' GROUP BY f.id' +\n ` HAVING COUNT(*) = ${colCount}` +\n ` AND SUM(CASE WHEN (f.\"from\", f.\"to\") IN (${tuples}) THEN 1 ELSE 0 END) = ${colCount})`,\n });\n }\n }\n\n return checks;\n}\n"],"mappings":";;;;;AAOA,SAAgB,KAAK,aAAqB,KAAmD;CAC3F,OAAO;EAAE;EAAa;CAAI;AAC5B;AAoEA,MAAM,yBAA4D;CAChE,UAAU;CACV,UAAU;CACV,SAAS;CACT,SAAS;CACT,YAAY;AACd;;;;;;;AAQA,SAAgB,uBAAuB,QAAkC;CACvE,MAAM,QAAkB,CAAC,gBAAgB,OAAO,IAAI,GAAG,OAAO,OAAO;CACrE,IAAI,OAAO,+BACT,MAAM,KAAK,2BAA2B;MACjC;EACL,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AAQ,KAAK,IAAI,EAAE,MAAM,GAAG,WAAW,MAAM,GAAG,GAAG,WAAW,QAAQ,KAAK,IAAI,EAAE,QAAQ,UAAU;EACjJ,OAAO,KAAK;GACV;GACA,KACE,yDAAyD,EAAE,0BACpC,SAAS,oCAEV,SAAA,4CACuB,OAAO,yBAAyB,SAAS;EAC1F,CAAC;CACH;CAGF,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,34 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/target-sqlite",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@prisma-next/cli": "0.
|
|
9
|
-
"@prisma-next/contract": "0.
|
|
10
|
-
"@prisma-next/errors": "0.
|
|
11
|
-
"@prisma-next/family-sql": "0.
|
|
12
|
-
"@prisma-next/framework-components": "0.
|
|
13
|
-
"@prisma-next/migration-tools": "0.
|
|
14
|
-
"@prisma-next/sql-contract": "0.
|
|
15
|
-
"@prisma-next/sql-errors": "0.
|
|
16
|
-
"@prisma-next/sql-relational-core": "0.
|
|
17
|
-
"@prisma-next/sql-runtime": "0.
|
|
18
|
-
"@prisma-next/sql-schema-ir": "0.
|
|
19
|
-
"@prisma-next/ts-render": "0.
|
|
20
|
-
"@prisma-next/utils": "0.
|
|
8
|
+
"@prisma-next/cli": "0.12.0",
|
|
9
|
+
"@prisma-next/contract": "0.12.0",
|
|
10
|
+
"@prisma-next/errors": "0.12.0",
|
|
11
|
+
"@prisma-next/family-sql": "0.12.0",
|
|
12
|
+
"@prisma-next/framework-components": "0.12.0",
|
|
13
|
+
"@prisma-next/migration-tools": "0.12.0",
|
|
14
|
+
"@prisma-next/sql-contract": "0.12.0",
|
|
15
|
+
"@prisma-next/sql-errors": "0.12.0",
|
|
16
|
+
"@prisma-next/sql-relational-core": "0.12.0",
|
|
17
|
+
"@prisma-next/sql-runtime": "0.12.0",
|
|
18
|
+
"@prisma-next/sql-schema-ir": "0.12.0",
|
|
19
|
+
"@prisma-next/ts-render": "0.12.0",
|
|
20
|
+
"@prisma-next/utils": "0.12.0",
|
|
21
21
|
"@standard-schema/spec": "1.1.0"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@prisma-next/driver-sqlite": "0.
|
|
25
|
-
"@prisma-next/test-utils": "0.
|
|
26
|
-
"@prisma-next/tsconfig": "0.
|
|
27
|
-
"@prisma-next/tsdown": "0.
|
|
24
|
+
"@prisma-next/driver-sqlite": "0.12.0",
|
|
25
|
+
"@prisma-next/test-utils": "0.12.0",
|
|
26
|
+
"@prisma-next/tsconfig": "0.12.0",
|
|
27
|
+
"@prisma-next/tsdown": "0.12.0",
|
|
28
28
|
"tsdown": "0.22.0",
|
|
29
29
|
"typescript": "5.9.3",
|
|
30
30
|
"vitest": "4.1.6"
|
|
31
31
|
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"typescript": ">=5.9"
|
|
34
|
+
},
|
|
35
|
+
"peerDependenciesMeta": {
|
|
36
|
+
"typescript": {
|
|
37
|
+
"optional": true
|
|
38
|
+
}
|
|
39
|
+
},
|
|
32
40
|
"files": [
|
|
33
41
|
"dist",
|
|
34
42
|
"src"
|
|
@@ -52,6 +60,9 @@
|
|
|
52
60
|
"./statement-builders": "./dist/statement-builders.mjs",
|
|
53
61
|
"./package.json": "./package.json"
|
|
54
62
|
},
|
|
63
|
+
"engines": {
|
|
64
|
+
"node": ">=24"
|
|
65
|
+
},
|
|
55
66
|
"repository": {
|
|
56
67
|
"type": "git",
|
|
57
68
|
"url": "https://github.com/prisma/prisma-next.git",
|
|
@@ -4,7 +4,6 @@ import type {
|
|
|
4
4
|
OpFactoryCall,
|
|
5
5
|
} from '@prisma-next/framework-components/control';
|
|
6
6
|
import type { MigrationMeta } from '@prisma-next/migration-tools/migration';
|
|
7
|
-
import { ifDefined } from '@prisma-next/utils/defined';
|
|
8
7
|
import type { SqlitePlanTargetDetails } from './planner-target-details';
|
|
9
8
|
import { renderOps } from './render-ops';
|
|
10
9
|
import { renderCallsToTypeScript } from './render-typescript';
|
|
@@ -64,7 +63,6 @@ export class TypeScriptRenderableSqliteMigration
|
|
|
64
63
|
return renderCallsToTypeScript(this.#calls, {
|
|
65
64
|
from: this.#meta.from,
|
|
66
65
|
to: this.#meta.to,
|
|
67
|
-
...ifDefined('labels', this.#meta.labels),
|
|
68
66
|
});
|
|
69
67
|
}
|
|
70
68
|
}
|
|
@@ -6,12 +6,11 @@
|
|
|
6
6
|
|
|
7
7
|
import type { OpFactoryCall } from '@prisma-next/framework-components/control';
|
|
8
8
|
import { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';
|
|
9
|
-
import { type ImportRequirement,
|
|
9
|
+
import { type ImportRequirement, renderImports } from '@prisma-next/ts-render';
|
|
10
10
|
|
|
11
11
|
export interface RenderMigrationMeta {
|
|
12
12
|
readonly from: string | null;
|
|
13
13
|
readonly to: string;
|
|
14
|
-
readonly labels?: readonly string[];
|
|
15
14
|
}
|
|
16
15
|
|
|
17
16
|
/**
|
|
@@ -73,9 +72,6 @@ function buildDescribeMethod(meta: RenderMigrationMeta): string {
|
|
|
73
72
|
lines.push(' return {');
|
|
74
73
|
lines.push(` from: ${JSON.stringify(meta.from)},`);
|
|
75
74
|
lines.push(` to: ${JSON.stringify(meta.to)},`);
|
|
76
|
-
if (meta.labels && meta.labels.length > 0) {
|
|
77
|
-
lines.push(` labels: ${jsonToTsSource(meta.labels)},`);
|
|
78
|
-
}
|
|
79
75
|
lines.push(' };');
|
|
80
76
|
lines.push(' }');
|
|
81
77
|
lines.push('');
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { ContractMarkerRecord } from '@prisma-next/contract/types';
|
|
2
2
|
import type {
|
|
3
3
|
MigrationOperationPolicy,
|
|
4
|
-
MultiSpaceRunnerResult,
|
|
5
4
|
SqlControlFamilyInstance,
|
|
6
5
|
SqlMigrationPlanContractInfo,
|
|
7
6
|
SqlMigrationPlanOperation,
|
|
@@ -15,7 +14,10 @@ import type {
|
|
|
15
14
|
import { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';
|
|
16
15
|
import { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';
|
|
17
16
|
import { type ContractMarkerRow, parseContractMarkerRow } from '@prisma-next/family-sql/verify';
|
|
18
|
-
import type {
|
|
17
|
+
import type {
|
|
18
|
+
ControlDriverInstance,
|
|
19
|
+
MigrationRunnerResult,
|
|
20
|
+
} from '@prisma-next/framework-components/control';
|
|
19
21
|
import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
|
|
20
22
|
import { ifDefined } from '@prisma-next/utils/defined';
|
|
21
23
|
import type { Result } from '@prisma-next/utils/result';
|
|
@@ -42,63 +44,11 @@ export function createSqliteMigrationRunner(
|
|
|
42
44
|
class SqliteMigrationRunner implements SqlMigrationRunner<SqlitePlanTargetDetails> {
|
|
43
45
|
constructor(private readonly family: SqlControlFamilyInstance) {}
|
|
44
46
|
|
|
45
|
-
async execute(
|
|
46
|
-
options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,
|
|
47
|
-
): Promise<SqlMigrationRunnerResult> {
|
|
48
|
-
const driver = options.driver;
|
|
49
|
-
|
|
50
|
-
const destinationCheck = this.ensurePlanMatchesDestinationContract(
|
|
51
|
-
options.plan.destination,
|
|
52
|
-
options.destinationContract,
|
|
53
|
-
);
|
|
54
|
-
if (!destinationCheck.ok) return destinationCheck;
|
|
55
|
-
|
|
56
|
-
const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
|
|
57
|
-
if (!policyCheck.ok) return policyCheck;
|
|
58
|
-
|
|
59
|
-
// SQLite recreate-table drops and rebuilds the table. If foreign_keys is ON,
|
|
60
|
-
// dropping a referenced parent cascade-deletes child rows; we must disable FK
|
|
61
|
-
// enforcement for the duration of the migration and validate integrity before
|
|
62
|
-
// committing. PRAGMA foreign_keys is a no-op inside a transaction, so toggle
|
|
63
|
-
// around BEGIN/COMMIT.
|
|
64
|
-
const fkWasEnabled = await this.readForeignKeysEnabled(driver);
|
|
65
|
-
if (fkWasEnabled) {
|
|
66
|
-
await driver.query('PRAGMA foreign_keys = OFF');
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
try {
|
|
70
|
-
await this.beginExclusiveTransaction(driver);
|
|
71
|
-
let committed = false;
|
|
72
|
-
try {
|
|
73
|
-
const result = await this.executeOnConnection(options);
|
|
74
|
-
if (!result.ok) return result;
|
|
75
|
-
|
|
76
|
-
if (fkWasEnabled) {
|
|
77
|
-
const fkIntegrityCheck = await this.verifyForeignKeyIntegrity(driver);
|
|
78
|
-
if (!fkIntegrityCheck.ok) return fkIntegrityCheck;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
await this.commitTransaction(driver);
|
|
82
|
-
committed = true;
|
|
83
|
-
return result;
|
|
84
|
-
} finally {
|
|
85
|
-
if (!committed) {
|
|
86
|
-
await this.rollbackTransaction(driver);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
} finally {
|
|
90
|
-
if (fkWasEnabled) {
|
|
91
|
-
await driver.query('PRAGMA foreign_keys = ON');
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
47
|
/**
|
|
97
48
|
* Apply the plan against an already-open connection without managing
|
|
98
|
-
* the transaction lifecycle. The caller
|
|
99
|
-
* and any connection-level setup (FK pragma
|
|
100
|
-
* check).
|
|
101
|
-
* across contract spaces inside one outer transaction.
|
|
49
|
+
* the transaction lifecycle. The caller ({@link SqliteMigrationRunner.execute})
|
|
50
|
+
* owns BEGIN/COMMIT/ROLLBACK and any connection-level setup (FK pragma
|
|
51
|
+
* toggle, FK integrity check).
|
|
102
52
|
*/
|
|
103
53
|
async executeOnConnection(
|
|
104
54
|
options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,
|
|
@@ -186,12 +136,12 @@ class SqliteMigrationRunner implements SqlMigrationRunner<SqlitePlanTargetDetail
|
|
|
186
136
|
});
|
|
187
137
|
}
|
|
188
138
|
|
|
189
|
-
async
|
|
139
|
+
async execute(options: {
|
|
190
140
|
readonly driver: ControlDriverInstance<'sql', string>;
|
|
191
141
|
readonly perSpaceOptions: ReadonlyArray<
|
|
192
142
|
SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>
|
|
193
143
|
>;
|
|
194
|
-
}): Promise<
|
|
144
|
+
}): Promise<MigrationRunnerResult> {
|
|
195
145
|
const driver = options.driver;
|
|
196
146
|
const perSpaceOptions = options.perSpaceOptions;
|
|
197
147
|
|
|
@@ -200,7 +150,8 @@ class SqliteMigrationRunner implements SqlMigrationRunner<SqlitePlanTargetDetail
|
|
|
200
150
|
}
|
|
201
151
|
|
|
202
152
|
// FK pragma toggle and the FK integrity check both span the outer
|
|
203
|
-
// transaction
|
|
153
|
+
// transaction: PRAGMA foreign_keys is a no-op inside a transaction, so the
|
|
154
|
+
// toggle has to wrap BEGIN/COMMIT.
|
|
204
155
|
const fkWasEnabled = await this.readForeignKeysEnabled(driver);
|
|
205
156
|
if (fkWasEnabled) {
|
|
206
157
|
await driver.query('PRAGMA foreign_keys = OFF');
|
|
@@ -80,7 +80,7 @@ export interface WriteMarkerInput {
|
|
|
80
80
|
* Logical space identifier for this marker row. Required at every
|
|
81
81
|
* call site so the type system surfaces every place that needs to
|
|
82
82
|
* thread the value (rather than letting an `?? APP_SPACE_ID`
|
|
83
|
-
* fall-through silently collapse
|
|
83
|
+
* fall-through silently collapse per-space markers onto the
|
|
84
84
|
* `'app'` row). App-plan callers pass {@link APP_SPACE_ID}
|
|
85
85
|
* (`'app'`); per-extension callers pass the extension's space id.
|
|
86
86
|
*/
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"planner-produced-sqlite-migration-BqzfeOFu.mjs","names":["#calls","#meta","#destination","#spaceId"],"sources":["../src/core/migrations/render-typescript.ts","../src/core/migrations/planner-produced-sqlite-migration.ts"],"sourcesContent":["/**\n * Polymorphic TypeScript emitter for the SQLite migration IR. Mirrors the\n * Postgres `render-typescript.ts` — different base-class + factory module\n * specifier, same overall shape.\n */\n\nimport type { OpFactoryCall } from '@prisma-next/framework-components/control';\nimport { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, jsonToTsSource, renderImports } from '@prisma-next/ts-render';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n readonly labels?: readonly string[];\n}\n\n/**\n * Always-present base imports for the rendered scaffold. Both come from\n * `@prisma-next/sqlite/migration` so an authored SQLite\n * `migration.ts` only needs a single dependency for its base class and\n * its CLI entrypoint. Mirrors Postgres's `BASE_IMPORTS`.\n *\n * - `Migration` — the facade re-export fixes the `SqlMigration`\n * generic to `SqlitePlanTargetDetails` and the abstract `targetId` to\n * `'sqlite'`.\n * - `MigrationCLI` — the migration-file CLI entrypoint, re-exported from\n * `@prisma-next/cli/migration-cli`. Loads `prisma-next.config.ts`,\n * assembles a `ControlStack`, and instantiates the migration class.\n */\nconst BASE_IMPORTS: readonly ImportRequirement[] = [\n { moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'Migration' },\n { moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'MigrationCLI' },\n];\n\nexport function renderCallsToTypeScript(\n calls: ReadonlyArray<OpFactoryCall>,\n meta: RenderMigrationMeta,\n): string {\n const imports = buildImports(calls);\n const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n\n return [\n shebangLineFor(detectScaffoldRuntime()),\n imports,\n '',\n 'export default class M extends Migration {',\n buildDescribeMethod(meta),\n ' override get operations() {',\n ' return [',\n indent(operationsBody, 6),\n ' ];',\n ' }',\n '}',\n '',\n 'MigrationCLI.run(import.meta.url, M);',\n '',\n ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<OpFactoryCall>): string {\n const requirements: ImportRequirement[] = [...BASE_IMPORTS];\n for (const call of calls) {\n for (const req of call.importRequirements()) {\n requirements.push(req);\n }\n }\n return renderImports(requirements);\n}\n\nfunction buildDescribeMethod(meta: RenderMigrationMeta): string {\n const lines: string[] = [];\n lines.push(' override describe() {');\n lines.push(' return {');\n lines.push(` from: ${JSON.stringify(meta.from)},`);\n lines.push(` to: ${JSON.stringify(meta.to)},`);\n if (meta.labels && meta.labels.length > 0) {\n lines.push(` labels: ${jsonToTsSource(meta.labels)},`);\n }\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction indent(text: string, spaces: number): string {\n const pad = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : line))\n .join('\\n');\n}\n","import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\nimport { SqliteMigration } from './sqlite-migration';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport interface SqliteMigrationDestinationInfo {\n readonly storageHash: string;\n readonly profileHash?: string;\n}\n\nexport class TypeScriptRenderableSqliteMigration\n extends SqliteMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #destination: SqliteMigrationDestinationInfo;\n readonly #spaceId: string;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n destination?: SqliteMigrationDestinationInfo,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#destination = destination ?? { storageHash: meta.to };\n }\n\n override get operations(): readonly Op[] {\n return renderOps(this.#calls);\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n override get destination(): SqliteMigrationDestinationInfo {\n return this.#destination;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from {@link SqlMigrationPlannerPlanOptions.spaceId} so the runner\n * keys the marker row by the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, {\n from: this.#meta.from,\n to: this.#meta.to,\n ...ifDefined('labels', this.#meta.labels),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAA6C,CACjD;CAAE,iBAAiB;CAAiC,QAAQ;CAAa,EACzE;CAAE,iBAAiB;CAAiC,QAAQ;CAAgB,CAC7E;AAED,SAAgB,wBACd,OACA,MACQ;CACR,MAAM,UAAU,aAAa,MAAM;CACnC,MAAM,iBAAiB,MAAM,KAAK,MAAM,EAAE,kBAAkB,CAAC,CAAC,KAAK,MAAM;CAEzE,OAAO;EACL,eAAe,uBAAuB,CAAC;EACvC;EACA;EACA;EACA,oBAAoB,KAAK;EACzB;EACA;EACA,OAAO,gBAAgB,EAAE;EACzB;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,SAAS,aAAa,OAA6C;CACjE,MAAM,eAAoC,CAAC,GAAG,aAAa;CAC3D,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,OAAO,KAAK,oBAAoB,EACzC,aAAa,KAAK,IAAI;CAG1B,OAAO,cAAc,aAAa;;AAGpC,SAAS,oBAAoB,MAAmC;CAC9D,MAAM,QAAkB,EAAE;CAC1B,MAAM,KAAK,0BAA0B;CACrC,MAAM,KAAK,eAAe;CAC1B,MAAM,KAAK,eAAe,KAAK,UAAU,KAAK,KAAK,CAAC,GAAG;CACvD,MAAM,KAAK,aAAa,KAAK,UAAU,KAAK,GAAG,CAAC,GAAG;CACnD,IAAI,KAA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