hekireki 0.52.0 → 0.52.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.
Files changed (66) hide show
  1. package/README.md +8 -0
  2. package/dist/bin/activerecord.js +1 -1
  3. package/dist/bin/ajv.js +1 -1
  4. package/dist/bin/arktype.js +1 -1
  5. package/dist/bin/atlas.js +1 -1
  6. package/dist/bin/django.js +1 -1
  7. package/dist/bin/docs.js +1 -1
  8. package/dist/bin/drizzle.js +1 -1
  9. package/dist/bin/ecto.js +1 -1
  10. package/dist/bin/efcore.js +1 -1
  11. package/dist/bin/effect.js +1 -1
  12. package/dist/bin/eloquent.js +1 -1
  13. package/dist/bin/er.js +1 -1
  14. package/dist/bin/exposed.js +1 -1
  15. package/dist/bin/gorm.js +1 -1
  16. package/dist/bin/hekireki.js +5 -5
  17. package/dist/bin/kysely.js +1 -1
  18. package/dist/bin/openapi.js +1 -1
  19. package/dist/bin/pydantic.js +1 -1
  20. package/dist/bin/sea-orm.js +1 -1
  21. package/dist/bin/seed.js +1 -1
  22. package/dist/bin/sqlalchemy.js +1 -1
  23. package/dist/bin/typebox.js +1 -1
  24. package/dist/bin/valibot.js +1 -1
  25. package/dist/bin/zod-openapi-hono.js +1 -1
  26. package/dist/bin/zod.js +1 -1
  27. package/dist/{bin-BcqPhgiX.js → bin-i7iQQ-V-.js} +3295 -2428
  28. package/dist/case-D3JCqTLI.js +54 -0
  29. package/dist/{discover-BKlX-LLS.js → discover-CLLycWcR.js} +3 -3
  30. package/dist/{emit-BSQAIFiF.js → emit-DsCT5gLu.js} +5 -2
  31. package/dist/{errors-fAN1Og-7.js → errors-CRIxtr-P.js} +88 -26
  32. package/dist/index.d.ts +1 -1
  33. package/dist/index.js +1 -1
  34. package/dist/{migrate-BS6d_8aA.js → migrate-1xVrRUlb.js} +77 -21
  35. package/dist/{native-engine-DcZUEqO8.js → native-engine-DeQEnJxi.js} +145 -30
  36. package/dist/{plan-BMypogKp.js → plan-8rsBBJcs.js} +1294 -768
  37. package/dist/{run-BYq7BEVd.js → run-DbZYkHVI.js} +235 -128
  38. package/dist/{schema-B7beUJic.js → schema-CyJTUCF1.js} +54 -182
  39. package/dist/{sql-BwL2BncN.js → sql-LMMCiAlf.js} +48 -19
  40. package/dist/{start-s1j4PqUM.js → start-Ba8wQAD1.js} +1304 -929
  41. package/dist/studio/assets/client-8R97eV42.js +2 -0
  42. package/dist/studio/assets/{confirm-dialog-CKCkchiq.js → confirm-dialog-BfMzwGyk.js} +1 -1
  43. package/dist/studio/assets/docs-C7FtC4KG.js +1 -0
  44. package/dist/studio/assets/enums._name-DLAiEdMc.js +1 -0
  45. package/dist/studio/assets/{field-icon-C1wSRFKO.js → field-icon-LVK7vIIn.js} +1 -1
  46. package/dist/studio/assets/index-T46k2NyA.js +15 -0
  47. package/dist/studio/assets/{labels-B5gZ2suK.js → labels-Bn-KWaMa.js} +2 -2
  48. package/dist/studio/assets/{marked-text-B27DfhKS.js → marked-text-BdU5_qSK.js} +1 -1
  49. package/dist/studio/assets/models._name-BKzAVcW3.js +1 -0
  50. package/dist/studio/assets/{monaco-DRYJTcJl.js → monaco-33yj-p0X.js} +1 -1
  51. package/dist/studio/assets/prisma-DqpMbUwJ.js +2 -0
  52. package/dist/studio/assets/result-table-PN64JbsN.js +1 -0
  53. package/dist/studio/assets/{routes-Bl7HRpBJ.js → routes-C1Aze5QM.js} +1 -1
  54. package/dist/studio/assets/{schema-view-BEdx0cC2.js → schema-view-Bq2_9B5a.js} +4 -4
  55. package/dist/studio/assets/sql-FZV6GAdV.js +6 -0
  56. package/dist/studio/assets/{tabs-BpZ0hh1V.js → tabs-GBri63Xo.js} +1 -1
  57. package/dist/studio/index.html +2 -2
  58. package/package.json +12 -5
  59. package/dist/studio/assets/client-C-v3Paav.js +0 -2
  60. package/dist/studio/assets/docs-CXORFY0Y.js +0 -1
  61. package/dist/studio/assets/enums._name-BUBU_WMt.js +0 -1
  62. package/dist/studio/assets/index-DzCcMC-d.js +0 -15
  63. package/dist/studio/assets/models._name-CQFgPD0T.js +0 -1
  64. package/dist/studio/assets/prisma-1nDx08Wb.js +0 -2
  65. package/dist/studio/assets/result-table-0P18Nywh.js +0 -1
  66. package/dist/studio/assets/sql-GBZZtEKI.js +0 -6
@@ -1,8 +1,8 @@
1
1
  import { _ as NO_SQLITE, c as removePath, d as importFromProject, i as makeDirectory, m as DISCONNECTED, r as isDirectory, s as readFile, t as exists, u as writeFile, v as READ_STATEMENT } from "./file-DOGnu_Q2.js";
2
2
  import { d as DatabaseError, f as DatabaseUnavailableError } from "./bin/hekireki.js";
3
- import { S as isJoinSideA, a as schemaText, d as makePostgresSchema, f as makeRedactedUrl, h as backRelation, i as readSchemaFiles, l as isLibsqlUrl, n as parseSchema, p as makeSqliteFilePath, t as dialectOf, u as makeDialect } from "./schema-B7beUJic.js";
4
- import { a as splitStatements, c as sqliteAffinity, n as MigrateDatabaseError, o as splitTopLevel, t as MigrateConfigError } from "./errors-fAN1Og-7.js";
5
- import { d as resolveDatabaseUrl, f as placeholder, h as stringLiteral, i as withTypeScriptImports, m as quoteIdentifier, n as renderLiteral, o as readConfigUrl, p as qualifiedName } from "./sql-BwL2BncN.js";
3
+ import { C as isJoinSideA, a as schemaText, d as makePostgresSchema, f as makeRedactedUrl, h as backRelation, i as readSchemaFiles, l as isLibsqlUrl, n as parseSchema, p as makeSqliteFilePath, t as dialectOf, u as makeDialect } from "./schema-CyJTUCF1.js";
4
+ import { a as splitStatements, c as sqliteAffinity, n as MigrateDatabaseError, o as splitTopLevel, t as MigrateConfigError } from "./errors-CRIxtr-P.js";
5
+ import { d as resolveDatabaseUrl, f as placeholder, h as stringLiteral, i as withTypeScriptImports, m as quoteIdentifier, n as renderLiteral, o as readConfigUrl, p as qualifiedName } from "./sql-LMMCiAlf.js";
6
6
  import { Effect } from "effect";
7
7
  import path from "node:path";
8
8
  import { layer } from "@effect/platform-node/NodeFileSystem";
@@ -585,7 +585,7 @@ function openMysqlCopy(input) {
585
585
  const source = (yield* driver.query({
586
586
  sql: "SELECT DATABASE() AS `name`",
587
587
  params: []
588
- })).rows[0]?.name;
588
+ })).rows[0]?.["name"];
589
589
  const name = `hk_rehearsal_${globalThis.crypto.randomUUID().replaceAll("-", "")}`;
590
590
  const quoted = quoteIdentifier("mysql", name);
591
591
  yield* driver.executeScript(`CREATE DATABASE ${quoted}`);
@@ -619,7 +619,7 @@ function fillMysqlCopy(input) {
619
619
  sql: "SET FOREIGN_KEY_CHECKS = 0",
620
620
  params: []
621
621
  });
622
- yield* Effect.forEach(tables.rows.flatMap((row) => typeof row.table === "string" ? [row.table] : []), (table) => copyMysqlTable({
622
+ yield* Effect.forEach(tables.rows.flatMap((row) => typeof row["table"] === "string" ? [row["table"]] : []), (table) => copyMysqlTable({
623
623
  ...input,
624
624
  table
625
625
  }), {
@@ -634,7 +634,7 @@ function fillMysqlCopy(input) {
634
634
  sql: "SELECT trigger_name AS `name` FROM information_schema.triggers WHERE trigger_schema = DATABASE() ORDER BY 1",
635
635
  params: []
636
636
  });
637
- yield* Effect.forEach(triggers.rows.flatMap((row) => typeof row.name === "string" ? [row.name] : []), (trigger) => copyMysqlTrigger({
637
+ yield* Effect.forEach(triggers.rows.flatMap((row) => typeof row["name"] === "string" ? [row["name"]] : []), (trigger) => copyMysqlTrigger({
638
638
  driver,
639
639
  copy,
640
640
  trigger
@@ -672,7 +672,7 @@ function copyMysqlTable(input) {
672
672
  const names = (yield* input.driver.query({
673
673
  sql: "SELECT column_name AS `column` FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND COALESCE(generation_expression, '') = '' ORDER BY ordinal_position",
674
674
  params: [input.table]
675
- })).rows.flatMap((row) => typeof row.column === "string" ? [quoteIdentifier("mysql", row.column)] : []).join(", ");
675
+ })).rows.flatMap((row) => typeof row["column"] === "string" ? [quoteIdentifier("mysql", row["column"])] : []).join(", ");
676
676
  yield* input.copy.executeRaw({
677
677
  sql: `INSERT INTO ${table} (${names}) SELECT ${names} FROM ${quoteIdentifier("mysql", input.source)}.${table}`,
678
678
  params: []
@@ -744,6 +744,10 @@ function openShadowDatabase(input) {
744
744
  * @param input.schemaDir - where relative sqlite files resolve from
745
745
  * @returns the status, the driver, the URL as found and how to close it
746
746
  */
747
+ function openDriver(dialect, url, cwd, schemaDir) {
748
+ if (dialect === "sqlite") return isLibsqlUrl({ url }) ? openLibsql(url, cwd) : openSqlite(url, schemaDir);
749
+ return dialect === "postgresql" ? openPostgres(url, cwd) : openMysql(url, cwd);
750
+ }
747
751
  function connectDatabase(input) {
748
752
  return Effect.gen(function* () {
749
753
  const found = yield* resolveDatabaseUrl(input).pipe(Effect.mapError((error) => new DatabaseUnavailableError({ reason: error.reason })));
@@ -753,7 +757,7 @@ function connectDatabase(input) {
753
757
  schemaProvider: input.schemaProvider
754
758
  });
755
759
  if (dialect === null) return yield* new DatabaseUnavailableError({ reason: `Cannot tell which database "${url}" points at.\n Use a postgresql://, mysql:// or file: URL.` });
756
- const driver = dialect === "sqlite" ? isLibsqlUrl({ url: found.url }) ? yield* openLibsql(found.url, input.cwd) : yield* openSqlite(found.url, input.schemaDir) : dialect === "postgresql" ? yield* openPostgres(found.url, input.cwd) : yield* openMysql(found.url, input.cwd);
760
+ const driver = yield* openDriver(dialect, found.url, input.cwd, input.schemaDir);
757
761
  return {
758
762
  status: {
759
763
  connected: true,
@@ -890,8 +894,8 @@ function parseMapping(written) {
890
894
  const pairs = written.match(/(?:"(?:[^"]|"")*"|[^,\n])+/gu) ?? [];
891
895
  return Object.fromEntries(pairs.flatMap((pair) => {
892
896
  const groups = /^\s*(?:"(?<quoted>(?:[^"]|"")*)"|(?<bare>[^="]*?))\s*=\s*(?<member>.*?)\s*$/u.exec(pair)?.groups;
893
- const stored = groups?.quoted?.replaceAll("\"\"", "\"") ?? groups?.bare ?? "";
894
- const member = groups?.member ?? "";
897
+ const stored = groups?.["quoted"]?.replaceAll("\"\"", "\"") ?? groups?.["bare"] ?? "";
898
+ const member = groups?.["member"] ?? "";
895
899
  return stored === "" || member === "" ? [] : [[stored, member]];
896
900
  }));
897
901
  }
@@ -940,13 +944,7 @@ function fixValue(decision) {
940
944
  /** What a decision puts on the field: `nulls` fills, `invalid` says what becomes of a bad value. */
941
945
  function fieldFix(decision) {
942
946
  const value = decision.value ?? "";
943
- if (decision.kind === "column-dropped") {
944
- if (decision.choice === "move") return fixTarget(decision).field === "" ? null : { movedFrom: {
945
- model: decision.modelName,
946
- column: decision.field
947
- } };
948
- return decision.choice === "rename" && value !== "" ? { renamedFrom: decision.field } : null;
949
- }
947
+ if (decision.kind === "column-dropped") return droppedColumnFix(decision, value);
950
948
  if (decision.kind === "enum") {
951
949
  const values = parseMapping(value);
952
950
  return Object.keys(values).length === 0 ? null : { values };
@@ -954,14 +952,28 @@ function fieldFix(decision) {
954
952
  if (decision.kind === "not-null" || decision.kind === "column-added") return { nulls: fixValue(decision) };
955
953
  if (decision.kind === "column-type" || decision.kind === "column-recreated") return decision.choice === "sql" ? { convert: { sql: value } } : null;
956
954
  if (decision.kind === "table-dropped") return null;
957
- if (decision.kind === "unique") {
958
- const [, keep = "first", others = "delete"] = decision.choice.split("-");
959
- return keep === "first" || keep === "last" ? { duplicates: {
960
- keep,
961
- ...value.trim() === "" ? {} : { orderBy: value.trim() },
962
- others: others === "null" ? "null" : "delete"
963
- } } : null;
964
- }
955
+ if (decision.kind === "unique") return duplicatesFix(decision.choice, value);
956
+ return invalidFix$1(decision);
957
+ }
958
+ /** A dropped column's values moved to a related model, or the column renamed. */
959
+ function droppedColumnFix(decision, value) {
960
+ if (decision.choice === "move") return fixTarget(decision).field === "" ? null : { movedFrom: {
961
+ model: decision.modelName,
962
+ column: decision.field
963
+ } };
964
+ return decision.choice === "rename" && value !== "" ? { renamedFrom: decision.field } : null;
965
+ }
966
+ /** Which of a group of duplicates is kept, and what becomes of the others. */
967
+ function duplicatesFix(choice, value) {
968
+ const [, keep = "first", others = "delete"] = choice.split("-");
969
+ return keep === "first" || keep === "last" ? { duplicates: {
970
+ keep,
971
+ ...value.trim() === "" ? {} : { orderBy: value.trim() },
972
+ others: others === "null" ? "null" : "delete"
973
+ } } : null;
974
+ }
975
+ /** What becomes of a value the column can no longer hold. */
976
+ function invalidFix$1(decision) {
965
977
  if (decision.choice === "value" || decision.choice === "sql") return { invalid: { set: fixValue(decision) } };
966
978
  return decision.choice === "clamp" || decision.choice === "truncate" || decision.choice === "null" || decision.choice === "delete" ? { invalid: decision.choice } : null;
967
979
  }
@@ -997,7 +1009,7 @@ function modelFix(decisions) {
997
1009
  }];
998
1010
  });
999
1011
  return {
1000
- ...fields.length === 0 ? {} : { fields: Object.fromEntries([...new Set(named.map((one) => one.name))].map((name) => [name, named.filter((one) => one.name === name).reduce((merged, one) => Object.assign(merged, one.fix), {})])) },
1012
+ ...fields.length === 0 ? {} : { fields: Object.fromEntries([...Map.groupBy(named, (one) => one.name)].map(([name, ones]) => [name, ones.reduce((merged, one) => Object.assign(merged, one.fix), {})])) },
1001
1013
  ...composites.length === 0 ? {} : { unique: composites.flatMap((decision) => {
1002
1014
  const fix = fieldFix(decision);
1003
1015
  return fix?.duplicates === void 0 ? [] : [{
@@ -1016,7 +1028,7 @@ function modelFix(decisions) {
1016
1028
  */
1017
1029
  function makeDecisionModels(decisions) {
1018
1030
  const fixing = decisions.filter((decision) => decision.kind !== "table-dropped");
1019
- return Object.fromEntries([...new Set(fixing.map((decision) => fixTarget(decision).model))].map((modelName) => [modelName, modelFix(fixing.filter((decision) => fixTarget(decision).model === modelName))]));
1031
+ return Object.fromEntries([...Map.groupBy(fixing, (decision) => fixTarget(decision).model)].map(([modelName, ofModel]) => [modelName, modelFix(ofModel)]));
1020
1032
  }
1021
1033
  // src/migrate/adapter/decisions-file.ts
1022
1034
  /** Where Studio keeps what was decided on the page, beside the schema it was decided about. */
@@ -1223,14 +1235,15 @@ function sqliteCheckClauses(definition) {
1223
1235
  };
1224
1236
  if (char === "(") {
1225
1237
  const wordEnd = (at) => at > 0 && /\s/u.test(definition[at - 1] ?? "") ? wordEnd(at - 1) : at;
1226
- return state.start === null ? /\bCHECK\s*$/iu.test(definition.slice(Math.max(0, wordEnd(index) - 6), index)) ? {
1227
- ...state,
1228
- start: index + 1,
1229
- depth: 1
1230
- } : state : {
1238
+ if (state.start !== null) return {
1231
1239
  ...state,
1232
1240
  depth: state.depth + 1
1233
1241
  };
1242
+ return /\bCHECK\s*$/iu.test(definition.slice(Math.max(0, wordEnd(index) - 6), index)) ? {
1243
+ ...state,
1244
+ start: index + 1,
1245
+ depth: 1
1246
+ } : state;
1234
1247
  }
1235
1248
  if (char !== ")" || state.start === null) return state;
1236
1249
  return state.depth === 1 ? {
@@ -1332,7 +1345,7 @@ function makePostgresTables(input) {
1332
1345
  triggers: input.triggers ?? [],
1333
1346
  checks: input.checks ?? [],
1334
1347
  refSchema: (row) => catalogueText(row, "refSchema"),
1335
- enforced: (row) => row.validated === true
1348
+ enforced: (row) => row["validated"] === true
1336
1349
  });
1337
1350
  return groupsOf(input.columns, tableKey).filter((rows) => !INTERNAL_TABLES.has(catalogueText(rows[0] ?? {}, "table"))).map((rows) => {
1338
1351
  const parts = partsOf(tableKey(rows[0] ?? {}));
@@ -1361,8 +1374,8 @@ function makePostgresTables(input) {
1361
1374
  /** The MySQL tables from the rows of the three catalogue queries. */
1362
1375
  function makeMysqlTables(input) {
1363
1376
  const checks = input.escapedChecks === true ? (input.checks ?? []).map((row) => ({
1364
- table: row.table,
1365
- name: row.name,
1377
+ table: row["table"],
1378
+ name: row["name"],
1366
1379
  clause: catalogueText(row, "clause").replaceAll(/\\(?<escaped>.)/gsu, "$<escaped>")
1367
1380
  })) : input.checks ?? [];
1368
1381
  const partsOf = makeTableParts({
@@ -1401,13 +1414,13 @@ function makeMysqlTables(input) {
1401
1414
  * there; they tell which deletes the database may refuse or cascade.
1402
1415
  */
1403
1416
  function makeSqliteTable(input) {
1404
- const primaryKey = input.columns.filter((row) => Number(row.pk) > 0).toSorted((a, b) => Number(a.pk) - Number(b.pk)).map((row) => catalogueText(row, "name"));
1417
+ const primaryKey = input.columns.filter((row) => Number(row["pk"]) > 0).toSorted((a, b) => Number(a["pk"]) - Number(b["pk"])).map((row) => catalogueText(row, "name"));
1405
1418
  return {
1406
1419
  schema: null,
1407
1420
  table: input.table,
1408
1421
  columns: input.columns.map((row) => ({
1409
1422
  name: catalogueText(row, "name"),
1410
- nullable: catalogueText(row, "notnull") !== "1" && Number(row.pk) === 0,
1423
+ nullable: catalogueText(row, "notnull") !== "1" && Number(row["pk"]) === 0,
1411
1424
  dataType: catalogueText(row, "type"),
1412
1425
  columnType: null,
1413
1426
  maxLength: null,
@@ -1449,6 +1462,14 @@ function sqliteIndexStatement(index) {
1449
1462
  };
1450
1463
  }
1451
1464
  // src/migrate/adapter/introspect.ts
1465
+ /** The rows of a catalogue query that a server too old to answer it is read as having none of. */
1466
+ function rowsOrNone(driver, statement) {
1467
+ return driver.query(statement).pipe(Effect.map((result) => result.rows), Effect.orElseSucceed(() => []));
1468
+ }
1469
+ /** The columns of one SQLite index, in order. */
1470
+ function indexColumns(driver, index) {
1471
+ return driver.query(sqliteIndexStatement(index)).pipe(Effect.map((result) => result.rows.map((column) => catalogueText(column, "name"))));
1472
+ }
1452
1473
  /** One SQLite table: its columns, then the columns of each unique index that covers every row. */
1453
1474
  function introspectSqliteTable(driver, input) {
1454
1475
  const { table } = input;
@@ -1457,7 +1478,7 @@ function introspectSqliteTable(driver, input) {
1457
1478
  const columns = yield* driver.query(statements.columns);
1458
1479
  const indexes = yield* driver.query(statements.indexes);
1459
1480
  const foreignKeys = yield* driver.query(statements.foreignKeys);
1460
- const uniques = yield* Effect.forEach(indexes.rows.filter((row) => catalogueText(row, "unique") === "1" && catalogueText(row, "partial") !== "1"), (row) => driver.query(sqliteIndexStatement(catalogueText(row, "name"))).pipe(Effect.map((result) => result.rows.map((column) => catalogueText(column, "name")))));
1481
+ const uniques = yield* Effect.forEach(indexes.rows.filter((row) => catalogueText(row, "unique") === "1" && catalogueText(row, "partial") !== "1"), (row) => indexColumns(driver, catalogueText(row, "name")), { concurrency: 1 });
1461
1482
  return makeSqliteTable({
1462
1483
  table,
1463
1484
  columns: columns.rows,
@@ -1483,51 +1504,62 @@ function introspectSqliteTable(driver, input) {
1483
1504
  function introspectDatabase(input) {
1484
1505
  const { driver } = input;
1485
1506
  return Effect.gen(function* () {
1486
- if (input.dialect === "postgresql") {
1487
- const statements = postgresStatements(input.schemas);
1488
- const current = yield* driver.query(statements.current);
1489
- const [columns, enums, uniques, foreignKeys] = yield* Effect.forEach([
1490
- statements.columns,
1491
- statements.enums,
1492
- statements.uniques,
1493
- statements.foreignKeys
1494
- ], (statement) => driver.query(statement).pipe(Effect.map((result) => result.rows)));
1495
- const [triggers, checks] = yield* Effect.forEach([statements.triggers, statements.checks], (statement) => driver.query(statement).pipe(Effect.map((result) => result.rows), Effect.orElseSucceed(() => [])));
1496
- return {
1497
- defaultSchema: catalogueText(current.rows[0] ?? {}, "schema") || "public",
1498
- mariadb: false,
1499
- tables: makePostgresTables({
1500
- columns: columns ?? [],
1501
- enums: enums ?? [],
1502
- uniques: uniques ?? [],
1503
- foreignKeys: foreignKeys ?? [],
1504
- triggers: triggers ?? [],
1505
- checks: checks ?? []
1506
- })
1507
- };
1508
- }
1509
- if (input.dialect === "mysql") {
1510
- const version = yield* driver.query(MYSQL_STATEMENTS.version);
1511
- const [columns, uniques, foreignKeys] = yield* Effect.forEach([
1512
- MYSQL_STATEMENTS.columns,
1513
- MYSQL_STATEMENTS.uniques,
1514
- MYSQL_STATEMENTS.foreignKeys
1515
- ], (statement) => driver.query(statement).pipe(Effect.map((result) => result.rows)));
1516
- const mariadb = /mariadb/iu.test(catalogueText(version.rows[0] ?? {}, "version"));
1517
- const [triggers, checks] = yield* Effect.forEach([MYSQL_STATEMENTS.triggers, mariadb ? MYSQL_STATEMENTS.mariadbChecks : MYSQL_STATEMENTS.checks], (statement) => driver.query(statement).pipe(Effect.map((result) => result.rows), Effect.orElseSucceed(() => [])));
1518
- return {
1519
- defaultSchema: null,
1520
- mariadb,
1521
- tables: makeMysqlTables({
1522
- columns: columns ?? [],
1523
- uniques: uniques ?? [],
1524
- foreignKeys: foreignKeys ?? [],
1525
- triggers: triggers ?? [],
1526
- checks: checks ?? [],
1527
- escapedChecks: !mariadb
1528
- })
1529
- };
1530
- }
1507
+ if (input.dialect === "postgresql") return yield* introspectPostgres(driver, input.schemas);
1508
+ if (input.dialect === "mysql") return yield* introspectMysql(driver);
1509
+ return yield* introspectSqlite(driver);
1510
+ });
1511
+ }
1512
+ function introspectPostgres(driver, schemas) {
1513
+ return Effect.gen(function* () {
1514
+ const statements = postgresStatements(schemas);
1515
+ const current = yield* driver.query(statements.current);
1516
+ const [columns, enums, uniques, foreignKeys] = yield* Effect.forEach([
1517
+ statements.columns,
1518
+ statements.enums,
1519
+ statements.uniques,
1520
+ statements.foreignKeys
1521
+ ], (statement) => driver.query(statement).pipe(Effect.map((result) => result.rows)), { concurrency: 1 });
1522
+ const [triggers, checks] = yield* Effect.forEach([statements.triggers, statements.checks], (statement) => rowsOrNone(driver, statement), { concurrency: 1 });
1523
+ return {
1524
+ defaultSchema: catalogueText(current.rows[0] ?? {}, "schema") || "public",
1525
+ mariadb: false,
1526
+ tables: makePostgresTables({
1527
+ columns: columns ?? [],
1528
+ enums: enums ?? [],
1529
+ uniques: uniques ?? [],
1530
+ foreignKeys: foreignKeys ?? [],
1531
+ triggers: triggers ?? [],
1532
+ checks: checks ?? []
1533
+ })
1534
+ };
1535
+ });
1536
+ }
1537
+ function introspectMysql(driver) {
1538
+ return Effect.gen(function* () {
1539
+ const version = yield* driver.query(MYSQL_STATEMENTS.version);
1540
+ const [columns, uniques, foreignKeys] = yield* Effect.forEach([
1541
+ MYSQL_STATEMENTS.columns,
1542
+ MYSQL_STATEMENTS.uniques,
1543
+ MYSQL_STATEMENTS.foreignKeys
1544
+ ], (statement) => driver.query(statement).pipe(Effect.map((result) => result.rows)), { concurrency: 1 });
1545
+ const mariadb = /mariadb/iu.test(catalogueText(version.rows[0] ?? {}, "version"));
1546
+ const [triggers, checks] = yield* Effect.forEach([MYSQL_STATEMENTS.triggers, mariadb ? MYSQL_STATEMENTS.mariadbChecks : MYSQL_STATEMENTS.checks], (statement) => rowsOrNone(driver, statement), { concurrency: 1 });
1547
+ return {
1548
+ defaultSchema: null,
1549
+ mariadb,
1550
+ tables: makeMysqlTables({
1551
+ columns: columns ?? [],
1552
+ uniques: uniques ?? [],
1553
+ foreignKeys: foreignKeys ?? [],
1554
+ triggers: triggers ?? [],
1555
+ checks: checks ?? [],
1556
+ escapedChecks: !mariadb
1557
+ })
1558
+ };
1559
+ });
1560
+ }
1561
+ function introspectSqlite(driver) {
1562
+ return Effect.gen(function* () {
1531
1563
  const names = (yield* driver.query(SQLITE_TABLES)).rows.map((row) => catalogueText(row, "table")).filter((name) => !INTERNAL_TABLES.has(name));
1532
1564
  const triggers = yield* driver.query(SQLITE_EXTRAS.triggers);
1533
1565
  const definitions = yield* driver.query(SQLITE_EXTRAS.definitions);
@@ -1538,7 +1570,7 @@ function introspectDatabase(input) {
1538
1570
  table,
1539
1571
  triggers: triggers.rows.filter((row) => catalogueText(row, "table") === table).map((row) => catalogueText(row, "name")),
1540
1572
  definition: catalogueText(definitions.rows.find((row) => catalogueText(row, "table") === table) ?? {}, "sql")
1541
- }))
1573
+ }), { concurrency: 1 })
1542
1574
  };
1543
1575
  });
1544
1576
  }
@@ -1867,6 +1899,30 @@ function makeConversions(input) {
1867
1899
  columnType: existing.columnType
1868
1900
  });
1869
1901
  if (expected === null || actual === null) return [];
1902
+ const kit = conversionKit(input, expected, actual);
1903
+ if (dialect === "sqlite") return sqliteConversions(kit);
1904
+ if (dialect === "postgresql") return input.cockroach === true ? cockroachConversions(kit) : postgresConversions(kit);
1905
+ return mysqlConversions(kit);
1906
+ }
1907
+ /**
1908
+ * The value as the database rounds it: a float by its shortest decimal form, as both
1909
+ * PostgreSQL's numeric cast and MySQL's DECIMAL conversion read it.
1910
+ *
1911
+ * @example
1912
+ * ```sql
1913
+ * -- PostgreSQL
1914
+ * CAST("price" AS NUMERIC)
1915
+ * -- MySQL, a float
1916
+ * CAST(CAST(`price` AS CHAR) AS DECIMAL(65, 30))
1917
+ * ```
1918
+ */
1919
+ function exactValue(dialect, actual, name) {
1920
+ if (dialect === "postgresql") return `CAST(${name} AS NUMERIC)`;
1921
+ return actual === "float" ? `CAST(CAST(${name} AS CHAR) AS DECIMAL(65, 30))` : name;
1922
+ }
1923
+ /** What every dialect's reading of a type change is made from: the column, and its entries. */
1924
+ function conversionKit(input, expected, actual) {
1925
+ const { dialect, column, existing } = input;
1870
1926
  const name = quoteIdentifier(dialect, column.column);
1871
1927
  const from = existing.columnType ?? existing.dataType;
1872
1928
  const changed = entry({
@@ -1926,7 +1982,7 @@ function makeConversions(input) {
1926
1982
  hint: "The conversion goes through and the value changes: round them yourself first if the rule matters.",
1927
1983
  condition
1928
1984
  });
1929
- const exact = dialect === "postgresql" ? `CAST(${name} AS NUMERIC)` : actual === "float" ? `CAST(CAST(${name} AS CHAR) AS DECIMAL(65, 30))` : name;
1985
+ const exact = exactValue(dialect, actual, name);
1930
1986
  const fractional = actual === "float" || actual === "decimal";
1931
1987
  const range = targetRange(dialect, column);
1932
1988
  const length = targetLength(dialect, column);
@@ -1966,74 +2022,164 @@ function makeConversions(input) {
1966
2022
  const cast = dialect === "postgresql" ? `CAST(${name} AS ${existing.dataType === "timestamp with time zone" ? "TIMESTAMPTZ" : "TIMESTAMP"}(${digits}))` : `CAST(${name} AS DATETIME(${digits}))`;
1967
2023
  return [rounded(`values with more than ${digits} digits of fractional seconds`, `${name} <> ${cast}`)];
1968
2024
  };
1969
- if (dialect === "sqlite") return expected === actual || expected === "enum" && actual === "string" || expected === "bigint" && actual === "int" ? [] : [changed];
1970
- if (dialect === "postgresql" && input.cockroach === true) {
1971
- if (column.kind === "enum") return existing.enumValues === null ? [recreated] : [];
1972
- const sameLength = (length ?? null) === (existing.maxLength ?? null);
1973
- if (expected === "string") {
1974
- const special = column.nativeType === null ? void 0 : POSTGRES_STRING_NATIVES[column.nativeType[0]];
1975
- if (special !== void 0) return existing.dataType === special ? [] : [recreated];
1976
- if (actual === "string" && POSTGRES_TEXT.has(existing.dataType)) return sameLength ? [] : [recreated];
1977
- return existing.dataType === "integer" && length === null ? [] : [recreated];
1978
- }
1979
- if (range !== null && NUMERIC.has(actual)) {
1980
- if (held !== null && held.min === range.min && held.max === range.max) return [];
1981
- return existing.dataType === "bigint" && range.max === 2147483647n ? [outOfRange(name, integerBounds(range))] : [recreated];
1982
- }
1983
- if (expected === "decimal" && actual === "decimal") return decimal !== null && existing.precision === decimal.precision && existing.scale === decimal.scale ? [] : [recreated];
1984
- if (expected === "datetime" && actual === "datetime") {
1985
- const date = column.nativeType?.[0] === "Date";
1986
- const digits = targetSeconds(column);
1987
- return date === (existing.dataType === "date") && (date || digits === (existing.datetimePrecision ?? 6)) ? [] : [recreated];
1988
- }
1989
- return expected === actual ? [] : [recreated];
1990
- }
1991
- if (dialect === "postgresql") {
1992
- if (column.kind === "enum") return existing.enumValues === null ? [recreated] : [];
1993
- if (expected === "string") {
1994
- const special = column.nativeType === null ? void 0 : POSTGRES_STRING_NATIVES[column.nativeType[0]];
1995
- if (special !== void 0) return existing.dataType === special ? [] : [recreated];
1996
- if (actual === "enum") return [recreated];
1997
- if (length === null) return [];
1998
- if (!POSTGRES_TEXT.has(existing.dataType)) return [recreated];
1999
- return existing.maxLength !== null && existing.maxLength <= length ? [] : [tooLong(length)];
2000
- }
2001
- if (NUMERIC.has(expected) && NUMERIC.has(actual)) return expected === "decimal" ? toDecimal() : toInteger();
2002
- if (expected === "datetime" && actual === "datetime") return toDateTime();
2003
- return expected === actual ? [] : [recreated];
2004
- }
2025
+ return {
2026
+ input,
2027
+ dialect,
2028
+ column,
2029
+ existing,
2030
+ expected,
2031
+ actual,
2032
+ name,
2033
+ /** The value read as MySQL's widest DECIMAL. */
2034
+ text: `CAST(${name} AS DECIMAL(65, 30))`,
2035
+ changed,
2036
+ recreated,
2037
+ tooLong,
2038
+ outOfRange,
2039
+ notConvertible,
2040
+ rounded,
2041
+ range,
2042
+ length,
2043
+ decimal,
2044
+ held,
2045
+ toInteger,
2046
+ toDecimal,
2047
+ toDateTime
2048
+ };
2049
+ }
2050
+ /** SQLite copies the values into the new table as they are. */
2051
+ function sqliteConversions(kit) {
2052
+ const { expected, actual, changed } = kit;
2053
+ return expected === actual || expected === "enum" && actual === "string" || expected === "bigint" && actual === "int" ? [] : [changed];
2054
+ }
2055
+ /** The native type a PostgreSQL string field names that is not text (`@db.Uuid`), if any. */
2056
+ function postgresStringNative(column) {
2057
+ return column.nativeType === null ? void 0 : POSTGRES_STRING_NATIVES[column.nativeType[0]];
2058
+ }
2059
+ /**
2060
+ * CockroachDB has Prisma drop and add a column again for nearly every type change: only a BIGINT
2061
+ * narrowed to INT4 and an INT4 turned into an unbounded STRING are converted in place.
2062
+ */
2063
+ function cockroachConversions(kit) {
2064
+ const { column, existing, expected, actual, recreated, range } = kit;
2065
+ if (column.kind === "enum") return existing.enumValues === null ? [recreated] : [];
2066
+ if (expected === "string") return cockroachToString(kit);
2067
+ if (range !== null && NUMERIC.has(actual)) return cockroachToInteger(kit, range);
2068
+ if (expected === "decimal" && actual === "decimal") return cockroachToDecimal(kit);
2069
+ if (expected === "datetime" && actual === "datetime") return cockroachToDateTime(kit);
2070
+ return expected === actual ? [] : [recreated];
2071
+ }
2072
+ function cockroachToString(kit) {
2073
+ const { column, existing, actual, recreated, length } = kit;
2074
+ const special = postgresStringNative(column);
2075
+ if (special !== void 0) return existing.dataType === special ? [] : [recreated];
2076
+ if (actual === "string" && POSTGRES_TEXT.has(existing.dataType)) return (length ?? null) === (existing.maxLength ?? null) ? [] : [recreated];
2077
+ return existing.dataType === "integer" && length === null ? [] : [recreated];
2078
+ }
2079
+ function cockroachToInteger(kit, range) {
2080
+ const { existing, name, recreated, outOfRange, held } = kit;
2081
+ if (held !== null && held.min === range.min && held.max === range.max) return [];
2082
+ return existing.dataType === "bigint" && range.max === 2147483647n ? [outOfRange(name, integerBounds(range))] : [recreated];
2083
+ }
2084
+ function cockroachToDecimal(kit) {
2085
+ const { existing, recreated, decimal } = kit;
2086
+ return decimal !== null && existing.precision === decimal.precision && existing.scale === decimal.scale ? [] : [recreated];
2087
+ }
2088
+ function cockroachToDateTime(kit) {
2089
+ const { column, existing, recreated } = kit;
2090
+ const date = column.nativeType?.[0] === "Date";
2091
+ const digits = targetSeconds(column);
2092
+ return date === (existing.dataType === "date") && (date || digits === (existing.datetimePrecision ?? 6)) ? [] : [recreated];
2093
+ }
2094
+ /** PostgreSQL changes the type in place with a cast where it has one, and re-adds the column where not. */
2095
+ function postgresConversions(kit) {
2096
+ const { column, existing, expected, actual, recreated } = kit;
2097
+ if (column.kind === "enum") return existing.enumValues === null ? [recreated] : [];
2098
+ if (expected === "string") return postgresToString(kit);
2099
+ if (NUMERIC.has(expected) && NUMERIC.has(actual)) return expected === "decimal" ? kit.toDecimal() : kit.toInteger();
2100
+ if (expected === "datetime" && actual === "datetime") return kit.toDateTime();
2101
+ return expected === actual ? [] : [recreated];
2102
+ }
2103
+ function postgresToString(kit) {
2104
+ const { column, existing, actual, recreated, length, tooLong } = kit;
2105
+ const special = postgresStringNative(column);
2106
+ if (special !== void 0) return existing.dataType === special ? [] : [recreated];
2107
+ if (actual === "enum") return [recreated];
2108
+ if (length === null) return [];
2109
+ if (!POSTGRES_TEXT.has(existing.dataType)) return [recreated];
2110
+ return existing.maxLength !== null && existing.maxLength <= length ? [] : [tooLong(length)];
2111
+ }
2112
+ const MYSQL_STRING_SOURCES = /* @__PURE__ */ new Set([
2113
+ "string",
2114
+ "json",
2115
+ "bytes"
2116
+ ]);
2117
+ /** MySQL converts the column in place with MODIFY, and strict mode refuses the value that does not fit. */
2118
+ function mysqlConversions(kit) {
2119
+ const { column, existing, expected, actual, range, length, tooLong } = kit;
2005
2120
  if (column.kind === "enum") return [];
2006
2121
  if (expected === "string") {
2007
- if (length === null || ![
2008
- "string",
2009
- "json",
2010
- "bytes"
2011
- ].includes(actual)) return [];
2122
+ if (length === null || !MYSQL_STRING_SOURCES.has(actual)) return [];
2012
2123
  return existing.maxLength !== null && existing.maxLength <= length ? [] : [tooLong(length)];
2013
2124
  }
2014
- const text = `CAST(${name} AS DECIMAL(65, 30))`;
2015
- if (range !== null) {
2016
- if (actual === "string") {
2017
- const pattern = input.mariadb ? MARIADB_INTEGER : MYSQL_ROUNDED_INTEGER;
2018
- const value = input.mariadb ? `CAST(${name} AS DECIMAL(65, 0))` : `ROUND(${text})`;
2019
- return [notConvertible(`${name} NOT REGEXP '${pattern}' OR ${value} < ${String(range.min)} OR ${value} > ${String(range.max)}`), ...input.mariadb ? [] : [rounded("values with a fraction, rounded to whole numbers", `${name} REGEXP '${pattern}' AND ${text} <> ROUND(${text})`)]];
2020
- }
2021
- if (NUMERIC.has(actual) || actual === "boolean") return toInteger();
2022
- return [changed];
2125
+ if (range !== null) return mysqlToInteger(kit, range);
2126
+ if (expected === "decimal" || expected === "float") return mysqlToNumber(kit);
2127
+ return mysqlToOther(kit);
2128
+ }
2129
+ /**
2130
+ * MySQL to an integer.
2131
+ *
2132
+ * @example
2133
+ * ```sql
2134
+ * `views` IS NOT NULL AND (`views` NOT REGEXP '^[[:space:]]*[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]*)?[[:space:]]*$'
2135
+ * OR ROUND(CAST(`views` AS DECIMAL(65, 30))) < -2147483648
2136
+ * OR ROUND(CAST(`views` AS DECIMAL(65, 30))) > 2147483647)
2137
+ * ```
2138
+ */
2139
+ function mysqlToInteger(kit, range) {
2140
+ const { input, actual, name, text, notConvertible, rounded, changed } = kit;
2141
+ if (actual === "string") {
2142
+ const pattern = input.mariadb ? MARIADB_INTEGER : MYSQL_ROUNDED_INTEGER;
2143
+ const value = input.mariadb ? `CAST(${name} AS DECIMAL(65, 0))` : `ROUND(${text})`;
2144
+ return [notConvertible(`${name} NOT REGEXP '${pattern}' OR ${value} < ${String(range.min)} OR ${value} > ${String(range.max)}`), ...input.mariadb ? [] : [rounded("values with a fraction, rounded to whole numbers", `${name} REGEXP '${pattern}' AND ${text} <> ROUND(${text})`)]];
2023
2145
  }
2024
- if (expected === "decimal" || expected === "float") {
2025
- if (actual === "string" && expected === "decimal" && decimal !== null) {
2026
- const bounds = decimalBounds(decimal.precision, decimal.scale);
2027
- const value = `ROUND(${text}, ${decimal.scale})`;
2028
- return [notConvertible(`${name} NOT REGEXP '${MYSQL_NUMBER}' OR ${value} < ${bounds.min} OR ${value} > ${bounds.max}`), rounded(`values rounded to ${decimal.scale} decimal places`, `${name} REGEXP '${MYSQL_NUMBER}' AND ${text} <> ${value}`)];
2029
- }
2030
- if (actual === "string") return [notConvertible(`${name} NOT REGEXP '${MYSQL_NUMBER}'`)];
2031
- if (expected === "decimal" && (NUMERIC.has(actual) || actual === "boolean")) return toDecimal();
2032
- return NUMERIC.has(actual) || actual === "boolean" ? [] : [changed];
2146
+ if (NUMERIC.has(actual) || actual === "boolean") return kit.toInteger();
2147
+ return [changed];
2148
+ }
2149
+ /**
2150
+ * MySQL to a decimal or a float.
2151
+ *
2152
+ * @example
2153
+ * ```sql
2154
+ * `price` IS NOT NULL AND (`price` NOT REGEXP '^[[:space:]]*[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?[[:space:]]*$'
2155
+ * OR ROUND(CAST(`price` AS DECIMAL(65, 30)), 2) < -999.99 OR ROUND(CAST(`price` AS DECIMAL(65, 30)), 2) > 999.99)
2156
+ * ```
2157
+ */
2158
+ function mysqlToNumber(kit) {
2159
+ const { expected, actual, name, text, decimal, notConvertible, rounded, changed } = kit;
2160
+ if (actual === "string" && expected === "decimal" && decimal !== null) {
2161
+ const bounds = decimalBounds(decimal.precision, decimal.scale);
2162
+ const value = `ROUND(${text}, ${decimal.scale})`;
2163
+ return [notConvertible(`${name} NOT REGEXP '${MYSQL_NUMBER}' OR ${value} < ${bounds.min} OR ${value} > ${bounds.max}`), rounded(`values rounded to ${decimal.scale} decimal places`, `${name} REGEXP '${MYSQL_NUMBER}' AND ${text} <> ${value}`)];
2033
2164
  }
2165
+ if (actual === "string") return [notConvertible(`${name} NOT REGEXP '${MYSQL_NUMBER}'`)];
2166
+ if (expected === "decimal" && (NUMERIC.has(actual) || actual === "boolean")) return kit.toDecimal();
2167
+ return NUMERIC.has(actual) || actual === "boolean" ? [] : [changed];
2168
+ }
2169
+ /**
2170
+ * MySQL to a date and time, JSON or bytes.
2171
+ *
2172
+ * @example
2173
+ * ```sql
2174
+ * `at` IS NOT NULL AND (CAST(`at` AS DATETIME(3)) IS NULL)
2175
+ * `data` IS NOT NULL AND (JSON_VALID(`data`) = 0)
2176
+ * ```
2177
+ */
2178
+ function mysqlToOther(kit) {
2179
+ const { expected, actual, name, notConvertible, changed } = kit;
2034
2180
  if (expected === "datetime") {
2035
2181
  if (actual === "string") return [notConvertible(`CAST(${name} AS DATETIME(3)) IS NULL`)];
2036
- return actual === "datetime" ? toDateTime() : [changed];
2182
+ return actual === "datetime" ? kit.toDateTime() : [changed];
2037
2183
  }
2038
2184
  if (expected === "json") {
2039
2185
  if (actual === "string") return [notConvertible(`JSON_VALID(${name}) = 0`)];
@@ -2043,6 +2189,48 @@ function makeConversions(input) {
2043
2189
  return expected === actual ? [] : [changed];
2044
2190
  }
2045
2191
  // src/migrate/domain/dialect.ts
2192
+ function flavourOf(dialect, cockroach) {
2193
+ if (dialect !== "postgresql") return dialect;
2194
+ return cockroach ? "cockroach" : "postgresql";
2195
+ }
2196
+ const UUID = {
2197
+ mysql: "UUID()",
2198
+ sqlite: "lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || substr(hex(randomblob(2)), 2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))",
2199
+ cockroach: "gen_random_uuid()::STRING",
2200
+ postgresql: "gen_random_uuid()::text"
2201
+ };
2202
+ const RANDOM_ID = {
2203
+ mysql: "REPLACE(UUID(), '-', '')",
2204
+ sqlite: "lower(hex(randomblob(12)))",
2205
+ cockroach: "md5(random()::STRING || now()::STRING)",
2206
+ postgresql: "md5(random()::text || clock_timestamp()::text)"
2207
+ };
2208
+ const NOW = {
2209
+ mysql: "CURRENT_TIMESTAMP(3)",
2210
+ sqlite: "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')",
2211
+ postgresql: "CURRENT_TIMESTAMP"
2212
+ };
2213
+ /** The type text is cast to for each Prisma number type. */
2214
+ const NUMBER_TYPES = {
2215
+ mysql: /* @__PURE__ */ new Map([
2216
+ ["Int", "SIGNED"],
2217
+ ["BigInt", "SIGNED"],
2218
+ ["Float", "DOUBLE"],
2219
+ ["Decimal", "DECIMAL(65, 30)"]
2220
+ ]),
2221
+ sqlite: /* @__PURE__ */ new Map([
2222
+ ["Int", "INTEGER"],
2223
+ ["BigInt", "INTEGER"],
2224
+ ["Float", "REAL"],
2225
+ ["Decimal", "REAL"]
2226
+ ]),
2227
+ postgresql: /* @__PURE__ */ new Map([
2228
+ ["Int", "INTEGER"],
2229
+ ["BigInt", "BIGINT"],
2230
+ ["Float", "DOUBLE PRECISION"],
2231
+ ["Decimal", "DECIMAL(65, 30)"]
2232
+ ])
2233
+ };
2046
2234
  /**
2047
2235
  * How each dialect writes what a suggestion or a fix needs of it.
2048
2236
  *
@@ -2071,34 +2259,20 @@ function makeConversions(input) {
2071
2259
  */
2072
2260
  function sqlOf(dialect, cockroach) {
2073
2261
  const q = (name) => quoteIdentifier(dialect, name);
2262
+ const flavour = flavourOf(dialect, cockroach);
2074
2263
  return {
2075
2264
  q,
2076
2265
  /** A text prefix before the key of the row: `'slug-' || "id"`. */
2077
- prefixed: (prefix, column) => dialect === "mysql" ? `CONCAT('${prefix}', ${q(column)})` : cockroach ? `'${prefix}' || ${q(column)}::STRING` : `'${prefix}' || ${q(column)}`,
2078
- uuid: dialect === "mysql" ? "UUID()" : dialect === "sqlite" ? "lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || substr(hex(randomblob(2)), 2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))" : cockroach ? "gen_random_uuid()::STRING" : "gen_random_uuid()::text",
2079
- randomId: dialect === "mysql" ? "REPLACE(UUID(), '-', '')" : dialect === "sqlite" ? "lower(hex(randomblob(12)))" : cockroach ? "md5(random()::STRING || now()::STRING)" : "md5(random()::text || clock_timestamp()::text)",
2080
- now: dialect === "mysql" ? "CURRENT_TIMESTAMP(3)" : dialect === "sqlite" ? "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')" : "CURRENT_TIMESTAMP",
2266
+ prefixed: (prefix, column) => dialect === "mysql" ? `CONCAT('${prefix}', ${q(column)})` : `'${prefix}' || ${q(column)}${cockroach ? "::STRING" : ""}`,
2267
+ uuid: UUID[flavour],
2268
+ randomId: RANDOM_ID[flavour],
2269
+ now: NOW[dialect],
2081
2270
  falsy: dialect === "sqlite" ? "0" : "FALSE",
2082
2271
  /** The smallest key of the table a foreign key points at: a row that is there. */
2083
2272
  firstKey: (table, schema, column) => `(SELECT MIN(${q(column)}) FROM ${schema === null ? "" : `${q(schema)}.`}${q(table)})`,
2084
2273
  /** Text read as a number: blanks trimmed, an empty string as NULL. */
2085
2274
  number: (column, type) => {
2086
- const target = dialect === "mysql" ? {
2087
- Int: "SIGNED",
2088
- BigInt: "SIGNED",
2089
- Float: "DOUBLE",
2090
- Decimal: "DECIMAL(65, 30)"
2091
- }[type] : dialect === "sqlite" ? {
2092
- Int: "INTEGER",
2093
- BigInt: "INTEGER",
2094
- Float: "REAL",
2095
- Decimal: "REAL"
2096
- }[type] : {
2097
- Int: "INTEGER",
2098
- BigInt: "BIGINT",
2099
- Float: "DOUBLE PRECISION",
2100
- Decimal: "DECIMAL(65, 30)"
2101
- }[type];
2275
+ const target = NUMBER_TYPES[dialect].get(type);
2102
2276
  return target === void 0 ? null : `CAST(NULLIF(TRIM(${q(column)}), '') AS ${target})`;
2103
2277
  }
2104
2278
  };
@@ -2138,86 +2312,39 @@ function hasColumn(table, name) {
2138
2312
  * ```
2139
2313
  */
2140
2314
  function resolveMoves(context, models) {
2141
- const { dialect, keyOf, q, actualByKey } = context;
2142
- const [moveErrors, moved] = separate(context.expected.flatMap((target) => Object.entries(models?.[target.model]?.fields ?? {}).flatMap(([field, fix]) => fix.movedFrom === void 0 ? [] : [{
2315
+ const { dialect, q } = context;
2316
+ const moveRequests = context.expected.flatMap((target) => Object.entries(models?.[target.model]?.fields ?? {}).flatMap(([field, fix]) => fix.movedFrom === void 0 ? [] : [{
2143
2317
  target,
2144
2318
  field,
2145
2319
  from: fix.movedFrom
2146
- }])).map(({ target, field, from }) => {
2147
- const path = `${target.model}.${field}`;
2148
- const column = target.columns.find((c) => c.field === field);
2149
- const targetActual = actualByKey.get(keyOf(target));
2150
- const source = context.expected.find((t) => t.model === from.model);
2151
- const sourceActual = source === void 0 ? void 0 : actualByKey.get(keyOf(source));
2152
- const child = target.foreignKeys.find((fk) => fk.toModel === from.model && oneColumn(fk));
2153
- const parent = targetActual === void 0 ? void 0 : source?.foreignKeys.find((fk) => fk.toModel === target.model && oneColumn(fk));
2154
- const link = child !== void 0 ? {
2155
- key: child.toColumns[0] ?? "",
2156
- match: child.fromColumns[0] ?? ""
2157
- } : parent !== void 0 ? {
2158
- key: parent.fromColumns[0] ?? "",
2159
- match: parent.toColumns[0] ?? ""
2160
- } : null;
2161
- const errors = column === void 0 ? targetActual === void 0 ? [`${path}: ${target.model} has no field ${field}.`] : [] : source === void 0 || sourceActual === void 0 ? [`${path}: the database has no table of ${from.model} to move ${from.column} from.`] : !hasColumn(sourceActual, from.column) ? [`${path}: ${sourceActual.table} has no column ${from.column}.`] : link === null ? [`${path}: ${target.model} and ${from.model} are not related by a foreign key over one column, so no row of ${target.model} can be told which value of ${from.model}.${from.column} is its own.`] : !hasColumn(sourceActual, link.key) || targetActual !== void 0 && !hasColumn(targetActual, link.match) ? [`${path}: the relation between ${target.model} and ${from.model} is added by this migration; relate them in a migration before the one that moves ${from.column}.`] : [];
2162
- if (errors.length > 0 || column === void 0 || source === void 0 || sourceActual === void 0 || link === null) return {
2163
- refused: true,
2164
- reason: errors
2165
- };
2166
- const named = `hk_move_${sourceActual.table}_${from.column}`.replaceAll(/\W/gu, "_");
2167
- const holdingName = named.length <= 60 ? named : `${named.slice(0, 51)}_${Array.from({ length: named.length }, (_, index) => named.codePointAt(index) ?? 0).reduce((hash, code) => (hash * 31 + code) % 4294967291, 7).toString(16).padStart(8, "0")}`;
2168
- if (context.actual.some((table) => table.table === holdingName)) return {
2169
- refused: true,
2170
- reason: [`${path}: the database has a table ${holdingName}, left by a plan that did not finish. It holds the values of ${from.model}.${from.column} as they were then: check that ${sourceActual.table}.${from.column} still has them, then drop ${holdingName} and run the check again.`]
2171
- };
2172
- const holding = q(holdingName);
2173
- const several = child === void 0;
2174
- const orderBy = source.primaryKey.every((c) => hasColumn(sourceActual, c)) ? source.primaryKey : [];
2175
- const ordered = [...orderBy.map((_, index) => q(`hk_order_${index}`)), q("hk_value")].join(", ");
2176
- return {
2177
- refused: false,
2178
- value: {
2179
- path,
2180
- target,
2181
- created: targetActual === void 0,
2182
- column,
2183
- source,
2184
- sourceActual,
2185
- from,
2186
- link,
2187
- holding,
2188
- /** Whether several rows of the source can point at one row of the target. */
2189
- several,
2190
- /** The columns of the source the kept values are read with: the key, the value, its primary key. */
2191
- kept: [
2192
- `${q(link.key)} AS ${q("hk_key")}`,
2193
- `${q(from.column)} AS ${q("hk_value")}`,
2194
- ...orderBy.map((c, index) => `${q(c)} AS ${q(`hk_order_${index}`)}`)
2195
- ].join(", "),
2196
- /** Which of the kept values a row takes, read from `source`: the holding table, or the rows in the check. */
2197
- valueFrom: (kept) => `(SELECT ${q("hk_value")} FROM ${kept} WHERE ${q("hk_key")} = ${q(link.match)} AND ${q("hk_value")} IS NOT NULL ORDER BY ${ordered} LIMIT 1)`
2198
- }
2199
- };
2200
- }));
2320
+ }]));
2321
+ const sourceByModel = new Map(context.expected.toReversed().map((t) => [t.model, t]));
2322
+ const tableNames = new Set(context.actual.map((table) => table.table));
2323
+ const [moveErrors, moved] = separate(moveRequests.map((request) => resolveMove(context, request, sourceByModel, tableNames)));
2201
2324
  const createdTargets = [...new Set(moved.filter((m) => m.created).map((m) => m.target))];
2325
+ const movedInto = Map.groupBy(moved, (m) => m.target);
2202
2326
  const createdErrors = createdTargets.flatMap((target) => {
2203
- const into = moved.filter((m) => m.target === target);
2327
+ const into = movedInto.get(target) ?? [];
2204
2328
  const [first] = into;
2205
2329
  if (first === void 0) return [];
2206
- return into.some((m) => m.source !== first.source || m.link.match !== first.link.match) ? [`${target.model}: the migration creates ${target.table}, and its rows can be made from the values of one related table only.`] : target.columns.filter((c) => c.required && !c.databaseDefault && !c.updatedAt && ![
2330
+ const mixed = into.some((m) => m.source !== first.source || m.link.match !== first.link.match);
2331
+ const filled = new Set(into.map((m) => m.column.column));
2332
+ return mixed ? [`${target.model}: the migration creates ${target.table}, and its rows can be made from the values of one related table only.`] : target.columns.filter((c) => c.required && !c.databaseDefault && !c.updatedAt && ![
2207
2333
  "uuid",
2208
2334
  "cuid",
2209
2335
  "nanoid",
2210
2336
  "ulid"
2211
- ].includes(c.defaultFunction ?? "") && c.column !== first.link.match && !into.some((m) => m.column.column === c.column)).map((c) => `${target.model}.${c.field}: the migration creates ${target.table}, and ${c.field} is required with no default to make its rows with.`);
2337
+ ].includes(c.defaultFunction ?? "") && c.column !== first.link.match && !filled.has(c.column)).map((c) => `${target.model}.${c.field}: the migration creates ${target.table}, and ${c.field} is required with no default to make its rows with.`);
2212
2338
  });
2213
2339
  const afterMigration = [...createdTargets.flatMap((target) => {
2214
- const into = moved.filter((m) => m.target === target);
2340
+ const into = movedInto.get(target) ?? [];
2215
2341
  const [first] = into;
2216
2342
  if (first === void 0) return [];
2343
+ const filled = new Set(into.map((m) => m.column.column));
2217
2344
  const sql = sqlOf(dialect, false);
2218
2345
  const alias = (index) => q(`hk_${index}`);
2219
2346
  const generated = target.columns.flatMap((c) => {
2220
- if (!c.required || c.databaseDefault || c.column === first.link.match || into.some((m) => m.column.column === c.column)) return [];
2347
+ if (!c.required || c.databaseDefault || c.column === first.link.match || filled.has(c.column)) return [];
2221
2348
  if (c.updatedAt) return [{
2222
2349
  column: c.column,
2223
2350
  sql: sql.now
@@ -2256,6 +2383,98 @@ function resolveMoves(context, models) {
2256
2383
  after: afterMigration
2257
2384
  };
2258
2385
  }
2386
+ /** How the target's rows find their source rows: the key read from the source, and what it matches. */
2387
+ function linkOf$1(child, parent) {
2388
+ if (child !== void 0) return {
2389
+ key: child.toColumns[0] ?? "",
2390
+ match: child.fromColumns[0] ?? ""
2391
+ };
2392
+ if (parent !== void 0) return {
2393
+ key: parent.fromColumns[0] ?? "",
2394
+ match: parent.toColumns[0] ?? ""
2395
+ };
2396
+ return null;
2397
+ }
2398
+ /** Why a move cannot be made, read in order: the first thing missing is the one reported. */
2399
+ function whyNotMovable(move) {
2400
+ const { path, target, field, from, column, targetActual, source, sourceActual, link } = move;
2401
+ if (column === void 0) return targetActual === void 0 ? [`${path}: ${target.model} has no field ${field}.`] : [];
2402
+ if (source === void 0 || sourceActual === void 0) return [`${path}: the database has no table of ${from.model} to move ${from.column} from.`];
2403
+ if (!hasColumn(sourceActual, from.column)) return [`${path}: ${sourceActual.table} has no column ${from.column}.`];
2404
+ if (link === null) return [`${path}: ${target.model} and ${from.model} are not related by a foreign key over one column, so no row of ${target.model} can be told which value of ${from.model}.${from.column} is its own.`];
2405
+ if (!hasColumn(sourceActual, link.key) || targetActual !== void 0 && !hasColumn(targetActual, link.match)) return [`${path}: the relation between ${target.model} and ${from.model} is added by this migration; relate them in a migration before the one that moves ${from.column}.`];
2406
+ return [];
2407
+ }
2408
+ /**
2409
+ * The table a moved column's values are kept in. PostgreSQL cuts a name at 63 bytes without
2410
+ * saying so, and MySQL refuses one over 64 characters: a long one keeps its start and ends in a
2411
+ * number made of the whole of it.
2412
+ */
2413
+ function holdingTableName(sourceTable, column) {
2414
+ const named = `hk_move_${sourceTable}_${column}`.replaceAll(/\W/gu, "_");
2415
+ if (named.length <= 60) return named;
2416
+ return `${named.slice(0, 51)}_${Array.from({ length: named.length }, (_, index) => named.codePointAt(index) ?? 0).reduce((hash, code) => (hash * 31 + code) % 4294967291, 7).toString(16).padStart(8, "0")}`;
2417
+ }
2418
+ /** One column moved to a related model, resolved against the schema and the database. */
2419
+ function resolveMove(context, request, sourceByModel, tableNames) {
2420
+ const { keyOf, q, actualByKey } = context;
2421
+ const { target, field, from } = request;
2422
+ const path = `${target.model}.${field}`;
2423
+ const column = target.columns.find((c) => c.field === field);
2424
+ const targetActual = actualByKey.get(keyOf(target));
2425
+ const source = sourceByModel.get(from.model);
2426
+ const sourceActual = source === void 0 ? void 0 : actualByKey.get(keyOf(source));
2427
+ const child = target.foreignKeys.find((fk) => fk.toModel === from.model && oneColumn(fk));
2428
+ const link = linkOf$1(child, targetActual === void 0 ? void 0 : source?.foreignKeys.find((fk) => fk.toModel === target.model && oneColumn(fk)));
2429
+ const errors = whyNotMovable({
2430
+ path,
2431
+ target,
2432
+ field,
2433
+ from,
2434
+ column,
2435
+ targetActual,
2436
+ source,
2437
+ sourceActual,
2438
+ link
2439
+ });
2440
+ if (errors.length > 0 || column === void 0 || source === void 0 || sourceActual === void 0 || link === null) return {
2441
+ refused: true,
2442
+ reason: errors
2443
+ };
2444
+ const holdingName = holdingTableName(sourceActual.table, from.column);
2445
+ if (tableNames.has(holdingName)) return {
2446
+ refused: true,
2447
+ reason: [`${path}: the database has a table ${holdingName}, left by a plan that did not finish. It holds the values of ${from.model}.${from.column} as they were then: check that ${sourceActual.table}.${from.column} still has them, then drop ${holdingName} and run the check again.`]
2448
+ };
2449
+ const holding = q(holdingName);
2450
+ const several = child === void 0;
2451
+ const orderBy = source.primaryKey.every((c) => hasColumn(sourceActual, c)) ? source.primaryKey : [];
2452
+ const ordered = [...orderBy.map((_, index) => q(`hk_order_${index}`)), q("hk_value")].join(", ");
2453
+ return {
2454
+ refused: false,
2455
+ value: {
2456
+ path,
2457
+ target,
2458
+ created: targetActual === void 0,
2459
+ column,
2460
+ source,
2461
+ sourceActual,
2462
+ from,
2463
+ link,
2464
+ holding,
2465
+ /** Whether several rows of the source can point at one row of the target. */
2466
+ several,
2467
+ /** The columns of the source the kept values are read with: the key, the value, its primary key. */
2468
+ kept: [
2469
+ `${q(link.key)} AS ${q("hk_key")}`,
2470
+ `${q(from.column)} AS ${q("hk_value")}`,
2471
+ ...orderBy.map((c, index) => `${q(c)} AS ${q(`hk_order_${index}`)}`)
2472
+ ].join(", "),
2473
+ /** Which of the kept values a row takes, read from `source`: the holding table, or the rows in the check. */
2474
+ valueFrom: (kept) => `(SELECT ${q("hk_value")} FROM ${kept} WHERE ${q("hk_key")} = ${q(link.match)} AND ${q("hk_value")} IS NOT NULL ORDER BY ${ordered} LIMIT 1)`
2475
+ }
2476
+ };
2477
+ }
2259
2478
  // src/migrate/domain/fixes/values.ts
2260
2479
  /**
2261
2480
  * The members a fix's `values` map stored values onto, each by the name the database stores it
@@ -2268,9 +2487,10 @@ function resolveMoves(context, models) {
2268
2487
  * ```
2269
2488
  */
2270
2489
  function mappedValues(column, values) {
2490
+ const dbNameOf = new Map((column.enumMembers ?? []).toReversed().map((m) => [m.name, m.dbName]));
2271
2491
  return Object.entries(values ?? {}).map(([stored, member]) => ({
2272
2492
  from: stored,
2273
- to: column.enumMembers?.find((m) => m.name === member)?.dbName ?? member
2493
+ to: dbNameOf.get(member) ?? member
2274
2494
  }));
2275
2495
  }
2276
2496
  /**
@@ -2320,7 +2540,8 @@ function describe(value) {
2320
2540
  */
2321
2541
  function identityColumns(actual, expectedKey, fixing) {
2322
2542
  const names = new Set(actual.columns.map((c) => c.name));
2323
- const sameAsFixed = (key) => key.length === fixing.length && key.every((column) => fixing.includes(column));
2543
+ const fixed = new Set(fixing);
2544
+ const sameAsFixed = (key) => key.length === fixing.length && key.every((column) => fixed.has(column));
2324
2545
  return [expectedKey, ...actual.uniques].find((key) => key.length > 0 && key.every((column) => names.has(column)) && !sameAsFixed(key)) ?? null;
2325
2546
  }
2326
2547
  /**
@@ -2338,6 +2559,22 @@ function anyOf(conditions) {
2338
2559
  if (conditions.length === 0) return "1 = 0";
2339
2560
  return conditions.length === 1 ? conditions[0] ?? "" : conditions.map((c) => `(${c})`).join(" OR ");
2340
2561
  }
2562
+ /** A PostgreSQL type with the arguments of its native type, if it has any. */
2563
+ function sized(name, args) {
2564
+ return args.length === 0 ? name : `${name}(${args.join(", ")})`;
2565
+ }
2566
+ /** The PostgreSQL type of each Prisma scalar, from the native type the field names. */
2567
+ const POSTGRES_TYPES = /* @__PURE__ */ new Map([
2568
+ ["String", (native, args) => native === null || native === "Text" ? "TEXT" : sized(native.toUpperCase(), args)],
2569
+ ["Int", (native) => native === "SmallInt" ? "SMALLINT" : "INTEGER"],
2570
+ ["BigInt", () => "BIGINT"],
2571
+ ["Float", (native) => native === "Real" ? "REAL" : "DOUBLE PRECISION"],
2572
+ ["Decimal", (_, args) => args.length === 0 ? "DECIMAL(65, 30)" : sized("DECIMAL", args)],
2573
+ ["Boolean", () => "BOOLEAN"],
2574
+ ["DateTime", (native, args) => native === "Date" ? "DATE" : sized(native === "Timestamptz" ? "TIMESTAMPTZ" : "TIMESTAMP", args)],
2575
+ ["Json", (native) => native === "Json" ? "JSON" : "JSONB"],
2576
+ ["Bytes", () => "BYTEA"]
2577
+ ]);
2341
2578
  /**
2342
2579
  * The PostgreSQL type a converted value is cast to in the check, as the migration's column will be.
2343
2580
  *
@@ -2351,20 +2588,8 @@ function anyOf(conditions) {
2351
2588
  */
2352
2589
  function postgresType(column) {
2353
2590
  const [native, args] = column.nativeType ?? [null, []];
2354
- const sized = (name) => args.length === 0 ? name : `${name}(${args.join(", ")})`;
2355
2591
  if (column.kind === "enum") return "TEXT";
2356
- switch (column.type) {
2357
- case "String": return native === null || native === "Text" ? "TEXT" : sized(native.toUpperCase());
2358
- case "Int": return native === "SmallInt" ? "SMALLINT" : "INTEGER";
2359
- case "BigInt": return "BIGINT";
2360
- case "Float": return native === "Real" ? "REAL" : "DOUBLE PRECISION";
2361
- case "Decimal": return args.length === 0 ? "DECIMAL(65, 30)" : sized("DECIMAL");
2362
- case "Boolean": return "BOOLEAN";
2363
- case "DateTime": return native === "Date" ? "DATE" : sized(native === "Timestamptz" ? "TIMESTAMPTZ" : "TIMESTAMP");
2364
- case "Json": return native === "Json" ? "JSON" : "JSONB";
2365
- case "Bytes": return "BYTEA";
2366
- default: return null;
2367
- }
2592
+ return POSTGRES_TYPES.get(column.type)?.(native, args) ?? null;
2368
2593
  }
2369
2594
  // src/migrate/domain/fixes/resolve-table.ts
2370
2595
  /** The check's decision for one table: what it fixes, resolved against the schema and the database. */
@@ -2373,6 +2598,7 @@ function resolveTable(input) {
2373
2598
  const where = table.model;
2374
2599
  const inDatabase = (column) => actual.columns.some((c) => c.name === column);
2375
2600
  const fieldOf = (field) => table.columns.find((c) => c.field === field);
2601
+ const actualColumnOf = new Map(actual.columns.toReversed().map((c) => [c.name, c]));
2376
2602
  const [fieldErrors, fixedColumns] = separate(Object.entries(config.fields ?? {}).map(([field, fix]) => {
2377
2603
  const column = fieldOf(field);
2378
2604
  if (column === void 0) return {
@@ -2406,7 +2632,7 @@ function resolveTable(input) {
2406
2632
  refused: true,
2407
2633
  reason: `${where}.${field}: ${table.table} has a column ${column.column} already; values are moved into a column the migration adds.`
2408
2634
  };
2409
- if (actual.columns.find((c) => c.name === column.column)?.generated === true) return {
2635
+ if (actualColumnOf.get(column.column)?.generated === true) return {
2410
2636
  refused: true,
2411
2637
  reason: `${where}.${field}: ${table.table}.${column.column} is generated by the database, which refuses a statement that writes to it. Change what it is generated from, or settle its rows by hand.`
2412
2638
  };
@@ -2419,8 +2645,9 @@ function resolveTable(input) {
2419
2645
  }
2420
2646
  };
2421
2647
  }));
2648
+ const foreignKeyOf = new Map(table.foreignKeys.toReversed().map((fk) => [fk.field, fk]));
2422
2649
  const [relationErrors, related] = separate(Object.entries(config.relations ?? {}).map(([field, fix]) => {
2423
- const foreignKey = table.foreignKeys.find((fk) => fk.field === field);
2650
+ const foreignKey = foreignKeyOf.get(field);
2424
2651
  return foreignKey === void 0 ? {
2425
2652
  refused: true,
2426
2653
  reason: `${where}.${field}: ${table.model} has no relation ${field} that holds a foreign key.`
@@ -2432,7 +2659,7 @@ function resolveTable(input) {
2432
2659
  }
2433
2660
  };
2434
2661
  }));
2435
- const [duplicateErrors, duplicates] = separate([...fixedColumns.flatMap((entry) => entry.fix.duplicates === void 0 ? [] : [{
2662
+ const duplicateSettings = [...fixedColumns.flatMap((entry) => entry.fix.duplicates === void 0 ? [] : [{
2436
2663
  path: `${where}.${entry.column.field}`,
2437
2664
  fields: [entry.column.field],
2438
2665
  fix: entry.fix.duplicates
@@ -2440,9 +2667,12 @@ function resolveTable(input) {
2440
2667
  path: `${where}.${unique.fields.join(", ")}`,
2441
2668
  fields: unique.fields,
2442
2669
  fix: unique
2443
- }))].map((setting) => {
2670
+ }))];
2671
+ const uniqueOver = new Map(table.uniques.toReversed().map((unique) => [columnSetKey(unique.columns), unique]));
2672
+ const uniqueOverColumns = (columns) => columns.every((column) => column !== null) ? uniqueOver.get(columnSetKey(columns)) : void 0;
2673
+ const [duplicateErrors, duplicates] = separate(duplicateSettings.map((setting) => {
2444
2674
  const columns = setting.fields.map((field) => fieldOf(field)?.column ?? null);
2445
- const key = table.uniques.find((unique) => unique.columns.length === columns.length && unique.columns.every((column) => columns.includes(column)));
2675
+ const key = uniqueOverColumns(columns);
2446
2676
  const order = setting.fix.orderBy === void 0 ? null : fieldOf(setting.fix.orderBy)?.column ?? null;
2447
2677
  const errors = [
2448
2678
  ...key === void 0 || columns.includes(null) ? [`${setting.path}: ${table.model} has no unique key over ${setting.fields.join(", ")}.`] : [],
@@ -2467,11 +2697,11 @@ function resolveTable(input) {
2467
2697
  const path = `${where}.${column.field}`;
2468
2698
  const blocking = input.conversionsOf(column.column).filter((c) => c.severity === "blocking" && c.kind !== "column-recreated");
2469
2699
  const invalid = fix.convert === void 0 ? fix.invalid : void 0;
2470
- const invalidErrors = invalid === "clamp" && !blocking.some((c) => c.bounds !== null) ? [`${path}: clamp applies to values out of range, and the type change of ${table.model}.${column.field} has none.`] : invalid === "truncate" && !blocking.some((c) => c.length !== null) ? [`${path}: truncate applies to values too long, and the type change of ${table.model}.${column.field} has none.`] : [];
2471
- const members = column.enumMembers ?? [];
2700
+ const invalidErrors = invalidErrorsOf(path, `${table.model}.${column.field}`, invalid, blocking);
2701
+ const memberNames = new Set((column.enumMembers ?? []).map((m) => m.name));
2472
2702
  const valueErrors = Object.entries(fix.values ?? {}).flatMap(([stored, member]) => {
2473
2703
  if (column.kind !== "enum") return [`${path}: ${table.model}.${column.field} is not an enum.`];
2474
- return members.some((m) => m.name === member) ? [] : [`${path}: ${member}, for ${stored}, is not a member of ${column.type}.`];
2704
+ return memberNames.has(member) ? [] : [`${path}: ${member}, for ${stored}, is not a member of ${column.type}.`];
2475
2705
  });
2476
2706
  const convertErrors = fix.convert !== void 0 && fix.invalid !== void 0 ? [`${path}: a conversion says how every value becomes the new type, which leaves what becomes of the values it refuses nothing to do; keep one of the two.`] : [];
2477
2707
  return [
@@ -2495,6 +2725,16 @@ function resolveTable(input) {
2495
2725
  duplicates
2496
2726
  };
2497
2727
  }
2728
+ /** A set of columns as one key, the same whatever their order. */
2729
+ function columnSetKey(columns) {
2730
+ return JSON.stringify(columns.toSorted((a, b) => Number(a > b) - Number(a < b)));
2731
+ }
2732
+ /** A clamp or truncate asked of a type change that refuses no value it would apply to. */
2733
+ function invalidErrorsOf(path, subject, invalid, blocking) {
2734
+ if (invalid === "clamp" && !blocking.some((c) => c.bounds !== null)) return [`${path}: clamp applies to values out of range, and the type change of ${subject} has none.`];
2735
+ if (invalid === "truncate" && !blocking.some((c) => c.length !== null)) return [`${path}: truncate applies to values too long, and the type change of ${subject} has none.`];
2736
+ return [];
2737
+ }
2498
2738
  /** Whether the only fixes of a table the migration creates are values moved into it, which its rows are made from. */
2499
2739
  function onlyMoves(config) {
2500
2740
  return config.relations === void 0 && config.unique === void 0 && Object.values(config.fields ?? {}).every((fix) => fix.movedFrom !== void 0 && Object.keys(fix).every((name) => name === "movedFrom"));
@@ -2575,7 +2815,8 @@ function cascade(context, state, key, deleted, cause, path) {
2575
2815
  count
2576
2816
  };
2577
2817
  if (rule === "set null") {
2578
- const next = version(acc.state, childKey, `SELECT ${table.columns.map((c) => fk.columns.includes(c) ? `CASE WHEN ${pointing} THEN NULL ELSE ${ref}.${q(c)} END AS ${q(c)}` : `${ref}.${q(c)}`).join(", ")} FROM ${source} AS ${ref}`);
2818
+ const keyColumns = new Set(fk.columns);
2819
+ const next = version(acc.state, childKey, `SELECT ${table.columns.map((c) => keyColumns.has(c) ? `CASE WHEN ${pointing} THEN NULL ELSE ${ref}.${q(c)} END AS ${q(c)}` : `${ref}.${q(c)}`).join(", ")} FROM ${source} AS ${ref}`);
2579
2820
  return {
2580
2821
  ...acc,
2581
2822
  state: {
@@ -2666,7 +2907,8 @@ function updated(context, state, key, changed, columns, cause, path = [key]) {
2666
2907
  const parent = versioned(key);
2667
2908
  if (parent === null) return state;
2668
2909
  const after = current(state, key);
2669
- const into = incoming(key).filter(({ references }) => references.some((c) => columns.includes(c)));
2910
+ const changing = new Set(columns);
2911
+ const into = incoming(key).filter((entry) => entry.references.some((c) => changing.has(c)));
2670
2912
  const step = (acc, { child, fk, references }) => {
2671
2913
  const childKey = keyOf(child);
2672
2914
  const table = versioned(childKey);
@@ -2701,7 +2943,7 @@ function updated(context, state, key, changed, columns, cause, path = [key]) {
2701
2943
  hint: "MySQL does not follow an ON UPDATE cascade into a table it has changed: settle these rows first, or leave the values."
2702
2944
  })]
2703
2945
  };
2704
- const byPrimaryKey = parent.primaryKey.every((c) => !columns.includes(c));
2946
+ const byPrimaryKey = parent.primaryKey.every((c) => !changing.has(c));
2705
2947
  if (!follows || rule === "cascade" && !byPrimaryKey || path.includes(childKey) && childKey !== key) return {
2706
2948
  ...acc,
2707
2949
  effects: [...acc.effects, effectOf({
@@ -2712,9 +2954,10 @@ function updated(context, state, key, changed, columns, cause, path = [key]) {
2712
2954
  };
2713
2955
  const renewed = q("hk_new");
2714
2956
  const valueOf = (index) => rule === "set null" ? "NULL" : `(SELECT ${renewed}.${q(references[index] ?? "")} FROM (${changed}) AS ${gone} JOIN ${after} AS ${renewed} ON ${parent.primaryKey.map((c) => `${renewed}.${q(c)} = ${gone}.${q(c)}`).join(" AND ")} WHERE ${match})`;
2957
+ const positionOf = new Map(fk.columns.map((c, i) => [c, i]).toReversed());
2715
2958
  const next = version(acc, childKey, `SELECT ${table.columns.map((c) => {
2716
- const index = fk.columns.indexOf(c);
2717
- return index === -1 ? `${ref}.${q(c)}` : `CASE WHEN ${pointing} THEN ${valueOf(index)} ELSE ${ref}.${q(c)} END AS ${q(c)}`;
2959
+ const index = positionOf.get(c);
2960
+ return index === void 0 ? `${ref}.${q(c)}` : `CASE WHEN ${pointing} THEN ${valueOf(index)} ELSE ${ref}.${q(c)} END AS ${q(c)}`;
2718
2961
  }).join(", ")} FROM ${source} AS ${ref}`);
2719
2962
  const effect = effectOf({
2720
2963
  kind: "update-cascades",
@@ -2748,101 +2991,167 @@ function updated(context, state, key, changed, columns, cause, path = [key]) {
2748
2991
  * ```
2749
2992
  */
2750
2993
  function columnStep(context, state, entry, column, fix, conversions) {
2751
- const { dialect, keyOf, q, current, version, listOf } = context;
2994
+ const { dialect, keyOf, q, current, version } = context;
2752
2995
  const { table, actual } = entry;
2753
2996
  const key = keyOf(table);
2754
- const base = qualifiedName(dialect, table);
2755
2997
  const from = current(state, key);
2998
+ const values = columnValues(dialect, q, actual, column, fix, conversions);
2999
+ const { refused, invalid, mapped, fill, expression } = values;
3000
+ if (invalid === void 0 && mapped.length === 0 && fill === null) return state;
3001
+ const removed = invalid === "delete" && refused !== null ? refused : null;
3002
+ const next = version(state, key, `SELECT ${actual.columns.map((c) => c.name === column.column ? `${expression} AS ${q(c.name)}` : q(c.name)).join(", ")} FROM ${from}${removed === null ? "" : ` WHERE (${removed}) IS NOT TRUE`}`);
3003
+ const site = {
3004
+ table,
3005
+ subject: `${table.model}.${column.field}`,
3006
+ base: qualifiedName(dialect, table),
3007
+ from,
3008
+ name: q(column.column),
3009
+ kept: removed === null ? "" : `(${removed}) IS NOT TRUE AND `
3010
+ };
3011
+ const fixes = [
3012
+ ...invalidFix(q, site, values),
3013
+ ...mappedFix(q, site, values),
3014
+ ...nullsFix(q, site, values, fix)
3015
+ ];
3016
+ return followChangedRows(context, {
3017
+ ...next.state,
3018
+ fixes: [...next.state.fixes, ...fixes]
3019
+ }, key, actual, column, site, values, removed);
3020
+ }
3021
+ /**
3022
+ * A column's value as its fixes leave it, one stage at a time: the values the new type refuses
3023
+ * replaced, the stored enum values mapped, and the NULLs filled.
3024
+ */
3025
+ function columnValues(dialect, q, actual, column, fix, conversions) {
2756
3026
  const name = q(column.column);
2757
3027
  const blocking = conversions.filter((c) => c.severity === "blocking" && c.kind !== "column-recreated" && c.condition !== null);
2758
3028
  const refused = blocking.length === 0 ? null : anyOf(blocking.map((c) => c.condition ?? ""));
2759
3029
  const invalid = refused === null ? void 0 : fix.invalid;
2760
- const bounded = blocking.find((c) => c.bounds !== null)?.bounds ?? null;
2761
- const length = blocking.find((c) => c.length !== null)?.length ?? null;
2762
- const replaced = invalid === void 0 || invalid === "delete" ? null : invalid === "null" ? "NULL" : invalid === "clamp" ? bounded === null ? null : `CASE WHEN ${name} < ${bounded.min} THEN ${bounded.min} ELSE ${bounded.max} END` : invalid === "truncate" ? length === null ? null : dialect === "sqlite" ? `SUBSTR(${name}, 1, ${length})` : `LEFT(${name}, ${length})` : valueSql(dialect, column, invalid.set);
2763
- const deletes = invalid === "delete";
3030
+ const replaced = replacementSql(dialect, column, name, invalid, blocking.find((c) => c.bounds !== null)?.bounds ?? null, blocking.find((c) => c.length !== null)?.length ?? null);
2764
3031
  const afterInvalid = replaced === null || refused === null ? name : `CASE WHEN ${refused} THEN ${replaced} ELSE ${name} END`;
3032
+ const mapped = storedValuesMapped(dialect, actual, column, fix);
3033
+ const afterValues = mapped.length === 0 ? afterInvalid : caseMap(afterInvalid, mapped);
3034
+ const fill = fix.nulls === void 0 ? null : valueSql(dialect, column, fix.nulls);
3035
+ return {
3036
+ refused,
3037
+ invalid,
3038
+ replaced,
3039
+ afterInvalid,
3040
+ mapped,
3041
+ afterValues,
3042
+ fill,
3043
+ expression: fill === null ? afterValues : `COALESCE(${afterValues}, ${fill})`
3044
+ };
3045
+ }
3046
+ /** What a value the new type refuses becomes, or null where it is not replaced. */
3047
+ function replacementSql(dialect, column, name, invalid, bounded, length) {
3048
+ if (invalid === void 0 || invalid === "delete") return null;
3049
+ if (invalid === "null") return "NULL";
3050
+ if (invalid === "clamp") return bounded === null ? null : `CASE WHEN ${name} < ${bounded.min} THEN ${bounded.min} ELSE ${bounded.max} END`;
3051
+ if (invalid === "truncate") {
3052
+ if (length === null) return null;
3053
+ return dialect === "sqlite" ? `SUBSTR(${name}, 1, ${length})` : `LEFT(${name}, ${length})`;
3054
+ }
3055
+ return valueSql(dialect, column, invalid.set);
3056
+ }
3057
+ /**
3058
+ * The stored values and the members they become, written as the plain text they are. A member
3059
+ * the column's type does not have yet is mapped by the migration, in its cast.
3060
+ */
3061
+ function storedValuesMapped(dialect, actual, column, fix) {
2765
3062
  const existing = actual.columns.find((c) => c.name === column.column)?.enumValues ?? null;
3063
+ const members = existing === null ? null : new Set(existing);
2766
3064
  const asText = {
2767
3065
  ...column,
2768
3066
  kind: "scalar",
2769
3067
  type: "String",
2770
3068
  isList: false
2771
3069
  };
2772
- const mapped = mappedValues(column, fix.values).filter((m) => existing === null || dialect === "sqlite" || existing.includes(m.to)).map((m) => ({
3070
+ return mappedValues(column, fix.values).filter((m) => members === null || dialect === "sqlite" || members.has(m.to)).map((m) => ({
2773
3071
  from: valueSql(dialect, asText, m.from),
2774
3072
  to: valueSql(dialect, asText, m.to)
2775
3073
  }));
2776
- const afterValues = mapped.length === 0 ? afterInvalid : caseMap(afterInvalid, mapped);
2777
- const fill = fix.nulls === void 0 ? null : valueSql(dialect, column, fix.nulls);
2778
- const expression = fill === null ? afterValues : `COALESCE(${afterValues}, ${fill})`;
2779
- if (invalid === void 0 && mapped.length === 0 && fill === null) return state;
2780
- const kept = deletes && refused !== null ? `(${refused}) IS NOT TRUE AND ` : "";
2781
- const next = version(state, key, `SELECT ${actual.columns.map((c) => c.name === column.column ? `${expression} AS ${q(c.name)}` : q(c.name)).join(", ")} FROM ${from}${deletes && refused !== null ? ` WHERE (${refused}) IS NOT TRUE` : ""}`);
2782
- const subject = `${table.model}.${column.field}`;
2783
- const invalidHead = deletes ? `DELETE FROM ${base}` : `UPDATE ${base} SET ${name} = ${replaced ?? name}`;
2784
- const mappedHead = `UPDATE ${base} SET ${name} = ${caseMap(name, mapped)}`;
2785
- const mappedWhere = `${name} IN (${mapped.map((m) => m.from).join(", ")})`;
2786
- const fixes = [
2787
- ...invalid === void 0 || refused === null ? [] : [{
2788
- model: table.model,
2789
- table,
2790
- subject,
2791
- kind: "invalid",
2792
- inMigration: false,
2793
- action: typeof invalid === "string" ? {
2794
- null: "values the new type refuses set to NULL",
2795
- delete: "rows whose value the new type refuses deleted",
2796
- clamp: "values out of range clamped to the range",
2797
- truncate: "values too long cut to the length"
2798
- }[invalid] : `values the new type refuses set to ${describe(invalid.set)}`,
2799
- count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} WHERE ${refused}`,
2800
- statements: [`${invalidHead} WHERE ${refused}`],
2801
- parts: {
2802
- head: invalidHead,
2803
- table: base,
2804
- where: refused
2805
- }
2806
- }],
2807
- ...mapped.length === 0 ? [] : [{
2808
- model: table.model,
2809
- table,
2810
- subject,
2811
- kind: "values",
2812
- inMigration: false,
2813
- action: `values mapped: ${mapped.map((m) => `${m.from} → ${m.to}`).join(", ")}`.replaceAll("'", ""),
2814
- count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} WHERE ${kept}${afterInvalid} IN (${mapped.map((m) => m.from).join(", ")})`,
2815
- statements: [`${mappedHead} WHERE ${mappedWhere}`],
2816
- parts: {
2817
- head: mappedHead,
2818
- table: base,
2819
- where: mappedWhere
2820
- }
2821
- }],
2822
- ...fill === null ? [] : [{
2823
- model: table.model,
2824
- table,
2825
- subject,
2826
- kind: "nulls",
2827
- inMigration: false,
2828
- action: `NULLs set to ${describe(fix.nulls ?? null)}`,
2829
- count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} WHERE ${kept}${afterValues} IS NULL`,
2830
- statements: [`UPDATE ${base} SET ${name} = ${fill} WHERE ${name} IS NULL`],
2831
- parts: {
2832
- head: `UPDATE ${base} SET ${name} = ${fill}`,
2833
- table: base,
2834
- where: `${name} IS NULL`
2835
- }
2836
- }]
2837
- ];
2838
- const withFixes = {
2839
- ...next.state,
2840
- fixes: [...next.state.fixes, ...fixes]
2841
- };
3074
+ }
3075
+ const INVALID_ACTIONS = {
3076
+ null: "values the new type refuses set to NULL",
3077
+ delete: "rows whose value the new type refuses deleted",
3078
+ clamp: "values out of range clamped to the range",
3079
+ truncate: "values too long cut to the length"
3080
+ };
3081
+ /** The fix of the values the new type refuses: replaced, or their rows deleted. */
3082
+ function invalidFix(q, site, values) {
3083
+ const { invalid, refused, replaced } = values;
3084
+ if (invalid === void 0 || refused === null) return [];
3085
+ const { table, subject, base, from, name } = site;
3086
+ const head = invalid === "delete" ? `DELETE FROM ${base}` : `UPDATE ${base} SET ${name} = ${replaced ?? name}`;
3087
+ return [{
3088
+ model: table.model,
3089
+ table,
3090
+ subject,
3091
+ kind: "invalid",
3092
+ inMigration: false,
3093
+ action: typeof invalid === "string" ? INVALID_ACTIONS[invalid] : `values the new type refuses set to ${describe(invalid.set)}`,
3094
+ count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} WHERE ${refused}`,
3095
+ statements: [`${head} WHERE ${refused}`],
3096
+ parts: {
3097
+ head,
3098
+ table: base,
3099
+ where: refused
3100
+ }
3101
+ }];
3102
+ }
3103
+ /** The fix of the stored enum values mapped to the members they become. */
3104
+ function mappedFix(q, site, values) {
3105
+ const { mapped, afterInvalid } = values;
3106
+ if (mapped.length === 0) return [];
3107
+ const { table, subject, base, from, name, kept } = site;
3108
+ const head = `UPDATE ${base} SET ${name} = ${caseMap(name, mapped)}`;
3109
+ const where = `${name} IN (${mapped.map((m) => m.from).join(", ")})`;
3110
+ return [{
3111
+ model: table.model,
3112
+ table,
3113
+ subject,
3114
+ kind: "values",
3115
+ inMigration: false,
3116
+ action: `values mapped: ${mapped.map((m) => `${m.from} → ${m.to}`).join(", ")}`.replaceAll("'", ""),
3117
+ count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} WHERE ${kept}${afterInvalid} IN (${mapped.map((m) => m.from).join(", ")})`,
3118
+ statements: [`${head} WHERE ${where}`],
3119
+ parts: {
3120
+ head,
3121
+ table: base,
3122
+ where
3123
+ }
3124
+ }];
3125
+ }
3126
+ /** The fix of the NULLs filled with a value. */
3127
+ function nullsFix(q, site, values, fix) {
3128
+ const { fill, afterValues } = values;
3129
+ if (fill === null) return [];
3130
+ const { table, subject, base, from, name, kept } = site;
3131
+ return [{
3132
+ model: table.model,
3133
+ table,
3134
+ subject,
3135
+ kind: "nulls",
3136
+ inMigration: false,
3137
+ action: `NULLs set to ${describe(fix.nulls ?? null)}`,
3138
+ count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} WHERE ${kept}${afterValues} IS NULL`,
3139
+ statements: [`UPDATE ${base} SET ${name} = ${fill} WHERE ${name} IS NULL`],
3140
+ parts: {
3141
+ head: `UPDATE ${base} SET ${name} = ${fill}`,
3142
+ table: base,
3143
+ where: `${name} IS NULL`
3144
+ }
3145
+ }];
3146
+ }
3147
+ /** What the database does to the rows pointing at the ones a column's fixes change or delete. */
3148
+ function followChangedRows(context, state, key, actual, column, site, values, removed) {
3149
+ const { listOf } = context;
3150
+ const { replaced, refused, mapped, afterInvalid } = values;
2842
3151
  const columns = actual.columns.map((c) => c.name);
2843
3152
  const changedRows = [...replaced !== null && refused !== null ? [refused] : [], ...mapped.length > 0 ? [`${afterInvalid} IN (${mapped.map((m) => m.from).join(", ")})`] : []];
2844
- const afterUpdate = changedRows.length === 0 ? withFixes : updated(context, withFixes, key, `SELECT ${listOf(columns)} FROM ${from} WHERE ${anyOf(changedRows)}`, [column.column], subject);
2845
- return deletes && refused !== null ? cascade(context, afterUpdate, key, `SELECT ${listOf(columns)} FROM ${from} WHERE ${refused}`, subject, [key]) : afterUpdate;
3153
+ const afterUpdate = changedRows.length === 0 ? state : updated(context, state, key, `SELECT ${listOf(columns)} FROM ${site.from} WHERE ${anyOf(changedRows)}`, [column.column], site.subject);
3154
+ return removed === null ? afterUpdate : cascade(context, afterUpdate, key, `SELECT ${listOf(columns)} FROM ${site.from} WHERE ${removed}`, site.subject, [key]);
2846
3155
  }
2847
3156
  /**
2848
3157
  * The rows a duplicates fix removes or clears: every row of a group of equal keys but the one kept.
@@ -2856,7 +3165,8 @@ function columnStep(context, state, entry, column, fix, conversions) {
2856
3165
  */
2857
3166
  function ranked(q, from, columns, duplicate, table) {
2858
3167
  const direction = duplicate.fix.keep === "first" ? "ASC" : "DESC";
2859
- const order = [...duplicate.order, ...table.primaryKey.filter((c) => !duplicate.order.includes(c))].map((c) => `${q(c)} ${direction}`).join(", ");
3168
+ const ordered = new Set(duplicate.order);
3169
+ const order = [...duplicate.order, ...table.primaryKey.filter((c) => !ordered.has(c))].map((c) => `${q(c)} ${direction}`).join(", ");
2860
3170
  const rank = q("hk_rank");
2861
3171
  const partition = duplicate.key.map(q).join(", ");
2862
3172
  const chosen = `${rank} > 1 AND ${duplicate.key.map((c) => `${q(c)} IS NOT NULL`).join(" AND ")}`;
@@ -2896,11 +3206,13 @@ function duplicateStep(context, state, entry, duplicate) {
2896
3206
  const columns = actual.columns.map((c) => q(c.name));
2897
3207
  const rows = ranked(q, from, columns, duplicate, table);
2898
3208
  const clear = duplicate.fix.others === "null";
2899
- const next = version(state, key, clear ? `SELECT ${actual.columns.map((c) => duplicate.key.includes(c.name) ? `CASE WHEN ${rows.chosen} THEN NULL ELSE ${q(c.name)} END AS ${q(c.name)}` : q(c.name)).join(", ")} FROM (${rows.sql}) AS ${q("hk_ranked")}` : `SELECT ${columns.join(", ")} FROM (${rows.sql}) AS ${q("hk_ranked")} WHERE (${rows.chosen}) IS NOT TRUE`);
3209
+ const keyColumns = new Set(duplicate.key);
3210
+ const next = version(state, key, clear ? `SELECT ${actual.columns.map((c) => keyColumns.has(c.name) ? `CASE WHEN ${rows.chosen} THEN NULL ELSE ${q(c.name)} END AS ${q(c.name)}` : q(c.name)).join(", ")} FROM (${rows.sql}) AS ${q("hk_ranked")}` : `SELECT ${columns.join(", ")} FROM (${rows.sql}) AS ${q("hk_ranked")} WHERE (${rows.chosen}) IS NOT TRUE`);
2900
3211
  const base = qualifiedName(dialect, table);
2901
3212
  const identity = identityColumns(actual, table.primaryKey, duplicate.key) ?? table.primaryKey;
2902
3213
  const keys = identity.length === 1 ? q(identity[0] ?? "") : `(${identity.map(q).join(", ")})`;
2903
- const inPlace = ranked(q, base, [...identity.map(q), ...duplicate.key.filter((c) => !identity.includes(c)).map(q)], duplicate, table);
3214
+ const identifying = new Set(identity);
3215
+ const inPlace = ranked(q, base, [...identity.map(q), ...duplicate.key.filter((c) => !identifying.has(c)).map(q)], duplicate, table);
2904
3216
  const target = `${keys} IN (SELECT ${identity.map(q).join(", ")} FROM (${inPlace.sql}) AS ${q("hk_ranked")} WHERE ${inPlace.chosen})`;
2905
3217
  const subject = `${table.model}.${duplicate.fields.join(", ")}`;
2906
3218
  const head = clear ? `UPDATE ${base} SET ${duplicate.key.map((c) => `${q(c)} = NULL`).join(", ")}` : `DELETE FROM ${base}`;
@@ -2964,7 +3276,8 @@ function orphanStep(context, state, entry, relation) {
2964
3276
  const base = qualifiedName(dialect, table);
2965
3277
  const inPlace = condition(dialect === "mysql" ? `(SELECT DISTINCT ${fk.toColumns.map(q).join(", ")} FROM ${qualifiedName(dialect, parentTable)})` : qualifiedName(dialect, parentTable));
2966
3278
  const clear = relation.orphans === "null";
2967
- const next = version(state, key, clear ? `SELECT ${actual.columns.map((c) => fk.fromColumns.includes(c.name) ? `CASE WHEN ${simulated} THEN NULL ELSE ${child}.${q(c.name)} END AS ${q(c.name)}` : `${child}.${q(c.name)}`).join(", ")} FROM ${from} AS ${child}` : `SELECT ${listOf(actual.columns.map((c) => c.name), child)} FROM ${from} AS ${child} WHERE (${simulated}) IS NOT TRUE`);
3279
+ const keyColumns = new Set(fk.fromColumns);
3280
+ const next = version(state, key, clear ? `SELECT ${actual.columns.map((c) => keyColumns.has(c.name) ? `CASE WHEN ${simulated} THEN NULL ELSE ${child}.${q(c.name)} END AS ${q(c.name)}` : `${child}.${q(c.name)}`).join(", ")} FROM ${from} AS ${child}` : `SELECT ${listOf(actual.columns.map((c) => c.name), child)} FROM ${from} AS ${child} WHERE (${simulated}) IS NOT TRUE`);
2968
3281
  const subject = `${table.model}.${fk.field} → ${fk.toModel}`;
2969
3282
  const fix = {
2970
3283
  model: table.model,
@@ -2974,7 +3287,7 @@ function orphanStep(context, state, entry, relation) {
2974
3287
  inMigration: false,
2975
3288
  action: clear ? "orphans set to NULL" : "orphans deleted",
2976
3289
  count: `SELECT COUNT(*) AS ${q("count")} FROM ${from} AS ${child} WHERE ${simulated}`,
2977
- statements: [clear ? `UPDATE ${base} AS ${child} SET ${fk.fromColumns.map((c) => `${q(c)} = NULL`).join(", ")} WHERE ${inPlace}` : dialect === "mysql" ? `DELETE ${child} FROM ${base} AS ${child} WHERE ${inPlace}` : `DELETE FROM ${base} AS ${child} WHERE ${inPlace}`],
3290
+ statements: [clear ? `UPDATE ${base} AS ${child} SET ${fk.fromColumns.map((c) => `${q(c)} = NULL`).join(", ")} WHERE ${inPlace}` : `DELETE ${dialect === "mysql" ? `${child} ` : ""}FROM ${base} AS ${child} WHERE ${inPlace}`],
2978
3291
  parts: null
2979
3292
  };
2980
3293
  const withFix = {
@@ -3008,11 +3321,13 @@ function migrationStep(context, state, entry, moved) {
3008
3321
  const key = keyOf(table);
3009
3322
  const from = current(state, key);
3010
3323
  const converted = entry.resolved.columns.filter((c) => !c.added && c.fix.convert !== void 0);
3324
+ const enumValuesOf = new Map(actual.columns.toReversed().map((c) => [c.name, c.enumValues]));
3011
3325
  const mappings = entry.resolved.columns.flatMap(({ column, fix, added }) => {
3012
3326
  if (added || column.kind !== "enum" || dialect === "sqlite") return [];
3013
- const existing = actual.columns.find((c) => c.name === column.column)?.enumValues ?? null;
3327
+ const existing = enumValuesOf.get(column.column) ?? null;
3014
3328
  if (existing === null) return [];
3015
- const late = mappedValues(column, fix.values).filter((m) => !existing.includes(m.to));
3329
+ const members = new Set(existing);
3330
+ const late = mappedValues(column, fix.values).filter((m) => !members.has(m.to));
3016
3331
  return late.length === 0 ? [] : [{
3017
3332
  column,
3018
3333
  existing,
@@ -3023,15 +3338,17 @@ function migrationStep(context, state, entry, moved) {
3023
3338
  const movedIn = moved.filter((m) => !m.created && m.target === table);
3024
3339
  if (converted.length + mappings.length + fills.length + movedIn.length === 0) return state;
3025
3340
  const read = (column) => dialect === "postgresql" ? `CAST(${q(column)} AS TEXT)` : q(column);
3341
+ const conversionOf = new Map(converted.toReversed().map((each) => [each.column.column, each]));
3342
+ const mappingOf = new Map(mappings.toReversed().map((m) => [m.column.column, m]));
3026
3343
  const next = version(state, key, `SELECT ${[
3027
3344
  ...actual.columns.map((c) => {
3028
- const conversion = converted.find((each) => each.column.column === c.name);
3345
+ const conversion = conversionOf.get(c.name);
3029
3346
  if (conversion !== void 0) {
3030
3347
  const sql = `(${conversion.fix.convert?.sql ?? q(c.name)})`;
3031
3348
  const type = dialect === "postgresql" ? postgresType(conversion.column) : null;
3032
3349
  return `${type === null ? sql : `CAST(${sql} AS ${type})`} AS ${q(c.name)}`;
3033
3350
  }
3034
- const mapping = mappings.find((m) => m.column.column === c.name);
3351
+ const mapping = mappingOf.get(c.name);
3035
3352
  if (mapping !== void 0) return `${caseMap(read(c.name), mapping.mapping.map((m) => ({
3036
3353
  from: stringLiteral(dialect, m.from),
3037
3354
  to: stringLiteral(dialect, m.to)
@@ -3123,7 +3440,7 @@ function makeFixContext(input) {
3123
3440
  return (pointingAt.get(key) ?? []).map(({ child, fk }) => ({
3124
3441
  child,
3125
3442
  fk,
3126
- references: fk.refColumns.every((c) => c !== "") ? fk.refColumns : parent.primaryKey
3443
+ references: referencedColumns(fk.refColumns, parent.primaryKey)
3127
3444
  })).filter(({ fk, references }) => references.length === fk.columns.length);
3128
3445
  };
3129
3446
  /** Every version of every changed table so far, as CTEs, with the fixes and effects that made them. */
@@ -3183,6 +3500,10 @@ function makeFixContext(input) {
3183
3500
  gone
3184
3501
  };
3185
3502
  }
3503
+ /** The columns a foreign key references: its own, or the primary key where it names none. */
3504
+ function referencedColumns(refColumns, primaryKey) {
3505
+ return refColumns.every((c) => c !== "") ? refColumns : primaryKey;
3506
+ }
3186
3507
  // src/migrate/domain/fixes/index.ts
3187
3508
  /**
3188
3509
  * The fixes the decisions of the Migrate page make, made twice from one description.
@@ -3217,7 +3538,9 @@ function makeFixContext(input) {
3217
3538
  function resolveFixes(input) {
3218
3539
  const context = makeFixContext(input);
3219
3540
  const { dialect, keyOf, q, actualByKey, versioned, current, empty } = context;
3220
- const unknownModels = Object.entries(input.models ?? {}).flatMap(([model]) => input.expected.some((table) => table.model === model) ? [] : [`${model}: the schema has no model ${model}.`]);
3541
+ const configured = Object.entries(input.models ?? {});
3542
+ const modelNames = new Set(input.expected.map((table) => table.model));
3543
+ const unknownModels = configured.flatMap(([model]) => modelNames.has(model) ? [] : [`${model}: the schema has no model ${model}.`]);
3221
3544
  const missing = input.expected.flatMap((table) => {
3222
3545
  const config = input.models?.[table.model];
3223
3546
  return config !== void 0 && !actualByKey.has(keyOf(table)) && !onlyMoves(config) ? [`${table.model}: the migration creates ${table.table}, so there are no rows of it to fix.`] : [];
@@ -3239,6 +3562,7 @@ function resolveFixes(input) {
3239
3562
  });
3240
3563
  const moves = resolveMoves(context, input.models);
3241
3564
  const { moved } = moves;
3565
+ const movedIntoExisting = Map.groupBy(moved.filter((m) => !m.created), (m) => m.target);
3242
3566
  const errors = [
3243
3567
  ...unknownModels,
3244
3568
  ...missing,
@@ -3325,29 +3649,38 @@ function resolveFixes(input) {
3325
3649
  column: column.column,
3326
3650
  sql: fix.convert.sql
3327
3651
  }]),
3328
- enumMaps: entry.resolved.columns.flatMap(({ column, fix, added }) => {
3329
- if (added || column.kind !== "enum" || dialect === "sqlite") return [];
3330
- const existing = entry.actual.columns.find((c) => c.name === column.column)?.enumValues ?? null;
3331
- if (existing === null) return [];
3332
- const mapping = mappedValues(column, fix.values).filter((m) => !existing.includes(m.to));
3333
- return mapping.length === 0 ? [] : [{
3334
- column: column.column,
3335
- type: column.enumType ?? column.type,
3336
- mapping,
3337
- existing,
3338
- members: (column.enumMembers ?? []).map((m) => m.dbName)
3339
- }];
3340
- }),
3652
+ enumMaps: enumMapsOf(dialect, entry),
3341
3653
  fills: [...entry.resolved.columns.flatMap(({ column, fix, added }) => added && fix.nulls !== void 0 ? [{
3342
3654
  column: column.column,
3343
3655
  sql: valueSql(dialect, column, fix.nulls)
3344
- }] : []), ...moved.filter((m) => !m.created && m.target === entry.table).map((m) => ({
3656
+ }] : []), ...(movedIntoExisting.get(entry.table) ?? []).map((m) => ({
3345
3657
  column: m.column.column,
3346
3658
  sql: m.valueFrom(m.holding)
3347
3659
  }))]
3348
3660
  }))
3349
3661
  };
3350
3662
  }
3663
+ /**
3664
+ * The enum values of a table mapped to a member the old type does not have, which the migration
3665
+ * maps in its cast (PostgreSQL) or over a widened ENUM (MySQL).
3666
+ */
3667
+ function enumMapsOf(dialect, entry) {
3668
+ const enumValuesOf = new Map(entry.actual.columns.toReversed().map((c) => [c.name, c.enumValues]));
3669
+ return entry.resolved.columns.flatMap(({ column, fix, added }) => {
3670
+ if (added || column.kind !== "enum" || dialect === "sqlite") return [];
3671
+ const existing = enumValuesOf.get(column.column) ?? null;
3672
+ if (existing === null) return [];
3673
+ const members = new Set(existing);
3674
+ const mapping = mappedValues(column, fix.values).filter((m) => !members.has(m.to));
3675
+ return mapping.length === 0 ? [] : [{
3676
+ column: column.column,
3677
+ type: column.enumType ?? column.type,
3678
+ mapping,
3679
+ existing,
3680
+ members: (column.enumMembers ?? []).map((m) => m.dbName)
3681
+ }];
3682
+ });
3683
+ }
3351
3684
  // src/migrate/domain/checks.ts
3352
3685
  /**
3353
3686
  * The head of every count query: the count comes back under one name, whatever the dialect.
@@ -3446,6 +3779,15 @@ function countOrphans(dialect, from, target, foreignKey) {
3446
3779
  params: []
3447
3780
  };
3448
3781
  }
3782
+ /** Whether a type change drops the column and adds it again. */
3783
+ function recreatesColumn(found) {
3784
+ return found.some((conversion) => conversion.kind === "column-recreated");
3785
+ }
3786
+ /** Whether a key the database has covers the columns: a key over some makes every wider set unique. */
3787
+ function coveredByKey(keys, columns) {
3788
+ const wanted = new Set(columns);
3789
+ return keys.some((key) => key.length > 0 && key.every((column) => wanted.has(column)));
3790
+ }
3449
3791
  function pairs(from, to) {
3450
3792
  return from.map((column, index) => `${column}=${to[index] ?? ""}`).toSorted().join(" ");
3451
3793
  }
@@ -3607,24 +3949,41 @@ function makeChecks(input) {
3607
3949
  const found = conversionsOf(wanted, column.column);
3608
3950
  return found.length === 0 ? [] : [[column.column, found]];
3609
3951
  }));
3610
- const recreated = new Set([...conversions].filter(([, found]) => found.some((conversion) => conversion.kind === "column-recreated")).map(([column]) => column));
3952
+ const recreated = new Set([...conversions].filter(([, found]) => recreatesColumn(found)).map(([column]) => column));
3953
+ const addedColumnChecks = (column, subject) => {
3954
+ if (!column.required || column.databaseDefault) return [];
3955
+ return [{
3956
+ kind: "column-added",
3957
+ severity: "blocking",
3958
+ model: wanted.model,
3959
+ subject,
3960
+ what: "required column added without a database default",
3961
+ unit: "row",
3962
+ hint: dialect === "mysql" ? "MySQL fills the rows already there with '', 0, the first enum member or a zero date, not a value Prisma Client would write: give the field a @default the database fills (not uuid(), cuid(), nanoid(), ulid() or @updatedAt), or add it optional, fill it, then make it required; filling them on the Migrate page of hekireki studio does it in the migration." : "The database has no value for the rows already there: give the field a @default the database fills (not uuid(), cuid(), nanoid(), ulid() or @updatedAt), or add it optional, fill it, then make it required; filling them on the Migrate page of hekireki studio does it in the migration.",
3963
+ guaranteed: false,
3964
+ statement: withFixes(countRows(dialect, from))
3965
+ }];
3966
+ };
3967
+ const enumChecks = (column, existing, subject) => {
3968
+ const allowed = column.enumValues ?? [];
3969
+ if (column.kind !== "enum" || column.isList || allowed.length === 0) return [];
3970
+ const members = new Set(allowed);
3971
+ return [{
3972
+ kind: "enum",
3973
+ severity: "blocking",
3974
+ model: wanted.model,
3975
+ subject,
3976
+ what: `values outside enum ${column.type}`,
3977
+ unit: "row",
3978
+ hint: "Move the rows to a member that stays before the enum changes, or say what each stored value becomes on the Migrate page of hekireki studio.",
3979
+ guaranteed: trusted && (existing.enumValues?.every((value) => members.has(value)) ?? false),
3980
+ statement: withFixes(countOutsideEnum(dialect, from, column.column, allowed))
3981
+ }];
3982
+ };
3611
3983
  const columns = wanted.columns.flatMap((column) => {
3612
3984
  const subject = `${wanted.model}.${column.field}`;
3613
3985
  const existing = find(column.column);
3614
- if (existing === void 0) {
3615
- if (!column.required || column.databaseDefault) return [];
3616
- return [{
3617
- kind: "column-added",
3618
- severity: "blocking",
3619
- model: wanted.model,
3620
- subject,
3621
- what: "required column added without a database default",
3622
- unit: "row",
3623
- hint: dialect === "mysql" ? "MySQL fills the rows already there with '', 0, the first enum member or a zero date, not a value Prisma Client would write: give the field a @default the database fills (not uuid(), cuid(), nanoid(), ulid() or @updatedAt), or add it optional, fill it, then make it required; filling them on the Migrate page of hekireki studio does it in the migration." : "The database has no value for the rows already there: give the field a @default the database fills (not uuid(), cuid(), nanoid(), ulid() or @updatedAt), or add it optional, fill it, then make it required; filling them on the Migrate page of hekireki studio does it in the migration.",
3624
- guaranteed: false,
3625
- statement: withFixes(countRows(dialect, from))
3626
- }];
3627
- }
3986
+ if (existing === void 0) return addedColumnChecks(column, subject);
3628
3987
  const conversionChecks = (conversions.get(column.column) ?? []).map((conversion) => ({
3629
3988
  kind: conversion.kind,
3630
3989
  severity: conversion.severity,
@@ -3638,33 +3997,20 @@ function makeChecks(input) {
3638
3997
  lost: conversion.kind === "column-recreated" ? `SELECT * FROM ${qualifiedName(dialect, actual)} WHERE ${quoteIdentifier(dialect, column.column)} IS NOT NULL` : null
3639
3998
  }));
3640
3999
  if (recreated.has(column.column)) return conversionChecks;
3641
- const notNull = column.required ? [{
3642
- kind: "not-null",
3643
- severity: "blocking",
3644
- model: wanted.model,
3645
- subject,
3646
- what: existing.nullable ? "column becomes NOT NULL" : "NOT NULL",
3647
- unit: "NULL row",
3648
- hint: "Fill the NULLs before the column becomes NOT NULL, or say what fills them on the Migrate page of hekireki studio; a @default does not fill rows already there.",
3649
- guaranteed: trusted && !existing.nullable,
3650
- statement: withFixes(countWhere(dialect, from, `${quoteIdentifier(dialect, column.column)} IS NULL`))
3651
- }] : [];
3652
- const allowed = column.enumValues ?? [];
3653
- const members = column.kind === "enum" && !column.isList && allowed.length > 0 ? [{
3654
- kind: "enum",
3655
- severity: "blocking",
3656
- model: wanted.model,
3657
- subject,
3658
- what: `values outside enum ${column.type}`,
3659
- unit: "row",
3660
- hint: "Move the rows to a member that stays before the enum changes, or say what each stored value becomes on the Migrate page of hekireki studio.",
3661
- guaranteed: trusted && (existing.enumValues?.every((value) => allowed.includes(value)) ?? false),
3662
- statement: withFixes(countOutsideEnum(dialect, from, column.column, allowed))
3663
- }] : [];
3664
4000
  return [
3665
- ...notNull,
4001
+ ...column.required ? [{
4002
+ kind: "not-null",
4003
+ severity: "blocking",
4004
+ model: wanted.model,
4005
+ subject,
4006
+ what: existing.nullable ? "column becomes NOT NULL" : "NOT NULL",
4007
+ unit: "NULL row",
4008
+ hint: "Fill the NULLs before the column becomes NOT NULL, or say what fills them on the Migrate page of hekireki studio; a @default does not fill rows already there.",
4009
+ guaranteed: trusted && !existing.nullable,
4010
+ statement: withFixes(countWhere(dialect, from, `${quoteIdentifier(dialect, column.column)} IS NULL`))
4011
+ }] : [],
3666
4012
  ...conversionChecks,
3667
- ...members
4013
+ ...enumChecks(column, existing, subject)
3668
4014
  ];
3669
4015
  });
3670
4016
  const uniques = wanted.uniques.filter((unique) => unique.columns.every(has) && !unique.columns.some((column) => recreated.has(column))).map((unique) => ({
@@ -3675,15 +4021,21 @@ function makeChecks(input) {
3675
4021
  what: unique.fields.length === 1 ? "unique" : "unique together",
3676
4022
  unit: "duplicate group",
3677
4023
  hint: "Merge or remove the duplicates before the constraint is created, or say which to keep on the Migrate page of hekireki studio.",
3678
- guaranteed: trusted && actual.uniques.some((existing) => existing.length > 0 && existing.every((column) => unique.columns.includes(column))),
4024
+ guaranteed: trusted && coveredByKey(actual.uniques, unique.columns),
3679
4025
  statement: withFixes(countDuplicates(dialect, from, unique.columns))
3680
4026
  }));
4027
+ const enforced = new Set(actual.foreignKeys.filter((existing) => existing.enforced).map((existing) => JSON.stringify([keyOf({
4028
+ schema: existing.refSchema,
4029
+ table: existing.refTable
4030
+ }), pairs(existing.columns, existing.refColumns)])));
3681
4031
  const foreignKeys = wanted.foreignKeys.filter((foreignKey) => {
3682
4032
  const target = actualByKey.get(keyOf({
3683
4033
  schema: foreignKey.toSchema,
3684
4034
  table: foreignKey.toTable
3685
4035
  }));
3686
- return target !== void 0 && foreignKey.fromColumns.every(has) && !foreignKey.fromColumns.some((column) => recreated.has(column)) && foreignKey.toColumns.every((column) => target.columns.some((c) => c.name === column));
4036
+ if (target === void 0) return false;
4037
+ const targetColumns = new Set(target.columns.map((c) => c.name));
4038
+ return foreignKey.fromColumns.every(has) && !foreignKey.fromColumns.some((column) => recreated.has(column)) && foreignKey.toColumns.every((column) => targetColumns.has(column));
3687
4039
  }).map((foreignKey) => ({
3688
4040
  kind: "foreign-key",
3689
4041
  severity: "blocking",
@@ -3695,19 +4047,18 @@ function makeChecks(input) {
3695
4047
  guaranteed: trusted && !fixed({
3696
4048
  schema: foreignKey.toSchema,
3697
4049
  table: foreignKey.toTable
3698
- }) && actual.foreignKeys.some((existing) => existing.enforced && keyOf({
3699
- schema: existing.refSchema,
3700
- table: existing.refTable
3701
- }) === keyOf({
4050
+ }) && enforced.has(JSON.stringify([keyOf({
3702
4051
  schema: foreignKey.toSchema,
3703
4052
  table: foreignKey.toTable
3704
- }) && pairs(existing.columns, existing.refColumns) === pairs(foreignKey.fromColumns, foreignKey.toColumns)),
4053
+ }), pairs(foreignKey.fromColumns, foreignKey.toColumns)])),
3705
4054
  statement: withFixes(countOrphans(dialect, from, source({
3706
4055
  schema: foreignKey.toSchema,
3707
4056
  table: foreignKey.toTable
3708
4057
  }), foreignKey))
3709
4058
  }));
3710
- const dropped = actual.columns.filter((column) => !wanted.columns.some((c) => c.column === column.name) && !fixes.moved.some((m) => m.key === keyOf(actual) && m.column === column.name)).map((column) => ({
4059
+ const wantedColumns = new Set(wanted.columns.map((c) => c.column));
4060
+ const movedAway = new Set(fixes.moved.filter((m) => m.key === keyOf(actual)).map((m) => m.column));
4061
+ const dropped = actual.columns.filter((column) => !wantedColumns.has(column.name) && !movedAway.has(column.name)).map((column) => ({
3711
4062
  kind: "column-dropped",
3712
4063
  severity: "warning",
3713
4064
  model: wanted.model,
@@ -3881,7 +4232,10 @@ function spelling(text) {
3881
4232
  }
3882
4233
  /** What fills the rows already there of a column that becomes, or is added, required. */
3883
4234
  function fill(input) {
3884
- const { column, sql } = input;
4235
+ return generatedFill(input.column, input.sql) ?? referencedFill(input) ?? valueFill(input);
4236
+ }
4237
+ /** The schema's own default, or the value a generated default would have made. */
4238
+ function generatedFill(column, sql) {
3885
4239
  if (column.defaultValue !== null) return {
3886
4240
  choice: "value",
3887
4241
  value: column.defaultValue,
@@ -3906,6 +4260,14 @@ function fill(input) {
3906
4260
  value: sql.now,
3907
4261
  reason: "now"
3908
4262
  };
4263
+ return null;
4264
+ }
4265
+ /**
4266
+ * A key that points at another table cannot take a made-up value: the foreign key refuses what
4267
+ * is not there. The rows go to a row that is, to be pointed at the right one afterwards.
4268
+ */
4269
+ function referencedFill(input) {
4270
+ const { column, sql } = input;
3909
4271
  const pointing = input.table.foreignKeys.find((fk) => fk.fromColumns.length === 1 && fk.fromColumns[0] === column.column);
3910
4272
  const [target] = pointing?.toColumns ?? [];
3911
4273
  if (pointing !== void 0 && target !== void 0 && pointing.toColumns.length === 1) return {
@@ -3913,25 +4275,14 @@ function fill(input) {
3913
4275
  value: sql.firstKey(pointing.toTable, pointing.toSchema ?? null, target),
3914
4276
  reason: "first-referenced"
3915
4277
  };
3916
- const [key] = input.table.primaryKey;
3917
- if (column.kind === "enum") {
3918
- const member = column.enumMembers?.[0]?.name;
3919
- return member === void 0 ? null : {
3920
- choice: "value",
3921
- value: member,
3922
- reason: "enum-first"
3923
- };
3924
- }
4278
+ return null;
4279
+ }
4280
+ /** A plain value of the column's type: its first enum member, nothing, zero, false, now. */
4281
+ function valueFill(input) {
4282
+ const { column, sql } = input;
4283
+ if (column.kind === "enum") return enumFill(column);
3925
4284
  switch (column.type) {
3926
- case "String": return input.unique && key !== void 0 && input.table.primaryKey.length === 1 ? {
3927
- choice: "sql",
3928
- value: sql.prefixed(`${column.field}-`, key),
3929
- reason: "from-key"
3930
- } : {
3931
- choice: "value",
3932
- value: "",
3933
- reason: "empty-string"
3934
- };
4285
+ case "String": return stringFill(input);
3935
4286
  case "Int":
3936
4287
  case "BigInt":
3937
4288
  case "Float":
@@ -3958,6 +4309,337 @@ function fill(input) {
3958
4309
  default: return null;
3959
4310
  }
3960
4311
  }
4312
+ function enumFill(column) {
4313
+ const member = column.enumMembers?.[0]?.name;
4314
+ return member === void 0 ? null : {
4315
+ choice: "value",
4316
+ value: member,
4317
+ reason: "enum-first"
4318
+ };
4319
+ }
4320
+ /** A unique column cannot take one value for every row: each gets its own, from its key. */
4321
+ function stringFill(input) {
4322
+ const { column, table, sql } = input;
4323
+ const [key] = table.primaryKey;
4324
+ return input.unique && key !== void 0 && table.primaryKey.length === 1 ? {
4325
+ choice: "sql",
4326
+ value: sql.prefixed(`${column.field}-`, key),
4327
+ reason: "from-key"
4328
+ } : {
4329
+ choice: "value",
4330
+ value: "",
4331
+ reason: "empty-string"
4332
+ };
4333
+ }
4334
+ /** The types a type change goes between, whatever it does to the values. */
4335
+ function typeChangeFacts(kind, column, existing) {
4336
+ if (column === void 0 || existing === void 0) return {};
4337
+ return kind.startsWith("value-") || kind.startsWith("column-") ? {
4338
+ from: existing.columnType ?? existing.dataType,
4339
+ to: column.type
4340
+ } : {};
4341
+ }
4342
+ function adviseFill(site) {
4343
+ const { table, column, sql, advise } = site;
4344
+ if (column === void 0) return advise(null);
4345
+ const suggestion = fill({
4346
+ column,
4347
+ table,
4348
+ sql,
4349
+ unique: table.uniques.some((key) => key.columns.length === 1 && key.columns[0] === column.column)
4350
+ });
4351
+ return advise(suggestion, {
4352
+ type: column.type,
4353
+ ...suggestion?.reason === "schema-default" ? { default: column.defaultValue ?? "" } : {},
4354
+ ...suggestion?.reason === "enum-first" ? { member: suggestion.value ?? "" } : {},
4355
+ ...suggestion?.reason === "first-referenced" ? { target: table.foreignKeys.find((fk) => fk.fromColumns[0] === column.column)?.toModel ?? "" } : {}
4356
+ });
4357
+ }
4358
+ function adviseEnum(site) {
4359
+ const { input, check, field, column, existing, advise } = site;
4360
+ if (column === void 0) return advise(null);
4361
+ const members = column.enumMembers ?? [];
4362
+ const allowed = new Set(members.map((m) => m.dbName));
4363
+ const stored = input.stored.get(`${check.model}.${field}`) ?? [];
4364
+ const removed = stored.filter((value) => !allowed.has(value));
4365
+ const before = /* @__PURE__ */ new Set([...existing?.enumValues ?? [], ...stored]);
4366
+ const added = members.filter((m) => !before.has(m.dbName));
4367
+ const facts = {
4368
+ enum: column.type,
4369
+ removed: removed.join(", "),
4370
+ members: members.map((m) => m.name).join(", ")
4371
+ };
4372
+ const mapped = enumMapping(members, column.defaultValue, removed, added);
4373
+ return mapped === null ? advise(null, facts) : advise(mapped.suggestion, {
4374
+ ...facts,
4375
+ member: mapped.member
4376
+ });
4377
+ }
4378
+ /** Where the values an enum loses go, and the member the page names for it. */
4379
+ function enumMapping(members, defaultValue, removed, added) {
4380
+ const fallback = members.find((m) => m.name === defaultValue) ?? members[0];
4381
+ const sameName = (value) => members.find((m) => spelling(m.name) === spelling(value)) ?? members.find((m) => spelling(m.dbName) === spelling(value));
4382
+ const unmatched = removed.filter((value) => sameName(value) === void 0);
4383
+ if (removed.length > 0 && unmatched.length < removed.length && fallback !== void 0) return {
4384
+ suggestion: {
4385
+ choice: "map",
4386
+ value: formatMapping(removed.map((value) => [value, (sameName(value) ?? fallback).name])),
4387
+ reason: "enum-same-name"
4388
+ },
4389
+ member: unmatched.length === 0 ? "" : fallback.name
4390
+ };
4391
+ const [only] = removed;
4392
+ const [replacement] = added;
4393
+ if (removed.length === 1 && added.length === 1 && only !== void 0 && replacement !== void 0) return {
4394
+ suggestion: {
4395
+ choice: "map",
4396
+ value: formatMapping([[only, replacement.name]]),
4397
+ reason: "enum-replaced"
4398
+ },
4399
+ member: replacement.name
4400
+ };
4401
+ if (removed.length === 0 || fallback === void 0) return null;
4402
+ return {
4403
+ suggestion: {
4404
+ choice: "map",
4405
+ value: formatMapping(removed.map((value) => [value, fallback.name])),
4406
+ reason: fallback.name === defaultValue ? "enum-default" : "enum-first"
4407
+ },
4408
+ member: fallback.name
4409
+ };
4410
+ }
4411
+ function adviseUnique(site) {
4412
+ const { table, field, advise } = site;
4413
+ const fields = field.split(", ");
4414
+ const columnOf = new Map(table.columns.toReversed().map((c) => [c.field, c]));
4415
+ const optional = fields.map((one) => columnOf.get(one)).some((c) => c !== void 0 && !c.required);
4416
+ const created = table.columns.find((c) => c.defaultFunction === "now" && /created/iu.test(c.field)) ?? table.columns.find((c) => c.defaultFunction === "now");
4417
+ const choice = `keep-first-${optional ? "null" : "delete"}`;
4418
+ return created === void 0 ? advise({
4419
+ choice,
4420
+ value: null,
4421
+ reason: "first-by-key"
4422
+ }, { fields: fields.join(", ") }) : advise({
4423
+ choice,
4424
+ value: created.field,
4425
+ reason: "oldest"
4426
+ }, {
4427
+ fields: fields.join(", "),
4428
+ orderBy: created.field
4429
+ });
4430
+ }
4431
+ function adviseForeignKey(site) {
4432
+ const { table, field, advise } = site;
4433
+ const foreignKey = table.foreignKeys.find((fk) => fk.field === field);
4434
+ if (foreignKey === void 0) return advise(null);
4435
+ const requiredOf = new Map(table.columns.toReversed().map((c) => [c.column, c.required]));
4436
+ return advise(foreignKey.fromColumns.every((name) => requiredOf.get(name) === false) ? {
4437
+ choice: "null",
4438
+ value: null,
4439
+ reason: "optional-relation"
4440
+ } : {
4441
+ choice: "delete",
4442
+ value: null,
4443
+ reason: "required-relation"
4444
+ }, { target: foreignKey.toModel });
4445
+ }
4446
+ /**
4447
+ * How much a column the migration adds reads as a dropped one: its name (the same but for case
4448
+ * and separators, else the longest run of letters they share, three at least), then its kind
4449
+ * (text takes any value), then whether it may be empty as the dropped one may.
4450
+ */
4451
+ function likeness(one, family, c) {
4452
+ const sameName = spelling(c.column) === spelling(one.name) || spelling(c.field) === spelling(one.name);
4453
+ const run = Math.max(sharedRun(one.name, c.column), sharedRun(one.name, c.field));
4454
+ const kind = prismaFamily(c);
4455
+ const fits = kind === family || kind === "string";
4456
+ return {
4457
+ fits,
4458
+ sameName,
4459
+ weight: !fits || !sameName && run < 3 ? null : (sameName ? 100 : run * 2) + (kind === family ? 4 : 0) + (one.nullable === !c.required ? 1 : 0)
4460
+ };
4461
+ }
4462
+ /** How a related model and the table are related, over one column on either side. */
4463
+ function linkOf(table, other, child, parent) {
4464
+ if (child !== void 0) return {
4465
+ relation: "points-here",
4466
+ via: `${other.model}.${child.fromColumns[0] ?? ""} → ${table.model}.${child.toColumns[0] ?? ""}`
4467
+ };
4468
+ if (parent !== void 0) return {
4469
+ relation: "pointed-at",
4470
+ via: `${table.model}.${parent.fromColumns[0] ?? ""} → ${other.model}.${parent.toColumns[0] ?? ""}`
4471
+ };
4472
+ return null;
4473
+ }
4474
+ /**
4475
+ * The columns of a related model the values of a dropped column could move to: its rows point
4476
+ * at this table's, or this table's at its, over one column the database has now.
4477
+ */
4478
+ function movesInto(site, actual, other, parentsByModel, like) {
4479
+ const { table, has, actualOf } = site;
4480
+ if (other === table) return [];
4481
+ const otherActual = actualOf(other);
4482
+ const link = linkOf(table, other, other.foreignKeys.find((fk) => fk.toModel === table.model && fk.fromColumns.length === 1 && has(actual.columns, fk.toColumns[0] ?? "") && (otherActual === void 0 || has(otherActual.columns, fk.fromColumns[0] ?? ""))), otherActual === void 0 ? void 0 : parentsByModel.get(other.model)?.[0]);
4483
+ if (link === null) return [];
4484
+ const keys = /* @__PURE__ */ new Set([...other.primaryKey, ...other.foreignKeys.flatMap((fk) => fk.fromColumns)]);
4485
+ return other.columns.filter((c) => !has(otherActual?.columns, c.column) && !keys.has(c.column)).map((c) => {
4486
+ const likeIt = like(c);
4487
+ return {
4488
+ choice: "move",
4489
+ value: `${other.model}.${c.field}`,
4490
+ type: c.type,
4491
+ relation: link.relation,
4492
+ via: link.via,
4493
+ created: otherActual === void 0,
4494
+ fits: likeIt.fits,
4495
+ sameName: likeIt.sameName,
4496
+ weight: likeIt.weight
4497
+ };
4498
+ });
4499
+ }
4500
+ /**
4501
+ * Every column the migration adds that a dropped column of this table could have gone to: in
4502
+ * the table itself (a rename), or in a related model (a move), with how the two are related and
4503
+ * how much it reads as the dropped one.
4504
+ */
4505
+ function placesOf(site, actual, one) {
4506
+ const { input, table, has } = site;
4507
+ const family = databaseFamily({
4508
+ dialect: input.dialect,
4509
+ dataType: one.dataType,
4510
+ columnType: one.columnType
4511
+ });
4512
+ const like = (c) => likeness(one, family, c);
4513
+ const keyColumns = new Set(table.primaryKey);
4514
+ const renames = table.columns.filter((c) => !has(actual.columns, c.column) && !keyColumns.has(c.column)).map((c) => {
4515
+ const likeIt = like(c);
4516
+ return {
4517
+ choice: "rename",
4518
+ value: c.field,
4519
+ type: c.type,
4520
+ relation: "same",
4521
+ via: null,
4522
+ created: false,
4523
+ fits: likeIt.fits,
4524
+ sameName: likeIt.sameName,
4525
+ weight: likeIt.weight
4526
+ };
4527
+ });
4528
+ const parentsByModel = Map.groupBy(table.foreignKeys.filter((fk) => fk.fromColumns.length === 1 && has(actual.columns, fk.fromColumns[0] ?? "")), (fk) => fk.toModel);
4529
+ const moves = input.expected.flatMap((other) => movesInto(site, actual, other, parentsByModel, like));
4530
+ return [...renames, ...moves];
4531
+ }
4532
+ /** Why a place reads as where the values went. */
4533
+ function placeReason(choice, sameName) {
4534
+ const named = sameName ? "same-name" : "similar-name";
4535
+ return choice === "move" ? `${named}-related` : named;
4536
+ }
4537
+ /** The places that read as where the values went, the likeliest first. */
4538
+ function rankPlaces(places) {
4539
+ return places.flatMap((place) => place.weight === null ? [] : [{
4540
+ choice: place.choice,
4541
+ value: place.value,
4542
+ reason: placeReason(place.choice, place.sameName),
4543
+ sameName: place.sameName,
4544
+ weight: place.weight
4545
+ }]).toSorted((x, y) => y.weight - x.weight);
4546
+ }
4547
+ /**
4548
+ * Two columns dropped can read as gone to one place (`fullName` and `nickname` to `name`): the
4549
+ * place is suggested for the one it reads as more, and for neither on a tie.
4550
+ */
4551
+ function outdone(site, actual, dropped, best) {
4552
+ const { table, normal } = site;
4553
+ const kept = new Set(table.columns.map((c) => normal(c.column)));
4554
+ return actual.columns.filter((other) => other.name !== dropped.name && !kept.has(normal(other.name))).some((other) => {
4555
+ const [theirs] = rankPlaces(placesOf(site, actual, other));
4556
+ return theirs !== void 0 && theirs.choice === best.choice && theirs.value === best.value && theirs.weight >= best.weight;
4557
+ });
4558
+ }
4559
+ function adviseDropped(site) {
4560
+ const { actual, field, advise } = site;
4561
+ const dropped = actual?.columns.find((c) => c.name === field);
4562
+ if (actual === void 0 || dropped === void 0) return advise(null);
4563
+ const places = placesOf(site, actual, dropped);
4564
+ const destinations = places.map((place) => ({
4565
+ choice: place.choice,
4566
+ value: place.value,
4567
+ type: place.type,
4568
+ fits: place.fits,
4569
+ relation: place.relation,
4570
+ via: place.via,
4571
+ created: place.created
4572
+ }));
4573
+ const ranked = rankPlaces(places);
4574
+ const candidates = ranked.map((c) => ({
4575
+ choice: c.choice,
4576
+ value: c.value,
4577
+ reason: c.reason
4578
+ }));
4579
+ const [best, second] = ranked;
4580
+ if (best === void 0) return advise(null, { column: field }, candidates, destinations);
4581
+ if (!(best.sameName || second === void 0 || best.weight > second.weight) || outdone(site, actual, dropped, best)) return advise(null, { column: field }, candidates, destinations);
4582
+ return advise({
4583
+ choice: best.choice,
4584
+ value: best.value,
4585
+ reason: best.choice === "move" ? "moved" : "renamed"
4586
+ }, best.choice === "move" ? {
4587
+ column: field,
4588
+ movedTo: best.value
4589
+ } : {
4590
+ column: field,
4591
+ renamedTo: best.value
4592
+ }, candidates, destinations);
4593
+ }
4594
+ function adviseConversion(site) {
4595
+ const { input, sql, column, existing, advise } = site;
4596
+ if (column === void 0 || existing === void 0) return advise(null);
4597
+ const converted = databaseFamily({
4598
+ dialect: input.dialect,
4599
+ dataType: existing.dataType,
4600
+ columnType: existing.columnType
4601
+ }) === "string" ? sql.number(column.column, column.type) : null;
4602
+ return converted === null ? advise(null) : advise({
4603
+ choice: "sql",
4604
+ value: converted,
4605
+ reason: "convert-number"
4606
+ });
4607
+ }
4608
+ /** What each kind of check is advised by. */
4609
+ const ADVISERS = /* @__PURE__ */ new Map([
4610
+ ["not-null", adviseFill],
4611
+ ["column-added", adviseFill],
4612
+ ["enum", adviseEnum],
4613
+ ["unique", adviseUnique],
4614
+ ["foreign-key", adviseForeignKey],
4615
+ ["column-dropped", adviseDropped],
4616
+ ["column-type", adviseConversion],
4617
+ ["column-recreated", adviseConversion],
4618
+ ["value-out-of-range", (site) => site.advise({
4619
+ choice: "clamp",
4620
+ value: null,
4621
+ reason: "clamp"
4622
+ })],
4623
+ ["value-too-long", (site) => site.advise({
4624
+ choice: "truncate",
4625
+ value: null,
4626
+ reason: "truncate"
4627
+ })],
4628
+ ["value-truncated", (site) => site.advise({
4629
+ choice: "truncate",
4630
+ value: null,
4631
+ reason: "truncate"
4632
+ })],
4633
+ ["value-not-convertible", (site) => site.advise(site.column?.required === false ? {
4634
+ choice: "null",
4635
+ value: null,
4636
+ reason: "nullable"
4637
+ } : {
4638
+ choice: "delete",
4639
+ value: null,
4640
+ reason: "not-nullable"
4641
+ })]
4642
+ ]);
3961
4643
  /**
3962
4644
  * The facts and the suggestion of each check, in the order the checks are given.
3963
4645
  *
@@ -3967,279 +4649,55 @@ function fill(input) {
3967
4649
  */
3968
4650
  function adviseChecks(input) {
3969
4651
  const sql = sqlOf(input.dialect, input.cockroach);
3970
- const same = (a, b) => input.dialect === "mysql" ? a.toLowerCase() === b.toLowerCase() : a === b;
4652
+ const normal = (name) => input.dialect === "mysql" ? name.toLowerCase() : name;
4653
+ const same = (a, b) => normal(a) === normal(b);
3971
4654
  const has = (columns, name) => columns?.some((c) => same(c.name, name)) === true;
3972
4655
  const actualOf = (table) => input.actual.find((t) => same(t.table, table.table) && (table.schema === null || t.schema === null || t.schema === table.schema));
3973
- return input.checks.map((check) => {
3974
- const field = fieldOf(check);
3975
- const table = input.expected.find((t) => t.model === check.model);
3976
- const actual = table === void 0 ? void 0 : actualOf(table);
3977
- const column = table?.columns.find((c) => c.field === field);
3978
- const existing = actual?.columns.find((c) => c.name === column?.column);
3979
- const base = {
3980
- model: check.model,
3981
- field,
3982
- subject: check.subject,
3983
- what: check.what,
3984
- ...column !== void 0 && existing !== void 0 && (check.kind.startsWith("value-") || check.kind.startsWith("column-")) ? {
3985
- from: existing.columnType ?? existing.dataType,
3986
- to: column.type
3987
- } : {}
3988
- };
3989
- const advise = (suggestion, facts = {}, candidates = [], destinations = []) => ({
3990
- facts: {
3991
- ...base,
3992
- ...facts
3993
- },
3994
- suggestion,
3995
- candidates,
3996
- destinations
3997
- });
3998
- if (check.kind === "table-dropped") return advise(null, { table: check.subject });
3999
- if (table === void 0) return advise(null);
4000
- switch (check.kind) {
4001
- case "not-null":
4002
- case "column-added": {
4003
- if (column === void 0) return advise(null);
4004
- const unique = table.uniques.some((key) => key.columns.length === 1 && key.columns[0] === column.column);
4005
- const suggestion = fill({
4006
- column,
4007
- table,
4008
- sql,
4009
- unique
4010
- });
4011
- return advise(suggestion, {
4012
- type: column.type,
4013
- ...suggestion?.reason === "schema-default" ? { default: column.defaultValue ?? "" } : {},
4014
- ...suggestion?.reason === "enum-first" ? { member: suggestion.value ?? "" } : {},
4015
- ...suggestion?.reason === "first-referenced" ? { target: table.foreignKeys.find((fk) => fk.fromColumns[0] === column.column)?.toModel ?? "" } : {}
4016
- });
4017
- }
4018
- case "enum": {
4019
- if (column === void 0) return advise(null);
4020
- const members = column.enumMembers ?? [];
4021
- const allowed = new Set(members.map((m) => m.dbName));
4022
- const stored = input.stored.get(`${check.model}.${field}`) ?? [];
4023
- const removed = stored.filter((value) => !allowed.has(value));
4024
- const before = /* @__PURE__ */ new Set([...existing?.enumValues ?? [], ...stored]);
4025
- const added = members.filter((m) => !before.has(m.dbName));
4026
- const facts = {
4027
- enum: column.type,
4028
- removed: removed.join(", "),
4029
- members: members.map((m) => m.name).join(", ")
4030
- };
4031
- const fallback = members.find((m) => m.name === column.defaultValue) ?? members[0];
4032
- const sameName = (value) => members.find((m) => spelling(m.name) === spelling(value)) ?? members.find((m) => spelling(m.dbName) === spelling(value));
4033
- const unmatched = removed.filter((value) => sameName(value) === void 0);
4034
- if (removed.length > 0 && unmatched.length < removed.length && fallback !== void 0) return advise({
4035
- choice: "map",
4036
- value: formatMapping(removed.map((value) => [value, (sameName(value) ?? fallback).name])),
4037
- reason: "enum-same-name"
4038
- }, {
4039
- ...facts,
4040
- member: unmatched.length === 0 ? "" : fallback.name
4041
- });
4042
- const [only] = removed;
4043
- const [replacement] = added;
4044
- if (removed.length === 1 && added.length === 1 && only !== void 0 && replacement) return advise({
4045
- choice: "map",
4046
- value: formatMapping([[only, replacement.name]]),
4047
- reason: "enum-replaced"
4048
- }, {
4049
- ...facts,
4050
- member: replacement.name
4051
- });
4052
- if (removed.length === 0 || fallback === void 0) return advise(null, facts);
4053
- return advise({
4054
- choice: "map",
4055
- value: formatMapping(removed.map((value) => [value, fallback.name])),
4056
- reason: fallback.name === column.defaultValue ? "enum-default" : "enum-first"
4057
- }, {
4058
- ...facts,
4059
- member: fallback.name
4060
- });
4061
- }
4062
- case "unique": {
4063
- const fields = field.split(", ");
4064
- const optional = fields.map((one) => table.columns.find((c) => c.field === one)).some((c) => c !== void 0 && !c.required);
4065
- const created = table.columns.find((c) => c.defaultFunction === "now" && /created/iu.test(c.field)) ?? table.columns.find((c) => c.defaultFunction === "now");
4066
- const choice = `keep-first-${optional ? "null" : "delete"}`;
4067
- return created === void 0 ? advise({
4068
- choice,
4069
- value: null,
4070
- reason: "first-by-key"
4071
- }, { fields: fields.join(", ") }) : advise({
4072
- choice,
4073
- value: created.field,
4074
- reason: "oldest"
4075
- }, {
4076
- fields: fields.join(", "),
4077
- orderBy: created.field
4078
- });
4079
- }
4080
- case "foreign-key": {
4081
- const foreignKey = table.foreignKeys.find((fk) => fk.field === field);
4082
- if (foreignKey === void 0) return advise(null);
4083
- return advise(foreignKey.fromColumns.every((name) => table.columns.find((c) => c.column === name)?.required === false) ? {
4084
- choice: "null",
4085
- value: null,
4086
- reason: "optional-relation"
4087
- } : {
4088
- choice: "delete",
4089
- value: null,
4090
- reason: "required-relation"
4091
- }, { target: foreignKey.toModel });
4092
- }
4093
- case "column-dropped": {
4094
- const dropped = actual?.columns.find((c) => c.name === field);
4095
- if (actual === void 0 || dropped === void 0) return advise(null);
4096
- /**
4097
- * Every column the migration adds that a dropped column of this table could have gone
4098
- * to: in the table itself (a rename), or in a related model (a move), with how the two
4099
- * are related and how much it reads as the dropped one.
4100
- */
4101
- const placesOf = (one) => {
4102
- const family = databaseFamily({
4103
- dialect: input.dialect,
4104
- dataType: one.dataType,
4105
- columnType: one.columnType
4106
- });
4107
- const likeness = (c) => {
4108
- const sameName = spelling(c.column) === spelling(one.name) || spelling(c.field) === spelling(one.name);
4109
- const run = Math.max(sharedRun(one.name, c.column), sharedRun(one.name, c.field));
4110
- const kind = prismaFamily(c);
4111
- const fits = kind === family || kind === "string";
4112
- return {
4113
- fits,
4114
- sameName,
4115
- weight: !fits || !sameName && run < 3 ? null : (sameName ? 100 : run * 2) + (kind === family ? 4 : 0) + (one.nullable === !c.required ? 1 : 0)
4116
- };
4117
- };
4118
- const renames = table.columns.filter((c) => !has(actual.columns, c.column) && !table.primaryKey.includes(c.column)).map((c) => {
4119
- const like = likeness(c);
4120
- return {
4121
- choice: "rename",
4122
- value: c.field,
4123
- type: c.type,
4124
- relation: "same",
4125
- via: null,
4126
- created: false,
4127
- fits: like.fits,
4128
- sameName: like.sameName,
4129
- weight: like.weight
4130
- };
4131
- });
4132
- const moves = input.expected.flatMap((other) => {
4133
- if (other === table) return [];
4134
- const otherActual = actualOf(other);
4135
- const child = other.foreignKeys.find((fk) => fk.toModel === table.model && fk.fromColumns.length === 1 && has(actual.columns, fk.toColumns[0] ?? "") && (otherActual === void 0 || has(otherActual.columns, fk.fromColumns[0] ?? "")));
4136
- const parent = otherActual === void 0 ? void 0 : table.foreignKeys.find((fk) => fk.toModel === other.model && fk.fromColumns.length === 1 && has(actual.columns, fk.fromColumns[0] ?? ""));
4137
- const link = child !== void 0 ? {
4138
- relation: "points-here",
4139
- via: `${other.model}.${child.fromColumns[0] ?? ""} → ${table.model}.${child.toColumns[0] ?? ""}`
4140
- } : parent !== void 0 ? {
4141
- relation: "pointed-at",
4142
- via: `${table.model}.${parent.fromColumns[0] ?? ""} → ${other.model}.${parent.toColumns[0] ?? ""}`
4143
- } : null;
4144
- if (link === null) return [];
4145
- const keys = /* @__PURE__ */ new Set([...other.primaryKey, ...other.foreignKeys.flatMap((fk) => fk.fromColumns)]);
4146
- return other.columns.filter((c) => !has(otherActual?.columns, c.column) && !keys.has(c.column)).map((c) => {
4147
- const like = likeness(c);
4148
- return {
4149
- choice: "move",
4150
- value: `${other.model}.${c.field}`,
4151
- type: c.type,
4152
- relation: link.relation,
4153
- via: link.via,
4154
- created: otherActual === void 0,
4155
- fits: like.fits,
4156
- sameName: like.sameName,
4157
- weight: like.weight
4158
- };
4159
- });
4160
- });
4161
- return [...renames, ...moves];
4162
- };
4163
- /** The places that read as where the values went, the likeliest first. */
4164
- const rankOf = (places) => places.flatMap((place) => place.weight === null ? [] : [{
4165
- choice: place.choice,
4166
- value: place.value,
4167
- reason: place.choice === "move" ? place.sameName ? "same-name-related" : "similar-name-related" : place.sameName ? "same-name" : "similar-name",
4168
- sameName: place.sameName,
4169
- weight: place.weight
4170
- }]).toSorted((x, y) => y.weight - x.weight);
4171
- const places = placesOf(dropped);
4172
- const destinations = places.map((place) => ({
4173
- choice: place.choice,
4174
- value: place.value,
4175
- type: place.type,
4176
- fits: place.fits,
4177
- relation: place.relation,
4178
- via: place.via,
4179
- created: place.created
4180
- }));
4181
- const ranked = rankOf(places);
4182
- const candidates = ranked.map((c) => ({
4183
- choice: c.choice,
4184
- value: c.value,
4185
- reason: c.reason
4186
- }));
4187
- const [best, second] = ranked;
4188
- const standsOut = best !== void 0 && (best.sameName || second === void 0 || best.weight > second.weight);
4189
- const outdone = best !== void 0 && actual.columns.filter((other) => other.name !== dropped.name && !table.columns.some((c) => same(c.column, other.name))).some((other) => {
4190
- const [theirs] = rankOf(placesOf(other));
4191
- return theirs !== void 0 && theirs.choice === best.choice && theirs.value === best.value && theirs.weight >= best.weight;
4192
- });
4193
- if (best === void 0 || !standsOut || outdone) return advise(null, { column: field }, candidates, destinations);
4194
- return advise({
4195
- choice: best.choice,
4196
- value: best.value,
4197
- reason: best.choice === "move" ? "moved" : "renamed"
4198
- }, best.choice === "move" ? {
4199
- column: field,
4200
- movedTo: best.value
4201
- } : {
4202
- column: field,
4203
- renamedTo: best.value
4204
- }, candidates, destinations);
4205
- }
4206
- case "column-type":
4207
- case "column-recreated": {
4208
- if (column === void 0 || existing === void 0) return advise(null);
4209
- const converted = databaseFamily({
4210
- dialect: input.dialect,
4211
- dataType: existing.dataType,
4212
- columnType: existing.columnType
4213
- }) === "string" ? sql.number(column.column, column.type) : null;
4214
- return converted === null ? advise(null) : advise({
4215
- choice: "sql",
4216
- value: converted,
4217
- reason: "convert-number"
4218
- });
4219
- }
4220
- case "value-out-of-range": return advise({
4221
- choice: "clamp",
4222
- value: null,
4223
- reason: "clamp"
4224
- });
4225
- case "value-too-long":
4226
- case "value-truncated": return advise({
4227
- choice: "truncate",
4228
- value: null,
4229
- reason: "truncate"
4230
- });
4231
- case "value-not-convertible": return advise(column?.required === false ? {
4232
- choice: "null",
4233
- value: null,
4234
- reason: "nullable"
4235
- } : {
4236
- choice: "delete",
4237
- value: null,
4238
- reason: "not-nullable"
4239
- });
4240
- default: return advise(null);
4241
- }
4656
+ const env = {
4657
+ input,
4658
+ sql,
4659
+ normal,
4660
+ has,
4661
+ actualOf
4662
+ };
4663
+ const modelOf = new Map(input.expected.toReversed().map((t) => [t.model, t]));
4664
+ return input.checks.map((check) => adviseCheck(env, check, modelOf.get(check.model)));
4665
+ }
4666
+ function adviseCheck(env, check, table) {
4667
+ const field = fieldOf(check);
4668
+ const actual = table === void 0 ? void 0 : env.actualOf(table);
4669
+ const column = table?.columns.find((c) => c.field === field);
4670
+ const existing = actual?.columns.find((c) => c.name === column?.column);
4671
+ const base = {
4672
+ model: check.model,
4673
+ field,
4674
+ subject: check.subject,
4675
+ what: check.what,
4676
+ ...typeChangeFacts(check.kind, column, existing)
4677
+ };
4678
+ const advise = (suggestion, facts = {}, candidates = [], destinations = []) => ({
4679
+ facts: {
4680
+ ...base,
4681
+ ...facts
4682
+ },
4683
+ suggestion,
4684
+ candidates,
4685
+ destinations
4242
4686
  });
4687
+ if (check.kind === "table-dropped") return advise(null, { table: check.subject });
4688
+ if (table === void 0) return advise(null);
4689
+ const adviser = ADVISERS.get(check.kind);
4690
+ const site = {
4691
+ ...env,
4692
+ check,
4693
+ field,
4694
+ table,
4695
+ actual,
4696
+ column,
4697
+ existing,
4698
+ advise
4699
+ };
4700
+ return adviser === void 0 ? advise(null) : adviser(site);
4243
4701
  }
4244
4702
  /**
4245
4703
  * The values an enum column stores now, to tell which of them the new enum loses: read from the
@@ -4356,14 +4814,14 @@ function uniqueSets(model) {
4356
4814
  const singles = model.fields.filter((f) => f.kind !== "object" && (f.isUnique || f.isId)).map((f) => [f.name]);
4357
4815
  const composite = [...model.primaryKey === null ? [] : [model.primaryKey.fields], ...model.uniqueFields];
4358
4816
  const all = [...singles, ...composite];
4359
- return all.filter((set, index) => all.findIndex((other) => other.join(" ") === set.join(" ")) === index).map((fields) => ({
4817
+ return [...Map.groupBy(all, (set) => set.join(" ")).values()].flatMap((same) => same.slice(0, 1)).map((fields) => ({
4360
4818
  fields,
4361
4819
  columns: fields.map((field) => columnOf(model, field))
4362
4820
  }));
4363
4821
  }
4364
- function makeModelTable(model, models, enums) {
4822
+ function makeModelTable(model, modelByName, enums) {
4365
4823
  const foreignKeys = model.fields.filter((f) => f.kind === "object" && (f.relationFromFields ?? []).length > 0).flatMap((f) => {
4366
- const target = models.find((m) => m.name === f.type);
4824
+ const target = modelByName.get(f.type);
4367
4825
  if (target === void 0) return [];
4368
4826
  return [{
4369
4827
  field: f.name,
@@ -4420,8 +4878,9 @@ function joinForeignKey(model, column) {
4420
4878
  }
4421
4879
  /** The `_AToB` table Prisma keeps each implicit many-to-many relation in, once per relation. */
4422
4880
  function makeJoinTables(models, enums) {
4881
+ const modelByName = byName(models);
4423
4882
  return models.flatMap((model) => model.fields.filter((f) => f.kind === "object" && f.isList && (f.relationFromFields ?? []).length === 0).flatMap((field) => {
4424
- const other = models.find((m) => m.name === field.type);
4883
+ const other = modelByName.get(field.type);
4425
4884
  const inverse = backRelation(field, model, models);
4426
4885
  if (other === void 0 || inverse === void 0 || !inverse.isList) return [];
4427
4886
  if (!isJoinSideA(field, model, inverse)) return [];
@@ -4449,12 +4908,17 @@ function makeJoinTables(models, enums) {
4449
4908
  * columns it is stored in, and the table and columns it points at.
4450
4909
  */
4451
4910
  function makeExpectedTables(datamodel) {
4452
- return [...datamodel.models.map((model) => makeModelTable(model, datamodel.models, datamodel.enums)), ...makeJoinTables(datamodel.models, datamodel.enums)];
4911
+ const modelByName = byName(datamodel.models);
4912
+ return [...datamodel.models.map((model) => makeModelTable(model, modelByName, datamodel.enums)), ...makeJoinTables(datamodel.models, datamodel.enums)];
4913
+ }
4914
+ /** The models by name, the first of a name where two share one. */
4915
+ function byName(models) {
4916
+ return new Map(models.toReversed().map((m) => [m.name, m]));
4453
4917
  }
4454
4918
  // src/migrate/check.ts
4455
4919
  /** The number a `COUNT(*)` came back as: a string from pg (it is a bigint), a number elsewhere. */
4456
4920
  function countOf(rows) {
4457
- const value = Number(rows[0]?.count);
4921
+ const value = Number(rows[0]?.["count"]);
4458
4922
  return Number.isFinite(value) ? value : null;
4459
4923
  }
4460
4924
  /** A check with its count: what the report calls it. */
@@ -4523,7 +4987,7 @@ function checkOpened(input) {
4523
4987
  const run = (statements) => Effect.forEach(statements, (sql) => driver.query({
4524
4988
  sql,
4525
4989
  params: []
4526
- })).pipe(Effect.mapError((error) => new MigrateDatabaseError({ message: `Cannot prepare the connection: ${error.cause}` })));
4990
+ }), { concurrency: 1 }).pipe(Effect.mapError((error) => new MigrateDatabaseError({ message: `Cannot prepare the connection: ${error.cause}` })));
4527
4991
  if (input.readOnly) yield* run(readOnlyStatements(dialect));
4528
4992
  const introspected = yield* introspectDatabase({
4529
4993
  driver,
@@ -4543,17 +5007,20 @@ function checkOpened(input) {
4543
5007
  fixes: makeDecisionModels(kept)
4544
5008
  });
4545
5009
  const tried = checksWith(decisions);
5010
+ const errorsAbout = Map.groupBy(tried.errors.map((error, index) => ({
5011
+ error,
5012
+ index
5013
+ })), ({ error }) => error.slice(0, error.indexOf(": ")));
5014
+ const reasonsFor = (decision) => [.../* @__PURE__ */ new Set([decisionSubject(decision), decision.modelName])].flatMap((about) => errorsAbout.get(about) ?? []).toSorted((a, b) => a.index - b.index).map(({ error }) => error);
4546
5015
  const setAside = input.setAside ? decisions.flatMap((decision) => {
4547
- const reasons = tried.errors.filter((error) => {
4548
- const about = error.slice(0, error.indexOf(": "));
4549
- return about === decisionSubject(decision) || about === decision.modelName;
4550
- });
5016
+ const reasons = reasonsFor(decision);
4551
5017
  return reasons.length === 0 ? [] : [{
4552
5018
  decision,
4553
5019
  reasons
4554
5020
  }];
4555
5021
  }) : [];
4556
- const planned = setAside.length === 0 ? tried : checksWith(decisions.filter((decision) => !setAside.some((one) => one.decision === decision)));
5022
+ const setAsideDecisions = new Set(setAside.map((one) => one.decision));
5023
+ const planned = setAside.length === 0 ? tried : checksWith(decisions.filter((decision) => !setAsideDecisions.has(decision)));
4557
5024
  if (planned.errors.length > 0) return yield* new MigrateConfigError({ message: `The decisions in ${input.decisionsPath} do not fit the schema and the database:\n ${planned.errors.join("\n ")}\n Decide them again on the Migrate page of hekireki studio.` });
4558
5025
  const stored = new Map(yield* Effect.forEach(planned.checks.filter((check) => check.kind === "enum" && !check.guaranteed), (check) => {
4559
5026
  const table = expected.find((t) => t.model === check.model);
@@ -4561,9 +5028,9 @@ function checkOpened(input) {
4561
5028
  if (table === void 0 || column === void 0) return Effect.succeed([]);
4562
5029
  return driver.query(storedValues(dialect, table, column.column)).pipe(Effect.match({
4563
5030
  onFailure: () => [],
4564
- onSuccess: (read) => [[check.subject, read.rows.map((row) => String(row.value))]]
5031
+ onSuccess: (read) => [[check.subject, read.rows.map((row) => String(row["value"]))]]
4565
5032
  }));
4566
- }).pipe(Effect.map((entries) => entries.flat())));
5033
+ }, { concurrency: 1 }).pipe(Effect.map((entries) => entries.flat())));
4567
5034
  const advice = adviseChecks({
4568
5035
  dialect,
4569
5036
  cockroach,
@@ -4583,7 +5050,7 @@ function checkOpened(input) {
4583
5050
  rows: countOf(counted.rows),
4584
5051
  error: null
4585
5052
  })
4586
- })));
5053
+ })), { concurrency: 1 });
4587
5054
  const results = yield* Effect.forEach(planned.checks, (check, index) => {
4588
5055
  const { facts, suggestion, candidates, destinations } = advice[index] ?? {
4589
5056
  facts: {},
@@ -4625,7 +5092,7 @@ function checkOpened(input) {
4625
5092
  };
4626
5093
  }
4627
5094
  }));
4628
- });
5095
+ }, { concurrency: 1 });
4629
5096
  return {
4630
5097
  schemaPath: path.resolve(input.schemaPath),
4631
5098
  decisionsPath: input.decisionsPath,
@@ -4735,15 +5202,19 @@ function rewriteMigration(input) {
4735
5202
  const split = splitStatements(input.migration);
4736
5203
  const statements = cockroach ? joinAlters(split) : split;
4737
5204
  const targets = [...input.renames.map((r) => r.table), ...input.tables.filter((t) => t.converts.length + t.enumMaps.length + t.fills.length > 0).map((t) => t.table)];
4738
- const plans = [...new Set(targets.map((table) => qualifiedName(dialect, table)))].map((name) => {
4739
- const changes = input.tables.find((t) => qualifiedName(dialect, t.table) === name);
5205
+ const names = [...new Set(targets.map((table) => qualifiedName(dialect, table)))];
5206
+ const changesByName = Map.groupBy(input.tables, (t) => qualifiedName(dialect, t.table));
5207
+ const targetsByName = Map.groupBy(targets, (table) => qualifiedName(dialect, table));
5208
+ const renamesByName = Map.groupBy(input.renames, (r) => qualifiedName(dialect, r.table));
5209
+ const plans = names.map((name) => {
5210
+ const changes = changesByName.get(name)?.[0];
4740
5211
  return {
4741
5212
  name,
4742
- table: targets.find((table) => qualifiedName(dialect, table) === name) ?? {
5213
+ table: targetsByName.get(name)?.[0] ?? {
4743
5214
  schema: null,
4744
5215
  table: name
4745
5216
  },
4746
- renames: input.renames.filter((r) => qualifiedName(dialect, r.table) === name),
5217
+ renames: renamesByName.get(name) ?? [],
4747
5218
  converts: changes?.converts ?? [],
4748
5219
  enumMaps: changes?.enumMaps ?? [],
4749
5220
  fills: changes?.fills ?? []
@@ -4771,12 +5242,17 @@ function rewriteMigration(input) {
4771
5242
  });
4772
5243
  return {
4773
5244
  sql: `${(transaction ? statementsOnly : written).map((statement, index) => {
4774
- return `${index === 0 ? "" : commentOf(statement).comment === "" ? "\n" : "\n\n"}${statement}${commentOf(statement).body === "" ? "" : ";"}`;
5245
+ return `${gapBefore(statement, index)}${statement}${commentOf(statement).body === "" ? "" : ";"}`;
4775
5246
  }).join("")}\n`,
4776
5247
  errors: rewritten.errors,
4777
5248
  transaction
4778
5249
  };
4779
5250
  }
5251
+ /** Prisma's layout: nothing before the first statement, an empty line before one under a comment. */
5252
+ function gapBefore(statement, index) {
5253
+ if (index === 0) return "";
5254
+ return commentOf(statement).comment === "" ? "\n" : "\n\n";
5255
+ }
4780
5256
  const COCKROACH_ALTER = /^ALTER TABLE ((?:"(?:[^"]|"")+"\.)?"(?:[^"]|"")+")\s+([\s\S]+)$/u;
4781
5257
  /** CockroachDB: the one-clause ALTER TABLEs in a row for one table, read as one. */
4782
5258
  function joinAlters(statements) {
@@ -4849,6 +5325,26 @@ function definition(def) {
4849
5325
  };
4850
5326
  }
4851
5327
  const NONE = [];
5328
+ const COCKROACH_DROP_VALUE = /^ALTER TYPE (?:"(?:[^"]|"")+"\.)?"((?:[^"]|"")+)"\s*DROP VALUE '((?:[^']|'')*)'$/u;
5329
+ /**
5330
+ * CockroachDB drops an enum value in place: the rows holding it go to their new member first,
5331
+ * which the ADD VALUE before it has made.
5332
+ *
5333
+ * @example
5334
+ * ```sql
5335
+ * UPDATE "User" SET "role" = CASE "role"::STRING WHEN 'EDITOR' THEN 'WRITER' ELSE "role"::STRING END::"Role" WHERE "role"::STRING IN ('EDITOR');
5336
+ * ```
5337
+ */
5338
+ function updatesBeforeDroppedValue(plans, type, value, found, mark, q, text) {
5339
+ return plans.flatMap((plan) => plan.enumMaps.filter((map) => map.type === type && map.mapping.some((m) => m.from === value) && !found.has(`enum ${plan.name}.${map.column}`)).map((map) => {
5340
+ mark(`enum ${plan.name}.${map.column}`);
5341
+ const pairs = map.mapping.map((m) => ({
5342
+ from: text(m.from),
5343
+ to: text(m.to)
5344
+ }));
5345
+ return `UPDATE ${plan.name} SET ${q(map.column)} = ${caseMap(`${q(map.column)}::STRING`, pairs)}::${q(type)} WHERE ${q(map.column)}::STRING IN (${map.mapping.map((m) => text(m.from)).join(", ")})`;
5346
+ }));
5347
+ }
4852
5348
  /**
4853
5349
  * PostgreSQL and MySQL: Prisma changes a table with one ALTER TABLE of clauses, which the rewrite edits.
4854
5350
  *
@@ -4874,37 +5370,19 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4874
5370
  const mark = (key) => {
4875
5371
  found.add(key);
4876
5372
  };
5373
+ const planByName = Map.groupBy(plans, (p) => p.name);
5374
+ const separator = dialect === "mysql" ? ",\n " : ",\n";
4877
5375
  return {
4878
5376
  statements: statements.flatMap((statement) => {
4879
5377
  const { comment, body } = commentOf(statement);
4880
- const dropped = /^ALTER TYPE (?:"(?:[^"]|"")+"\.)?"((?:[^"]|"")+)"\s*DROP VALUE '((?:[^']|'')*)'$/u.exec(body);
4881
- if (dialect === "postgresql" && dropped !== null) {
4882
- const type = (dropped[1] ?? "").replaceAll("\"\"", "\"");
4883
- const value = (dropped[2] ?? "").replaceAll("''", "'");
4884
- return underComment(comment, [...plans.flatMap((plan) => plan.enumMaps.filter((map) => map.type === type && map.mapping.some((m) => m.from === value) && !found.has(`enum ${plan.name}.${map.column}`)).map((map) => {
4885
- mark(`enum ${plan.name}.${map.column}`);
4886
- const pairs = map.mapping.map((m) => ({
4887
- from: text(m.from),
4888
- to: text(m.to)
4889
- }));
4890
- return `UPDATE ${plan.name} SET ${q(map.column)} = ${caseMap(`${q(map.column)}::STRING`, pairs)}::${q(type)} WHERE ${q(map.column)}::STRING IN (${map.mapping.map((m) => text(m.from)).join(", ")})`;
4891
- })), body]);
4892
- }
5378
+ const dropped = COCKROACH_DROP_VALUE.exec(body);
5379
+ if (dialect === "postgresql" && dropped !== null) return underComment(comment, [...updatesBeforeDroppedValue(plans, (dropped[1] ?? "").replaceAll("\"\"", "\""), (dropped[2] ?? "").replaceAll("''", "'"), found, mark, q, text), body]);
4893
5380
  const alter = alterPattern.exec(body);
4894
- const plan = alter === null ? void 0 : plans.find((p) => p.name === alter[1]);
5381
+ const plan = alter === null ? void 0 : planByName.get(alter[1] ?? "")?.[0];
4895
5382
  if (alter === null || plan === void 0) return [statement];
4896
5383
  const rest = alter[2] ?? "";
4897
5384
  const cast = new RegExp(`^ALTER COLUMN (${identifier}) TYPE (${tableName}) USING \\((${identifier})::text::(${tableName})\\)$`, "u").exec(rest.trim());
4898
- if (dialect === "postgresql" && cast !== null) {
4899
- const map = plan.enumMaps.find((m) => q(m.column) === cast[1]);
4900
- if (map === void 0) return [statement];
4901
- mark(`enum ${plan.name}.${map.column}`);
4902
- const mapped = caseMap(`${q(map.column)}::text`, map.mapping.map((m) => ({
4903
- from: text(m.from),
4904
- to: text(m.to)
4905
- })));
4906
- return [`${comment ? `${comment}\n` : ""}ALTER TABLE ${plan.name} ALTER COLUMN ${cast[1]} TYPE ${cast[2]} USING (${mapped})::${cast[4]}`];
4907
- }
5385
+ if (dialect === "postgresql" && cast !== null) return castWithMappedValues(statement, plan, cast, mark, q, text);
4908
5386
  const clauses = splitTopLevel(rest);
4909
5387
  const drop = (column) => {
4910
5388
  const pattern = new RegExp(`^DROP COLUMN ${escape(q(column))}$`, "u");
@@ -4914,6 +5392,20 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4914
5392
  const pattern = new RegExp(`^ADD COLUMN\\s+${escape(q(column))}\\s`, "u");
4915
5393
  return clauses.findIndex((c) => pattern.test(c));
4916
5394
  };
5395
+ const enumModify = (column) => {
5396
+ const changed = new RegExp(`^(?:MODIFY|CHANGE COLUMN ${escape(q(column))}) ${escape(q(column))} ENUM\\(`, "u");
5397
+ const modified = new RegExp(`^MODIFY ${escape(q(column))} ENUM\\(`, "u");
5398
+ return clauses.find((c) => changed.test(c) || modified.test(c));
5399
+ };
5400
+ const modifies = (column) => {
5401
+ const modified = new RegExp(`^MODIFY ${escape(q(column))}\\s`, "u");
5402
+ return clauses.some((c) => modified.test(c));
5403
+ };
5404
+ const typedAt = (column) => {
5405
+ const typed = new RegExp(`^ALTER COLUMN ${escape(q(column))} SET DATA TYPE `, "u");
5406
+ return clauses.findIndex((c) => typed.test(c));
5407
+ };
5408
+ const convertOf = new Map(plan.converts.toReversed().map((c) => [c.column, c]));
4917
5409
  const defOf = (index, column) => (clauses[index] ?? "").replace(new RegExp(`^ADD COLUMN\\s+${escape(q(column))}\\s+`, "u"), "");
4918
5410
  const sourceOfRename = new Set(plan.renames.map((r) => r.from));
4919
5411
  const fills = plan.fills.flatMap((fill) => {
@@ -4930,9 +5422,7 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4930
5422
  }];
4931
5423
  });
4932
5424
  const widened = dialect === "mysql" ? plan.enumMaps.flatMap((map) => {
4933
- const changed = new RegExp(`^(?:MODIFY|CHANGE COLUMN ${escape(q(map.column))}) ${escape(q(map.column))} ENUM\\(`, "u");
4934
- const modified = new RegExp(`^MODIFY ${escape(q(map.column))} ENUM\\(`, "u");
4935
- if (clauses.find((c) => changed.test(c) || modified.test(c)) === void 0) return [];
5425
+ if (enumModify(map.column) === void 0) return [];
4936
5426
  mark(`enum ${plan.name}.${map.column}`);
4937
5427
  const values = [.../* @__PURE__ */ new Set([...map.existing, ...map.members])];
4938
5428
  return [`ALTER TABLE ${plan.name} MODIFY ${q(map.column)} ENUM(${values.map(text).join(", ")}) ${nullable(plan.table, map.column) ? "NULL" : "NOT NULL"}`, `UPDATE ${plan.name} SET ${q(map.column)} = ${caseMap(q(map.column), map.mapping.map((m) => ({
@@ -4942,8 +5432,7 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4942
5432
  }) : [];
4943
5433
  const converts = plan.converts.filter((convert) => !sourceOfRename.has(convert.column)).flatMap((convert) => {
4944
5434
  if (dialect === "mysql") {
4945
- const modified = new RegExp(`^MODIFY ${escape(q(convert.column))}\\s`, "u");
4946
- if (!clauses.some((c) => modified.test(c))) return [];
5435
+ if (!modifies(convert.column)) return [];
4947
5436
  mark(`convert ${plan.name}.${convert.column}`);
4948
5437
  return [{
4949
5438
  drop: -1,
@@ -4965,8 +5454,7 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4965
5454
  keep: NONE
4966
5455
  }];
4967
5456
  }
4968
- const typed = new RegExp(`^ALTER COLUMN ${escape(q(convert.column))} SET DATA TYPE `, "u");
4969
- const castAt = clauses.findIndex((c) => typed.test(c));
5457
+ const castAt = typedAt(convert.column);
4970
5458
  if (castAt === -1) return [];
4971
5459
  mark(`convert ${plan.name}.${convert.column}`);
4972
5460
  return [{
@@ -4983,7 +5471,7 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4983
5471
  mark(`rename ${plan.name}.${rename.from}`);
4984
5472
  const def = defOf(addAt, rename.to);
4985
5473
  if (dialect === "mysql") {
4986
- const convert = plan.converts.find((c) => c.column === rename.from);
5474
+ const convert = convertOf.get(rename.from);
4987
5475
  if (convert !== void 0) mark(`convert ${plan.name}.${convert.column}`);
4988
5476
  return [{
4989
5477
  drop: dropAt,
@@ -4993,7 +5481,7 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
4993
5481
  }];
4994
5482
  }
4995
5483
  const parsed = definition(def);
4996
- const convert = plan.converts.find((c) => c.column === rename.from);
5484
+ const convert = convertOf.get(rename.from);
4997
5485
  if (convert !== void 0) mark(`convert ${plan.name}.${convert.column}`);
4998
5486
  const old = `ALTER COLUMN ${q(rename.from)}`;
4999
5487
  const now = `ALTER COLUMN ${q(rename.to)}`;
@@ -5018,7 +5506,6 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
5018
5506
  ...converts.flatMap((c) => c.keep),
5019
5507
  ...renames.flatMap((r) => r.keep)
5020
5508
  ];
5021
- const separator = dialect === "mysql" ? ",\n " : ",\n";
5022
5509
  return underComment(comment, [
5023
5510
  ...fills.flatMap((f) => f.before),
5024
5511
  ...widened,
@@ -5048,6 +5535,26 @@ function rewriteAlters(dialect, statements, plans, q, text, nullable) {
5048
5535
  ]).filter((e) => !found.has(e.key)).map((e) => e.message)
5049
5536
  };
5050
5537
  }
5538
+ /**
5539
+ * PostgreSQL's cast of an enum column to the new type, with the mapped values in it.
5540
+ *
5541
+ * @example
5542
+ * ```sql
5543
+ * ALTER TABLE "User" ALTER COLUMN "role" TYPE "Role_new"
5544
+ * USING (CASE "role"::text WHEN 'EDITOR' THEN 'WRITER' ELSE "role"::text END)::"Role_new";
5545
+ * ```
5546
+ */
5547
+ function castWithMappedValues(statement, plan, cast, mark, q, text) {
5548
+ const { comment } = commentOf(statement);
5549
+ const map = plan.enumMaps.find((m) => q(m.column) === cast[1]);
5550
+ if (map === void 0) return [statement];
5551
+ mark(`enum ${plan.name}.${map.column}`);
5552
+ const mapped = caseMap(`${q(map.column)}::text`, map.mapping.map((m) => ({
5553
+ from: text(m.from),
5554
+ to: text(m.to)
5555
+ })));
5556
+ return [`${comment ? `${comment}\n` : ""}ALTER TABLE ${plan.name} ALTER COLUMN ${cast[1]} TYPE ${cast[2]} USING (${mapped})::${cast[4]}`];
5557
+ }
5051
5558
  /** A string matched as it is inside a regular expression. */
5052
5559
  function escape(value) {
5053
5560
  return value.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
@@ -5067,19 +5574,21 @@ function escape(value) {
5067
5574
  */
5068
5575
  function rewriteSqlite(statements, plans, q) {
5069
5576
  const found = /* @__PURE__ */ new Set();
5577
+ const planByName = Map.groupBy(plans, (p) => p.name);
5070
5578
  return {
5071
5579
  statements: statements.map((statement) => {
5072
5580
  const { comment, body } = commentOf(statement);
5073
5581
  const copy = /^INSERT INTO ("(?:[^"]|"")+") \(([^)]*)\) SELECT ([\s\S]+) FROM ("(?:[^"]|"")+")$/u.exec(body);
5074
5582
  if (copy !== null) {
5075
- const plan = plans.find((p) => p.name === copy[4]);
5583
+ const plan = planByName.get(copy[4] ?? "")?.[0];
5076
5584
  if (plan === void 0) return statement;
5077
5585
  const into = splitTopLevel(copy[2] ?? "");
5078
5586
  const from = splitTopLevel(copy[3] ?? "");
5079
5587
  const converted = (column) => plan.converts.find((c) => c.column === column);
5588
+ const convertBySource = new Map(plan.converts.toReversed().map((c) => [q(c.column), c]));
5080
5589
  const columns = into.map((column, index) => {
5081
5590
  const source = from[index] ?? column;
5082
- const convert = plan.converts.find((c) => q(c.column) === source);
5591
+ const convert = convertBySource.get(source);
5083
5592
  if (convert !== void 0) found.add(`convert ${plan.name}.${convert.column}`);
5084
5593
  return {
5085
5594
  into: column,
@@ -5113,7 +5622,7 @@ function rewriteSqlite(statements, plans, q) {
5113
5622
  }).flatMap((statement) => {
5114
5623
  const { body } = commentOf(statement);
5115
5624
  const added = /^ALTER TABLE ("(?:[^"]|"")+") ADD COLUMN ("(?:[^"]|"")+") /u.exec(body);
5116
- const plan = added === null ? void 0 : plans.find((p) => p.name === added[1]);
5625
+ const plan = added === null ? void 0 : planByName.get(added[1] ?? "")?.[0];
5117
5626
  const fill = plan?.fills.find((f) => q(f.column) === added?.[2]);
5118
5627
  if (plan === void 0 || fill === void 0 || found.has(`fill ${plan.name}.${fill.column}`)) return [statement];
5119
5628
  found.add(`fill ${plan.name}.${fill.column}`);
@@ -5146,7 +5655,7 @@ const COMMENT_LINE = /^\s*--\s*(?<title>.*?)\s*$/u;
5146
5655
  /** The name in the first pair of quotes or backticks; the dialects quote differently. */
5147
5656
  const NAMES = /["`](?<name>[^"`]+)["`]/gu;
5148
5657
  function namesOf(sql) {
5149
- return [...sql.matchAll(NAMES)].map((match) => match.groups?.name ?? "");
5658
+ return [...sql.matchAll(NAMES)].map((match) => match.groups?.["name"] ?? "");
5150
5659
  }
5151
5660
  /** Whether the statement drops something or otherwise loses what a column holds. */
5152
5661
  function isDestructiveStatement(sql) {
@@ -5158,22 +5667,24 @@ function isDestructiveStatement(sql) {
5158
5667
  * `DROP TABLE` in the middle of that loses nothing, and calling it destructive would put a
5159
5668
  * warning on the one shape of migration that is careful by construction.
5160
5669
  */
5670
+ const INSERT_INTO = /^\s*INSERT\s+INTO/iu;
5671
+ const DROP_TABLE = /^\s*DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?["`](?<name>[^"`]+)["`]/iu;
5161
5672
  function rebuiltTables(statements) {
5162
5673
  const renamed = statements.flatMap((statement) => {
5163
5674
  const match = /^\s*ALTER\s+TABLE\s+["`](?<from>[^"`]+)["`]\s+RENAME\s+TO\s+["`](?<to>[^"`]+)["`]/iu.exec(statement);
5164
- const from = match?.groups?.from;
5165
- const to = match?.groups?.to;
5675
+ const from = match?.groups?.["from"];
5676
+ const to = match?.groups?.["to"];
5166
5677
  return from === void 0 || to === void 0 ? [] : [{
5167
5678
  from,
5168
5679
  to
5169
5680
  }];
5170
5681
  });
5171
- return new Set(renamed.flatMap(({ from, to }) => {
5172
- const copied = statements.some((statement) => /^\s*INSERT\s+INTO/iu.test(statement) && namesOf(statement).includes(from));
5173
- const drop = new RegExp(`^\\s*DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?["\`]${escape(to)}["\`]`, "iu");
5174
- const dropped = statements.some((statement) => drop.test(statement));
5175
- return copied && dropped ? [to] : [];
5682
+ const copied = new Set(statements.filter((statement) => INSERT_INTO.test(statement)).flatMap(namesOf));
5683
+ const dropped = new Set(statements.flatMap((statement) => {
5684
+ const name = DROP_TABLE.exec(statement)?.groups?.["name"];
5685
+ return name === void 0 ? [] : [name.toLowerCase()];
5176
5686
  }));
5687
+ return new Set(renamed.flatMap(({ from, to }) => copied.has(from) && dropped.has(to.toLowerCase()) ? [to] : []));
5177
5688
  }
5178
5689
  /** One change a statement makes, as a list so a statement that makes none is an empty one. */
5179
5690
  function change(kind, table, columns = [], target) {
@@ -5192,21 +5703,31 @@ function describeStatement(sql, rebuilt) {
5192
5703
  const statement = sql.trim();
5193
5704
  const [first = "", second = ""] = namesOf(statement);
5194
5705
  if (/^CREATE\s+(?:TYPE|)/iu.test(statement) && /AS\s+ENUM/iu.test(statement)) return change("create-enum", first);
5195
- if (/^CREATE\s+TABLE/iu.test(statement)) return rebuilt.has(first.replace(/^new_/u, "")) && first.startsWith("new_") ? change("rebuild-table", first.replace(/^new_/u, "")) : change("create-table", first);
5196
- if (/^INSERT\s+INTO/iu.test(statement)) return rebuilt.has(first.replace(/^new_/u, "")) ? [] : change("copy-rows", first);
5706
+ if (/^ALTER\s+TABLE/iu.test(statement)) return describeAlter(statement, first, second);
5707
+ if (/^CREATE\s+(?:UNIQUE\s+)?INDEX/iu.test(statement)) {
5708
+ const [, table = "", ...columns] = namesOf(statement);
5709
+ return change(/UNIQUE/iu.test(statement) ? "unique" : "index", table, columns);
5710
+ }
5711
+ return describeTableStatement(statement, first, rebuilt);
5712
+ }
5713
+ /** A table created, filled or dropped, where it is not SQLite's copy of a table it rebuilds. */
5714
+ function describeTableStatement(statement, first, rebuilt) {
5715
+ const original = first.replace(/^new_/u, "");
5716
+ if (/^CREATE\s+TABLE/iu.test(statement)) return rebuilt.has(original) && first.startsWith("new_") ? change("rebuild-table", original) : change("create-table", first);
5717
+ if (/^INSERT\s+INTO/iu.test(statement)) return rebuilt.has(original) ? [] : change("copy-rows", first);
5197
5718
  if (/^DROP\s+TABLE/iu.test(statement)) return rebuilt.has(first) ? [] : change("drop-table", first);
5719
+ return [];
5720
+ }
5721
+ /** An ALTER TABLE: a column added or dropped, or a foreign key; a rename is part of a rebuild. */
5722
+ function describeAlter(statement, first, second) {
5198
5723
  if (/^ALTER\s+TABLE[\s\S]*RENAME\s+TO/iu.test(statement)) return [];
5199
5724
  if (/^ALTER\s+TABLE[\s\S]*ADD\s+COLUMN/iu.test(statement)) return change("add-column", first, [second]);
5200
5725
  if (/^ALTER\s+TABLE[\s\S]*DROP\s+COLUMN/iu.test(statement)) return change("drop-column", first, [second]);
5201
5726
  if (/^ALTER\s+TABLE[\s\S]*FOREIGN\s+KEY/iu.test(statement)) {
5202
- const key = /FOREIGN\s+KEY\s*\(\s*["`](?<column>[^"`]+)["`]/iu.exec(statement)?.groups?.column;
5203
- const target = /REFERENCES\s+["`](?<table>[^"`]+)["`]/iu.exec(statement)?.groups?.table;
5727
+ const key = /FOREIGN\s+KEY\s*\(\s*["`](?<column>[^"`]+)["`]/iu.exec(statement)?.groups?.["column"];
5728
+ const target = /REFERENCES\s+["`](?<table>[^"`]+)["`]/iu.exec(statement)?.groups?.["table"];
5204
5729
  return change("foreign-key", first, key === void 0 ? [] : [key], target);
5205
5730
  }
5206
- if (/^CREATE\s+(?:UNIQUE\s+)?INDEX/iu.test(statement)) {
5207
- const [, table = "", ...columns] = namesOf(statement);
5208
- return change(/UNIQUE/iu.test(statement) ? "unique" : "index", table, columns);
5209
- }
5210
5731
  return [];
5211
5732
  }
5212
5733
  /**
@@ -5287,7 +5808,7 @@ function blocksOf(migration) {
5287
5808
  title: null,
5288
5809
  lines: lines.slice(0, starts[0] ?? lines.length)
5289
5810
  }, ...starts.map((start, index) => ({
5290
- title: COMMENT_LINE.exec(lines[start] ?? "")?.groups?.title ?? null,
5811
+ title: COMMENT_LINE.exec(lines[start] ?? "")?.groups?.["title"] ?? null,
5291
5812
  lines: lines.slice(start + 1, ends[index] ?? lines.length)
5292
5813
  }))].flatMap((block) => {
5293
5814
  const statements = splitStatements(block.lines.join("\n")).map((statement) => statement.trim()).filter((statement) => statement !== "");
@@ -5338,7 +5859,7 @@ function lostInRebuild(report, statements) {
5338
5859
  function batchedStatements(database, fix, batch) {
5339
5860
  const { parts } = fix;
5340
5861
  if (batch === null || parts === null || parts === void 0 || (fix.rows ?? 0) <= batch) return fix.statements;
5341
- const row = database.dialect === "mysql" || database.cockroach ? null : database.dialect === "postgresql" ? "ctid" : "rowid";
5862
+ const row = rowIdentifier(database);
5342
5863
  const limited = row === null ? `${parts.head} WHERE ${parts.where} LIMIT ${batch}` : `${parts.head} WHERE ${row} IN (SELECT ${row} FROM ${parts.table} WHERE ${parts.where} LIMIT ${batch})`;
5343
5864
  return [...Array.from({ length: Math.ceil((fix.rows ?? 0) / batch) }, () => limited), ...fix.statements];
5344
5865
  }
@@ -5420,4 +5941,9 @@ function makePlan(report, migration, batch = null) {
5420
5941
  errors: [...rewritten.errors, ...blocked.map((result) => `${result.subject}: ${result.what} — ${result.count ?? 0} rows block the migration. Decide what becomes of them in the checks above.`)]
5421
5942
  };
5422
5943
  }
5944
+ /** The hidden column that names a row, for a batch to pick its rows by; null where LIMIT does it. */
5945
+ function rowIdentifier(database) {
5946
+ if (database.dialect === "mysql" || database.cockroach) return null;
5947
+ return database.dialect === "postgresql" ? "ctid" : "rowid";
5948
+ }
5423
5949
  export { openSqliteCopy as _, makePlan as a, checkOpened as c, DECISIONS_FILE as d, readDecisions as f, openShadowDatabase as g, openMysqlCopy as h, lostInRebuild as i, runMigrateCheck as l, connectDatabase as m, isDestructiveStep as n, BLOCK_QUOTE as o, writeDecisions as p, isLossyFix as r, rewriteMigration as s, batchedStatements as t, introspectDatabase as u };