viborm 1.2.1 → 1.2.2
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/adapters.d.mts +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-XQSEkF90.d.mts → client-BKKA2CQj.d.mts} +1 -1
- package/dist/{client-CCgfcp5A.mjs → client-D291xo5z.mjs} +20 -20
- package/dist/client-D291xo5z.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/every-BJLkY4qm.mjs +2 -0
- package/dist/{every-4KE0p2Gw.mjs.map → every-BJLkY4qm.mjs.map} +1 -1
- package/dist/{index-Likdf5qP.d.mts → index-BaK35ze2.d.mts} +48 -25
- package/dist/index.d.mts +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{libsql-Bu_IdFU1.mjs → libsql-IdshHiw4.mjs} +3 -3
- package/dist/libsql-IdshHiw4.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/{memory-D4yxtCPK.mjs → memory-DSEeJ7ps.mjs} +2 -2
- package/dist/{memory-D4yxtCPK.mjs.map → memory-DSEeJ7ps.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-CibPaHSp.mjs → mysql-B7VGoX6t.mjs} +3 -3
- package/dist/mysql-B7VGoX6t.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/{object-store-CbjhsBQ3.d.mts → object-store-DCxwbkys.d.mts} +3 -3
- package/dist/pg.d.mts +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/{planner-CwFUkNHP.d.mts → planner-BKHHRpvB.d.mts} +1 -1
- package/dist/{postgres-oqNW9xqo.mjs → postgres-CeSmp2Tj.mjs} +4 -4
- package/dist/postgres-CeSmp2Tj.mjs.map +1 -0
- package/dist/postgres.d.mts +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/version-DxmSsAcv.mjs +2 -0
- package/dist/{version-B4VuToLC.mjs.map → version-DxmSsAcv.mjs.map} +1 -1
- package/package.json +2 -2
- package/dist/client-CCgfcp5A.mjs.map +0 -1
- package/dist/every-4KE0p2Gw.mjs +0 -2
- package/dist/libsql-Bu_IdFU1.mjs.map +0 -1
- package/dist/mysql-CibPaHSp.mjs.map +0 -1
- package/dist/postgres-oqNW9xqo.mjs.map +0 -1
- package/dist/version-B4VuToLC.mjs +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"libsql-IdshHiw4.mjs","names":[],"sources":["../src/migrations/drivers/sqlite/introspect.ts","../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts"],"sourcesContent":["import { isSqliteStateControlDefinition } from \"../../control\";\n/**\n * SQLite Schema Introspection\n *\n * Reads the current database schema from SQLite's PRAGMA statements\n * and sqlite_master, returning a normalized SchemaSnapshot.\n */\n\nimport { BATCH_REFS_TABLE } from \"@adapters/shared/batch-refs\";\nimport {\n sqliteDefinitionKeywords,\n sqliteTableDefinitions,\n} from \"../../../adapters/databases/sqlite/storage/column-constraints\";\nimport { readSqliteDecimalConstraint } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n readSqliteGeoPointColumn,\n SQLITE_GEO_POINT_TYPE,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport { skipSqlNonStructuralRegion } from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type {\n ColumnDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { mapReferentialAction } from \"../utils\";\nimport type {\n SqliteColumn,\n SqliteForeignKey,\n SqliteIndex,\n SqliteIndexColumn,\n SqliteInt,\n SqliteTable,\n} from \"./types\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction escapeIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * A pragma's integer column, as a number.\n *\n * SQLite reports integers, but the driver decides how they arrive: the LibSQL\n * driver runs with `intMode: \"bigint\"` (`src/drivers/libsql/index.ts`), so every\n * pragma integer reaches this file as BigInt. Read raw, each one is wrong in a\n * different way — `1n === 1` is false, so a unique index reads as non-unique\n * and a NOT NULL column reads as nullable; and `a.seqno - b.seqno` yields a\n * BigInt that `Array#sort` refuses outright, which crashes the introspection of\n * any index over two or more columns. Normalizing here, once, is what lets the\n * rest of this file compare plain numbers.\n */\nfunction int(value: SqliteInt): number {\n return Number(value);\n}\n\n/** The predicate half of a stored `CREATE INDEX … WHERE …`, if there is one. */\nconst TRAILING_WHERE = /^WHERE\\s+([\\s\\S]+)$/i;\n/** The defaults SQLite's column grammar takes without parentheses. */\n// Identifiers include NULL, TRUE, FALSE and CURRENT_*, and SQLite reads a\n// bare or double-quoted one in a default as a string literal.\nconst LITERAL_DEFAULT =\n /^(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|0x[\\da-f]+|'(?:[^']|'')*'|x'[\\da-f]*'|\"(?:[^\"]|\"\")*\"|[a-z_][\\w$]*)$/i;\n\n/**\n * A column's default as DDL. `PRAGMA table_info` reports `DEFAULT (expr)`\n * without its parentheses, and an expression is a legal default only inside\n * them: a table recreation that wrote `strftime(...)` back verbatim (an\n * `s.dateTime().now()` column) was a `CREATE TABLE` SQLite refused.\n */\nfunction columnDefault(value: string | null): string | undefined {\n if (value === null) return;\n return LITERAL_DEFAULT.test(value) ? value : `(${value})`;\n}\nconst AUTOINCREMENT = /\\bAUTOINCREMENT\\b/i;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * The CHECK the SQLite driver embeds in an enum column type.\n *\n * `PRAGMA table_info` reports only `TEXT`. The values live in\n * `sqlite_master.sql` as `CHECK(\"col\" IN ('a', 'b'))`, which is the same\n * spelling `getEnumColumnType` writes into the desired snapshot. Reconstruct\n * that suffix so fingerprint and differ see one type.\n */\nfunction sqliteEnumCheckSuffix(\n tableSql: string | null,\n columnName: string\n): string | undefined {\n if (!tableSql) return;\n const quoted = escapeIdentifier(columnName);\n const match = tableSql.match(\n new RegExp(\n `CHECK\\\\(\\\\s*${escapeRegExp(quoted)}\\\\s+IN\\\\s*\\\\((\\\\s*(?:'(?:[^']|'')*'\\\\s*,\\\\s*)*'(?:[^']|'')*'\\\\s*)\\\\)\\\\s*\\\\)`,\n \"i\"\n )\n );\n const list = match?.[1];\n if (!list) return;\n const values: string[] = [];\n const literals = /'((?:[^']|'')*)'/g;\n let literal = literals.exec(list);\n while (literal) {\n const value = literal[1];\n if (value !== undefined) values.push(value.replace(/''/g, \"'\"));\n literal = literals.exec(list);\n }\n if (values.length === 0) return;\n const escaped = values\n .map((value) => `'${value.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return ` CHECK(${quoted} IN (${escaped}))`;\n}\n\n/**\n * Reads the predicate of a partial index back out of the text SQLite stored.\n *\n * SQLite keeps `sqlite_master.sql` as the statement was written and re-spells\n * nothing (measured on 3.51: the predicate, its inner spacing and its padding\n * all come back byte-identical; only the statement terminator is dropped), so\n * the predicate the differ compares is the one the serializer emitted. This\n * reads it out and does not normalize it — `indexesEqual` is the one place the\n * two snapshot producers' spellings are reconciled.\n *\n * The predicate is whatever follows the column list, not whatever follows the\n * first `WHERE` in the text: a column may be named `a WHERE b`. So walk the\n * statement to the parenthesis that closes the column list, skipping quoted\n * identifiers and string literals, and read the tail from there.\n */\nfunction partialIndexPredicate(sql: string | null): string | undefined {\n if (!sql) return undefined;\n\n let depth = 0;\n let cursor = 0;\n let columnListEnd = -1;\n\n while (cursor < sql.length) {\n // Quoted tokens and comments are skipped through the ONE owner of where a\n // non-structural SQLite region ends, shared with the reserved decimal-\n // constraint reader: both read text SQLite stored verbatim, and both are\n // wrong the same way if its contents are read as syntax.\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n\n const char = sql[cursor];\n\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n if (depth === 0) {\n columnListEnd = cursor;\n break;\n }\n }\n cursor++;\n }\n\n if (columnListEnd === -1) return undefined;\n\n const match = TRAILING_WHERE.exec(sql.slice(columnListEnd + 1).trimStart());\n return match?.[1];\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n managedTables?: readonly string[],\n excludeD1SystemTables = false\n): Promise<SchemaSnapshot> {\n // Get all tables. `sql` rides along on the query that was already being made\n // — the reserved decimal constraints are read out of it, and a second live\n // read for them would be a raw-execution call site the architecture census\n // pins per file. The engine's batch reference scratch is not part of the\n // user's schema: it is TEMP where the transport admits temporary objects and\n // never appears here, but on D1 it is an ordinary table in `main`, and a\n // snapshot that carried it would have push and diff plan its drop.\n // D1 also exposes provider-owned `_cf_` tables but forbids their PRAGMAs.\n // Filter that exact reserved prefix only for D1; GLOB treats `_` literally,\n // and an ordinary SQLite application's similarly named tables stay visible.\n const tablesResult = await executeRaw<SqliteTable>(\n `\n SELECT name, sql\n FROM sqlite_master\n WHERE type = 'table'\n AND name NOT LIKE 'sqlite_%'\n AND name <> ?\n ${excludeD1SystemTables ? \"AND name NOT GLOB '_cf_*'\" : \"\"}\n ORDER BY name\n `,\n [BATCH_REFS_TABLE]\n );\n\n const tables: TableDef[] = [];\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.name;\n\n const selected =\n managedTables === undefined || managedTables.includes(tableName);\n const definitions = sqliteTableDefinitions(tableRow.sql ?? \"\");\n if (\n selected &&\n definitions.some((definition) =>\n sqliteDefinitionKeywords(definition.text).includes(\"AS\")\n )\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"generated columns\" } }\n );\n if (\n selected &&\n sqliteDefinitionKeywords((tableRow.sql ?? \"\").split(\"(\")[0]!).includes(\n \"VIRTUAL\"\n )\n )\n throw new MigrationError(\n `SQLite virtual table \"${tableName}\" cannot be faithfully reconstructed. Synchronization refuses before effects.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"virtual table\" } }\n );\n\n // Get columns using PRAGMA\n const columnsResult = await executeRaw<SqliteColumn>(\n `PRAGMA table_info(${escapeIdentifier(tableName)})`\n );\n const tableSql = tableRow.sql;\n const hasAutoincrement = AUTOINCREMENT.test(tableSql ?? \"\");\n\n // Get indexes\n const indexesResult = await executeRaw<SqliteIndex>(\n `PRAGMA index_list(${escapeIdentifier(tableName)})`\n );\n\n // The pragma reports that an index is partial but not what its predicate\n // is; only the stored statement carries that.\n const indexSqlResult = await executeRaw<{\n name: string;\n sql: string | null;\n }>(\n \"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?\",\n [tableName]\n );\n const indexSql = new Map(\n indexSqlResult.rows.map((row) => [row.name, row.sql])\n );\n\n // Get foreign keys\n const fksResult = await executeRaw<SqliteForeignKey>(\n `PRAGMA foreign_key_list(${escapeIdentifier(tableName)})`\n );\n\n // Build columns\n const columns: ColumnDef[] = [];\n const pkColumns: { name: string; position: number }[] = [];\n\n for (const col of columnsResult.rows) {\n const pk = int(col.pk);\n const type = col.type || \"TEXT\";\n const nullable = int(col.notnull) === 0 && pk === 0;\n const geoPointEncoding = readSqliteGeoPointColumn(\n tableSql,\n { name: col.name, type, nullable },\n escapeIdentifier\n );\n columns.push({\n name: col.name,\n geoPointEncoding,\n type: geoPointEncoding\n ? SQLITE_GEO_POINT_TYPE\n : `${type}${sqliteEnumCheckSuffix(tableSql, col.name) ?? \"\"}`,\n nullable,\n default: columnDefault(col.dflt_value),\n autoIncrement: pk === 1 && hasAutoincrement,\n // The declared domain, recovered from the reserved CHECK constraint\n // the driver wrote. Nothing else on this dialect carries it: the type\n // is `INTEGER` (or `TEXT`) at every precision and scale, and the\n // pragma reports no constraints at all — so a side that could not\n // recover it would read as a change on every push, forever.\n decimal: readSqliteDecimalConstraint(\n tableSql,\n // The descriptor proof consumes the exact declared type PRAGMA\n // reported. The generic snapshot fallback above may call an untyped\n // column TEXT, but that normalization cannot turn BLOB affinity into\n // the writer-owned TEXT decimal-list carrier.\n { name: col.name, type: col.type, nullable },\n escapeIdentifier\n ),\n });\n\n if (pk > 0) {\n pkColumns.push({ name: col.name, position: pk });\n }\n }\n\n if (selected) {\n const checks = definitions.reduce(\n (count, definition) =>\n count +\n sqliteDefinitionKeywords(definition.text).filter(\n (word) => word === \"CHECK\"\n ).length,\n 0\n );\n const represented = columns.reduce(\n (count, column) =>\n count +\n Number(column.decimal !== undefined) +\n Number(column.geoPointEncoding !== undefined) +\n Number(sqliteEnumCheckSuffix(tableSql, column.name) !== undefined),\n 0\n );\n if (\n checks !== represented &&\n !isSqliteStateControlDefinition(tableName, tableSql)\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"CHECK constraints\" } }\n );\n }\n\n // Build primary key (sort by pk position)\n let primaryKey: PrimaryKeyDef | undefined;\n if (pkColumns.length > 0) {\n pkColumns.sort((a, b) => a.position - b.position);\n primaryKey = {\n name: `${tableName}_pkey`,\n columns: pkColumns.map((p) => p.name),\n };\n }\n\n // Build indexes and unique constraints\n const indexes: IndexDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n for (const idx of indexesResult.rows) {\n // xinfo exposes the physical key semantics that index_info erases.\n // Auxiliary rowid columns are not key members; user expressions, DESC\n // and collations cannot be faithfully recreated by this declaration DSL.\n const indexColsResult = await executeRaw<SqliteIndexColumn>(\n `PRAGMA index_xinfo(${escapeIdentifier(idx.name)})`\n );\n const keys = indexColsResult.rows.filter(\n (column) => int(column.key) === 1\n );\n const unsupported =\n keys.length === 0 ||\n keys.some(\n (column) =>\n int(column.cid) < 0 ||\n column.name === null ||\n int(column.desc) !== 0 ||\n column.coll !== \"BINARY\"\n );\n if (unsupported) {\n if (managedTables === undefined || managedTables.includes(tableName)) {\n throw new MigrationError(\n `SQLite index \"${tableName}.${idx.name}\" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Manage its table outside this synchronization scope until a faithful declaration is available.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName: idx.name } }\n );\n }\n continue;\n }\n // PK membership is already represented by the table's primary key.\n if (idx.origin === \"pk\") continue;\n const indexColumns = keys\n .sort((a, b) => int(a.seqno) - int(b.seqno))\n .flatMap((column) => (column.name === null ? [] : [column.name]));\n\n const unique = int(idx.unique) === 1;\n if (unique && idx.origin === \"u\") {\n // This is a unique constraint\n uniqueConstraints.push({\n name: idx.name,\n columns: indexColumns,\n });\n } else {\n indexes.push({\n name: idx.name,\n columns: indexColumns,\n unique,\n where: partialIndexPredicate(indexSql.get(idx.name) ?? null),\n });\n }\n }\n\n // Build foreign keys - group by id (constraint)\n const fkMap = new Map<number, SqliteForeignKey[]>();\n for (const fk of fksResult.rows) {\n const id = int(fk.id);\n const existing = fkMap.get(id) || [];\n existing.push(fk);\n fkMap.set(id, existing);\n }\n\n const foreignKeys: ForeignKeyDef[] = [];\n for (const [id, fkCols] of fkMap) {\n const sorted = fkCols.sort((a, b) => int(a.seq) - int(b.seq));\n const first = sorted[0];\n if (first) {\n foreignKeys.push({\n name: `${tableName}_fk_${id}`,\n columns: sorted.map((f) => f.from),\n referencedTable: first.table,\n referencedColumns: sorted.map((f) => f.to),\n onDelete: mapReferentialAction(first.on_delete),\n onUpdate: mapReferentialAction(first.on_update),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // SQLite doesn't have native enum types\n return { tables, enums: [] };\n}\n","import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport { isDestructiveOperation } from \"../../differ\";\n/**\n * SQLite Migration Driver\n *\n * Implements the MigrationDriver interface for SQLite databases.\n * Uses table recreation for operations SQLite doesn't support natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { validateIsoTime } from \"@validation/primitives/iso\";\nimport {\n SQLITE_ABORT,\n sqliteDateTimeCopyExpression,\n sqliteDateTimeTargetRequiresRecreation,\n} from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport {\n sqliteDecimalCheck,\n sqliteDecimalCopyExpression,\n} from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCarrier,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionRequired,\n describeDecimalDomain,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport { foreignKeyPragmasCannotBeLifted } from \"../../foreign-keys\";\nimport { applyNativeRename } from \"../../native-rename\";\nimport type {\n ColumnDef,\n DiffOperation,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport { getSQLiteType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect } from \"./introspect\";\n\nconst COMPUTED_DEFAULT_PREFIX = /^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\\()/i;\n\nconst SQLITE_AUTOINDEX_PREFIX = \"sqlite_autoindex_\";\n\n/** The name a recreation builds its replacement under before the swap. */\nconst RECREATION_PREFIX = \"__new_\";\nconst CREATE_TABLE = /^CREATE\\s+TABLE\\s+/i;\nconst ALTER_TABLE = /^ALTER\\s+TABLE\\s+/i;\nconst RENAME_TO = /^\\s+RENAME\\s+TO\\s+/i;\nconst CREATE_DEPENDENT =\n /^CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?(TRIGGER|VIEW)\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?/i;\nconst DROP_DEPENDENT = /^DROP\\s+(?:TRIGGER|VIEW)\\s+(?:IF\\s+EXISTS\\s+)?/i;\nconst DROP_TABLE = /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?/i;\nconst IDENTIFIER_OPENERS = '\"`[';\nconst QUALIFIER_DOT = /^\\s*\\./;\n/**\n * The words SQLite never reads as a bare table name (checked on 3.53 against\n * every keyword, in FROM, INSERT, UPDATE, DELETE, JOIN and trigger `ON`). A\n * table spelled like one is quoted wherever SQL names it, so its bare spelling\n * is a keyword (`ORDER BY`), never a reference. Keywords SQLite also accepts\n * as names (`END`, `BY`, `VIEW`) stay references, the safe reading.\n */\nconst SQLITE_RESERVED_WORD =\n /^(?:add|all|alter|and|as|autoincrement|between|case|check|collate|commit|constraint|create|default|deferrable|delete|distinct|drop|else|escape|except|exists|foreign|from|group|having|in|index|insert|intersect|into|is|isnull|join|limit|not|nothing|notnull|null|on|or|order|primary|references|returning|select|set|table|then|to|transaction|union|unique|update|using|values|when|where)$/;\nconst COLUMN_CHECK = /\\s+CHECK\\s*\\(/;\nconst TEXT_AFFINITY = /CHAR|CLOB|TEXT/;\nconst REAL_AFFINITY = /REAL|FLOA|DOUB/;\n\n/**\n * A trigger or view as `sqlite_master` stores it; `table` is the lower-cased\n * `tbl_name`, a trigger's own table, unknown for one the program creates.\n */\ninterface SqliteDependent {\n readonly type: string;\n readonly name: string;\n readonly sql: string | null;\n readonly table?: string;\n}\n\n/**\n * The triggers and views a program's recreations would lose, each with the\n * live table it depends on.\n *\n * The program is walked in order from the catalog as it stands before it\n * runs, past leading comments and a `schema.` qualifier: a\n * `CREATE TRIGGER|VIEW` adds a dependent, a `DROP TRIGGER|VIEW` releases one,\n * a `DROP TABLE` releases the catalog's triggers on that table, which SQLite\n * drops with it, and each recreation — read from the one spelling\n * `compileTableRecreation` writes, `CREATE TABLE \"__new_<t>\"`, as the\n * foreign-key bracket is read from its pragmas — loses the dependents that\n * name the table at that point. A native `ALTER TABLE … RENAME TO` earlier in\n * the program maps the rebuilt name back to the live table, and both spellings\n * count, because the catalog was read before the rename rewrote it.\n */\nfunction lostDependents(\n program: readonly string[],\n catalog: readonly SqliteDependent[]\n): { readonly table: string; readonly dependent: SqliteDependent }[] {\n const dependents = new Map(\n catalog.map((row) => [row.name.toLowerCase(), row])\n );\n const formerNames = new Map<string, string>();\n const lost: { table: string; dependent: SqliteDependent }[] = [];\n for (const statement of program) {\n let text = statement.trim();\n // A leading comment does not hide the statement's head.\n let skipped = skipSqlNonStructuralRegion(text, 0);\n while (skipped > 0) {\n text = text.slice(skipped).trimStart();\n skipped = skipSqlNonStructuralRegion(text, 0);\n }\n const create = CREATE_TABLE.exec(text);\n const alter = ALTER_TABLE.exec(text);\n const created = CREATE_DEPENDENT.exec(text);\n const drop = DROP_DEPENDENT.exec(text);\n const dropTable = DROP_TABLE.exec(text);\n const head = create ?? alter ?? created ?? drop ?? dropTable;\n const name = head && readObjectName(text, head[0].length);\n if (!name) continue;\n const key = name.value.toLowerCase();\n if (created) {\n const type = created[1]!.toLowerCase();\n dependents.set(key, { type, name: name.value, sql: text });\n } else if (drop) {\n dependents.delete(key);\n } else if (dropTable) {\n const live = (formerNames.get(key) ?? name.value).toLowerCase();\n for (const [dependentKey, dependent] of dependents) {\n if (dependent.type === \"trigger\" && dependent.table === live) {\n dependents.delete(dependentKey);\n }\n }\n } else if (create && key.startsWith(RECREATION_PREFIX)) {\n const rebuilt = name.value.slice(RECREATION_PREFIX.length);\n const table = formerNames.get(rebuilt.toLowerCase()) ?? rebuilt;\n const spellings = [rebuilt.toLowerCase(), table.toLowerCase()];\n for (const [dependentKey, dependent] of dependents) {\n const sql = dependent.sql ?? \"\";\n if (!spellings.some((s) => sqlNamesTable(sql, dependent.name, s)))\n continue;\n lost.push({ table, dependent });\n dependents.delete(dependentKey);\n }\n } else if (alter && !key.startsWith(RECREATION_PREFIX)) {\n const rename = RENAME_TO.exec(text.slice(name.end));\n const to =\n rename && readSqliteIdentifier(text, name.end + rename[0].length);\n if (to)\n formerNames.set(\n to.value.toLowerCase(),\n formerNames.get(key) ?? name.value\n );\n }\n }\n return lost;\n}\n\n/** The object a statement head names, past an optional `schema.` qualifier. */\nfunction readObjectName(text: string, index: number) {\n const first = readSqliteIdentifier(text, index);\n const dot = first ? QUALIFIER_DOT.exec(text.slice(first.end)) : null;\n return first && dot\n ? readSqliteIdentifier(text, first.end + dot[0].length)\n : first;\n}\n\n/**\n * Whether a stored view or trigger names the lower-cased `table` as an\n * identifier, past its own name. String literals and comments are skipped, so\n * a trigger that writes the text 'item' does not name the table `item`, and\n * neither does a bare reserved word (`SQLITE_RESERVED_WORD`); a column spelled\n * like the table does, and refusing is the safe reading.\n */\nfunction sqlNamesTable(sql: string, ownName: string, table: string): boolean {\n let ownNamePending = true;\n let index = 0;\n while (index < sql.length) {\n const character = sql.charAt(index);\n const token =\n IDENTIFIER_OPENERS.includes(character) ||\n isSqliteBareIdentifierCharacter(character)\n ? readSqliteIdentifier(sql, index)\n : undefined;\n if (token) {\n const name = token.value.toLowerCase();\n if (ownNamePending && name === ownName.toLowerCase()) {\n ownNamePending = false;\n } else if (\n name === table &&\n (token.quoted || !SQLITE_RESERVED_WORD.test(name))\n ) {\n return true;\n }\n index = token.end;\n } else {\n index = Math.max(skipSqlNonStructuralRegion(sql, index), index + 1);\n }\n }\n return false;\n}\n\n/** SQLite's declared-type affinity rules; a column CHECK is not part of the type name. */\nfunction sqliteAffinity(type: string): string {\n const name = type.toUpperCase().split(COLUMN_CHECK)[0]!.trim();\n if (name.includes(\"INT\")) return \"INTEGER\";\n if (TEXT_AFFINITY.test(name)) return \"TEXT\";\n if (name === \"\" || name.includes(\"BLOB\")) return \"BLOB\";\n if (REAL_AFFINITY.test(name)) return \"REAL\";\n return \"NUMERIC\";\n}\n\n/**\n * The storage class a column type change converts copied values into, or\n * `undefined` when the copy keeps them as they are.\n *\n * Only a change of affinity into INTEGER, REAL or TEXT is guarded, because\n * SQLite converts into them silently and partially: an INTEGER column keeps\n * 'twelve' as TEXT and 1.5 as REAL, and a REAL one rounds an integer past\n * 2^53. A BLOB target stores values verbatim, and NUMERIC is the JSON\n * container's, whose CAST would read every JSON object as 0.\n */\nfunction sqliteConvertingAffinity(\n from: ColumnDef,\n to: ColumnDef\n): \"INTEGER\" | \"REAL\" | \"TEXT\" | undefined {\n const target = sqliteAffinity(to.type);\n if (target === sqliteAffinity(from.type)) return undefined;\n return target === \"INTEGER\" || target === \"REAL\" || target === \"TEXT\"\n ? target\n : undefined;\n}\n\n/**\n * One preceding operation of the batch, applied to the table definition a later\n * recreation will rebuild. `SQLite3MigrationDriver.getCurrentTable` explains\n * why the introspected definition alone is not enough, and what each list costs\n * when it is left behind.\n */\nfunction applyToTable(table: TableDef, op: DiffOperation): TableDef {\n if (!(\"tableName\" in op) || op.tableName !== table.name) {\n return table;\n }\n switch (op.type) {\n case \"addColumn\":\n return { ...table, columns: [...table.columns, op.column] };\n case \"dropColumn\":\n return {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== op.columnName\n ),\n };\n case \"alterColumn\":\n return {\n ...table,\n columns: table.columns.map((column) =>\n column.name === op.columnName ? op.to : column\n ),\n };\n case \"createIndex\":\n return { ...table, indexes: [...table.indexes, op.index] };\n case \"dropIndex\":\n return {\n ...table,\n indexes: table.indexes.filter((index) => index.name !== op.indexName),\n };\n case \"addForeignKey\":\n return { ...table, foreignKeys: [...table.foreignKeys, op.fk] };\n case \"dropForeignKey\":\n return {\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n };\n case \"addUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n };\n case \"dropUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n };\n case \"addPrimaryKey\":\n return { ...table, primaryKey: op.primaryKey };\n case \"dropPrimaryKey\":\n return { ...table, primaryKey: undefined };\n default:\n // `dropTable` is the only remaining operation that names this table, and\n // nothing rebuilds a table the same batch dropped.\n return table;\n }\n}\n\n/**\n * The schema-level table set after every preceding operation in the batch.\n *\n * Per-table replay cannot see a table created earlier in the same batch, and\n * retaining a dropped table invents relations the database no longer has.\n * This owner first evolves membership, then applies each operation's local and\n * inbound effects to every table that exists at that point.\n */\nfunction replaySchemaTables(\n tables: readonly TableDef[],\n operations: readonly DiffOperation[]\n): TableDef[] {\n let replayed = [...tables];\n for (const operation of operations) {\n if (operation.type === \"createTable\") {\n replayed = [...replayed, operation.table];\n continue;\n }\n if (operation.type === \"dropTable\") {\n replayed = replayed.filter((table) => table.name !== operation.tableName);\n continue;\n }\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n replayed = applyNativeRename({ tables: replayed }, operation).tables;\n continue;\n }\n replayed = replayed.map((table) => applyToTable(table, operation));\n }\n return replayed;\n}\n\n/** Whether a table carries an outbound FK or is the target of an inbound FK. */\nexport function sqliteTableBearsRelations(\n tableName: string,\n tables: readonly TableDef[],\n rebuiltTable?: TableDef,\n precedingOperations: readonly DiffOperation[] = []\n): boolean {\n if (rebuiltTable && rebuiltTable.foreignKeys.length > 0) return true;\n const replayed = replaySchemaTables(tables, precedingOperations);\n for (const table of replayed) {\n if (table.name === tableName && table.foreignKeys.length > 0) return true;\n if (\n table.foreignKeys.some(\n (foreignKey) => foreignKey.referencedTable === tableName\n )\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * SQLite3 Migration Driver\n *\n * Handles migrations for better-sqlite3 and similar synchronous SQLite drivers.\n * Uses table recreation for operations SQLite doesn't support natively:\n * - ALTER COLUMN (type, default, NOT NULL changes)\n * - ADD/DROP FOREIGN KEY\n * - ADD/DROP PRIMARY KEY\n *\n * LibSQL extends this class and overrides methods for operations it supports.\n */\nexport class SQLite3MigrationDriver extends MigrationDriver {\n readonly dialect = \"sqlite\" as const;\n readonly driverName: string = \"sqlite3\";\n\n override finalizeTable(table: TableDef): TableDef {\n const increments = table.columns.filter((column) => column.autoIncrement);\n if (\n increments.length > 0 &&\n (increments.length !== 1 ||\n table.primaryKey?.columns.length !== 1 ||\n table.primaryKey.columns[0] !== increments[0]!.name ||\n increments[0]!.type.toUpperCase() !== \"INTEGER\" ||\n increments[0]!.nullable)\n ) {\n throw new MigrationError(\n `SQLite table \"${table.name}\" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: table.name } }\n );\n }\n return table;\n }\n\n override getIrreversibleRollbackReason(\n operation: DiffOperation\n ): string | undefined {\n if (\n operation.type === \"alterColumn\" &&\n sqliteGeoPointEncoding(operation.from) === \"binary64\" &&\n sqliteGeoPointEncoding(operation.to) === \"legacy\"\n ) {\n return `Rollback cannot downgrade GeoPoint column \"${operation.tableName}.${operation.columnName}\" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`;\n }\n return super.getIrreversibleRollbackReason(operation);\n }\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true, // N/A but doesn't matter\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // No `ALTER TABLE ADD FOREIGN KEY`: FKs stay inline in CREATE TABLE and\n // rely on SQLite's lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // `PRAGMA foreign_key_list` has no name column, and an inline\n // `CONSTRAINT x UNIQUE (...)` is only ever reported as\n // `sqlite_autoindex_<table>_<n>`. Neither name survives a round trip.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Also refuses, by name, every trigger and view a table recreation in\n * `program` would lose. A recreation drops the table, and SQLite drops its\n * triggers with it silently; a view or another table's trigger that reads it\n * fails the swap with an error that names neither. A trigger always names\n * its own table (`ON \"t\"`), so one read of the stored SQL finds both kinds\n * (`lostDependents`). A trigger or view the program drops before the\n * recreation is its own business; one it creates earlier is checked too.\n */\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: Parameters<typeof introspect>[0],\n program: readonly string[]\n ): Promise<boolean> {\n const names = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (names.length === 0 && program.length === 0) return false;\n const objects = await executeRaw<SqliteDependent>(\n \"SELECT type, name, sql, lower(tbl_name) AS \\\"table\\\" FROM sqlite_master WHERE type IN ('view', 'trigger')\"\n );\n const collision = objects.rows.find(\n (row) => row.type === \"view\" && names.includes(row.name)\n );\n if (collision)\n throw new MigrationError(\n `SQLite relation \"${collision.name}\" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.name, feature: \"view\" } }\n );\n const lost = lostDependents(program, objects.rows);\n if (lost.length > 0)\n throw new MigrationError(\n `This migration rebuilds SQLite ${lost.map(({ table, dependent }) => `table \"${table}\", which ${dependent.type} \"${dependent.name}\" depends on`).join(\"; \")}. ` +\n \"A rebuild drops the table, which silently drops its triggers and breaks every view or trigger that reads it. \" +\n \"The migration is refused before any statement runs, so the schema and data are unchanged. Drop them before this change (a SQL step earlier in the same migration path counts) and recreate them after it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: lost[0]!.table,\n dependents: lost.map(\n ({ dependent }) => `${dependent.type}:${dependent.name}`\n ),\n feature: \"table recreation\",\n },\n }\n );\n return false;\n }\n\n introspect(\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<SchemaSnapshot> {\n const provider = this.executionDriver?.driverName;\n return introspect(executeRaw, this.target?.tables, provider === \"d1\");\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // See the PostgreSQL driver: one storage owner, override included.\n const idStorage =\n idDomain === undefined || scalarState.array === true\n ? undefined\n : idStorageOf(idDomain, declaration, \"sqlite\");\n if (idStorage) return idStorage.columnType;\n\n // SQLite has no native list type. A native declaration can describe one\n // scalar member only; every list keeps its container below.\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType && !scalarState.array) {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getSQLiteType({\n type: scalarState.type,\n array: scalarState.array,\n decimal: scalarState.decimal,\n });\n }\n\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n if (form === \"julianDay\") return \"(julianday('now'))\";\n if (form === \"epochMillis\")\n return \"(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))\";\n return \"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))\";\n }\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\") return \"(strftime('%Y-%m-%d','now'))\";\n if (scalarState.type === \"time\") return \"(strftime('%H:%M:%f','now'))\";\n }\n const defaultValue =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.array &&\n (scalarState.type === \"datetime\" || scalarState.type === \"time\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.array !== true &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n const physical = encodePhysicalDateTime(defaultValue, form);\n return typeof physical === \"string\"\n ? this.escapeValue(physical)\n : String(physical);\n }\n if (\n scalarState.type === \"time\" &&\n !scalarState.array &&\n !scalarState.autoGenerate &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const canonical = validateIsoTime(defaultValue);\n if (!(\"value\" in canonical))\n throw new MigrationError(\n \"Invalid Time literal default\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.escapeValue(canonical.value);\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n // Override formatBooleanDefault for SQLite's 1/0 representation\n\n /**\n * SQLite uses 1/0 for boolean values instead of true/false.\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n getEnumColumnType(\n _tableName: string,\n columnName: string,\n values: string[]\n ): string {\n // SQLite uses TEXT with CHECK constraint for enum validation\n const escapedValues = values\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return `TEXT CHECK(${this.escapeIdentifier(columnName)} IN (${escapedValues}))`;\n }\n\n // ===========================================================================\n // HELPER: Column Definition\n // ===========================================================================\n\n protected generateColumnDef(column: ColumnDef, _context: DDLContext): string {\n // SQLite auto-increment only works with INTEGER PRIMARY KEY\n // Validate that autoIncrement columns use INTEGER type\n if (column.autoIncrement && column.type.toUpperCase() !== \"INTEGER\") {\n throw new MigrationError(\n \"SQLite auto-increment requires INTEGER type. \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment. ` +\n \"Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n\n if (column.autoIncrement) {\n return `${this.escapeIdentifier(column.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;\n }\n\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK is a DERIVED render of the column's own\n // descriptor, emitted as a column CONSTRAINT beside the type — never\n // folded INTO `column.type`. `getEnumColumnType` above does fold its CHECK\n // into the type, and the measured cost is a full table recreation on every\n // push forever: `PRAGMA table_info.type` reports only the `type-name`\n // production, so the desired `TEXT CHECK(...)` never equals the\n // introspected `TEXT`. A named constraint reads back out of\n // `sqlite_master.sql` instead, which is where introspection recovers the\n // descriptor from.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // TABLE RECREATION\n // ===========================================================================\n\n /**\n * Generates SQL for table recreation.\n * This is the Drizzle-style pattern for operations SQLite doesn't support.\n *\n * Steps:\n * 1. PRAGMA foreign_keys=OFF\n * 2. Create new table with desired schema\n * 3. Copy data from old table (using explicit column mapping by name)\n * 4. Drop old table\n * 5. Rename new table\n * 6. Recreate indexes\n * 7. PRAGMA foreign_keys=ON\n *\n * @param tableName - The table to recreate\n * @param newTable - The new table definition\n * @param currentTable - The current table definition (required for safe column mapping)\n * @param columnRenames - Optional map of old column name to new column name\n */\n protected compileTableRecreation(\n tableName: string,\n newTable: TableDef,\n currentTable: TableDef,\n context: DDLContext,\n columnRenames?: Map<string, string>,\n valueExpressions?: ReadonlyMap<string, string>\n ): string[] {\n const statements: string[] = [];\n const tempName = `${RECREATION_PREFIX}${tableName}`;\n const currentColumns = new Map(\n currentTable.columns.map((column) => [column.name, column])\n );\n const sourceNames = new Map<string, string>();\n for (const [oldName, newName] of columnRenames ?? []) {\n sourceNames.set(newName, oldName);\n }\n const usesCorrelatedListCopy = newTable.columns.some((column) => {\n const sourceName = sourceNames.get(column.name) ?? column.name;\n return (\n this.decimalConversionKind(currentColumns.get(sourceName), column) ===\n \"list\"\n );\n });\n // A list conversion opens correlated `json_each` tables whose ten virtual\n // column names are ordinary legal user column names. Every outer read is\n // qualified through this one statement-local alias so `\"value\"`, `\"key\"`,\n // and their siblings cannot be captured by the inner table. Ordinary and\n // scalar-only recreations retain their original unaliased SQL.\n const sourceAlias = \"__viborm_source\";\n\n // 1. Disable foreign keys\n statements.push(\"PRAGMA foreign_keys=OFF\");\n\n // 2. Create new table\n statements.push(\n this.generateCreateTableDef({ ...newTable, name: tempName }, context)\n );\n\n // 3. Copy data - EXPLICIT column mapping by NAME, not position\n // Build a set of current column names for quick lookup\n // For each column in the new table, find the corresponding source column.\n // `source` is an EXPRESSION, not an identifier: a decimal column whose\n // declared domain moved is converted here, inside the database, on the way\n // across.\n const copyColumns: Array<{ source: string; target: string }> = [];\n\n for (const col of newTable.columns) {\n const sourceName = sourceNames.get(col.name) ?? col.name;\n\n // Only copy if source column exists in current table\n const currentColumn = currentColumns.get(sourceName);\n if (currentColumn !== undefined) {\n const source = usesCorrelatedListCopy\n ? `${this.escapeIdentifier(sourceAlias)}.${this.escapeIdentifier(sourceName)}`\n : this.escapeIdentifier(sourceName);\n copyColumns.push({\n source:\n valueExpressions?.get(col.name) ??\n this.copySourceExpression(\n tableName,\n sourceName,\n currentColumn,\n col,\n source\n ),\n target: col.name,\n });\n } else if (!col.nullable && col.default === undefined) {\n // New NOT NULL column without default - INSERT will fail\n throw new MigrationError(\n `Cannot add NOT NULL column \"${col.name}\" without a default value during table recreation. ` +\n \"SQLite requires a default value or nullable column for table recreation.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n // New columns with defaults or nullable will get their default/NULL values\n }\n\n if (copyColumns.length > 0) {\n const selectCols = copyColumns.map((c) => c.source).join(\", \");\n const insertCols = copyColumns\n .map((c) => this.escapeIdentifier(c.target))\n .join(\", \");\n\n statements.push(\n `INSERT INTO ${this.escapeIdentifier(tempName)} (${insertCols}) ` +\n `SELECT ${selectCols} FROM ${this.escapeIdentifier(tableName)}` +\n (usesCorrelatedListCopy\n ? ` AS ${this.escapeIdentifier(sourceAlias)}`\n : \"\")\n );\n }\n\n // 4. Drop old table\n statements.push(`DROP TABLE ${this.escapeIdentifier(tableName)}`);\n\n // 5. Rename new table\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tempName)} RENAME TO ${this.escapeIdentifier(tableName)}`\n );\n\n // 6. Recreate indexes (they were dropped with the old table)\n for (const idx of newTable.indexes) {\n statements.push(\n this.generateCreateIndex(\n { type: \"createIndex\", tableName, index: idx },\n context\n )\n );\n }\n\n // 7. Re-enable foreign keys\n statements.push(\"PRAGMA foreign_keys=ON\");\n\n return this.filterStatements(statements);\n }\n\n /**\n * What the recreation SELECTs for one column of the rebuilt table.\n *\n * Ordinarily the column itself. When the column's declared decimal domain\n * moved, it is the conversion expression instead: SQLite stores the unscaled\n * coefficient, so a scale change makes every stored integer mean a different\n * number until it is rescaled, and the whole conversion runs inside the\n * database because the rebuild is one `INSERT ... SELECT` this process never\n * reads a row of.\n *\n * A change that moves the STORAGE SHAPE — a scalar becoming a list, or the\n * other way — gets no conversion and no second guard: the value is copied as\n * it stands and the target column's own reserved CHECK refuses it, which\n * aborts the rebuild inside its transaction and leaves the old table exactly\n * as it was.\n *\n * A source column that declares NO domain is the third case, and it is a\n * conversion too. An `INTEGER` holding logical integers, adopted as\n * `decimal(p,s)`, has to become a coefficient: copied as it stands, `123`\n * would silently start reading as 1.23. Only that one adoption is converted.\n * A TEXT source or a list target has no proven logical scale, and SQLite can\n * coerce numeric text after the copy, so every other unmarked source refuses\n * here before the recreation exists.\n *\n * A decimal column leaving its domain is descaled the same way, by\n * `descaledDecimalSource`.\n *\n * A column with no decimal or DateTime target whose type changes affinity\n * (`sqliteConvertingAffinity`) is converted with a `CAST` that must compare\n * equal to the source under SQLite's own rules. A value that does not —\n * 'twelve' or 1.5 into INTEGER, a BLOB into TEXT — aborts the rebuild like\n * an inexact DateTime instead of being stored unconverted.\n */\n private copySourceExpression(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef,\n source: string\n ): string {\n if (\n targetColumn.geoPointEncoding === \"binary64\" &&\n currentColumn !== undefined &&\n sqliteGeoPointEncoding(currentColumn) === \"legacy\"\n ) {\n return `CASE WHEN ${source} IS NULL THEN NULL ELSE ${sqliteGeoPointCarrier(source)} END`;\n }\n const dateTime = targetColumn.dateTime;\n if (dateTime !== undefined) {\n const sourceForm = this.sqliteDateTimeSourceForm(currentColumn);\n if (sourceForm === undefined) {\n const sourceDomain =\n currentColumn?.decimal === undefined\n ? `${currentColumn?.type ?? \"unknown\"} storage`\n : `a fixed-decimal domain at ${describeDecimalDomain(currentColumn.decimal)}`;\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt ${sourceDomain} as a SQLite DateTime. ` +\n \"Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"SQLite DateTime storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDateTimeCopyExpression(\n source,\n sourceForm,\n dateTime,\n currentColumn?.dateTime !== undefined\n );\n }\n\n const to = targetColumn.decimal;\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n const from = currentColumn?.decimal;\n if (to === undefined && currentColumn !== undefined && from !== undefined) {\n return this.descaledDecimalSource(\n tableName,\n sourceName,\n { ...currentColumn, decimal: from },\n targetColumn.type,\n source\n );\n }\n if (to === undefined || targetKind === undefined) {\n const affinity =\n currentColumn && sqliteConvertingAffinity(currentColumn, targetColumn);\n return affinity === undefined\n ? source\n : `CASE WHEN ${source} IS NULL THEN NULL WHEN CAST(${source} AS ${affinity}) = ${source} THEN CAST(${source} AS ${affinity}) ELSE ${SQLITE_ABORT} END`;\n }\n\n if (from === undefined) {\n const adopting =\n targetKind === \"scalar\" &&\n currentColumn?.type.toUpperCase() === \"INTEGER\";\n if (!adopting) {\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt unmarked ${currentColumn?.type ?? \"unknown\"} storage as a fixed-decimal ${targetKind}. ` +\n \"Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage adoption\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDecimalCopyExpression(source, undefined, to, \"scalar\");\n }\n if (sameDecimalDescriptor(from, to)) return source;\n const conversionKind = this.decimalConversionKind(\n currentColumn,\n targetColumn\n );\n if (conversionKind === undefined) return source;\n return sqliteDecimalCopyExpression(source, from, to, conversionKind);\n }\n\n /**\n * A fixed-decimal source copied into a column that declares no domain.\n *\n * SQLite stores the scaled coefficient, so the value is descaled on the way\n * across: 1.23 at scale 2 is stored as 123 and must not read back as 123.\n * Only an INTEGER target holds the result exactly, and a value with a\n * fraction — or a stored value that is no coefficient at all — aborts the\n * rebuild through `SQLITE_ABORT`. The decimal copy helper guards the same\n * way, but its sentinel relies on a reserved CHECK this target does not\n * carry.\n * Every other target (TEXT, REAL, a list) has no one exact spelling of the\n * value and is refused here, before the recreation exists.\n */\n private descaledDecimalSource(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef & { decimal: NonNullable<ColumnDef[\"decimal\"]> },\n targetType: string,\n source: string\n ): string {\n const kind = sqliteDecimalStorageKind(currentColumn);\n if (kind === \"scalar\" && sqliteAffinity(targetType) === \"INTEGER\") {\n const factor = 10n ** BigInt(currentColumn.decimal.scale);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' AND ${source} % ${factor} = 0 THEN ${source} / ${factor} ELSE ${SQLITE_ABORT} END`;\n }\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would copy a fixed-decimal ${kind ?? \"column\"} at ${describeDecimalDomain(currentColumn.decimal)} into ${targetType} storage that declares no decimal domain. ` +\n \"SQLite stores the decimal as its scaled integer coefficient, and only a scalar copied into INTEGER storage can be descaled exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n\n /** Physical source vocabulary for a target known to be a DateTime. */\n private sqliteDateTimeSourceForm(\n column: ColumnDef | undefined\n ): \"text\" | \"epochMillis\" | \"julianDay\" | undefined {\n if (column?.dateTime !== undefined) return column.dateTime;\n if (column?.decimal !== undefined) return undefined;\n switch (column?.type.toUpperCase()) {\n case \"TEXT\":\n return \"text\";\n case \"INTEGER\":\n return \"epochMillis\";\n case \"REAL\":\n return \"julianDay\";\n default:\n return undefined;\n }\n }\n\n /** The shared-storage decimal conversion one copied column requires. */\n private decimalConversionKind(\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef\n ): \"scalar\" | \"list\" | undefined {\n const from = currentColumn?.decimal;\n const to = targetColumn.decimal;\n if (\n currentColumn === undefined ||\n from === undefined ||\n to === undefined ||\n sameDecimalDescriptor(from, to)\n ) {\n return undefined;\n }\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n if (\n targetKind === undefined ||\n sqliteDecimalStorageKind(currentColumn) !== targetKind\n ) {\n return undefined;\n }\n return targetKind;\n }\n\n /**\n * Refuses a domain conversion the substrate cannot rebuild safely, BEFORE\n * any statement runs.\n *\n * Every SQLite descriptor change is a table recreation, and a recreation\n * drops and rebuilds the table with foreign-key enforcement disabled. That\n * disable is only real when `PRAGMA foreign_keys=OFF` runs OUTSIDE the\n * transaction — SQLite documents it as a no-op inside one — and the lift is\n * proven only inside a transaction that can roll it back\n * (`foreignKeyPragmasCannotBeLifted`). A driver without one cannot prove it:\n * on D1 the pragma travels inside one native batch and does nothing, so\n * `DROP TABLE` either raises the constraint or silently fires the\n * referential action on every child row.\n *\n * D1 is the shipped case, and plan §7.4 states the prerequisite exactly: a\n * relation-bearing rebuild is admitted only after the foreign-key-safe\n * rebuild is proven across the ten relation shapes. Until then this refuses\n * with the substrate reason rather than shipping an unsafe drop/recreate or\n * a manual shadow-column instruction.\n *\n * Only relation-bearing tables are refused: a table with no reference in\n * either direction has nothing the disabled enforcement could damage, so\n * fresh decimal schemas and ordinary descriptor changes stay available.\n *\n * The question remains conversion-owned: decimal descriptor changes and\n * adoption, decimal carrier renames, and DateTime form/adoption transitions\n * ask this owner. A recreation requested by another column, constraint, key,\n * or enum does not become a domain conversion merely because the same table\n * also contains one of these scalars. General D1 reconstruction safety is an\n * existing migration concern outside this boundary.\n */\n private assertDomainReconstructionAdmitted(\n tableName: string,\n column: ColumnDef,\n table: TableDef,\n context: DDLContext,\n domain: \"decimal\" | \"dateTime\"\n ): void {\n let description: string;\n let feature: string;\n if (domain === \"decimal\") {\n if (column.decimal === undefined) return;\n description = `a fixed-decimal column at ${describeDecimalDomain(column.decimal)}`;\n feature = \"decimal descriptor conversion\";\n } else {\n if (column.dateTime === undefined) return;\n description = `a SQLite DateTime column in ${column.dateTime} storage`;\n feature = \"SQLite DateTime storage conversion\";\n }\n const driver = this.executionDriver;\n if (!(driver && foreignKeyPragmasCannotBeLifted(driver))) return;\n if (\n !sqliteTableBearsRelations(\n tableName,\n context.currentSchema?.tables ?? [],\n table,\n context.precedingOperations\n )\n ) {\n return;\n }\n throw new MigrationError(\n `Rebuilding \"${tableName}\".\"${column.name}\", ${description}, recreates the whole table, and the driver \"${driver.driverName}\" runs migrations without a transaction (D1 runs them as one native batch). ` +\n \"Without a transaction, `PRAGMA foreign_keys=OFF` cannot be proven before the rebuild drops a table that still has references, nor the drop rolled back — and a pragma that did not take raises on one referential action and silently deletes or nulls child rows on another. \" +\n \"The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver with transactions.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n driver: driver.driverName,\n table: tableName,\n column: column.name,\n feature,\n },\n }\n );\n }\n\n /**\n * Helper to generate CREATE TABLE DDL without indexes\n */\n protected generateCreateTableDef(\n table: TableDef,\n context: DDLContext\n ): string {\n const parts: string[] = [];\n\n // Columns\n for (const col of table.columns) {\n parts.push(this.generateColumnDef(col, context));\n }\n\n // Primary key (if composite or not INTEGER autoincrement)\n if (table.primaryKey) {\n const isSingleIntegerPK =\n table.primaryKey.columns.length === 1 &&\n table.columns.find(\n (c) =>\n c.name === table.primaryKey!.columns[0] &&\n c.type.toUpperCase() === \"INTEGER\" &&\n c.autoIncrement\n );\n\n if (!isSingleIntegerPK) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n parts.push(`PRIMARY KEY (${pkCols})`);\n }\n }\n\n // Unique constraints. One read back from the live table has SQLite's own\n // `sqlite_autoindex_<table>_<n>` for a name, which a recreation must not\n // carry into the new table: it is written unnamed, as SQLite reports it.\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n parts.push(\n uq.name.startsWith(SQLITE_AUTOINDEX_PREFIX)\n ? `UNIQUE (${uqCols})`\n : `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys\n for (const fk of table.foreignKeys) {\n const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n\n parts.push(fkDef);\n }\n\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)`;\n }\n\n /**\n * The table definition a recreation has to rebuild — the introspected one,\n * moved on by every preceding operation of the same batch.\n *\n * `currentSchema` is read once, before the first statement runs, so on its own\n * it describes the table as it was. A recreation drops the table and rebuilds\n * whatever this definition names, so read raw it destroys everything the same\n * batch created earlier and resurrects everything the same batch dropped. Each\n * list is a measured hazard, not a hypothetical:\n *\n * - INDEXES. `createIndex` runs at priority 15 and `addForeignKey` at 16, and\n * SQLite recreates the table for every foreign-key change — so on a database\n * that predates the FK index each foreign-key push created the index and\n * then threw it away, forever.\n *\n * - FOREIGN KEYS. `dropForeignKey` runs at 2 and `addForeignKey` at 16, and\n * the differ plans that pair for every changed key. With the pre-batch list\n * the add rebuilt the table around the constraint the drop had just removed\n * AND its replacement: measured on better-sqlite3, `zz_posts` held 1, then\n * 2, then 3 identical foreign keys after three idempotent pushes.\n *\n * - COLUMNS. `addColumn` runs at 10 and `alterColumn` at 12, and `alterColumn`\n * is a recreation on SQLite. Measured: pushing a model that both widens one\n * column's type and adds another emitted the `ALTER TABLE ... ADD COLUMN`,\n * then rebuilt the table from the pre-batch column list — and the new column\n * was gone. The push reported success, and the next one added and lost it\n * again. Two `alterColumn`s in one batch reverted each other the same way.\n *\n * - UNIQUE CONSTRAINTS. `dropUniqueConstraint` runs at 4 and\n * `addUniqueConstraint` at 14, and both ARE recreations here — the\n * constraint is inline in `CREATE TABLE` (see\n * `generateAddUniqueConstraint`). So the pair a changed constraint plans\n * reads its own predecessor, and a later recreation at 16 has to rebuild\n * around the constraint the add put there rather than the one the drop\n * removed.\n *\n * - PRIMARY KEY. `dropPrimaryKey` runs at 5 and `addPrimaryKey` at 13, both\n * ahead of `addForeignKey`, so a later recreation would rebuild around the\n * key that was just replaced.\n *\n * - INBOUND FOREIGN KEYS. Native SQLite table and column renames rewrite\n * references stored in OTHER tables. If one of those tables is recreated\n * later in the batch, its pre-batch definition would restore the old table\n * or column name unless the same replay carries the rename's remote effect.\n *\n * These are all the operations that move any of those five out of `TableDef`,\n * plus the two native renames whose effects cross table boundaries. Replaying\n * them gives what the database actually holds when the recreation runs.\n */\n protected getCurrentTable(\n tableName: string,\n context: DDLContext\n ): TableDef | undefined {\n return replaySchemaTables(\n context.currentSchema?.tables ?? [],\n context.precedingOperations ?? []\n ).find((table) => table.name === tableName);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const statements: string[] = [this.generateCreateTableDef(table, context)];\n\n // Create indexes separately\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.escapeIdentifier(op.tableName)}`;\n }\n\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n if (\n op.column.default !== undefined &&\n COMPUTED_DEFAULT_PREFIX.test(op.column.default)\n ) {\n const current = this.getCurrentTable(op.tableName, context);\n if (!current)\n throw new MigrationError(\n `Cannot add computed default: table \"${op.tableName}\" is absent`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.compileTableRecreation(\n op.tableName,\n { ...current, columns: [...current.columns, op.column] },\n current,\n context\n );\n }\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n // SQLite 3.35.0+ supports DROP COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n /**\n * Renames a column — natively first, then through a table recreation when\n * that column is a decimal.\n *\n * The descriptor rides in a CHECK constraint whose NAME contains the column\n * name, and `ALTER TABLE … RENAME COLUMN` rewrites column REFERENCES inside a\n * CHECK body but never a constraint NAME. So the native rename leaves the\n * carrier behind, pointing at a column that no longer exists: introspection\n * reads the renamed column as carrying no domain, the next push plans an\n * alteration between a domain and nothing, and the stored coefficient is\n * copied unchanged under whatever scale the schema now declares — 12345\n * meaning 123.45 silently becomes 1.2345. It is not even destructive by the\n * differ's reading, because no domain narrowed, so no prompt fires.\n *\n * The native statement has a second job a recreation cannot perform: SQLite\n * rewrites inbound foreign keys stored in OTHER tables. Only after that\n * schema-wide propagation does the ordinary recreation replace the stale\n * carrier name on the already-renamed table. The reconstruction therefore\n * copies the new column name from a current definition that already contains\n * the rename; it is not a second rename mechanism.\n */\n generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n const renamed = currentTable?.columns.find(\n (column) => column.name === op.from\n );\n // SQLite 3.25.0+ supports RENAME COLUMN\n const nativeRename = `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n if (currentTable === undefined || renamed?.decimal === undefined) {\n return nativeRename;\n }\n\n const renamedTable = applyNativeRename({ tables: [currentTable] }, op)\n .tables[0];\n if (renamedTable === undefined) {\n throw new MigrationError(\n `Cannot rename column: table \"${op.tableName}\" disappeared from the current schema.`,\n VibORMErrorCode.INTERNAL_ERROR,\n { meta: { table: op.tableName, column: op.from } }\n );\n }\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n renamed,\n renamedTable,\n context,\n \"decimal\"\n );\n return [\n nativeRename,\n ...this.compileTableRecreation(\n op.tableName,\n renamedTable,\n renamedTable,\n context\n ),\n ];\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.compileAlterColumnByRecreation(op, context, true);\n }\n\n /**\n * SQLite's value-preserving ALTER COLUMN implementation. `grouped` folds a\n * run of compatible changes to one table into one recreation; a dialect\n * that recreates only some changes (LibSQL) recreates each on its own.\n */\n protected compileAlterColumnByRecreation(\n op: AlterColumnOperation,\n context: DDLContext,\n grouped: boolean\n ): readonly string[] {\n const group = [op];\n if (grouped && context.followingOperations) {\n const compatible = (\n candidate: DiffOperation | undefined\n ): candidate is AlterColumnOperation =>\n candidate?.type === \"alterColumn\" &&\n candidate.tableName === op.tableName &&\n isDestructiveOperation(candidate) === isDestructiveOperation(op);\n const previous: AlterColumnOperation[] = [];\n for (const candidate of [\n ...(context.precedingOperations ?? []),\n ].reverse()) {\n if (!compatible(candidate)) break;\n previous.unshift(candidate);\n }\n const following: AlterColumnOperation[] = [];\n for (const candidate of context.followingOperations) {\n if (!compatible(candidate)) break;\n following.push(candidate);\n }\n const run = [...previous, op, ...following];\n // Repeated changes to the same column are sequential semantics, not one projection.\n if (new Set(run.map((change) => change.columnName)).size === run.length) {\n if (previous.length > 0) return [];\n group.push(...following);\n }\n }\n // SQLite doesn't support ALTER COLUMN - need table recreation\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot alter column: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const targets = new Map(\n group.map((change) => [change.columnName, change.to])\n );\n const newColumns = currentTable.columns.map(\n (column) => targets.get(column.name) ?? column\n );\n\n const newTable: TableDef = {\n ...currentTable,\n columns: newColumns,\n };\n\n for (const change of group) {\n if (decimalConversionRequired(change.from, change.to)) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"decimal\"\n );\n } else if (\n sqliteDateTimeTargetRequiresRecreation(\n change.from.dateTime,\n change.to.dateTime\n )\n ) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"dateTime\"\n );\n }\n }\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation, _context: DDLContext): string {\n const { tableName, index } = op;\n\n // Validate index type against capabilities (SQLite only supports btree)\n this.validateIndexType(index.type, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n // SQLite has supported partial indexes since 3.8.0. Dropping the predicate\n // silently would build a different index from the declared one, and the\n // differ would re-create it on every push forever, because introspection\n // reads the predicate back.\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // SQLite doesn't support USING clause - it only has btree indexes\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} (${cols})${where}`;\n }\n\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add foreign key\",\n (table) => ({\n ...table,\n foreignKeys: [...table.foreignKeys, op.fk],\n })\n );\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop foreign key\",\n (table) => ({\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n })\n );\n }\n\n /**\n * Recreates `tableName` as `change` derives it from the table the batch has\n * left, which is how SQLite changes an inline foreign key, unique or primary\n * key.\n */\n protected recreateWith(\n tableName: string,\n context: DDLContext,\n action: string,\n change: (table: TableDef) => TableDef\n ): string[] {\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot ${action}: table \"${tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n return this.compileTableRecreation(\n tableName,\n change(currentTable),\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n /**\n * A unique constraint is INLINE in `CREATE TABLE` on SQLite, so both halves\n * of the diff go through a table recreation. There is no other spelling that\n * round-trips.\n *\n * SQLite has two ways to spell \"these columns are unique\" and only one of\n * them survives introspection as a constraint. An inline\n * `CONSTRAINT x UNIQUE (...)` is reported by `PRAGMA index_list` with\n * `origin = \"u\"`, which `introspect` files under `uniqueConstraints` —\n * matched by shape against the declared one (see\n * `introspectionReadsConstraintNames`), so an unchanged schema plans nothing.\n * A standalone `CREATE UNIQUE INDEX` is reported with `origin = \"c\"` and\n * filed under `indexes` instead, where no declared unique constraint will\n * ever match it.\n *\n * Measured on better-sqlite3 at `f78fa83`, with the add as a standalone\n * index: push #2 of a model that gained `.unique([\"slug\", \"tenant\"])`\n * planned `addUniqueConstraint` and created the index; push #3 read that\n * index back under the wrong bucket and planned `addUniqueConstraint` again\n * beside `dropIndex` on the same name — and since `addUniqueConstraint` (14)\n * runs ahead of a superseded index drop (15.5), the push died on\n * `index \"…_slug_tenant_key\" already exists`. Every later push died the same\n * way. Before the shape matching landed the FK churn rebuilt the table on\n * every push and destroyed the index before push #3 could collide with it,\n * so the same schema pushed green forever and the unique was never enforced.\n *\n * The drop had no working spelling at all: every `dropUniqueConstraint` the\n * differ plans here names a constraint read out of `PRAGMA index_list` with\n * `origin = \"u\"`, i.e. `sqlite_autoindex_<table>_<n>`, and SQLite refuses\n * `DROP INDEX` on an index it created itself.\n *\n * A database written by the old add still holds the standalone index. It\n * heals on the next push: the recreation rebuilds the table with the\n * constraint inline, and the stale index — dropped with the old table and\n * re-created by step 6 of the recreation, because it is still in the\n * introspected definition — is removed by the `dropIndex` the same batch\n * plans for it.\n */\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add unique constraint\",\n (table) => ({\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n })\n );\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop unique constraint\",\n (table) => ({\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n })\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add primary key\",\n (table) => ({\n ...table,\n primaryKey: op.primaryKey,\n })\n );\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop primary key\",\n (table) => ({\n ...table,\n primaryKey: undefined,\n })\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context: DDLContext): string {\n // SQLite enums use CHECK constraints embedded in column definitions\n // No separate enum type creation needed\n return \"-- SQLite: enum CHECK constraint is part of column definition\";\n }\n\n generateDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): string | readonly string[] {\n // Dropping an enum means removing CHECK constraints from dependent columns\n // This requires table recreation for each dependent table\n const { enumName, dependentColumns } = op;\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns for enum \"${enumName}\"`;\n }\n\n const statements: string[] = [];\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n throw new MigrationError(\n `Table \"${dep.tableName}\" not found for enum \"${enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n // Change the column type to plain TEXT (remove CHECK constraint)\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName && col.type.includes(\"CHECK\")) {\n return { ...col, type: \"TEXT\" };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context\n )\n );\n }\n\n return statements;\n }\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): string | readonly string[] {\n // Altering an enum means updating CHECK constraints on dependent columns\n // This requires table recreation for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n const statements: string[] = [];\n\n if (!newValues || newValues.length === 0) {\n return `-- SQLite: no new values provided for enum \"${enumName}\"`;\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns found for enum \"${enumName}\"`;\n }\n\n // Apply mappings in the reconstruction SELECT. A replacement belongs to\n // the destination CHECK, including a value introduced in this change.\n\n // Generate new CHECK constraint\n const escapedValues = newValues\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n statements.push(`-- SQLite: table \"${dep.tableName}\" not found`);\n continue;\n }\n\n // Build new CHECK constraint for this column\n const newCheckType = `TEXT CHECK(${this.escapeIdentifier(dep.columnName)} IN (${escapedValues}))`;\n\n // Update the column type with new CHECK\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName) {\n return { ...col, type: newCheckType };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n const source = this.escapeIdentifier(dep.columnName);\n const cases = this.enumReplacementCases(\n op,\n dep.tableName,\n dep.columnName\n );\n const expressions =\n cases.length === 0\n ? undefined\n : new Map([\n [\n dep.columnName,\n `CASE ${source} ${cases.join(\" \")} ELSE ${source} END`,\n ],\n ]);\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context,\n undefined,\n expressions\n )\n );\n }\n\n return statements;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n // Return null to signal that locking is handled differently\n return null;\n }\n\n generateReleaseLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n return null;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n params: [],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n // SQLite doesn't support enums\n return null;\n }\n}\n\n// Export singleton instance\nexport const sqlite3MigrationDriver = new SQLite3MigrationDriver();\n","/**\n * LibSQL Migration Driver\n *\n * Extends SQLite3 driver with native ALTER COLUMN support.\n * LibSQL supports ALTER TABLE ALTER COLUMN syntax that SQLite doesn't,\n * avoiding expensive table recreation for column modifications.\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This differs from PostgreSQL's behavior where constraints\n * are validated against all existing rows.\n */\n\nimport { sqliteDateTimeTargetRequiresRecreation } from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport { sqliteDecimalCheck } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n decimalConversionRequired,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport type { ColumnDef, ReferentialAction } from \"../../types\";\nimport type {\n AddForeignKeyOperation,\n AlterColumnOperation,\n DDLContext,\n DropForeignKeyOperation,\n} from \"../base\";\nimport { SQLite3MigrationDriver } from \"../sqlite\";\nimport type { MigrationCapabilities } from \"../types\";\n\nexport class LibSQLMigrationDriver extends SQLite3MigrationDriver {\n override readonly driverName: string = \"libsql\";\n\n // Same capabilities as SQLite3 (no native enums, no arrays, btree only)\n override readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // Adds FKs by rewriting the column (`ALTER COLUMN ... TO`), which needs the\n // existing column def — not a standalone add. Keep FKs inline in CREATE\n // TABLE and rely on lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // Inherits SQLite's introspection verbatim, so the same two names are\n // unreadable here.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: ALTER COLUMN (native support)\n // ===========================================================================\n\n /**\n * LibSQL supports ALTER TABLE ... ALTER COLUMN ... TO syntax.\n * This avoids table recreation for column type/default/nullable changes.\n *\n * Syntax: ALTER TABLE t ALTER COLUMN c TO c <new_column_def>\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This is different from PostgreSQL's behavior.\n */\n override generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n // A decimal descriptor change CONVERTS stored values — SQLite holds the\n // unscaled coefficient, so the same integer means a different number at a\n // different scale. The native ALTER rewrites the column DECLARATION and\n // copies nothing, and by LibSQL's own contract (above) it validates only\n // rows written afterwards, so every existing row would keep its old\n // coefficient under the new domain and read back wrong. Table recreation\n // is the only route that carries the values across; §9.6 states it as a\n // falsifier (\"LibSQL cannot take a native ALTER route that skips\n // conversion\").\n if (\n decimalConversionRequired(op.from, op.to) ||\n sqliteDateTimeTargetRequiresRecreation(op.from.dateTime, op.to.dateTime)\n ) {\n return this.compileAlterColumnByRecreation(op, context, false);\n }\n\n const { tableName, columnName, to } = op;\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // Build new column definition\n const colDef = this.generateColumnDef(to, context);\n\n // LibSQL syntax: ALTER TABLE t ALTER COLUMN old_name TO new_def\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n // ===========================================================================\n // HELPER: Build column definition with optional REFERENCES\n // ===========================================================================\n\n /**\n * Builds a column definition string with optional foreign key REFERENCES clause.\n * Used for LibSQL's ALTER COLUMN TO syntax.\n */\n private buildColumnDefWithReferences(\n column: ColumnDef,\n fkRef?: {\n refTable: string;\n refCol: string;\n onDelete?: ReferentialAction;\n onUpdate?: ReferentialAction;\n }\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK travels with the rewritten declaration.\n // `ALTER COLUMN ... TO` replaces the WHOLE column definition, so a\n // constraint this rebuild left out would be gone from the stored\n // `CREATE TABLE` — and with it the only carrier of the column's declared\n // domain, which introspection would then read as a descriptor change on\n // every push afterwards.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n if (fkRef) {\n parts.push(\n `REFERENCES ${this.escapeIdentifier(fkRef.refTable)}(${this.escapeIdentifier(fkRef.refCol)})`\n );\n if (fkRef.onDelete && fkRef.onDelete !== \"noAction\") {\n parts.push(`ON DELETE ${this.formatReferentialAction(fkRef.onDelete)}`);\n }\n if (fkRef.onUpdate && fkRef.onUpdate !== \"noAction\") {\n parts.push(`ON UPDATE ${this.formatReferentialAction(fkRef.onUpdate)}`);\n }\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n /**\n * LibSQL can add foreign keys by redefining the column with REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n *\n * Note: Multi-column FKs still require table recreation.\n */\n override generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n const { tableName, fk } = op;\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateAddForeignKey(op, context);\n }\n\n // Validate columns exist FIRST (before any array access)\n const fkColumn = fk.columns[0];\n const refColumn = fk.referencedColumns[0];\n if (!(fkColumn && refColumn)) {\n throw new Error(\n `Invalid foreign key: columns array is empty for table \"${tableName}\".`\n );\n }\n\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the column to alter\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot add foreign key: column \"${fkColumn}\" not found in table \"${tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Build column definition with REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column, {\n refTable: fk.referencedTable,\n refCol: refColumn,\n onDelete: fk.onDelete,\n onUpdate: fk.onUpdate,\n });\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n /**\n * LibSQL can drop foreign keys by redefining the column without REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n */\n override generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n // Find the FK to drop\n const fk = currentTable.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n throw new Error(\n `Cannot drop foreign key: constraint \"${op.fkName}\" not found in table \"${op.tableName}\".`\n );\n }\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateDropForeignKey(op, context);\n }\n\n const fkColumn = fk.columns[0];\n if (!fkColumn) {\n throw new Error(\n `Invalid foreign key: columns array is empty for constraint \"${op.fkName}\".`\n );\n }\n\n // Find the column\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot drop foreign key: column \"${fkColumn}\" not found in table \"${op.tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(op.tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Rebuild column definition WITHOUT REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column);\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // PRIMARY KEY OPERATIONS\n // LibSQL still requires table recreation for PK changes\n // ===========================================================================\n\n // generateAddPrimaryKey and generateDropPrimaryKey inherit from SQLite3\n // which uses table recreation. LibSQL does not support native PK modifications.\n}\n\n// Export singleton instance\nexport const libsqlMigrationDriver = new LibSQLMigrationDriver();\n"],"mappings":"krBA2CA,SAA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gBACb,OAAQ,EACR,SAAU,EAAG,SACb,SAAU,EAAG,SACd,CAAC,GASJ,uBACE,EACA,EAC4B,CAC5B,IAAM,EAAe,KAAK,gBAAgB,EAAG,UAAW,EAAQ,CAChE,GAAI,CAAC,EACH,MAAU,MACR,mCAAmC,EAAG,UAAU,yFAEjD,CAIH,IAAM,EAAK,EAAa,YAAY,KAAM,GAAM,EAAE,OAAS,EAAG,OAAO,CACrE,GAAI,CAAC,EACH,MAAU,MACR,wCAAwC,EAAG,OAAO,wBAAwB,EAAG,UAAU,IACxF,CAIH,GAAI,EAAG,QAAQ,OAAS,EACtB,OAAO,MAAM,uBAAuB,EAAI,EAAQ,CAGlD,IAAM,EAAW,EAAG,QAAQ,GAC5B,GAAI,CAAC,EACH,MAAU,MACR,+DAA+D,EAAG,OAAO,IAC1E,CAIH,IAAM,EAAS,EAAa,QAAQ,KAAM,GAAM,EAAE,OAAS,EAAS,CACpE,GAAI,CAAC,EACH,MAAU,MACR,oCAAoC,EAAS,wBAAwB,EAAG,UAAU,IACnF,CASH,MAAO,eANO,KAAK,iBAAiB,EAAG,UAAU,CAMrB,gBALhB,KAAK,iBAAiB,EAAS,CAKK,MAFjC,KAAK,6BAA6B,EAAO,KAe5D,MAAa,EAAwB,IAAI"}
|
package/dist/libsql.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, En as DriverTransactionOptions, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as QueryExecutionContext, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-
|
|
1
|
+
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, En as DriverTransactionOptions, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as QueryExecutionContext, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-BaK35ze2.mjs";
|
|
2
2
|
import { Client, Config, Transaction } from "@libsql/client";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/libsql/index.d.ts
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{E as r}from"./client-
|
|
2
|
-
//# sourceMappingURL=memory-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{E as r}from"./client-D291xo5z.mjs";import{n as i}from"./canonical-json-rfC2Dg0X.mjs";import{a,c as o}from"./identity-CLFhCTZx.mjs";const isCorruption=e=>e instanceof n&&e.code===t.MIGRATION_CORRUPTION;function createStorageConformanceSuite(e){return[{name:`identical content-addressed publish is idempotent`,run:async()=>{let t=e(),n=o(`hello`),i=r(n),a=await t.publishSql(i,n),s=await t.publishSql(i,n);if(a.outcome!==`created`||s.outcome!==`identical`)throw Error(`idempotent publish failed`)}},{name:`same hash with different bytes is corruption`,run:async()=>{let t=e(),n=o(`hello`),i=r(n);await t.publishSql(i,n);try{await t.publishSql(i,o(`other`))}catch(e){if(isCorruption(e))return}throw Error(`corrupt publish was accepted`)}},{name:`listStates returns only committed manifests`,run:async()=>{if((await e().listStates()).length!==0)throw Error(`fresh writer is not empty`)}},{name:`estate publish is idempotent for identical bytes`,run:async()=>{let t=e(),n=o(`{"format":"1"}`),r=await t.publishEstate(n),i=await t.publishEstate(n);if(r.outcome!==`created`||i.outcome!==`identical`)throw Error(`estate idempotent publish failed`)}},{name:`concurrent identical creates report created exactly once`,run:async()=>{let t=e(),n=o(`race-identical`),i=r(n),a=(await Promise.all(Array.from({length:8},()=>t.publishState(i,n)))).filter(e=>e.outcome===`created`).length;if(a!==1)throw Error(`${a} of 8 concurrent creates won`)}},{name:`concurrent conflicting creates keep one winner and refuse the rest`,run:async()=>{let t=e(),n=r(o(`race-conflicting`)),a=Array.from({length:8},(e,t)=>o(`{"racer":${t}}`)),s=await Promise.allSettled(a.map(e=>t.publishState(n,e))),c=a.filter((e,t)=>s[t]?.status===`fulfilled`),l=s.filter(e=>e.status===`rejected`&&isCorruption(e.reason)).length,u=await t.readState(n);if(c.length!==1||l!==7||!(u&&i(u,c[0])))throw Error(`${c.length} winners and ${l} refusals of 8 conflicting creates`)}},{name:`absent artifacts read as null`,run:async()=>{let t=e(),n=r(o(`absent`));if((await Promise.all([t.readState(n),t.readSnapshot(n),t.readSql(n)])).some(e=>e!==null))throw Error(`an absent artifact read as bytes`)}},{name:`published artifacts are listed as soon as publish returns`,run:async()=>{let t=e(),n=Array.from({length:5},(e,t)=>o(`listed-${t}`)),i=n.map(r);for(let[e,r]of i.entries())await t.publishState(r,n[e]),await t.publishSnapshot(r,n[e]),await t.publishSql(r,n[e]);if((await Promise.all([t.listStates(),t.listSnapshots(),t.listSql()])).some(e=>i.some(t=>!e.includes(t))))throw Error(`a published artifact is missing from its listing`)}},{name:`a listed state's snapshot and SQL are already readable (manifest last)`,run:async()=>{let t=e(),n=o(`manifest-last`),i=r(n),a=!1,s=(async()=>{await t.publishSnapshot(i,n),await t.publishSql(i,n),await t.publishState(i,n)})().finally(()=>{a=!0});try{for(;;){let e=a;if((await t.listStates()).includes(i))break;if(e)throw Error(`a published state is not listed`)}let[e,n]=await Promise.all([t.readSnapshot(i),t.readSql(i)]);if(!(e&&n))throw Error(`a listed state's artifacts are not readable yet`)}finally{await s}}}]}var MemoryEstateStorage=class{estate=null;states=new Map;snapshots=new Map;sql=new Map;async readEstate(){return this.estate?this.estate.slice():null}async listStates(){return[...this.states.keys()].sort()}async listSnapshots(){return[...this.snapshots.keys()].sort()}async listSql(){return[...this.sql.keys()].sort()}async readState(e){let t=this.states.get(e);return t?t.slice():null}async readSnapshot(e){let t=this.snapshots.get(e);return t?t.slice():null}async readSql(e){let t=this.sql.get(e);return t?t.slice():null}async publishEstate(e){if(this.estate&&!i(this.estate,e))throw new n(`estate.json already exists with different bytes`,t.MIGRATION_CORRUPTION);return this.estate?{outcome:`identical`}:(this.estate=e.slice(),{outcome:`created`})}async publishSnapshot(e,t){return publishMap(this.snapshots,e,t,`snapshot`)}async publishSql(e,t){return publishMap(this.sql,e,t,`sql`)}async publishState(e,r){if(!a(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return publishMap(this.states,e,r,`state`)}};function publishMap(e,r,a,o){let s=e.get(r);if(s){if(!i(s,a))throw new n(`${o} ${r} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}return e.set(r,a.slice()),{outcome:`created`}}export{createStorageConformanceSuite as n,MemoryEstateStorage as t};
|
|
2
|
+
//# sourceMappingURL=memory-DSEeJ7ps.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory-D4yxtCPK.mjs","names":[],"sources":["../src/migrations/storage/conformance.ts","../src/migrations/storage/memory.ts"],"sourcesContent":["/**\n * Reusable storage conformance suite. A writable driver that cannot pass\n * these tests is not a V1 estate owner.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { utf8Bytes } from \"../identity\";\nimport { encodeSqlBlob } from \"../v1-parse\";\nimport type { MigrationStorageWriter } from \"./contract\";\n\nconst RACERS = 8;\nconst LISTED = 5;\n\nconst isCorruption = (error: unknown): boolean =>\n error instanceof MigrationError &&\n error.code === VibORMErrorCode.MIGRATION_CORRUPTION;\n\nexport function createStorageConformanceSuite(\n createWriter: () => MigrationStorageWriter\n): { readonly name: string; readonly run: () => Promise<void> }[] {\n return [\n {\n name: \"identical content-addressed publish is idempotent\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n const first = await storage.publishSql(hash, bytes);\n const second = await storage.publishSql(hash, bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"idempotent publish failed\");\n }\n },\n },\n {\n name: \"same hash with different bytes is corruption\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n await storage.publishSql(hash, bytes);\n try {\n await storage.publishSql(hash, utf8Bytes(\"other\"));\n } catch (error) {\n if (isCorruption(error)) return;\n }\n throw new Error(\"corrupt publish was accepted\");\n },\n },\n {\n name: \"listStates returns only committed manifests\",\n run: async () => {\n const storage = createWriter();\n const listed = await storage.listStates();\n if (listed.length !== 0) throw new Error(\"fresh writer is not empty\");\n },\n },\n {\n name: \"estate publish is idempotent for identical bytes\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes('{\"format\":\"1\"}');\n const first = await storage.publishEstate(bytes);\n const second = await storage.publishEstate(bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"estate idempotent publish failed\");\n }\n },\n },\n {\n name: \"concurrent identical creates report created exactly once\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"race-identical\");\n const id = encodeSqlBlob(bytes);\n const outcomes = await Promise.all(\n Array.from({ length: RACERS }, () => storage.publishState(id, bytes))\n );\n const created = outcomes.filter((o) => o.outcome === \"created\").length;\n if (created !== 1) {\n throw new Error(`${created} of ${RACERS} concurrent creates won`);\n }\n },\n },\n {\n name: \"concurrent conflicting creates keep one winner and refuse the rest\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"race-conflicting\"));\n const candidates = Array.from({ length: RACERS }, (_, n) =>\n utf8Bytes(`{\"racer\":${n}}`)\n );\n const settled = await Promise.allSettled(\n candidates.map((bytes) => storage.publishState(id, bytes))\n );\n const winners = candidates.filter(\n (_, n) => settled[n]?.status === \"fulfilled\"\n );\n const refused = settled.filter(\n (result) =>\n result.status === \"rejected\" && isCorruption(result.reason)\n ).length;\n const stored = await storage.readState(id);\n if (\n winners.length !== 1 ||\n refused !== RACERS - 1 ||\n !(stored && bytesEqual(stored, winners[0]!))\n ) {\n throw new Error(\n `${winners.length} winners and ${refused} refusals of ${RACERS} conflicting creates`\n );\n }\n },\n },\n {\n name: \"absent artifacts read as null\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"absent\"));\n const reads = await Promise.all([\n storage.readState(id),\n storage.readSnapshot(id),\n storage.readSql(id),\n ]);\n if (reads.some((bytes) => bytes !== null)) {\n throw new Error(\"an absent artifact read as bytes\");\n }\n },\n },\n {\n name: \"published artifacts are listed as soon as publish returns\",\n run: async () => {\n const storage = createWriter();\n const artifacts = Array.from({ length: LISTED }, (_, n) =>\n utf8Bytes(`listed-${n}`)\n );\n const ids = artifacts.map(encodeSqlBlob);\n for (const [n, id] of ids.entries()) {\n await storage.publishState(id, artifacts[n]!);\n await storage.publishSnapshot(id, artifacts[n]!);\n await storage.publishSql(id, artifacts[n]!);\n }\n const listings = await Promise.all([\n storage.listStates(),\n storage.listSnapshots(),\n storage.listSql(),\n ]);\n if (listings.some((listed) => ids.some((id) => !listed.includes(id)))) {\n throw new Error(\"a published artifact is missing from its listing\");\n }\n },\n },\n {\n name: \"a listed state's snapshot and SQL are already readable (manifest last)\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"manifest-last\");\n const hash = encodeSqlBlob(bytes);\n let published = false;\n const publishing = (async () => {\n await storage.publishSnapshot(hash, bytes);\n await storage.publishSql(hash, bytes);\n await storage.publishState(hash, bytes);\n })().finally(() => {\n published = true;\n });\n try {\n for (;;) {\n const settled = published;\n if ((await storage.listStates()).includes(hash)) break;\n if (settled) throw new Error(\"a published state is not listed\");\n }\n const [snapshot, sql] = await Promise.all([\n storage.readSnapshot(hash),\n storage.readSql(hash),\n ]);\n if (!(snapshot && sql)) {\n throw new Error(\"a listed state's artifacts are not readable yet\");\n }\n } finally {\n await publishing;\n }\n },\n },\n ];\n}\n","/**\n * In-memory estate writer for tests and conformance.\n * Conditional create: same hash + same bytes is identical; different bytes is corruption.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport class MemoryEstateStorage implements MigrationStorageWriter {\n private estate: Uint8Array | null = null;\n private readonly states = new Map<Sha256, Uint8Array>();\n private readonly snapshots = new Map<Sha256, Uint8Array>();\n private readonly sql = new Map<Sha256, Uint8Array>();\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.estate ? this.estate.slice() : null;\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return [...this.states.keys()].sort();\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return [...this.snapshots.keys()].sort();\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return [...this.sql.keys()].sort();\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n const bytes = this.states.get(id);\n return bytes ? bytes.slice() : null;\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.snapshots.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.sql.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n if (this.estate && !bytesEqual(this.estate, bytes)) {\n throw new MigrationError(\n \"estate.json already exists with different bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (this.estate) return { outcome: \"identical\" };\n this.estate = bytes.slice();\n return { outcome: \"created\" };\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishMap(this.snapshots, hash, bytes, \"snapshot\");\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishMap(this.sql, hash, bytes, \"sql\");\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return publishMap(this.states, id, bytes, \"state\");\n }\n}\n\nfunction publishMap(\n store: Map<Sha256, Uint8Array>,\n key: Sha256,\n bytes: Uint8Array,\n label: string\n): PublishResult {\n const existing = store.get(key);\n if (existing) {\n if (!bytesEqual(existing, bytes)) {\n throw new MigrationError(\n `${label} ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n store.set(key, bytes.slice());\n return { outcome: \"created\" };\n}\n"],"mappings":"yQAWA,MAGM,aAAgB,GACpB,aAAiB,GACjB,EAAM,OAAS,EAAgB,qBAEjC,SAAgB,8BACd,EACgE,CAChE,MAAO,CACL,CACE,KAAM,oDACN,IAAK,SAAY,CACf,IAAM,EAAU,GAAc,CACxB,EAAQ,EAAU,QAAQ,CAC1B,EAAO,EAAc,EAAM,CAC3B,EAAQ,MAAM,EAAQ,WAAW,EAAM,EAAM,CAC7C,EAAS,MAAM,EAAQ,WAAW,EAAM,EAAM,CACpD,GAAI,EAAM,UAAY,WAAa,EAAO,UAAY,YACpD,MAAU,MAAM,4BAA4B,EAGjD,CACD,CACE,KAAM,+CACN,IAAK,SAAY,CACf,IAAM,EAAU,GAAc,CACxB,EAAQ,EAAU,QAAQ,CAC1B,EAAO,EAAc,EAAM,CACjC,MAAM,EAAQ,WAAW,EAAM,EAAM,CACrC,GAAI,CACF,MAAM,EAAQ,WAAW,EAAM,EAAU,QAAQ,CAAC,OAC3C,EAAO,CACd,GAAI,aAAa,EAAM,CAAE,OAE3B,MAAU,MAAM,+BAA+B,EAElD,CACD,CACE,KAAM,8CACN,IAAK,SAAY,CAGf,IADe,MADC,GAAc,CACD,YAAY,EAC9B,SAAW,EAAG,MAAU,MAAM,4BAA4B,EAExE,CACD,CACE,KAAM,mDACN,IAAK,SAAY,CACf,IAAM,EAAU,GAAc,CACxB,EAAQ,EAAU,iBAAiB,CACnC,EAAQ,M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AAG,CACf,MAAM,IAAI,EACR,mCACA,EAAgB,yBACjB,CAEH,OAAO,WAAW,KAAK,OAAQ,EAAI,EAAO,QAAQ,GAItD,SAAS,WACP,EACA,EACA,EACA,EACe,CACf,IAAM,EAAW,EAAM,IAAI,EAAI,CAC/B,GAAI,EAAU,CACZ,GAAI,CAAC,EAAW,EAAU,EAAM,CAC9B,MAAM,IAAI,EACR,GAAG,EAAM,GAAG,EAAI,gCAChB,EAAgB,qBACjB,CAEH,MAAO,CAAE,QAAS,YAAa,CAGjC,OADA,EAAM,IAAI,EAAK,EAAM,OAAO,CAAC,CACtB,CAAE,QAAS,UAAW"}
|
|
1
|
+
{"version":3,"file":"memory-DSEeJ7ps.mjs","names":[],"sources":["../src/migrations/storage/conformance.ts","../src/migrations/storage/memory.ts"],"sourcesContent":["/**\n * Reusable storage conformance suite. A writable driver that cannot pass\n * these tests is not a V1 estate owner.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { utf8Bytes } from \"../identity\";\nimport { encodeSqlBlob } from \"../v1-parse\";\nimport type { MigrationStorageWriter } from \"./contract\";\n\nconst RACERS = 8;\nconst LISTED = 5;\n\nconst isCorruption = (error: unknown): boolean =>\n error instanceof MigrationError &&\n error.code === VibORMErrorCode.MIGRATION_CORRUPTION;\n\nexport function createStorageConformanceSuite(\n createWriter: () => MigrationStorageWriter\n): { readonly name: string; readonly run: () => Promise<void> }[] {\n return [\n {\n name: \"identical content-addressed publish is idempotent\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n const first = await storage.publishSql(hash, bytes);\n const second = await storage.publishSql(hash, bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"idempotent publish failed\");\n }\n },\n },\n {\n name: \"same hash with different bytes is corruption\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n await storage.publishSql(hash, bytes);\n try {\n await storage.publishSql(hash, utf8Bytes(\"other\"));\n } catch (error) {\n if (isCorruption(error)) return;\n }\n throw new Error(\"corrupt publish was accepted\");\n },\n },\n {\n name: \"listStates returns only committed manifests\",\n run: async () => {\n const storage = createWriter();\n const listed = await storage.listStates();\n if (listed.length !== 0) throw new Error(\"fresh writer is not empty\");\n },\n },\n {\n name: \"estate publish is idempotent for identical bytes\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes('{\"format\":\"1\"}');\n const first = await storage.publishEstate(bytes);\n const second = await storage.publishEstate(bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"estate idempotent publish failed\");\n }\n },\n },\n {\n name: \"concurrent identical creates report created exactly once\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"race-identical\");\n const id = encodeSqlBlob(bytes);\n const outcomes = await Promise.all(\n Array.from({ length: RACERS }, () => storage.publishState(id, bytes))\n );\n const created = outcomes.filter((o) => o.outcome === \"created\").length;\n if (created !== 1) {\n throw new Error(`${created} of ${RACERS} concurrent creates won`);\n }\n },\n },\n {\n name: \"concurrent conflicting creates keep one winner and refuse the rest\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"race-conflicting\"));\n const candidates = Array.from({ length: RACERS }, (_, n) =>\n utf8Bytes(`{\"racer\":${n}}`)\n );\n const settled = await Promise.allSettled(\n candidates.map((bytes) => storage.publishState(id, bytes))\n );\n const winners = candidates.filter(\n (_, n) => settled[n]?.status === \"fulfilled\"\n );\n const refused = settled.filter(\n (result) =>\n result.status === \"rejected\" && isCorruption(result.reason)\n ).length;\n const stored = await storage.readState(id);\n if (\n winners.length !== 1 ||\n refused !== RACERS - 1 ||\n !(stored && bytesEqual(stored, winners[0]!))\n ) {\n throw new Error(\n `${winners.length} winners and ${refused} refusals of ${RACERS} conflicting creates`\n );\n }\n },\n },\n {\n name: \"absent artifacts read as null\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"absent\"));\n const reads = await Promise.all([\n storage.readState(id),\n storage.readSnapshot(id),\n storage.readSql(id),\n ]);\n if (reads.some((bytes) => bytes !== null)) {\n throw new Error(\"an absent artifact read as bytes\");\n }\n },\n },\n {\n name: \"published artifacts are listed as soon as publish returns\",\n run: async () => {\n const storage = createWriter();\n const artifacts = Array.from({ length: LISTED }, (_, n) =>\n utf8Bytes(`listed-${n}`)\n );\n const ids = artifacts.map(encodeSqlBlob);\n for (const [n, id] of ids.entries()) {\n await storage.publishState(id, artifacts[n]!);\n await storage.publishSnapshot(id, artifacts[n]!);\n await storage.publishSql(id, artifacts[n]!);\n }\n const listings = await Promise.all([\n storage.listStates(),\n storage.listSnapshots(),\n storage.listSql(),\n ]);\n if (listings.some((listed) => ids.some((id) => !listed.includes(id)))) {\n throw new Error(\"a published artifact is missing from its listing\");\n }\n },\n },\n {\n name: \"a listed state's snapshot and SQL are already readable (manifest last)\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"manifest-last\");\n const hash = encodeSqlBlob(bytes);\n let published = false;\n const publishing = (async () => {\n await storage.publishSnapshot(hash, bytes);\n await storage.publishSql(hash, bytes);\n await storage.publishState(hash, bytes);\n })().finally(() => {\n published = true;\n });\n try {\n for (;;) {\n const settled = published;\n if ((await storage.listStates()).includes(hash)) break;\n if (settled) throw new Error(\"a published state is not listed\");\n }\n const [snapshot, sql] = await Promise.all([\n storage.readSnapshot(hash),\n storage.readSql(hash),\n ]);\n if (!(snapshot && sql)) {\n throw new Error(\"a listed state's artifacts are not readable yet\");\n }\n } finally {\n await publishing;\n }\n },\n },\n ];\n}\n","/**\n * In-memory estate writer for tests and conformance.\n * Conditional create: same hash + same bytes is identical; different bytes is corruption.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport class MemoryEstateStorage implements MigrationStorageWriter {\n private estate: Uint8Array | null = null;\n private readonly states = new Map<Sha256, Uint8Array>();\n private readonly snapshots = new Map<Sha256, Uint8Array>();\n private readonly sql = new Map<Sha256, Uint8Array>();\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.estate ? this.estate.slice() : null;\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return [...this.states.keys()].sort();\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return [...this.snapshots.keys()].sort();\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return [...this.sql.keys()].sort();\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n const bytes = this.states.get(id);\n return bytes ? bytes.slice() : null;\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.snapshots.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.sql.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n if (this.estate && !bytesEqual(this.estate, bytes)) {\n throw new MigrationError(\n \"estate.json already exists with different bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (this.estate) return { outcome: \"identical\" };\n this.estate = bytes.slice();\n return { outcome: \"created\" };\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishMap(this.snapshots, hash, bytes, \"snapshot\");\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishMap(this.sql, hash, bytes, \"sql\");\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return publishMap(this.states, id, bytes, \"state\");\n }\n}\n\nfunction publishMap(\n store: Map<Sha256, Uint8Array>,\n key: Sha256,\n bytes: Uint8Array,\n label: string\n): PublishResult {\n const existing = store.get(key);\n if (existing) {\n if (!bytesEqual(existing, bytes)) {\n throw new MigrationError(\n `${label} ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n store.set(key, bytes.slice());\n return { outcome: \"created\" };\n}\n"],"mappings":"yQAWA,MAGM,aAAgB,GACpB,aAAiB,GACjB,EAAM,OAAS,EAAgB,qBAEjC,SAAgB,8BACd,EACgE,CAChE,MAAO,CACL,CACE,KAAM,oDACN,IAAK,SAAY,CACf,IAAM,EAAU,GAAc,CACxB,EAAQ,EAAU,QAAQ,CAC1B,EAAO,EAAc,EAAM,CAC3B,EAAQ,MAAM,EAAQ,WAAW,EAAM,EAAM,CAC7C,EAAS,MAAM,EAAQ,WAAW,EAAM,EAAM,CACpD,GAAI,EAAM,UAAY,WAAa,EAAO,UAAY,YACpD,MAAU,MAAM,4BAA4B,EAGjD,CACD,CACE,KAAM,+CACN,IAAK,SAAY,CACf,IAAM,EAAU,GAAc,CACxB,EAAQ,EAAU,QAAQ,CAC1B,EAAO,EAAc,EAAM,CACjC,MAAM,EAAQ,WAAW,EAAM,EAAM,CACrC,GAAI,CACF,MAAM,EAAQ,WAAW,EAAM,EAAU,QAAQ,CAAC,OAC3C,EAAO,CACd,GAAI,aAAa,EAAM,CAAE,OAE3B,MAAU,MAAM,+BAA+B,EAElD,CACD,CACE,KAAM,8CACN,IAAK,SAAY,CAGf,IADe,MADC,GAAc,CACD,YAAY,EAC9B,SAAW,EAAG,MAAU,MAAM,4BAA4B,EAExE,CACD,CACE,KAAM,mDACN,IAAK,SAAY,CACf,IAAM,EAAU,GAAc,CACxB,EAAQ,EAAU,iBAAiB,CACnC,EAAQ,MAAM,EAAQ,cAAc,EAAM,CAC1C,EAAS,MAAM,EAAQ,cAAc,EAAM,CACjD,GAAI,EAAM,UAAY,WAAa,EAAO,UAAY,YACpD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WACP,EACA,EACA,EACA,EACe,CACf,IAAM,EAAW,EAAM,IAAI,EAAI,CAC/B,GAAI,EAAU,CACZ,GAAI,CAAC,EAAW,EAAU,EAAM,CAC9B,MAAM,IAAI,EACR,GAAG,EAAM,GAAG,EAAI,gCAChB,EAAgB,qBACjB,CAEH,MAAO,CAAE,QAAS,YAAa,CAGjC,OADA,EAAM,IAAI,EAAK,EAAM,OAAO,CAAC,CACtB,CAAE,QAAS,UAAW"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { gi as isMigrationError, hi as MigrationError } from "../index-
|
|
2
|
-
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-
|
|
1
|
+
import { gi as isMigrationError, hi as MigrationError } from "../index-BaK35ze2.mjs";
|
|
2
|
+
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-BKHHRpvB.mjs";
|
|
3
3
|
import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CIIqgFyb.mjs";
|
|
4
|
-
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-
|
|
5
|
-
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-
|
|
4
|
+
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-DCxwbkys.mjs";
|
|
5
|
+
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-BKKA2CQj.mjs";
|
|
6
6
|
export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"../migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-
|
|
1
|
+
import{n as e,t}from"../migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-D291xo5z.mjs";import{t as d}from"../identifier-conversion-GgbwHc2G.mjs";import{t as f}from"../mysql-B7VGoX6t.mjs";import{n as p,t as m}from"../memory-DSEeJ7ps.mjs";import{n as h,r as g,t as _}from"../object-store-DQR6bTBY.mjs";o(f);export{_ as MemoryConditionalObjectStore,m as MemoryEstateStorage,t as MigrationError,h as ObjectStoreEstateStorage,r as addDropResolver,s as auditStorage,c as createMigrationClient,n as createPredefinedResolver,p as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,u as lenientResolver,g as refuseWorkersKvWritable,i as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
|
|
2
2
|
//# sourceMappingURL=mysql.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { gi as isMigrationError, hi as MigrationError } from "../index-
|
|
2
|
-
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-
|
|
1
|
+
import { gi as isMigrationError, hi as MigrationError } from "../index-BaK35ze2.mjs";
|
|
2
|
+
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-BKHHRpvB.mjs";
|
|
3
3
|
import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CIIqgFyb.mjs";
|
|
4
|
-
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-
|
|
5
|
-
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-
|
|
4
|
+
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-DCxwbkys.mjs";
|
|
5
|
+
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-BKKA2CQj.mjs";
|
|
6
6
|
export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"../migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-
|
|
1
|
+
import{n as e,t}from"../migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-D291xo5z.mjs";import{t as d}from"../identifier-conversion-GgbwHc2G.mjs";import{t as f}from"../postgres-CeSmp2Tj.mjs";import{n as p,t as m}from"../memory-DSEeJ7ps.mjs";import{n as h,r as g,t as _}from"../object-store-DQR6bTBY.mjs";o(f);export{_ as MemoryConditionalObjectStore,m as MemoryEstateStorage,t as MigrationError,h as ObjectStoreEstateStorage,r as addDropResolver,s as auditStorage,c as createMigrationClient,n as createPredefinedResolver,p as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,u as lenientResolver,g as refuseWorkersKvWritable,i as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
|
|
2
2
|
//# sourceMappingURL=postgres.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { gi as isMigrationError, hi as MigrationError } from "../index-
|
|
2
|
-
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-
|
|
1
|
+
import { gi as isMigrationError, hi as MigrationError } from "../index-BaK35ze2.mjs";
|
|
2
|
+
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-BKHHRpvB.mjs";
|
|
3
3
|
import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CIIqgFyb.mjs";
|
|
4
|
-
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-
|
|
5
|
-
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-
|
|
4
|
+
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-DCxwbkys.mjs";
|
|
5
|
+
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-BKKA2CQj.mjs";
|
|
6
6
|
export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"../migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-
|
|
1
|
+
import{n as e,t}from"../migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-D291xo5z.mjs";import{t as d}from"../identifier-conversion-GgbwHc2G.mjs";import{n as f,t as p}from"../libsql-IdshHiw4.mjs";import{n as m,t as h}from"../memory-DSEeJ7ps.mjs";import{n as g,r as _,t as v}from"../object-store-DQR6bTBY.mjs";o(f),o(p);export{v as MemoryConditionalObjectStore,h as MemoryEstateStorage,t as MigrationError,g as ObjectStoreEstateStorage,r as addDropResolver,s as auditStorage,c as createMigrationClient,n as createPredefinedResolver,m as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,u as lenientResolver,_ as refuseWorkersKvWritable,i as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
|
|
2
2
|
//# sourceMappingURL=sqlite.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { s as MigrationLimits, t as MigrationClient } from "../planner-
|
|
1
|
+
import { s as MigrationLimits, t as MigrationClient } from "../planner-BKHHRpvB.mjs";
|
|
2
2
|
import { i as Sha256, n as MigrationStorageWriter } from "../contract-CIIqgFyb.mjs";
|
|
3
|
-
import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-
|
|
3
|
+
import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-BKKA2CQj.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/migrations/tenant.d.ts
|
|
6
6
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{i as t,n,r}from"../base-AdXAoy6l.mjs";import{C as i,i as a,r as o,t as s,x as c}from"../client-
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{i as t,n,r}from"../base-AdXAoy6l.mjs";import{C as i,i as a,r as o,t as s,x as c}from"../client-D291xo5z.mjs";const l=new Set([n.MIGRATION_PARTIAL_EFFECT,n.MIGRATION_AMBIGUOUS_COMMIT,n.MIGRATION_UNFINISHED_ATTEMPT]),u=new Set([n.MIGRATION_FAILED,n.MIGRATION_MARKER_CONFLICT]);function createTenantMigrator({client:e,history:t,tables:n,limits:r}){let c={storage:t,tables:n,limits:r},l=s(e,c),u=Promise.resolve(),exclusive=async(e,t)=>{let n=u,release=()=>void 0;u=new Promise(e=>{release=e}).then(()=>n);try{return await untilAborted(n,t),await e()}finally{release()}},change=async(n,{decisions:r=[],signal:l,beforeDestructive:u}={})=>{let d,f;try{l?.throwIfAborted(),a(o(e),`batch`,`apply()`),f=s({$driver:e.$driver,$schema:n},c);let p=i(r);if(u&&await isDestructive(f,p,t)){l?.throwIfAborted();try{await u()}catch(e){return{kind:`refused`,error:describe(e)}}}l?.throwIfAborted(),d=(await f.generate({resolve:p})).outcome===`published`}catch(e){return{kind:classify(e),error:describe(e)}}for(let e=1;;e+=1)try{let e=await f.apply();return e.outcome===`noop`&&!d?{kind:`noop`}:{kind:`applied`,path:e.path,...e.warnings?{warnings:e.warnings}:{}}}catch(t){let n=classify(t),r=d&&n===`refused`?`failed`:n;if(e===4||r!==`failed`||!retryable(t)||!await backoff(e,l))return withMarker({kind:r,error:describe(t)},f)}};return Object.freeze({change:(e,t)=>exclusive(()=>change(e,t),t?.signal).catch(e=>({kind:`failed`,error:describe(e)})),status:()=>l.status(),log:()=>l.log(),resolve:e=>exclusive(()=>l.resolve(e)),down:e=>exclusive(()=>l.down(e)),reanchor:e=>exclusive(()=>l.reanchor(e)),prune:e=>exclusive(()=>l.prune(e))})}async function isDestructive(e,t,n){if((await e.generate({dryRun:!0,resolve:t})).operations.some(c))return!0;if(!await n.readEstate())return!1;let{states:r,edges:i}=await e.graph();if(r.length===0)return!1;let{path:a}=await e.apply({dryRun:!0});return i.some(e=>a.includes(e.toState)&&(e.approvals.length>0||e.risks.includes(`destructive`)))}function retryable(e){if(t(e)&&e.code===n.MIGRATION_LOCK_FAILED)return!0;for(let t=e;t instanceof Error;t=t.cause)if(r(t))return!0;return!1}function classify(e){return t(e)?l.has(e.code)||e.meta.partial===!0?`ambiguous`:u.has(e.code)||retryable(e)?`failed`:`refused`:`failed`}async function withMarker(e,t){try{return{...e,marker:(await t.status()).marker}}catch{return e}}function describe(e){if(!(e instanceof Error))return{name:`Error`,message:String(e)};let n=e.cause instanceof Error?Reflect.get(e.cause,`code`):null,r=t(e)?e.meta.providerSqlState:void 0;return{name:e.name,...t(e)?{code:e.code}:{},message:e.message,...typeof n==`string`?{causeCode:n}:{},...typeof r==`string`?{providerSqlState:r}:{}}}function untilAborted(e,t){if(!t)return e;t.throwIfAborted();let abort=()=>void 0,n=new Promise((e,n)=>{abort=()=>n(t.reason),t.addEventListener(`abort`,abort,{once:!0})});return Promise.race([e,n]).finally(()=>t.removeEventListener(`abort`,abort))}async function backoff(e,t){let n=200*2**(e-1)*(.5+Math.random()/2);try{return await untilAborted(new Promise(e=>setTimeout(e,n)),t),!0}catch{return!1}}export{createTenantMigrator};
|
|
2
2
|
//# sourceMappingURL=tenant.mjs.map
|
package/dist/migrations.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { gi as isMigrationError, hi as MigrationError } from "./index-
|
|
2
|
-
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-
|
|
1
|
+
import { gi as isMigrationError, hi as MigrationError } from "./index-BaK35ze2.mjs";
|
|
2
|
+
import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-BKHHRpvB.mjs";
|
|
3
3
|
import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "./contract-CIIqgFyb.mjs";
|
|
4
|
-
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-
|
|
5
|
-
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-
|
|
4
|
+
import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-DCxwbkys.mjs";
|
|
5
|
+
import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-BKKA2CQj.mjs";
|
|
6
6
|
export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
|
package/dist/migrations.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"./migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,s as o,t as s,u as c,w as l}from"./client-
|
|
1
|
+
import{n as e,t}from"./migrations-DTObIjAm.mjs";import{C as n,S as r,T as i,l as a,s as o,t as s,u as c,w as l}from"./client-D291xo5z.mjs";import{t as u}from"./identifier-conversion-GgbwHc2G.mjs";import{t as d}from"./every-BJLkY4qm.mjs";import{n as f,t as p}from"./memory-DSEeJ7ps.mjs";import{n as m,r as h,t as g}from"./object-store-DQR6bTBY.mjs";d();export{g as MemoryConditionalObjectStore,p as MemoryEstateStorage,t as MigrationError,m as ObjectStoreEstateStorage,r as addDropResolver,o as auditStorage,s as createMigrationClient,n as createPredefinedResolver,f as createStorageConformanceSuite,u as identifierConversionChecks,e as isMigrationError,l as lenientResolver,h as refuseWorkersKvWritable,i as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,c as sqliteCanonicalTimeExpression};
|
|
2
2
|
//# sourceMappingURL=migrations.mjs.map
|