drizzle-kit 0.23.2-eddab2e → 0.24.0-38d6dab

Sign up to get free protection for your applications and to get access to all the features.
Files changed (8) hide show
  1. package/api.d.mts +20 -4
  2. package/api.d.ts +20 -4
  3. package/api.js +1694 -783
  4. package/api.mjs +1694 -783
  5. package/bin.cjs +1658 -394
  6. package/package.json +2 -2
  7. package/utils.js +14 -0
  8. package/utils.mjs +12 -0
package/bin.cjs CHANGED
@@ -6561,6 +6561,16 @@ var init_sqliteSchema = __esm({
6561
6561
  });
6562
6562
 
6563
6563
  // src/utils.ts
6564
+ function isPgArrayType(sqlType) {
6565
+ return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
6566
+ }
6567
+ function findAddedAndRemoved(columnNames1, columnNames2) {
6568
+ const set1 = new Set(columnNames1);
6569
+ const set2 = new Set(columnNames2);
6570
+ const addedColumns = columnNames2.filter((it) => !set1.has(it));
6571
+ const removedColumns = columnNames1.filter((it) => !set2.has(it));
6572
+ return { addedColumns, removedColumns };
6573
+ }
6564
6574
  var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl;
6565
6575
  var init_utils = __esm({
6566
6576
  "src/utils.ts"() {
@@ -11358,7 +11368,8 @@ var init_cli = __esm({
11358
11368
  schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
11359
11369
  extensionsFilters: literalType("postgis").array().optional(),
11360
11370
  verbose: booleanType().optional(),
11361
- strict: booleanType().optional()
11371
+ strict: booleanType().optional(),
11372
+ driver: driver.optional()
11362
11373
  }).passthrough();
11363
11374
  pullParams = objectType({
11364
11375
  config: stringType().optional(),
@@ -17362,7 +17373,8 @@ var init_utils4 = __esm({
17362
17373
  breakpoints: breakpoints || true,
17363
17374
  schema: schema5,
17364
17375
  out: out || "drizzle",
17365
- bundle: driver2 === "expo"
17376
+ bundle: driver2 === "expo",
17377
+ driver: driver2
17366
17378
  };
17367
17379
  };
17368
17380
  flattenDatabaseCredentials = (config) => {
@@ -17390,6 +17402,7 @@ var init_utils4 = __esm({
17390
17402
  const raw2 = flattenDatabaseCredentials(
17391
17403
  from === "config" ? await drizzleConfigFromFile(options.config) : options
17392
17404
  );
17405
+ raw2.driver ||= options.driver;
17393
17406
  raw2.verbose ||= options.verbose;
17394
17407
  raw2.strict ||= options.strict;
17395
17408
  const parsed = pushParams.safeParse(raw2);
@@ -17464,7 +17477,8 @@ var init_utils4 = __esm({
17464
17477
  force: options.force ?? false,
17465
17478
  credentials: parsed2.data,
17466
17479
  tablesFilter,
17467
- schemasFilter
17480
+ schemasFilter,
17481
+ driver: config.driver
17468
17482
  };
17469
17483
  }
17470
17484
  assertUnreachable(config.dialect);
@@ -18107,7 +18121,7 @@ We have encountered a collision between the index name on columns ${source_defau
18107
18121
  onUpdate = true;
18108
18122
  }
18109
18123
  const newColumn = {
18110
- default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !columnType.startsWith("decimal") ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${columnDefault}'`,
18124
+ default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${columnDefault}'`,
18111
18125
  autoincrement: isAutoincrement,
18112
18126
  name: columnName,
18113
18127
  type: changedType,
@@ -18406,6 +18420,30 @@ function minRangeForIdentityBasedOn(columnType) {
18406
18420
  function stringFromDatabaseIdentityProperty(field) {
18407
18421
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
18408
18422
  }
18423
+ function buildArrayString(array, sqlType) {
18424
+ sqlType = sqlType.split("[")[0];
18425
+ const values = array.map((value) => {
18426
+ if (typeof value === "number" || typeof value === "bigint") {
18427
+ return value.toString();
18428
+ } else if (typeof value === "boolean") {
18429
+ return value ? "true" : "false";
18430
+ } else if (Array.isArray(value)) {
18431
+ return buildArrayString(value, sqlType);
18432
+ } else if (value instanceof Date) {
18433
+ if (sqlType === "date") {
18434
+ return `"${value.toISOString().split("T")[0]}"`;
18435
+ } else if (sqlType === "timestamp") {
18436
+ return `"${value.toISOString().replace("T", " ").slice(0, 23)}"`;
18437
+ } else {
18438
+ return `"${value.toISOString()}"`;
18439
+ }
18440
+ } else if (typeof value === "object") {
18441
+ return `"${JSON.stringify(value).replaceAll('"', '\\"')}"`;
18442
+ }
18443
+ return `"${value}"`;
18444
+ }).join(",");
18445
+ return `{${values}}`;
18446
+ }
18409
18447
  var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, columnToDefault, defaultForColumn;
18410
18448
  var init_pgSerializer = __esm({
18411
18449
  "src/serializer/pgSerializer.ts"() {
@@ -18416,6 +18454,7 @@ var init_pgSerializer = __esm({
18416
18454
  import_pg_core3 = require("drizzle-orm/pg-core");
18417
18455
  init_vector();
18418
18456
  init_outputs();
18457
+ init_utils();
18419
18458
  init_serializer();
18420
18459
  dialect5 = new import_pg_core2.PgDialect();
18421
18460
  indexName2 = (tableName, columns) => {
@@ -18524,6 +18563,11 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18524
18563
  } else {
18525
18564
  columnToSet.default = `'${column7.default.toISOString()}'`;
18526
18565
  }
18566
+ } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column7.default)) {
18567
+ columnToSet.default = `'${buildArrayString(
18568
+ column7.default,
18569
+ sqlTypeLowered
18570
+ )}'::${sqlTypeLowered}`;
18527
18571
  } else {
18528
18572
  columnToSet.default = column7.default;
18529
18573
  }
@@ -19570,7 +19614,7 @@ The unique constraint ${source_default.underline.blue(
19570
19614
  primaryKeys.forEach((it) => {
19571
19615
  if (it.columns.length > 1) {
19572
19616
  primaryKeysObject[it.getName()] = {
19573
- columns: it.columns.map((it2) => it2.name).sort(),
19617
+ columns: it.columns.map((it2) => it2.name),
19574
19618
  name: it.getName()
19575
19619
  };
19576
19620
  } else {
@@ -19696,7 +19740,6 @@ The unique constraint ${source_default.underline.blue(
19696
19740
  }
19697
19741
  for (const [key, value] of Object.entries(tableToPk)) {
19698
19742
  if (value.length > 1) {
19699
- value.sort();
19700
19743
  result[key].compositePrimaryKeys = {
19701
19744
  [`${key}_${value.join("_")}_pk`]: {
19702
19745
  columns: value,
@@ -22820,7 +22863,20 @@ var init_jsonDiffer = __esm({
22820
22863
  });
22821
22864
 
22822
22865
  // src/sqlgenerator.ts
22823
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, SQLiteAlterTableAddUniqueConstraintConvertor, SQLiteAlterTableDropUniqueConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, AlterTypeAddValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, SQLiteAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, SqliteAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, MySqlModifyColumn, SqliteAlterTableAlterColumnDropDefaultConvertor, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, SqliteAlterTableCreateCompositePrimaryKeyConvertor, SqliteAlterTableDeleteCompositePrimaryKeyConvertor, SqliteAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, SqliteAlterTableAlterColumnSetNotNullConvertor, SqliteAlterTableAlterColumnSetAutoincrementConvertor, SqliteAlterTableAlterColumnDropAutoincrementConvertor, PgAlterTableAlterColumnDropNotNullConvertor, SqliteAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, SqliteCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, SqliteAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, SqliteDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, convertors, fromJson;
22866
+ function fromJson(statements, dialect7, action, driver2, json2) {
22867
+ const result = statements.flatMap((statement) => {
22868
+ const filtered = convertors.filter((it) => {
22869
+ return it.can(statement, dialect7, driver2);
22870
+ });
22871
+ const convertor = filtered.length === 1 ? filtered[0] : void 0;
22872
+ if (!convertor) {
22873
+ return "";
22874
+ }
22875
+ return convertor.convert(statement, json2, action);
22876
+ }).filter((it) => it !== "");
22877
+ return result;
22878
+ }
22879
+ var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, SQLiteAlterTableAddUniqueConstraintConvertor, SQLiteAlterTableDropUniqueConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, AlterTypeAddValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, SQLiteAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, SqliteAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SqliteAlterTableAlterColumnDropDefaultConvertor, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, SqliteAlterTableCreateCompositePrimaryKeyConvertor, SqliteAlterTableDeleteCompositePrimaryKeyConvertor, SqliteAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, SqliteAlterTableAlterColumnSetNotNullConvertor, SqliteAlterTableAlterColumnSetAutoincrementConvertor, SqliteAlterTableAlterColumnDropAutoincrementConvertor, PgAlterTableAlterColumnDropNotNullConvertor, SqliteAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, SqliteCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, SqliteAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, SqliteDeleteForeignKeyConvertor, LibSQLDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
22824
22880
  var init_sqlgenerator = __esm({
22825
22881
  "src/sqlgenerator.ts"() {
22826
22882
  "use strict";
@@ -23339,7 +23395,7 @@ var init_sqlgenerator = __esm({
23339
23395
  }
23340
23396
  convert(statement) {
23341
23397
  const { tableName, oldColumnName, newColumnName } = statement;
23342
- return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
23398
+ return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
23343
23399
  }
23344
23400
  };
23345
23401
  PgAlterTableDropColumnConvertor = class extends Convertor {
@@ -23441,8 +23497,8 @@ var init_sqlgenerator = __esm({
23441
23497
  }
23442
23498
  };
23443
23499
  SQLiteAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
23444
- can(statement, dialect7) {
23445
- return statement.type === "alter_table_alter_column_set_type" && dialect7 === "sqlite";
23500
+ can(statement, dialect7, driver2) {
23501
+ return statement.type === "alter_table_alter_column_set_type" && dialect7 === "sqlite" && !driver2;
23446
23502
  }
23447
23503
  convert(statement) {
23448
23504
  return `/*
@@ -23753,6 +23809,46 @@ var init_sqlgenerator = __esm({
23753
23809
  return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
23754
23810
  }
23755
23811
  };
23812
+ LibSQLModifyColumn = class extends Convertor {
23813
+ can(statement, dialect7, driver2) {
23814
+ return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") && dialect7 === "sqlite" && driver2 === "turso";
23815
+ }
23816
+ convert(statement, json2) {
23817
+ const { tableName, columnName } = statement;
23818
+ let columnType = ``;
23819
+ let columnDefault = "";
23820
+ let columnNotNull = "";
23821
+ switch (statement.type) {
23822
+ case "alter_table_alter_column_set_type":
23823
+ columnType = ` ${statement.newDataType}`;
23824
+ columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
23825
+ columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
23826
+ break;
23827
+ case "alter_table_alter_column_drop_notnull":
23828
+ columnType = ` ${statement.newDataType}`;
23829
+ columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
23830
+ columnNotNull = "";
23831
+ break;
23832
+ case "alter_table_alter_column_set_notnull":
23833
+ columnType = ` ${statement.newDataType}`;
23834
+ columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
23835
+ columnNotNull = ` NOT NULL`;
23836
+ break;
23837
+ case "alter_table_alter_column_set_default":
23838
+ columnType = ` ${statement.newDataType}`;
23839
+ columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
23840
+ columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
23841
+ break;
23842
+ case "alter_table_alter_column_drop_default":
23843
+ columnType = ` ${statement.newDataType}`;
23844
+ columnDefault = "";
23845
+ columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
23846
+ break;
23847
+ }
23848
+ columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
23849
+ return `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};`;
23850
+ }
23851
+ };
23756
23852
  MySqlModifyColumn = class extends Convertor {
23757
23853
  can(statement, dialect7) {
23758
23854
  return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect7 === "mysql";
@@ -24094,8 +24190,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24094
24190
  }
24095
24191
  };
24096
24192
  SqliteAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
24097
- can(statement, dialect7) {
24098
- return statement.type === "alter_table_alter_column_set_notnull" && dialect7 === "sqlite";
24193
+ can(statement, dialect7, driver2) {
24194
+ return statement.type === "alter_table_alter_column_set_notnull" && dialect7 === "sqlite" && !driver2;
24099
24195
  }
24100
24196
  convert(statement) {
24101
24197
  return `/*
@@ -24109,8 +24205,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24109
24205
  }
24110
24206
  };
24111
24207
  SqliteAlterTableAlterColumnSetAutoincrementConvertor = class extends Convertor {
24112
- can(statement, dialect7) {
24113
- return statement.type === "alter_table_alter_column_set_autoincrement" && dialect7 === "sqlite";
24208
+ can(statement, dialect7, driver2) {
24209
+ return statement.type === "alter_table_alter_column_set_autoincrement" && dialect7 === "sqlite" && !driver2;
24114
24210
  }
24115
24211
  convert(statement) {
24116
24212
  return `/*
@@ -24124,8 +24220,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24124
24220
  }
24125
24221
  };
24126
24222
  SqliteAlterTableAlterColumnDropAutoincrementConvertor = class extends Convertor {
24127
- can(statement, dialect7) {
24128
- return statement.type === "alter_table_alter_column_drop_autoincrement" && dialect7 === "sqlite";
24223
+ can(statement, dialect7, driver2) {
24224
+ return statement.type === "alter_table_alter_column_drop_autoincrement" && dialect7 === "sqlite" && !driver2;
24129
24225
  }
24130
24226
  convert(statement) {
24131
24227
  return `/*
@@ -24149,8 +24245,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24149
24245
  }
24150
24246
  };
24151
24247
  SqliteAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
24152
- can(statement, dialect7) {
24153
- return statement.type === "alter_table_alter_column_drop_notnull" && dialect7 === "sqlite";
24248
+ can(statement, dialect7, driver2) {
24249
+ return statement.type === "alter_table_alter_column_drop_notnull" && dialect7 === "sqlite" && !driver2;
24154
24250
  }
24155
24251
  convert(statement) {
24156
24252
  return `/*
@@ -24194,8 +24290,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24194
24290
  }
24195
24291
  };
24196
24292
  SqliteCreateForeignKeyConvertor = class extends Convertor {
24197
- can(statement, dialect7) {
24198
- return statement.type === "create_reference" && dialect7 === "sqlite";
24293
+ can(statement, dialect7, driver2) {
24294
+ return statement.type === "create_reference" && dialect7 === "sqlite" && !driver2;
24199
24295
  }
24200
24296
  convert(statement) {
24201
24297
  return `/*
@@ -24207,6 +24303,32 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24207
24303
  */`;
24208
24304
  }
24209
24305
  };
24306
+ LibSQLCreateForeignKeyConvertor = class extends Convertor {
24307
+ can(statement, dialect7, driver2) {
24308
+ return statement.type === "create_reference" && dialect7 === "sqlite" && driver2 === "turso";
24309
+ }
24310
+ convert(statement, json2, action) {
24311
+ const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
24312
+ const { columnDefault, columnNotNull, columnType, isMulticolumn } = statement;
24313
+ if (isMulticolumn) {
24314
+ return `/*
24315
+ LibSQL does not support "Creating foreign key on multiple columns" out of the box, we do not generate automatic migration for that, so it has to be done manually
24316
+ Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php
24317
+ https://www.sqlite.org/lang_altertable.html
24318
+
24319
+ Due to that we don't generate migration automatically and it has to be done manually
24320
+ */`;
24321
+ }
24322
+ const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
24323
+ const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
24324
+ const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
24325
+ const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
24326
+ const columnTypeValue = columnType ? ` ${columnType}` : "";
24327
+ const columnFrom = columnsFrom[0];
24328
+ const columnTo = columnsTo[0];
24329
+ return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`;
24330
+ }
24331
+ };
24210
24332
  MySqlCreateForeignKeyConvertor = class extends Convertor {
24211
24333
  can(statement, dialect7) {
24212
24334
  return statement.type === "create_reference" && dialect7 === "mysql";
@@ -24280,8 +24402,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24280
24402
  }
24281
24403
  };
24282
24404
  SqliteDeleteForeignKeyConvertor = class extends Convertor {
24283
- can(statement, dialect7) {
24284
- return statement.type === "delete_reference" && dialect7 === "sqlite";
24405
+ can(statement, dialect7, driver2) {
24406
+ return statement.type === "delete_reference" && dialect7 === "sqlite" && !driver2;
24285
24407
  }
24286
24408
  convert(statement) {
24287
24409
  return `/*
@@ -24293,6 +24415,29 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24293
24415
  */`;
24294
24416
  }
24295
24417
  };
24418
+ LibSQLDeleteForeignKeyConvertor = class extends Convertor {
24419
+ can(statement, dialect7, driver2) {
24420
+ return statement.type === "delete_reference" && dialect7 === "sqlite" && driver2 === "turso";
24421
+ }
24422
+ convert(statement, json2, action) {
24423
+ const { columnsFrom, tableFrom } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
24424
+ const { columnDefault, columnNotNull, columnType, isMulticolumn } = statement;
24425
+ if (isMulticolumn) {
24426
+ return `/*
24427
+ LibSQL does not support "Creating foreign key on multiple columns" out of the box, we do not generate automatic migration for that, so it has to be done manually
24428
+ Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php
24429
+ https://www.sqlite.org/lang_altertable.html
24430
+
24431
+ Due to that we don't generate migration automatically and it has to be done manually
24432
+ */`;
24433
+ }
24434
+ const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
24435
+ const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
24436
+ const columnTypeValue = columnType ? ` ${columnType}` : "";
24437
+ const columnFrom = columnsFrom[0];
24438
+ return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue};`;
24439
+ }
24440
+ };
24296
24441
  MySqlDeleteForeignKeyConvertor = class extends Convertor {
24297
24442
  can(statement, dialect7) {
24298
24443
  return statement.type === "delete_reference" && dialect7 === "mysql";
@@ -24458,10 +24603,90 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24458
24603
  return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
24459
24604
  }
24460
24605
  };
24606
+ SQLiteRecreateTableConvertor = class extends Convertor {
24607
+ can(statement, dialect7, driver2) {
24608
+ return statement.type === "recreate_table" && dialect7 === "sqlite" && !driver2;
24609
+ }
24610
+ convert(statement) {
24611
+ const { tableName, columns, compositePKs, referenceData } = statement;
24612
+ const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
24613
+ const sqlStatements = [];
24614
+ sqlStatements.push(
24615
+ new SqliteRenameTableConvertor().convert({
24616
+ fromSchema: "",
24617
+ tableNameFrom: tableName,
24618
+ tableNameTo: `__old__generate_${tableName}`,
24619
+ toSchema: "",
24620
+ type: "rename_table"
24621
+ })
24622
+ );
24623
+ sqlStatements.push(
24624
+ new SQLiteCreateTableConvertor().convert({
24625
+ type: "sqlite_create_table",
24626
+ tableName,
24627
+ columns,
24628
+ referenceData,
24629
+ compositePKs
24630
+ })
24631
+ );
24632
+ sqlStatements.push(
24633
+ `INSERT INTO \`${tableName}\`(${columnNames}) SELECT ${columnNames} FROM \`__old__generate_${tableName}\`;`
24634
+ );
24635
+ sqlStatements.push(
24636
+ new SQLiteDropTableConvertor().convert({
24637
+ type: "drop_table",
24638
+ tableName: `__old__generate_${tableName}`,
24639
+ schema: ""
24640
+ })
24641
+ );
24642
+ return sqlStatements;
24643
+ }
24644
+ };
24645
+ LibSQLRecreateTableConvertor = class extends Convertor {
24646
+ can(statement, dialect7, driver2) {
24647
+ return statement.type === "recreate_table" && dialect7 === "sqlite" && driver2 === "turso";
24648
+ }
24649
+ convert(statement) {
24650
+ const { tableName, columns, compositePKs, referenceData } = statement;
24651
+ const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
24652
+ const sqlStatements = [];
24653
+ sqlStatements.push(
24654
+ new SqliteRenameTableConvertor().convert({
24655
+ fromSchema: "",
24656
+ tableNameFrom: tableName,
24657
+ tableNameTo: `__old__generate_${tableName}`,
24658
+ toSchema: "",
24659
+ type: "rename_table"
24660
+ })
24661
+ );
24662
+ sqlStatements.push(
24663
+ new SQLiteCreateTableConvertor().convert({
24664
+ type: "sqlite_create_table",
24665
+ tableName,
24666
+ columns,
24667
+ referenceData,
24668
+ compositePKs
24669
+ })
24670
+ );
24671
+ sqlStatements.push(
24672
+ `INSERT INTO \`${tableName}\`(${columnNames}) SELECT ${columnNames} FROM \`__old__generate_${tableName}\`;`
24673
+ );
24674
+ sqlStatements.push(
24675
+ new SQLiteDropTableConvertor().convert({
24676
+ type: "drop_table",
24677
+ tableName: `__old__generate_${tableName}`,
24678
+ schema: ""
24679
+ })
24680
+ );
24681
+ return sqlStatements;
24682
+ }
24683
+ };
24461
24684
  convertors = [];
24462
24685
  convertors.push(new PgCreateTableConvertor());
24463
24686
  convertors.push(new MySqlCreateTableConvertor());
24464
24687
  convertors.push(new SQLiteCreateTableConvertor());
24688
+ convertors.push(new SQLiteRecreateTableConvertor());
24689
+ convertors.push(new LibSQLRecreateTableConvertor());
24465
24690
  convertors.push(new CreateTypeEnumConvertor());
24466
24691
  convertors.push(new CreatePgSequenceConvertor());
24467
24692
  convertors.push(new DropPgSequenceConvertor());
@@ -24509,6 +24734,7 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24509
24734
  convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
24510
24735
  convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
24511
24736
  convertors.push(new MySqlModifyColumn());
24737
+ convertors.push(new LibSQLModifyColumn());
24512
24738
  convertors.push(new PgCreateForeignKeyConvertor());
24513
24739
  convertors.push(new MySqlCreateForeignKeyConvertor());
24514
24740
  convertors.push(new PgAlterForeignKeyConvertor());
@@ -24523,7 +24749,9 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24523
24749
  convertors.push(new SQLiteAlterTableAlterColumnSetTypeConvertor());
24524
24750
  convertors.push(new SqliteAlterForeignKeyConvertor());
24525
24751
  convertors.push(new SqliteDeleteForeignKeyConvertor());
24752
+ convertors.push(new LibSQLDeleteForeignKeyConvertor());
24526
24753
  convertors.push(new SqliteCreateForeignKeyConvertor());
24754
+ convertors.push(new LibSQLCreateForeignKeyConvertor());
24527
24755
  convertors.push(new SQLiteAlterTableAddUniqueConstraintConvertor());
24528
24756
  convertors.push(new SQLiteAlterTableDropUniqueConstraintConvertor());
24529
24757
  convertors.push(new PgAlterTableAlterColumnDropGenerated());
@@ -24546,19 +24774,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24546
24774
  convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
24547
24775
  convertors.push(new MySqlAlterTableAddPk());
24548
24776
  convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
24549
- fromJson = (statements, dialect7) => {
24550
- const result = statements.flatMap((statement) => {
24551
- const filtered = convertors.filter((it) => {
24552
- return it.can(statement, dialect7);
24553
- });
24554
- const convertor = filtered.length === 1 ? filtered[0] : void 0;
24555
- if (!convertor) {
24556
- return "";
24557
- }
24558
- return convertor.convert(statement);
24559
- }).filter((it) => it !== "");
24560
- return result;
24561
- };
24562
24777
  https:
24563
24778
  `
24564
24779
  create table users (
@@ -24586,12 +24801,237 @@ drop type __venum;
24586
24801
  }
24587
24802
  });
24588
24803
 
24804
+ // src/cli/commands/sqlitePushUtils.ts
24805
+ var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn;
24806
+ var init_sqlitePushUtils = __esm({
24807
+ "src/cli/commands/sqlitePushUtils.ts"() {
24808
+ "use strict";
24809
+ init_source();
24810
+ init_sqliteSchema();
24811
+ init_sqlgenerator();
24812
+ init_utils();
24813
+ _moveDataStatements = (tableName, json, dataLoss = false) => {
24814
+ const statements = [];
24815
+ statements.push(
24816
+ new SqliteRenameTableConvertor().convert({
24817
+ type: "rename_table",
24818
+ tableNameFrom: tableName,
24819
+ tableNameTo: `__old_push_${tableName}`,
24820
+ fromSchema: "",
24821
+ toSchema: ""
24822
+ })
24823
+ );
24824
+ const tableColumns = Object.values(json.tables[tableName].columns);
24825
+ const referenceData = Object.values(json.tables[tableName].foreignKeys);
24826
+ const compositePKs = Object.values(
24827
+ json.tables[tableName].compositePrimaryKeys
24828
+ ).map((it) => SQLiteSquasher.unsquashPK(it));
24829
+ const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
24830
+ statements.push(
24831
+ new SQLiteCreateTableConvertor().convert({
24832
+ type: "sqlite_create_table",
24833
+ tableName,
24834
+ columns: tableColumns,
24835
+ referenceData: fks,
24836
+ compositePKs
24837
+ })
24838
+ );
24839
+ if (!dataLoss) {
24840
+ const columns = Object.keys(json.tables[tableName].columns).map(
24841
+ (c) => `"${c}"`
24842
+ );
24843
+ statements.push(
24844
+ `INSERT INTO \`${tableName}\`(${columns.join(
24845
+ ", "
24846
+ )}) SELECT (${columns.join(", ")}) FROM \`__old_push_${tableName}\`;`
24847
+ );
24848
+ }
24849
+ statements.push(
24850
+ new SQLiteDropTableConvertor().convert({
24851
+ type: "drop_table",
24852
+ tableName: `__old_push_${tableName}`,
24853
+ schema: ""
24854
+ })
24855
+ );
24856
+ for (const idx of Object.values(json.tables[tableName].indexes)) {
24857
+ statements.push(
24858
+ new CreateSqliteIndexConvertor().convert({
24859
+ type: "create_index",
24860
+ tableName,
24861
+ schema: "",
24862
+ data: idx
24863
+ })
24864
+ );
24865
+ }
24866
+ return statements;
24867
+ };
24868
+ getOldTableName = (tableName, meta) => {
24869
+ for (const key of Object.keys(meta.tables)) {
24870
+ const value = meta.tables[key];
24871
+ if (`"${tableName}"` === value) {
24872
+ return key.substring(1, key.length - 1);
24873
+ }
24874
+ }
24875
+ return tableName;
24876
+ };
24877
+ getNewTableName = (tableName, meta) => {
24878
+ if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
24879
+ return meta.tables[`"${tableName}"`].substring(
24880
+ 1,
24881
+ meta.tables[`"${tableName}"`].length - 1
24882
+ );
24883
+ }
24884
+ return tableName;
24885
+ };
24886
+ logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
24887
+ let shouldAskForApprove = false;
24888
+ const statementsToExecute = [];
24889
+ const infoToPrint = [];
24890
+ const tablesToRemove = [];
24891
+ const columnsToRemove = [];
24892
+ const schemasToRemove = [];
24893
+ const tablesToTruncate = [];
24894
+ for (const statement of statements) {
24895
+ if (statement.type === "drop_table") {
24896
+ const res = await connection.query(
24897
+ `select count(*) as count from \`${statement.tableName}\``
24898
+ );
24899
+ const count = Number(res[0].count);
24900
+ if (count > 0) {
24901
+ infoToPrint.push(
24902
+ `\xB7 You're about to delete ${source_default.underline(
24903
+ statement.tableName
24904
+ )} table with ${count} items`
24905
+ );
24906
+ tablesToRemove.push(statement.tableName);
24907
+ shouldAskForApprove = true;
24908
+ }
24909
+ const fromJsonStatement = fromJson([statement], "sqlite", "push");
24910
+ statementsToExecute.push(
24911
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
24912
+ );
24913
+ } else if (statement.type === "alter_table_drop_column") {
24914
+ const tableName = statement.tableName;
24915
+ const columnName = statement.columnName;
24916
+ const res = await connection.query(
24917
+ `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\``
24918
+ );
24919
+ const count = Number(res[0].count);
24920
+ if (count > 0) {
24921
+ infoToPrint.push(
24922
+ `\xB7 You're about to delete ${source_default.underline(
24923
+ columnName
24924
+ )} column in ${tableName} table with ${count} items`
24925
+ );
24926
+ columnsToRemove.push(`${tableName}_${statement.columnName}`);
24927
+ shouldAskForApprove = true;
24928
+ }
24929
+ const fromJsonStatement = fromJson([statement], "sqlite", "push");
24930
+ statementsToExecute.push(
24931
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
24932
+ );
24933
+ } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) {
24934
+ const tableName = statement.tableName;
24935
+ const columnName = statement.column.name;
24936
+ const res = await connection.query(
24937
+ `select count(*) as count from \`${tableName}\``
24938
+ );
24939
+ const count = Number(res[0].count);
24940
+ if (count > 0) {
24941
+ infoToPrint.push(
24942
+ `\xB7 You're about to add not-null ${source_default.underline(
24943
+ columnName
24944
+ )} column without default value, which contains ${count} items`
24945
+ );
24946
+ tablesToTruncate.push(tableName);
24947
+ statementsToExecute.push(`delete from ${tableName};`);
24948
+ shouldAskForApprove = true;
24949
+ }
24950
+ const fromJsonStatement = fromJson([statement], "sqlite", "push");
24951
+ statementsToExecute.push(
24952
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
24953
+ );
24954
+ } else if (statement.type === "recreate_table") {
24955
+ const tableName = statement.tableName;
24956
+ const oldTableName = getOldTableName(tableName, meta);
24957
+ const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
24958
+ const currentColumnNames = Object.keys(json2.tables[tableName].columns);
24959
+ const { removedColumns, addedColumns } = findAddedAndRemoved(
24960
+ prevColumnNames,
24961
+ currentColumnNames
24962
+ );
24963
+ if (removedColumns.length) {
24964
+ for (const removedColumn of removedColumns) {
24965
+ const res = await connection.query(
24966
+ `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
24967
+ );
24968
+ const count = Number(res[0].count);
24969
+ if (count > 0) {
24970
+ infoToPrint.push(
24971
+ `\xB7 You're about to delete ${source_default.underline(
24972
+ removedColumn
24973
+ )} column in ${tableName} table with ${count} items`
24974
+ );
24975
+ columnsToRemove.push(removedColumn);
24976
+ shouldAskForApprove = true;
24977
+ }
24978
+ }
24979
+ }
24980
+ if (addedColumns.length) {
24981
+ for (const addedColumn of addedColumns) {
24982
+ const [res] = await connection.query(
24983
+ `select count(*) as count from \`${tableName}\``
24984
+ );
24985
+ const columnConf = json2.tables[tableName].columns[addedColumn];
24986
+ const count = Number(res.count);
24987
+ if (count > 0 && columnConf.notNull && !columnConf.default) {
24988
+ infoToPrint.push(
24989
+ `\xB7 You're about to add not-null ${source_default.underline(
24990
+ addedColumn
24991
+ )} column without default value to table, which contains ${count} items`
24992
+ );
24993
+ shouldAskForApprove = true;
24994
+ tablesToTruncate.push(tableName);
24995
+ }
24996
+ }
24997
+ }
24998
+ statementsToExecute.push(..._moveDataStatements(tableName, json2));
24999
+ const tablesReferencingCurrent = [];
25000
+ for (const table4 of Object.values(json2.tables)) {
25001
+ const tablesRefs = Object.values(json2.tables[table4.name].foreignKeys).filter((t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
25002
+ tablesReferencingCurrent.push(...tablesRefs);
25003
+ }
25004
+ const uniqueTableRefs = [...new Set(tablesReferencingCurrent)];
25005
+ for (const table4 of uniqueTableRefs) {
25006
+ statementsToExecute.push(..._moveDataStatements(table4, json2));
25007
+ }
25008
+ } else {
25009
+ const fromJsonStatement = fromJson([statement], "sqlite", "push");
25010
+ statementsToExecute.push(
25011
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
25012
+ );
25013
+ }
25014
+ }
25015
+ return {
25016
+ statementsToExecute,
25017
+ shouldAskForApprove,
25018
+ infoToPrint,
25019
+ columnsToRemove: [...new Set(columnsToRemove)],
25020
+ schemasToRemove: [...new Set(schemasToRemove)],
25021
+ tablesToTruncate: [...new Set(tablesToTruncate)],
25022
+ tablesToRemove: [...new Set(tablesToRemove)]
25023
+ };
25024
+ };
25025
+ }
25026
+ });
25027
+
24589
25028
  // src/jsonStatements.ts
24590
- var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql;
25029
+ var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql;
24591
25030
  var init_jsonStatements = __esm({
24592
25031
  "src/jsonStatements.ts"() {
24593
25032
  "use strict";
24594
25033
  init_source();
25034
+ init_sqlitePushUtils();
24595
25035
  init_views();
24596
25036
  init_mysqlSchema();
24597
25037
  init_pgSchema();
@@ -25365,7 +25805,7 @@ var init_jsonStatements = __esm({
25365
25805
  return [...dropPkStatements, ...setPkStatements, ...statements];
25366
25806
  };
25367
25807
  prepareSqliteAlterColumns = (tableName, schema5, columns, json2) => {
25368
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
25808
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
25369
25809
  let statements = [];
25370
25810
  let dropPkStatements = [];
25371
25811
  let setPkStatements = [];
@@ -25379,6 +25819,49 @@ var init_jsonStatements = __esm({
25379
25819
  const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
25380
25820
  const columnGenerated = json2.tables[tableName].columns[columnName].generated;
25381
25821
  const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
25822
+ if (((_a = column7.autoincrement) == null ? void 0 : _a.type) === "added") {
25823
+ statements.push({
25824
+ type: "alter_table_alter_column_set_autoincrement",
25825
+ tableName,
25826
+ columnName,
25827
+ schema: schema5,
25828
+ newDataType: columnType,
25829
+ columnDefault,
25830
+ columnOnUpdate,
25831
+ columnNotNull,
25832
+ columnAutoIncrement,
25833
+ columnPk
25834
+ });
25835
+ }
25836
+ if (((_b = column7.autoincrement) == null ? void 0 : _b.type) === "changed") {
25837
+ const type = column7.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
25838
+ statements.push({
25839
+ type,
25840
+ tableName,
25841
+ columnName,
25842
+ schema: schema5,
25843
+ newDataType: columnType,
25844
+ columnDefault,
25845
+ columnOnUpdate,
25846
+ columnNotNull,
25847
+ columnAutoIncrement,
25848
+ columnPk
25849
+ });
25850
+ }
25851
+ if (((_c = column7.autoincrement) == null ? void 0 : _c.type) === "deleted") {
25852
+ statements.push({
25853
+ type: "alter_table_alter_column_drop_autoincrement",
25854
+ tableName,
25855
+ columnName,
25856
+ schema: schema5,
25857
+ newDataType: columnType,
25858
+ columnDefault,
25859
+ columnOnUpdate,
25860
+ columnNotNull,
25861
+ columnAutoIncrement,
25862
+ columnPk
25863
+ });
25864
+ }
25382
25865
  if (typeof column7.name !== "string") {
25383
25866
  statements.push({
25384
25867
  type: "alter_table_rename_column",
@@ -25388,7 +25871,7 @@ var init_jsonStatements = __esm({
25388
25871
  schema: schema5
25389
25872
  });
25390
25873
  }
25391
- if (((_a = column7.type) == null ? void 0 : _a.type) === "changed") {
25874
+ if (((_d = column7.type) == null ? void 0 : _d.type) === "changed") {
25392
25875
  statements.push({
25393
25876
  type: "alter_table_alter_column_set_type",
25394
25877
  tableName,
@@ -25403,7 +25886,7 @@ var init_jsonStatements = __esm({
25403
25886
  columnPk
25404
25887
  });
25405
25888
  }
25406
- if (((_b = column7.primaryKey) == null ? void 0 : _b.type) === "deleted" || ((_c = column7.primaryKey) == null ? void 0 : _c.type) === "changed" && !column7.primaryKey.new && typeof compositePk === "undefined") {
25889
+ if (((_e = column7.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column7.primaryKey) == null ? void 0 : _f.type) === "changed" && !column7.primaryKey.new && typeof compositePk === "undefined") {
25407
25890
  dropPkStatements.push({
25408
25891
  ////
25409
25892
  type: "alter_table_alter_column_drop_pk",
@@ -25412,7 +25895,7 @@ var init_jsonStatements = __esm({
25412
25895
  schema: schema5
25413
25896
  });
25414
25897
  }
25415
- if (((_d = column7.default) == null ? void 0 : _d.type) === "added") {
25898
+ if (((_g = column7.default) == null ? void 0 : _g.type) === "added") {
25416
25899
  statements.push({
25417
25900
  type: "alter_table_alter_column_set_default",
25418
25901
  tableName,
@@ -25426,7 +25909,7 @@ var init_jsonStatements = __esm({
25426
25909
  columnPk
25427
25910
  });
25428
25911
  }
25429
- if (((_e = column7.default) == null ? void 0 : _e.type) === "changed") {
25912
+ if (((_h = column7.default) == null ? void 0 : _h.type) === "changed") {
25430
25913
  statements.push({
25431
25914
  type: "alter_table_alter_column_set_default",
25432
25915
  tableName,
@@ -25441,7 +25924,7 @@ var init_jsonStatements = __esm({
25441
25924
  columnPk
25442
25925
  });
25443
25926
  }
25444
- if (((_f = column7.default) == null ? void 0 : _f.type) === "deleted") {
25927
+ if (((_i = column7.default) == null ? void 0 : _i.type) === "deleted") {
25445
25928
  statements.push({
25446
25929
  type: "alter_table_alter_column_drop_default",
25447
25930
  tableName,
@@ -25455,7 +25938,7 @@ var init_jsonStatements = __esm({
25455
25938
  columnPk
25456
25939
  });
25457
25940
  }
25458
- if (((_g = column7.notNull) == null ? void 0 : _g.type) === "added") {
25941
+ if (((_j = column7.notNull) == null ? void 0 : _j.type) === "added") {
25459
25942
  statements.push({
25460
25943
  type: "alter_table_alter_column_set_notnull",
25461
25944
  tableName,
@@ -25469,7 +25952,7 @@ var init_jsonStatements = __esm({
25469
25952
  columnPk
25470
25953
  });
25471
25954
  }
25472
- if (((_h = column7.notNull) == null ? void 0 : _h.type) === "changed") {
25955
+ if (((_k = column7.notNull) == null ? void 0 : _k.type) === "changed") {
25473
25956
  const type = column7.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
25474
25957
  statements.push({
25475
25958
  type,
@@ -25484,7 +25967,7 @@ var init_jsonStatements = __esm({
25484
25967
  columnPk
25485
25968
  });
25486
25969
  }
25487
- if (((_i = column7.notNull) == null ? void 0 : _i.type) === "deleted") {
25970
+ if (((_l = column7.notNull) == null ? void 0 : _l.type) === "deleted") {
25488
25971
  statements.push({
25489
25972
  type: "alter_table_alter_column_drop_notnull",
25490
25973
  tableName,
@@ -25498,7 +25981,7 @@ var init_jsonStatements = __esm({
25498
25981
  columnPk
25499
25982
  });
25500
25983
  }
25501
- if (((_j = column7.generated) == null ? void 0 : _j.type) === "added") {
25984
+ if (((_m = column7.generated) == null ? void 0 : _m.type) === "added") {
25502
25985
  if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
25503
25986
  statements.push({
25504
25987
  type: "alter_table_alter_column_set_generated",
@@ -25519,7 +26002,7 @@ var init_jsonStatements = __esm({
25519
26002
  );
25520
26003
  }
25521
26004
  }
25522
- if (((_k = column7.generated) == null ? void 0 : _k.type) === "changed") {
26005
+ if (((_n = column7.generated) == null ? void 0 : _n.type) === "changed") {
25523
26006
  if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
25524
26007
  statements.push({
25525
26008
  type: "alter_table_alter_column_alter_generated",
@@ -25540,7 +26023,7 @@ var init_jsonStatements = __esm({
25540
26023
  );
25541
26024
  }
25542
26025
  }
25543
- if (((_l = column7.generated) == null ? void 0 : _l.type) === "deleted") {
26026
+ if (((_o = column7.generated) == null ? void 0 : _o.type) === "deleted") {
25544
26027
  statements.push({
25545
26028
  type: "alter_table_alter_column_drop_generated",
25546
26029
  tableName,
@@ -25555,7 +26038,7 @@ var init_jsonStatements = __esm({
25555
26038
  columnGenerated
25556
26039
  });
25557
26040
  }
25558
- if (((_m = column7.primaryKey) == null ? void 0 : _m.type) === "added" || ((_n = column7.primaryKey) == null ? void 0 : _n.type) === "changed" && column7.primaryKey.new) {
26041
+ if (((_p = column7.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column7.primaryKey) == null ? void 0 : _q.type) === "changed" && column7.primaryKey.new) {
25559
26042
  const wasAutoincrement = statements.filter(
25560
26043
  (it) => it.type === "alter_table_alter_column_set_autoincrement"
25561
26044
  );
@@ -25568,7 +26051,7 @@ var init_jsonStatements = __esm({
25568
26051
  });
25569
26052
  }
25570
26053
  }
25571
- if (((_o = column7.onUpdate) == null ? void 0 : _o.type) === "added") {
26054
+ if (((_r = column7.onUpdate) == null ? void 0 : _r.type) === "added") {
25572
26055
  statements.push({
25573
26056
  type: "alter_table_alter_column_set_on_update",
25574
26057
  tableName,
@@ -25582,7 +26065,7 @@ var init_jsonStatements = __esm({
25582
26065
  columnPk
25583
26066
  });
25584
26067
  }
25585
- if (((_p = column7.onUpdate) == null ? void 0 : _p.type) === "deleted") {
26068
+ if (((_s = column7.onUpdate) == null ? void 0 : _s.type) === "deleted") {
25586
26069
  statements.push({
25587
26070
  type: "alter_table_alter_column_drop_on_update",
25588
26071
  tableName,
@@ -25642,6 +26125,37 @@ var init_jsonStatements = __esm({
25642
26125
  };
25643
26126
  });
25644
26127
  };
26128
+ prepareLibSQLCreateReferencesJson = (tableName, schema5, foreignKeys, json2, action) => {
26129
+ return Object.values(foreignKeys).map((fkData) => {
26130
+ const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
26131
+ let isMulticolumn = false;
26132
+ if (columnsFrom.length > 1 || columnsTo.length > 1) {
26133
+ isMulticolumn = true;
26134
+ return {
26135
+ type: "create_reference",
26136
+ tableName,
26137
+ data: fkData,
26138
+ schema: schema5,
26139
+ isMulticolumn
26140
+ };
26141
+ }
26142
+ const columnFrom = columnsFrom[0];
26143
+ const {
26144
+ notNull: columnNotNull,
26145
+ default: columnDefault,
26146
+ type: columnType
26147
+ } = json2.tables[tableFrom].columns[columnFrom];
26148
+ return {
26149
+ type: "create_reference",
26150
+ tableName,
26151
+ data: fkData,
26152
+ schema: schema5,
26153
+ columnNotNull,
26154
+ columnDefault,
26155
+ columnType
26156
+ };
26157
+ });
26158
+ };
25645
26159
  prepareDropReferencesJson = (tableName, schema5, foreignKeys) => {
25646
26160
  return Object.values(foreignKeys).map((fkData) => {
25647
26161
  return {
@@ -25652,6 +26166,54 @@ var init_jsonStatements = __esm({
25652
26166
  };
25653
26167
  });
25654
26168
  };
26169
+ prepareLibSQLDropReferencesJson = (tableName, schema5, foreignKeys, json2, meta, action) => {
26170
+ const statements = Object.values(foreignKeys).map((fkData) => {
26171
+ const { columnsFrom, tableFrom, columnsTo, name, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
26172
+ const keys = Object.keys(json2.tables[tableName].columns);
26173
+ const filtered = columnsFrom.filter((it) => keys.includes(it));
26174
+ const fullDrop = filtered.length === 0;
26175
+ if (fullDrop)
26176
+ return;
26177
+ let isMulticolumn = false;
26178
+ if (columnsFrom.length > 1 || columnsTo.length > 1) {
26179
+ isMulticolumn = true;
26180
+ return {
26181
+ type: "delete_reference",
26182
+ tableName,
26183
+ data: fkData,
26184
+ schema: schema5,
26185
+ isMulticolumn
26186
+ };
26187
+ }
26188
+ const columnFrom = columnsFrom[0];
26189
+ const newTableName = getNewTableName(tableFrom, meta);
26190
+ const {
26191
+ notNull: columnNotNull,
26192
+ default: columnDefault,
26193
+ type: columnType
26194
+ } = json2.tables[newTableName].columns[columnFrom];
26195
+ const fkToSquash = {
26196
+ columnsFrom,
26197
+ columnsTo,
26198
+ name,
26199
+ tableFrom: newTableName,
26200
+ tableTo,
26201
+ onDelete,
26202
+ onUpdate
26203
+ };
26204
+ const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash);
26205
+ return {
26206
+ type: "delete_reference",
26207
+ tableName,
26208
+ data: foreignKey,
26209
+ schema: schema5,
26210
+ columnNotNull,
26211
+ columnDefault,
26212
+ columnType
26213
+ };
26214
+ });
26215
+ return statements.filter((it) => it);
26216
+ };
25655
26217
  prepareAlterReferencesJson = (tableName, schema5, foreignKeys) => {
25656
26218
  const stmts = [];
25657
26219
  Object.values(foreignKeys).map((val2) => {
@@ -25806,8 +26368,295 @@ var init_jsonStatements = __esm({
25806
26368
  }
25807
26369
  });
25808
26370
 
26371
+ // src/statementCombiner.ts
26372
+ var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements;
26373
+ var init_statementCombiner = __esm({
26374
+ "src/statementCombiner.ts"() {
26375
+ "use strict";
26376
+ init_jsonStatements();
26377
+ init_sqliteSchema();
26378
+ prepareLibSQLRecreateTable = (table4, action) => {
26379
+ const { name, columns, uniqueConstraints, indexes } = table4;
26380
+ const composites = Object.values(table4.compositePrimaryKeys).map(
26381
+ (it) => SQLiteSquasher.unsquashPK(it)
26382
+ );
26383
+ const references2 = Object.values(table4.foreignKeys);
26384
+ const fks = references2.map(
26385
+ (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
26386
+ );
26387
+ const statements = [
26388
+ {
26389
+ type: "recreate_table",
26390
+ tableName: name,
26391
+ columns: Object.values(columns),
26392
+ compositePKs: composites,
26393
+ referenceData: fks,
26394
+ uniqueConstraints: Object.values(uniqueConstraints)
26395
+ }
26396
+ ];
26397
+ if (Object.keys(indexes).length) {
26398
+ statements.push(...prepareCreateIndexesJson(name, "", indexes));
26399
+ }
26400
+ return statements;
26401
+ };
26402
+ prepareSQLiteRecreateTable = (table4, action) => {
26403
+ const { name, columns, uniqueConstraints, indexes } = table4;
26404
+ const composites = Object.values(table4.compositePrimaryKeys).map(
26405
+ (it) => SQLiteSquasher.unsquashPK(it)
26406
+ );
26407
+ const references2 = Object.values(table4.foreignKeys);
26408
+ const fks = references2.map(
26409
+ (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
26410
+ );
26411
+ const statements = [
26412
+ {
26413
+ type: "recreate_table",
26414
+ tableName: name,
26415
+ columns: Object.values(columns),
26416
+ compositePKs: composites,
26417
+ referenceData: fks,
26418
+ uniqueConstraints: Object.values(uniqueConstraints)
26419
+ }
26420
+ ];
26421
+ if (Object.keys(indexes).length) {
26422
+ statements.push(...prepareCreateIndexesJson(name, "", indexes));
26423
+ }
26424
+ return statements;
26425
+ };
26426
+ libSQLCombineStatements = (statements, json2, action) => {
26427
+ const newStatements = {};
26428
+ for (const statement of statements) {
26429
+ if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") {
26430
+ const tableName2 = statement.tableName;
26431
+ const statementsForTable2 = newStatements[tableName2];
26432
+ if (!statementsForTable2) {
26433
+ newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26434
+ continue;
26435
+ }
26436
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26437
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26438
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26439
+ if (wasRename) {
26440
+ newStatements[tableName2].push(...preparedStatements);
26441
+ } else {
26442
+ newStatements[tableName2] = preparedStatements;
26443
+ }
26444
+ continue;
26445
+ }
26446
+ continue;
26447
+ }
26448
+ if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") {
26449
+ const { tableName: tableName2, columnName, columnPk } = statement;
26450
+ const columnIsPartOfUniqueIndex = Object.values(
26451
+ json2.tables[tableName2].indexes
26452
+ ).some((it) => {
26453
+ const unsquashIndex = SQLiteSquasher.unsquashIdx(it);
26454
+ return unsquashIndex.columns.includes(columnName) && unsquashIndex.isUnique;
26455
+ });
26456
+ const columnIsPartOfForeignKey = Object.values(
26457
+ json2.tables[tableName2].foreignKeys
26458
+ ).some((it) => {
26459
+ const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it);
26460
+ return unsquashFk.columnsFrom.includes(columnName);
26461
+ });
26462
+ const statementsForTable2 = newStatements[tableName2];
26463
+ if (!statementsForTable2 && (columnIsPartOfUniqueIndex || columnIsPartOfForeignKey || columnPk)) {
26464
+ newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26465
+ continue;
26466
+ }
26467
+ if (statementsForTable2 && (columnIsPartOfUniqueIndex || columnIsPartOfForeignKey || columnPk)) {
26468
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26469
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26470
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26471
+ if (wasRename) {
26472
+ newStatements[tableName2].push(...preparedStatements);
26473
+ } else {
26474
+ newStatements[tableName2] = preparedStatements;
26475
+ }
26476
+ }
26477
+ continue;
26478
+ }
26479
+ if (statementsForTable2 && !(columnIsPartOfUniqueIndex || columnIsPartOfForeignKey || columnPk)) {
26480
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26481
+ newStatements[tableName2].push(statement);
26482
+ }
26483
+ continue;
26484
+ }
26485
+ newStatements[tableName2] = [statement];
26486
+ continue;
26487
+ }
26488
+ if (statement.type === "create_reference") {
26489
+ const tableName2 = statement.tableName;
26490
+ const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
26491
+ const statementsForTable2 = newStatements[tableName2];
26492
+ if (!statementsForTable2) {
26493
+ newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : newStatements[tableName2] = [statement];
26494
+ continue;
26495
+ }
26496
+ if (!statement.isMulticolumn && statementsForTable2.some(
26497
+ (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
26498
+ )) {
26499
+ continue;
26500
+ }
26501
+ if (statement.isMulticolumn) {
26502
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26503
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26504
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26505
+ if (wasRename) {
26506
+ newStatements[tableName2].push(...preparedStatements);
26507
+ } else {
26508
+ newStatements[tableName2] = preparedStatements;
26509
+ }
26510
+ continue;
26511
+ }
26512
+ continue;
26513
+ }
26514
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26515
+ newStatements[tableName2].push(statement);
26516
+ }
26517
+ continue;
26518
+ }
26519
+ if (statement.type === "delete_reference") {
26520
+ const tableName2 = statement.tableName;
26521
+ const statementsForTable2 = newStatements[tableName2];
26522
+ if (!statementsForTable2) {
26523
+ newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26524
+ continue;
26525
+ }
26526
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26527
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26528
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26529
+ if (wasRename) {
26530
+ newStatements[tableName2].push(...preparedStatements);
26531
+ } else {
26532
+ newStatements[tableName2] = preparedStatements;
26533
+ }
26534
+ continue;
26535
+ }
26536
+ continue;
26537
+ }
26538
+ if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
26539
+ const tableName2 = statement.tableName;
26540
+ const statementsForTable2 = newStatements[tableName2];
26541
+ if (!statementsForTable2) {
26542
+ newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26543
+ continue;
26544
+ }
26545
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26546
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26547
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26548
+ if (wasRename) {
26549
+ newStatements[tableName2].push(...preparedStatements);
26550
+ } else {
26551
+ newStatements[tableName2] = preparedStatements;
26552
+ }
26553
+ continue;
26554
+ }
26555
+ continue;
26556
+ }
26557
+ const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
26558
+ const statementsForTable = newStatements[tableName];
26559
+ if (!statementsForTable) {
26560
+ newStatements[tableName] = [statement];
26561
+ continue;
26562
+ }
26563
+ if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
26564
+ newStatements[tableName].push(statement);
26565
+ }
26566
+ }
26567
+ const combinedStatements = Object.values(newStatements).flat();
26568
+ const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
26569
+ const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
26570
+ const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
26571
+ return [...renamedTables, ...renamedColumns, ...rest];
26572
+ };
26573
+ sqliteCombineStatements = (statements, json2, action) => {
26574
+ const newStatements = {};
26575
+ for (const statement of statements) {
26576
+ if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint") {
26577
+ const tableName2 = statement.tableName;
26578
+ const statementsForTable2 = newStatements[tableName2];
26579
+ if (!statementsForTable2) {
26580
+ newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26581
+ continue;
26582
+ }
26583
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26584
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26585
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26586
+ if (wasRename) {
26587
+ newStatements[tableName2].push(...preparedStatements);
26588
+ } else {
26589
+ newStatements[tableName2] = preparedStatements;
26590
+ }
26591
+ continue;
26592
+ }
26593
+ continue;
26594
+ }
26595
+ if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
26596
+ const tableName2 = statement.tableName;
26597
+ const statementsForTable2 = newStatements[tableName2];
26598
+ if (!statementsForTable2) {
26599
+ newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26600
+ continue;
26601
+ }
26602
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26603
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26604
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26605
+ if (wasRename) {
26606
+ newStatements[tableName2].push(...preparedStatements);
26607
+ } else {
26608
+ newStatements[tableName2] = preparedStatements;
26609
+ }
26610
+ continue;
26611
+ }
26612
+ continue;
26613
+ }
26614
+ if (statement.type === "create_reference") {
26615
+ const tableName2 = statement.tableName;
26616
+ const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
26617
+ const statementsForTable2 = newStatements[tableName2];
26618
+ if (!statementsForTable2) {
26619
+ newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
26620
+ continue;
26621
+ }
26622
+ if (data.columnsFrom.length === 1 && statementsForTable2.some(
26623
+ (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
26624
+ )) {
26625
+ continue;
26626
+ }
26627
+ if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
26628
+ const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
26629
+ const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
26630
+ if (wasRename) {
26631
+ newStatements[tableName2].push(...preparedStatements);
26632
+ } else {
26633
+ newStatements[tableName2] = preparedStatements;
26634
+ }
26635
+ continue;
26636
+ }
26637
+ continue;
26638
+ }
26639
+ const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
26640
+ const statementsForTable = newStatements[tableName];
26641
+ if (!statementsForTable) {
26642
+ newStatements[tableName] = [statement];
26643
+ continue;
26644
+ }
26645
+ if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
26646
+ newStatements[tableName].push(statement);
26647
+ }
26648
+ }
26649
+ const combinedStatements = Object.values(newStatements).flat();
26650
+ const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
26651
+ const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
26652
+ const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
26653
+ return [...renamedTables, ...renamedColumns, ...rest];
26654
+ };
26655
+ }
26656
+ });
26657
+
25809
26658
  // src/snapshotsDiffer.ts
25810
- var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff;
26659
+ var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
25811
26660
  var init_snapshotsDiffer = __esm({
25812
26661
  "src/snapshotsDiffer.ts"() {
25813
26662
  "use strict";
@@ -25819,6 +26668,7 @@ var init_snapshotsDiffer = __esm({
25819
26668
  init_mysqlSchema();
25820
26669
  init_pgSchema();
25821
26670
  init_sqliteSchema();
26671
+ init_statementCombiner();
25822
26672
  init_utils();
25823
26673
  makeChanged = (schema5) => {
25824
26674
  return objectType({
@@ -26835,35 +27685,319 @@ var init_snapshotsDiffer = __esm({
26835
27685
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
26836
27686
  (t2) => t2.type === "delete_reference"
26837
27687
  );
26838
- const jsonMySqlCreateTables = createdTables.map((it) => {
26839
- return prepareMySqlCreateTableJson(
26840
- it,
26841
- curFull,
26842
- curFull.internal
26843
- );
26844
- });
26845
- jsonStatements.push(...jsonMySqlCreateTables);
27688
+ const jsonMySqlCreateTables = createdTables.map((it) => {
27689
+ return prepareMySqlCreateTableJson(
27690
+ it,
27691
+ curFull,
27692
+ curFull.internal
27693
+ );
27694
+ });
27695
+ jsonStatements.push(...jsonMySqlCreateTables);
27696
+ jsonStatements.push(...jsonDropTables);
27697
+ jsonStatements.push(...jsonRenameTables);
27698
+ jsonStatements.push(...jsonRenameColumnsStatements);
27699
+ jsonStatements.push(...jsonDeletedUniqueConstraints);
27700
+ jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
27701
+ jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
27702
+ jsonStatements.push(...jsonDeletedCompositePKs);
27703
+ jsonStatements.push(...jsonTableAlternations);
27704
+ jsonStatements.push(...jsonAddedCompositePKs);
27705
+ jsonStatements.push(...jsonAddedUniqueConstraints);
27706
+ jsonStatements.push(...jsonDeletedUniqueConstraints);
27707
+ jsonStatements.push(...jsonAddColumnsStatemets);
27708
+ jsonStatements.push(...jsonCreateReferencesForCreatedTables);
27709
+ jsonStatements.push(...jsonCreateIndexesForCreatedTables);
27710
+ jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
27711
+ jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
27712
+ jsonStatements.push(...jsonDropColumnsStatemets);
27713
+ jsonStatements.push(...jsonAlteredCompositePKs);
27714
+ jsonStatements.push(...jsonAddedUniqueConstraints);
27715
+ jsonStatements.push(...jsonAlteredUniqueConstraints);
27716
+ const sqlStatements = fromJson(jsonStatements, "mysql");
27717
+ const uniqueSqlStatements = [];
27718
+ sqlStatements.forEach((ss) => {
27719
+ if (!uniqueSqlStatements.includes(ss)) {
27720
+ uniqueSqlStatements.push(ss);
27721
+ }
27722
+ });
27723
+ const rTables = renamedTables.map((it) => {
27724
+ return { from: it.from, to: it.to };
27725
+ });
27726
+ const _meta = prepareMigrationMeta([], rTables, rColumns);
27727
+ return {
27728
+ statements: jsonStatements,
27729
+ sqlStatements: uniqueSqlStatements,
27730
+ _meta
27731
+ };
27732
+ };
27733
+ applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
27734
+ const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
27735
+ const {
27736
+ created: createdTables,
27737
+ deleted: deletedTables,
27738
+ renamed: renamedTables
27739
+ } = await tablesResolver2({
27740
+ created: tablesDiff.added,
27741
+ deleted: tablesDiff.deleted
27742
+ });
27743
+ const tablesPatchedSnap1 = copy(json1);
27744
+ tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
27745
+ const { name } = nameChangeFor(it, renamedTables);
27746
+ it.name = name;
27747
+ return [name, it];
27748
+ });
27749
+ const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
27750
+ const columnRenames = [];
27751
+ const columnCreates = [];
27752
+ const columnDeletes = [];
27753
+ for (let entry of Object.values(res)) {
27754
+ const { renamed, created, deleted } = await columnsResolver2({
27755
+ tableName: entry.name,
27756
+ schema: entry.schema,
27757
+ deleted: entry.columns.deleted,
27758
+ created: entry.columns.added
27759
+ });
27760
+ if (created.length > 0) {
27761
+ columnCreates.push({
27762
+ table: entry.name,
27763
+ columns: created
27764
+ });
27765
+ }
27766
+ if (deleted.length > 0) {
27767
+ columnDeletes.push({
27768
+ table: entry.name,
27769
+ columns: deleted
27770
+ });
27771
+ }
27772
+ if (renamed.length > 0) {
27773
+ columnRenames.push({
27774
+ table: entry.name,
27775
+ renames: renamed
27776
+ });
27777
+ }
27778
+ }
27779
+ const columnRenamesDict = columnRenames.reduce(
27780
+ (acc, it) => {
27781
+ acc[it.table] = it.renames;
27782
+ return acc;
27783
+ },
27784
+ {}
27785
+ );
27786
+ const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
27787
+ columnsPatchedSnap1.tables = mapEntries(
27788
+ columnsPatchedSnap1.tables,
27789
+ (tableKey2, tableValue) => {
27790
+ const patchedColumns = mapKeys(
27791
+ tableValue.columns,
27792
+ (columnKey, column7) => {
27793
+ const rens = columnRenamesDict[tableValue.name] || [];
27794
+ const newName = columnChangeFor(columnKey, rens);
27795
+ column7.name = newName;
27796
+ return newName;
27797
+ }
27798
+ );
27799
+ tableValue.columns = patchedColumns;
27800
+ return [tableKey2, tableValue];
27801
+ }
27802
+ );
27803
+ const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
27804
+ const typedResult = diffResultSchemeSQLite.parse(diffResult);
27805
+ const tablesMap = {};
27806
+ typedResult.alteredTablesWithColumns.forEach((obj) => {
27807
+ tablesMap[obj.name] = obj;
27808
+ });
27809
+ const jsonCreateTables = createdTables.map((it) => {
27810
+ return prepareSQLiteCreateTable(it, action);
27811
+ });
27812
+ const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
27813
+ return prepareCreateIndexesJson(
27814
+ it.name,
27815
+ it.schema,
27816
+ it.indexes,
27817
+ curFull.internal
27818
+ );
27819
+ }).flat();
27820
+ const jsonDropTables = deletedTables.map((it) => {
27821
+ return prepareDropTableJson(it);
27822
+ });
27823
+ const jsonRenameTables = renamedTables.map((it) => {
27824
+ return prepareRenameTableJson(it.from, it.to);
27825
+ });
27826
+ const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
27827
+ const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
27828
+ const jsonAddColumnsStatemets = columnCreates.map((it) => {
27829
+ return _prepareSqliteAddColumns(
27830
+ it.table,
27831
+ it.columns,
27832
+ tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
27833
+ );
27834
+ }).flat();
27835
+ const allAltered = typedResult.alteredTablesWithColumns;
27836
+ const jsonAddedCompositePKs = [];
27837
+ const jsonDeletedCompositePKs = [];
27838
+ const jsonAlteredCompositePKs = [];
27839
+ const jsonAddedUniqueConstraints = [];
27840
+ const jsonDeletedUniqueConstraints = [];
27841
+ const jsonAlteredUniqueConstraints = [];
27842
+ allAltered.forEach((it) => {
27843
+ let addedColumns = [];
27844
+ for (const addedPkName of Object.keys(it.addedCompositePKs)) {
27845
+ const addedPkColumns = it.addedCompositePKs[addedPkName];
27846
+ addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
27847
+ }
27848
+ let deletedColumns = [];
27849
+ for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
27850
+ const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
27851
+ deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
27852
+ }
27853
+ const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
27854
+ let addedCompositePKs = [];
27855
+ let deletedCompositePKs = [];
27856
+ let alteredCompositePKs = [];
27857
+ if (doPerformDeleteAndCreate) {
27858
+ addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
27859
+ it.name,
27860
+ it.addedCompositePKs
27861
+ );
27862
+ deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
27863
+ it.name,
27864
+ it.deletedCompositePKs
27865
+ );
27866
+ }
27867
+ alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
27868
+ it.name,
27869
+ it.alteredCompositePKs
27870
+ );
27871
+ let addedUniqueConstraints = [];
27872
+ let deletedUniqueConstraints = [];
27873
+ let alteredUniqueConstraints = [];
27874
+ addedUniqueConstraints = prepareAddUniqueConstraintPg(
27875
+ it.name,
27876
+ it.schema,
27877
+ it.addedUniqueConstraints
27878
+ );
27879
+ deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
27880
+ it.name,
27881
+ it.schema,
27882
+ it.deletedUniqueConstraints
27883
+ );
27884
+ if (it.alteredUniqueConstraints) {
27885
+ const added = {};
27886
+ const deleted = {};
27887
+ for (const k of Object.keys(it.alteredUniqueConstraints)) {
27888
+ added[k] = it.alteredUniqueConstraints[k].__new;
27889
+ deleted[k] = it.alteredUniqueConstraints[k].__old;
27890
+ }
27891
+ addedUniqueConstraints.push(
27892
+ ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
27893
+ );
27894
+ deletedUniqueConstraints.push(
27895
+ ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
27896
+ );
27897
+ }
27898
+ jsonAddedCompositePKs.push(...addedCompositePKs);
27899
+ jsonDeletedCompositePKs.push(...deletedCompositePKs);
27900
+ jsonAlteredCompositePKs.push(...alteredCompositePKs);
27901
+ jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
27902
+ jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
27903
+ jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
27904
+ });
27905
+ const rColumns = jsonRenameColumnsStatements.map((it) => {
27906
+ const tableName = it.tableName;
27907
+ const schema5 = it.schema;
27908
+ return {
27909
+ from: { schema: schema5, table: tableName, column: it.oldColumnName },
27910
+ to: { schema: schema5, table: tableName, column: it.newColumnName }
27911
+ };
27912
+ });
27913
+ const jsonTableAlternations = allAltered.map((it) => {
27914
+ return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
27915
+ }).flat();
27916
+ const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
27917
+ return prepareCreateIndexesJson(
27918
+ it.name,
27919
+ it.schema,
27920
+ it.addedIndexes || {},
27921
+ curFull.internal
27922
+ );
27923
+ }).flat();
27924
+ const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
27925
+ return prepareDropIndexesJson(
27926
+ it.name,
27927
+ it.schema,
27928
+ it.deletedIndexes || {}
27929
+ );
27930
+ }).flat();
27931
+ allAltered.forEach((it) => {
27932
+ const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
27933
+ (current, item) => {
27934
+ current[item] = it.alteredIndexes[item].__old;
27935
+ return current;
27936
+ },
27937
+ {}
27938
+ );
27939
+ const createdIndexes = Object.keys(it.alteredIndexes).reduce(
27940
+ (current, item) => {
27941
+ current[item] = it.alteredIndexes[item].__new;
27942
+ return current;
27943
+ },
27944
+ {}
27945
+ );
27946
+ jsonCreateIndexesForAllAlteredTables.push(
27947
+ ...prepareCreateIndexesJson(
27948
+ it.name,
27949
+ it.schema,
27950
+ createdIndexes || {},
27951
+ curFull.internal
27952
+ )
27953
+ );
27954
+ jsonDropIndexesForAllAlteredTables.push(
27955
+ ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
27956
+ );
27957
+ });
27958
+ const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
27959
+ const forAdded = prepareCreateReferencesJson(
27960
+ it.name,
27961
+ it.schema,
27962
+ it.addedForeignKeys
27963
+ );
27964
+ const forAltered = prepareDropReferencesJson(
27965
+ it.name,
27966
+ it.schema,
27967
+ it.deletedForeignKeys
27968
+ );
27969
+ const alteredFKs = prepareAlterReferencesJson(
27970
+ it.name,
27971
+ it.schema,
27972
+ it.alteredForeignKeys
27973
+ );
27974
+ return [...forAdded, ...forAltered, ...alteredFKs];
27975
+ }).flat();
27976
+ const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
27977
+ (t2) => t2.type === "create_reference"
27978
+ );
27979
+ const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
27980
+ (t2) => t2.type === "delete_reference"
27981
+ );
27982
+ const jsonStatements = [];
27983
+ jsonStatements.push(...jsonCreateTables);
26846
27984
  jsonStatements.push(...jsonDropTables);
26847
27985
  jsonStatements.push(...jsonRenameTables);
26848
27986
  jsonStatements.push(...jsonRenameColumnsStatements);
26849
- jsonStatements.push(...jsonDeletedUniqueConstraints);
26850
27987
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
26851
27988
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
26852
27989
  jsonStatements.push(...jsonDeletedCompositePKs);
26853
27990
  jsonStatements.push(...jsonTableAlternations);
26854
27991
  jsonStatements.push(...jsonAddedCompositePKs);
26855
- jsonStatements.push(...jsonAddedUniqueConstraints);
26856
- jsonStatements.push(...jsonDeletedUniqueConstraints);
26857
27992
  jsonStatements.push(...jsonAddColumnsStatemets);
26858
- jsonStatements.push(...jsonCreateReferencesForCreatedTables);
26859
27993
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
26860
- jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
26861
27994
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
27995
+ jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
26862
27996
  jsonStatements.push(...jsonDropColumnsStatemets);
26863
27997
  jsonStatements.push(...jsonAlteredCompositePKs);
26864
- jsonStatements.push(...jsonAddedUniqueConstraints);
26865
27998
  jsonStatements.push(...jsonAlteredUniqueConstraints);
26866
- const sqlStatements = fromJson(jsonStatements, "mysql");
27999
+ const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
28000
+ const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
26867
28001
  const uniqueSqlStatements = [];
26868
28002
  sqlStatements.forEach((ss) => {
26869
28003
  if (!uniqueSqlStatements.includes(ss)) {
@@ -26875,12 +28009,12 @@ var init_snapshotsDiffer = __esm({
26875
28009
  });
26876
28010
  const _meta = prepareMigrationMeta([], rTables, rColumns);
26877
28011
  return {
26878
- statements: jsonStatements,
28012
+ statements: combinedJsonStatements,
26879
28013
  sqlStatements: uniqueSqlStatements,
26880
28014
  _meta
26881
28015
  };
26882
28016
  };
26883
- applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
28017
+ applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
26884
28018
  const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
26885
28019
  const {
26886
28020
  created: createdTables,
@@ -26982,6 +28116,18 @@ var init_snapshotsDiffer = __esm({
26982
28116
  tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
26983
28117
  );
26984
28118
  }).flat();
28119
+ const rColumns = jsonRenameColumnsStatements.map((it) => {
28120
+ const tableName = it.tableName;
28121
+ const schema5 = it.schema;
28122
+ return {
28123
+ from: { schema: schema5, table: tableName, column: it.oldColumnName },
28124
+ to: { schema: schema5, table: tableName, column: it.newColumnName }
28125
+ };
28126
+ });
28127
+ const rTables = renamedTables.map((it) => {
28128
+ return { from: it.from, to: it.to };
28129
+ });
28130
+ const _meta = prepareMigrationMeta([], rTables, rColumns);
26985
28131
  const allAltered = typedResult.alteredTablesWithColumns;
26986
28132
  const jsonAddedCompositePKs = [];
26987
28133
  const jsonDeletedCompositePKs = [];
@@ -27052,14 +28198,6 @@ var init_snapshotsDiffer = __esm({
27052
28198
  jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
27053
28199
  jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
27054
28200
  });
27055
- const rColumns = jsonRenameColumnsStatements.map((it) => {
27056
- const tableName = it.tableName;
27057
- const schema5 = it.schema;
27058
- return {
27059
- from: { schema: schema5, table: tableName, column: it.oldColumnName },
27060
- to: { schema: schema5, table: tableName, column: it.newColumnName }
27061
- };
27062
- });
27063
28201
  const jsonTableAlternations = allAltered.map((it) => {
27064
28202
  return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
27065
28203
  }).flat();
@@ -27106,21 +28244,22 @@ var init_snapshotsDiffer = __esm({
27106
28244
  );
27107
28245
  });
27108
28246
  const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
27109
- const forAdded = prepareCreateReferencesJson(
28247
+ const forAdded = prepareLibSQLCreateReferencesJson(
27110
28248
  it.name,
27111
28249
  it.schema,
27112
- it.addedForeignKeys
27113
- );
27114
- const forAltered = prepareDropReferencesJson(
27115
- it.name,
27116
- it.schema,
27117
- it.deletedForeignKeys
28250
+ it.addedForeignKeys,
28251
+ json2,
28252
+ action
27118
28253
  );
27119
- const alteredFKs = prepareAlterReferencesJson(
28254
+ const forAltered = prepareLibSQLDropReferencesJson(
27120
28255
  it.name,
27121
28256
  it.schema,
27122
- it.alteredForeignKeys
28257
+ it.deletedForeignKeys,
28258
+ json2,
28259
+ _meta,
28260
+ action
27123
28261
  );
28262
+ const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
27124
28263
  return [...forAdded, ...forAltered, ...alteredFKs];
27125
28264
  }).flat();
27126
28265
  const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
@@ -27146,19 +28285,22 @@ var init_snapshotsDiffer = __esm({
27146
28285
  jsonStatements.push(...jsonDropColumnsStatemets);
27147
28286
  jsonStatements.push(...jsonAlteredCompositePKs);
27148
28287
  jsonStatements.push(...jsonAlteredUniqueConstraints);
27149
- const sqlStatements = fromJson(jsonStatements, "sqlite");
28288
+ const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action);
28289
+ const sqlStatements = fromJson(
28290
+ combinedJsonStatements,
28291
+ "sqlite",
28292
+ action,
28293
+ "turso",
28294
+ json2
28295
+ );
27150
28296
  const uniqueSqlStatements = [];
27151
28297
  sqlStatements.forEach((ss) => {
27152
28298
  if (!uniqueSqlStatements.includes(ss)) {
27153
28299
  uniqueSqlStatements.push(ss);
27154
28300
  }
27155
28301
  });
27156
- const rTables = renamedTables.map((it) => {
27157
- return { from: it.from, to: it.to };
27158
- });
27159
- const _meta = prepareMigrationMeta([], rTables, rColumns);
27160
28302
  return {
27161
- statements: jsonStatements,
28303
+ statements: combinedJsonStatements,
27162
28304
  sqlStatements: uniqueSqlStatements,
27163
28305
  _meta
27164
28306
  };
@@ -28497,6 +29639,7 @@ __export(migrate_exports, {
28497
29639
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
28498
29640
  prepareAndMigratePg: () => prepareAndMigratePg,
28499
29641
  prepareAndMigrateSqlite: () => prepareAndMigrateSqlite,
29642
+ prepareLibSQLPush: () => prepareLibSQLPush,
28500
29643
  prepareMySQLPush: () => prepareMySQLPush,
28501
29644
  preparePgPush: () => preparePgPush,
28502
29645
  prepareSQLitePush: () => prepareSQLitePush,
@@ -28509,7 +29652,7 @@ __export(migrate_exports, {
28509
29652
  tablesResolver: () => tablesResolver,
28510
29653
  writeResult: () => writeResult
28511
29654
  });
28512
- var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareSQLitePush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
29655
+ var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
28513
29656
  var init_migrate = __esm({
28514
29657
  "src/cli/commands/migrate.ts"() {
28515
29658
  "use strict";
@@ -28761,6 +29904,7 @@ var init_migrate = __esm({
28761
29904
  prepareAndMigrateSqlite = async (config) => {
28762
29905
  const outFolder = config.out;
28763
29906
  const schemaPath = config.schema;
29907
+ const driver2 = config.driver;
28764
29908
  try {
28765
29909
  assertV1OutFolder(outFolder);
28766
29910
  const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
@@ -28786,14 +29930,27 @@ var init_migrate = __esm({
28786
29930
  }
28787
29931
  const squashedPrev = squashSqliteScheme(validatedPrev);
28788
29932
  const squashedCur = squashSqliteScheme(validatedCur);
28789
- const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
28790
- squashedPrev,
28791
- squashedCur,
28792
- tablesResolver,
28793
- columnsResolver,
28794
- validatedPrev,
28795
- validatedCur
28796
- );
29933
+ let sqlStatements;
29934
+ let _meta;
29935
+ if (driver2 === "turso") {
29936
+ ({ sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
29937
+ squashedPrev,
29938
+ squashedCur,
29939
+ tablesResolver,
29940
+ columnsResolver,
29941
+ validatedPrev,
29942
+ validatedCur
29943
+ ));
29944
+ } else {
29945
+ ({ sqlStatements, _meta } = await applySqliteSnapshotsDiff(
29946
+ squashedPrev,
29947
+ squashedCur,
29948
+ tablesResolver,
29949
+ columnsResolver,
29950
+ validatedPrev,
29951
+ validatedCur
29952
+ ));
29953
+ }
28797
29954
  writeResult({
28798
29955
  cur,
28799
29956
  sqlStatements,
@@ -28809,13 +29966,51 @@ var init_migrate = __esm({
28809
29966
  console.error(e2);
28810
29967
  }
28811
29968
  };
28812
- prepareSQLitePush = async (schemaPath, snapshot) => {
29969
+ prepareSQLitePush = async (schemaPath, snapshot, driver2) => {
29970
+ const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath);
29971
+ const validatedPrev = sqliteSchema.parse(prev);
29972
+ const validatedCur = sqliteSchema.parse(cur);
29973
+ const squashedPrev = squashSqliteScheme(validatedPrev, "push");
29974
+ const squashedCur = squashSqliteScheme(validatedCur, "push");
29975
+ let sqlStatements;
29976
+ let statements;
29977
+ let _meta;
29978
+ if (driver2 === "turso") {
29979
+ ({ sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
29980
+ squashedPrev,
29981
+ squashedCur,
29982
+ tablesResolver,
29983
+ columnsResolver,
29984
+ validatedPrev,
29985
+ validatedCur,
29986
+ "push"
29987
+ ));
29988
+ } else {
29989
+ ({ sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
29990
+ squashedPrev,
29991
+ squashedCur,
29992
+ tablesResolver,
29993
+ columnsResolver,
29994
+ validatedPrev,
29995
+ validatedCur,
29996
+ "push"
29997
+ ));
29998
+ }
29999
+ return {
30000
+ sqlStatements,
30001
+ statements,
30002
+ squashedPrev,
30003
+ squashedCur,
30004
+ meta: _meta
30005
+ };
30006
+ };
30007
+ prepareLibSQLPush = async (schemaPath, snapshot) => {
28813
30008
  const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath);
28814
30009
  const validatedPrev = sqliteSchema.parse(prev);
28815
30010
  const validatedCur = sqliteSchema.parse(cur);
28816
30011
  const squashedPrev = squashSqliteScheme(validatedPrev, "push");
28817
30012
  const squashedCur = squashSqliteScheme(validatedCur, "push");
28818
- const { sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
30013
+ const { sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
28819
30014
  squashedPrev,
28820
30015
  squashedCur,
28821
30016
  tablesResolver,
@@ -72173,8 +73368,259 @@ var init_selector_ui = __esm({
72173
73368
  }
72174
73369
  });
72175
73370
 
73371
+ // src/cli/commands/libSqlPushUtils.ts
73372
+ var getOldTableName3, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
73373
+ var init_libSqlPushUtils = __esm({
73374
+ "src/cli/commands/libSqlPushUtils.ts"() {
73375
+ "use strict";
73376
+ init_source();
73377
+ init_utils();
73378
+ init_sqliteSchema();
73379
+ init_sqlgenerator();
73380
+ getOldTableName3 = (tableName, meta) => {
73381
+ for (const key of Object.keys(meta.tables)) {
73382
+ const value = meta.tables[key];
73383
+ if (`"${tableName}"` === value) {
73384
+ return key.substring(1, key.length - 1);
73385
+ }
73386
+ }
73387
+ return tableName;
73388
+ };
73389
+ _moveDataStatements2 = (tableName, json, dataLoss = false) => {
73390
+ const statements = [];
73391
+ statements.push(
73392
+ new SqliteRenameTableConvertor().convert({
73393
+ type: "rename_table",
73394
+ tableNameFrom: tableName,
73395
+ tableNameTo: `__old_push_${tableName}`,
73396
+ fromSchema: "",
73397
+ toSchema: ""
73398
+ })
73399
+ );
73400
+ const tableColumns = Object.values(json.tables[tableName].columns);
73401
+ const referenceData = Object.values(json.tables[tableName].foreignKeys);
73402
+ const compositePKs = Object.values(
73403
+ json.tables[tableName].compositePrimaryKeys
73404
+ ).map((it) => SQLiteSquasher.unsquashPK(it));
73405
+ statements.push(
73406
+ new SQLiteCreateTableConvertor().convert({
73407
+ type: "sqlite_create_table",
73408
+ tableName,
73409
+ columns: tableColumns,
73410
+ referenceData: referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it)),
73411
+ compositePKs
73412
+ })
73413
+ );
73414
+ if (!dataLoss) {
73415
+ const columns = Object.keys(json.tables[tableName].columns).map(
73416
+ (c) => `"${c}"`
73417
+ );
73418
+ statements.push(
73419
+ `INSERT INTO \`${tableName}\`(${columns.join(
73420
+ ", "
73421
+ )}) SELECT (${columns.join(", ")}) FROM \`__old_push_${tableName}\`;`
73422
+ );
73423
+ }
73424
+ statements.push(
73425
+ new SQLiteDropTableConvertor().convert({
73426
+ type: "drop_table",
73427
+ tableName: `__old_push_${tableName}`,
73428
+ schema: ""
73429
+ })
73430
+ );
73431
+ for (const idx of Object.values(json.tables[tableName].indexes)) {
73432
+ statements.push(
73433
+ new CreateSqliteIndexConvertor().convert({
73434
+ type: "create_index",
73435
+ tableName,
73436
+ schema: "",
73437
+ data: idx
73438
+ })
73439
+ );
73440
+ }
73441
+ return statements;
73442
+ };
73443
+ libSqlLogSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
73444
+ let shouldAskForApprove = false;
73445
+ const statementsToExecute = [];
73446
+ const infoToPrint = [];
73447
+ const tablesToRemove = [];
73448
+ const columnsToRemove = [];
73449
+ const tablesToTruncate = [];
73450
+ for (const statement of statements) {
73451
+ if (statement.type === "drop_table") {
73452
+ const res = await connection.query(
73453
+ `select count(*) as count from \`${statement.tableName}\``
73454
+ );
73455
+ const count = Number(res[0].count);
73456
+ if (count > 0) {
73457
+ infoToPrint.push(
73458
+ `\xB7 You're about to delete ${source_default.underline(
73459
+ statement.tableName
73460
+ )} table with ${count} items`
73461
+ );
73462
+ tablesToRemove.push(statement.tableName);
73463
+ shouldAskForApprove = true;
73464
+ }
73465
+ const fromJsonStatement = fromJson([statement], "sqlite", "push", "turso", json2);
73466
+ statementsToExecute.push(
73467
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
73468
+ );
73469
+ } else if (statement.type === "alter_table_drop_column") {
73470
+ const tableName = statement.tableName;
73471
+ const res = await connection.query(
73472
+ `select count(*) as count from \`${tableName}\``
73473
+ );
73474
+ const count = Number(res[0].count);
73475
+ if (count > 0) {
73476
+ infoToPrint.push(
73477
+ `\xB7 You're about to delete ${source_default.underline(
73478
+ statement.columnName
73479
+ )} column in ${tableName} table with ${count} items`
73480
+ );
73481
+ columnsToRemove.push(`${tableName}_${statement.columnName}`);
73482
+ shouldAskForApprove = true;
73483
+ }
73484
+ const fromJsonStatement = fromJson([statement], "sqlite", "push", "turso", json2);
73485
+ statementsToExecute.push(
73486
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
73487
+ );
73488
+ } else if (statement.type === "sqlite_alter_table_add_column" && statement.column.notNull && !statement.column.default) {
73489
+ const newTableName = statement.tableName;
73490
+ const res = await connection.query(
73491
+ `select count(*) as count from \`${newTableName}\``
73492
+ );
73493
+ const count = Number(res[0].count);
73494
+ if (count > 0) {
73495
+ infoToPrint.push(
73496
+ `\xB7 You're about to add not-null ${source_default.underline(
73497
+ statement.column.name
73498
+ )} column without default value, which contains ${count} items`
73499
+ );
73500
+ tablesToTruncate.push(newTableName);
73501
+ statementsToExecute.push(`delete from ${newTableName};`);
73502
+ shouldAskForApprove = true;
73503
+ }
73504
+ const fromJsonStatement = fromJson([statement], "sqlite", "push", "turso", json2);
73505
+ statementsToExecute.push(
73506
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
73507
+ );
73508
+ } else if (statement.type === "alter_table_alter_column_set_notnull") {
73509
+ const tableName = statement.tableName;
73510
+ if (statement.type === "alter_table_alter_column_set_notnull" && typeof statement.columnDefault === "undefined") {
73511
+ const res = await connection.query(
73512
+ `select count(*) as count from \`${tableName}\``
73513
+ );
73514
+ const count = Number(res[0].count);
73515
+ if (count > 0) {
73516
+ infoToPrint.push(
73517
+ `\xB7 You're about to add not-null constraint to ${source_default.underline(
73518
+ statement.columnName
73519
+ )} column without default value, which contains ${count} items`
73520
+ );
73521
+ tablesToTruncate.push(tableName);
73522
+ statementsToExecute.push(`delete from \`${tableName}\``);
73523
+ shouldAskForApprove = true;
73524
+ }
73525
+ }
73526
+ const modifyStatements = new LibSQLModifyColumn().convert(statement, json2);
73527
+ statementsToExecute.push(
73528
+ ...Array.isArray(modifyStatements) ? modifyStatements : [modifyStatements]
73529
+ );
73530
+ } else if (statement.type === "recreate_table") {
73531
+ const tableName = statement.tableName;
73532
+ const oldTableName = getOldTableName3(tableName, meta);
73533
+ const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
73534
+ const currentColumnNames = Object.keys(json2.tables[tableName].columns);
73535
+ const { removedColumns, addedColumns } = findAddedAndRemoved(
73536
+ prevColumnNames,
73537
+ currentColumnNames
73538
+ );
73539
+ if (removedColumns.length) {
73540
+ for (const removedColumn of removedColumns) {
73541
+ const res = await connection.query(
73542
+ `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
73543
+ );
73544
+ const count = Number(res[0].count);
73545
+ if (count > 0) {
73546
+ infoToPrint.push(
73547
+ `\xB7 You're about to delete ${source_default.underline(
73548
+ removedColumn
73549
+ )} column in ${tableName} table with ${count} items`
73550
+ );
73551
+ columnsToRemove.push(removedColumn);
73552
+ shouldAskForApprove = true;
73553
+ }
73554
+ }
73555
+ }
73556
+ if (addedColumns.length) {
73557
+ for (const addedColumn of addedColumns) {
73558
+ const [res] = await connection.query(
73559
+ `select count(\`${tableName}\`.\`${addedColumn}\`) as count from \`${tableName}\``
73560
+ );
73561
+ const columnConf = json2.tables[tableName].columns[addedColumn];
73562
+ const count = Number(res.count);
73563
+ if (count > 0 && columnConf.notNull && !columnConf.default) {
73564
+ infoToPrint.push(
73565
+ `\xB7 You're about to add not-null ${source_default.underline(
73566
+ addedColumn
73567
+ )} column without default value, which contains ${count} items`
73568
+ );
73569
+ shouldAskForApprove = true;
73570
+ tablesToTruncate.push(tableName);
73571
+ }
73572
+ }
73573
+ }
73574
+ statementsToExecute.push(..._moveDataStatements2(tableName, json2));
73575
+ const tablesReferencingCurrent = [];
73576
+ for (const table4 of Object.values(json2.tables)) {
73577
+ const tablesRefs = Object.values(json2.tables[table4.name].foreignKeys).filter((t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
73578
+ tablesReferencingCurrent.push(...tablesRefs);
73579
+ }
73580
+ const uniqueTableRefs = [...new Set(tablesReferencingCurrent)];
73581
+ for (const table4 of uniqueTableRefs) {
73582
+ statementsToExecute.push(..._moveDataStatements2(table4, json2));
73583
+ }
73584
+ } else if (statement.type === "alter_table_alter_column_set_generated") {
73585
+ const tableName = statement.tableName;
73586
+ const res = await connection.query(
73587
+ `select count("${statement.columnName}") as count from \`${tableName}\``
73588
+ );
73589
+ const count = Number(res[0].count);
73590
+ if (count > 0) {
73591
+ infoToPrint.push(
73592
+ `\xB7 You're about to delete ${source_default.underline(
73593
+ statement.columnName
73594
+ )} column in ${tableName} table with ${count} items`
73595
+ );
73596
+ columnsToRemove.push(`${tableName}_${statement.columnName}`);
73597
+ shouldAskForApprove = true;
73598
+ }
73599
+ const fromJsonStatement = fromJson([statement], "sqlite", "push", "turso", json2);
73600
+ statementsToExecute.push(
73601
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
73602
+ );
73603
+ } else {
73604
+ const fromJsonStatement = fromJson([statement], "sqlite", "push", "turso", json2);
73605
+ statementsToExecute.push(
73606
+ ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
73607
+ );
73608
+ }
73609
+ }
73610
+ return {
73611
+ statementsToExecute: [...new Set(statementsToExecute)],
73612
+ shouldAskForApprove,
73613
+ infoToPrint,
73614
+ columnsToRemove: [...new Set(columnsToRemove)],
73615
+ tablesToTruncate: [...new Set(tablesToTruncate)],
73616
+ tablesToRemove: [...new Set(tablesToRemove)]
73617
+ };
73618
+ };
73619
+ }
73620
+ });
73621
+
72176
73622
  // src/cli/commands/mysqlPushUtils.ts
72177
- var import_hanji6, filterStatements, logSuggestionsAndReturn;
73623
+ var import_hanji6, filterStatements, logSuggestionsAndReturn2;
72178
73624
  var init_mysqlPushUtils = __esm({
72179
73625
  "src/cli/commands/mysqlPushUtils.ts"() {
72180
73626
  "use strict";
@@ -72224,7 +73670,7 @@ var init_mysqlPushUtils = __esm({
72224
73670
  return true;
72225
73671
  });
72226
73672
  };
72227
- logSuggestionsAndReturn = async (db, statements, json2) => {
73673
+ logSuggestionsAndReturn2 = async (db, statements, json2) => {
72228
73674
  let shouldAskForApprove = false;
72229
73675
  const statementsToExecute = [];
72230
73676
  const infoToPrint = [];
@@ -72665,289 +74111,6 @@ var init_pgPushUtils = __esm({
72665
74111
  }
72666
74112
  });
72667
74113
 
72668
- // src/cli/commands/sqlitePushUtils.ts
72669
- var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn2;
72670
- var init_sqlitePushUtils = __esm({
72671
- "src/cli/commands/sqlitePushUtils.ts"() {
72672
- "use strict";
72673
- init_source();
72674
- init_sqliteSchema();
72675
- init_sqlgenerator();
72676
- _moveDataStatements = (tableName, json, dataLoss = false) => {
72677
- const statements = [];
72678
- statements.push(
72679
- new SqliteRenameTableConvertor().convert({
72680
- type: "rename_table",
72681
- tableNameFrom: tableName,
72682
- tableNameTo: `__old_push_${tableName}`,
72683
- fromSchema: "",
72684
- toSchema: ""
72685
- })
72686
- );
72687
- const tableColumns = Object.values(json.tables[tableName].columns);
72688
- const referenceData = Object.values(json.tables[tableName].foreignKeys);
72689
- const compositePKs = Object.values(
72690
- json.tables[tableName].compositePrimaryKeys
72691
- ).map((it) => SQLiteSquasher.unsquashPK(it));
72692
- const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
72693
- statements.push(
72694
- new SQLiteCreateTableConvertor().convert({
72695
- type: "sqlite_create_table",
72696
- tableName,
72697
- columns: tableColumns,
72698
- referenceData: fks,
72699
- compositePKs
72700
- })
72701
- );
72702
- if (!dataLoss) {
72703
- statements.push(
72704
- `INSERT INTO "${tableName}" SELECT * FROM "__old_push_${tableName}";`
72705
- );
72706
- }
72707
- statements.push(
72708
- new SQLiteDropTableConvertor().convert({
72709
- type: "drop_table",
72710
- tableName: `__old_push_${tableName}`,
72711
- schema: ""
72712
- })
72713
- );
72714
- for (const idx of Object.values(json.tables[tableName].indexes)) {
72715
- statements.push(
72716
- new CreateSqliteIndexConvertor().convert({
72717
- type: "create_index",
72718
- tableName,
72719
- schema: "",
72720
- data: idx
72721
- })
72722
- );
72723
- }
72724
- return statements;
72725
- };
72726
- getOldTableName = (tableName, meta) => {
72727
- for (const key of Object.keys(meta.tables)) {
72728
- const value = meta.tables[key];
72729
- if (`"${tableName}"` === value) {
72730
- return key.substring(1, key.length - 1);
72731
- }
72732
- }
72733
- return tableName;
72734
- };
72735
- getNewTableName = (tableName, meta) => {
72736
- if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
72737
- return meta.tables[`"${tableName}"`].substring(
72738
- 1,
72739
- meta.tables[`"${tableName}"`].length - 1
72740
- );
72741
- }
72742
- return tableName;
72743
- };
72744
- logSuggestionsAndReturn2 = async (connection, statements, json1, json2, meta) => {
72745
- let shouldAskForApprove = false;
72746
- const statementsToExecute = [];
72747
- const infoToPrint = [];
72748
- const tablesToRemove = [];
72749
- const columnsToRemove = [];
72750
- const schemasToRemove = [];
72751
- const tablesToTruncate = [];
72752
- const tablesContext = {};
72753
- for (const statement of statements) {
72754
- if (statement.type === "drop_table") {
72755
- const res = await connection.query(
72756
- `select count(*) as count from \`${statement.tableName}\``
72757
- );
72758
- const count = Number(res[0].count);
72759
- if (count > 0) {
72760
- infoToPrint.push(
72761
- `\xB7 You're about to delete ${source_default.underline(
72762
- statement.tableName
72763
- )} table with ${count} items`
72764
- );
72765
- tablesToRemove.push(statement.tableName);
72766
- shouldAskForApprove = true;
72767
- }
72768
- const stmnt = fromJson([statement], "sqlite")[0];
72769
- statementsToExecute.push(stmnt);
72770
- } else if (statement.type === "alter_table_drop_column") {
72771
- const newTableName = getOldTableName(statement.tableName, meta);
72772
- const columnIsPartOfPk = Object.values(
72773
- json1.tables[newTableName].compositePrimaryKeys
72774
- ).find((c) => SQLiteSquasher.unsquashPK(c).includes(statement.columnName));
72775
- const columnIsPartOfIndex = Object.values(
72776
- json1.tables[newTableName].indexes
72777
- ).find((c) => SQLiteSquasher.unsquashIdx(c).columns.includes(statement.columnName));
72778
- const columnIsPk = json1.tables[newTableName].columns[statement.columnName].primaryKey;
72779
- const columnIsPartOfFk = Object.values(
72780
- json1.tables[newTableName].foreignKeys
72781
- ).find(
72782
- (t2) => SQLiteSquasher.unsquashPushFK(t2).columnsFrom.includes(
72783
- statement.columnName
72784
- )
72785
- );
72786
- const res = await connection.query(
72787
- `select count(*) as count from \`${newTableName}\``
72788
- );
72789
- const count = Number(res[0].count);
72790
- if (count > 0) {
72791
- infoToPrint.push(
72792
- `\xB7 You're about to delete ${source_default.underline(
72793
- statement.columnName
72794
- )} column in ${newTableName} table with ${count} items`
72795
- );
72796
- columnsToRemove.push(`${newTableName}_${statement.columnName}`);
72797
- shouldAskForApprove = true;
72798
- }
72799
- if (columnIsPk || columnIsPartOfPk || columnIsPartOfIndex || columnIsPartOfFk) {
72800
- tablesContext[newTableName] = [
72801
- ..._moveDataStatements(statement.tableName, json2, true)
72802
- ];
72803
- const tablesReferncingCurrent = [];
72804
- for (const table4 of Object.values(json1.tables)) {
72805
- const tablesRefs = Object.values(json1.tables[table4.name].foreignKeys).filter(
72806
- (t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === newTableName
72807
- ).map((t2) => SQLiteSquasher.unsquashPushFK(t2).tableFrom);
72808
- tablesReferncingCurrent.push(...tablesRefs);
72809
- }
72810
- const uniqueTableRefs = [...new Set(tablesReferncingCurrent)];
72811
- for (const table4 of uniqueTableRefs) {
72812
- if (typeof tablesContext[table4] === "undefined") {
72813
- tablesContext[table4] = [..._moveDataStatements(table4, json2)];
72814
- }
72815
- }
72816
- } else {
72817
- if (typeof tablesContext[newTableName] === "undefined") {
72818
- const stmnt = fromJson([statement], "sqlite")[0];
72819
- statementsToExecute.push(stmnt);
72820
- }
72821
- }
72822
- } else if (statement.type === "sqlite_alter_table_add_column") {
72823
- const newTableName = getOldTableName(statement.tableName, meta);
72824
- if (statement.column.notNull && !statement.column.default) {
72825
- const res = await connection.query(
72826
- `select count(*) as count from \`${newTableName}\``
72827
- );
72828
- const count = Number(res[0].count);
72829
- if (count > 0) {
72830
- infoToPrint.push(
72831
- `\xB7 You're about to add not-null ${source_default.underline(
72832
- statement.column.name
72833
- )} column without default value, which contains ${count} items`
72834
- );
72835
- tablesToTruncate.push(newTableName);
72836
- statementsToExecute.push(`delete from ${newTableName};`);
72837
- shouldAskForApprove = true;
72838
- }
72839
- }
72840
- if (statement.column.primaryKey) {
72841
- tablesContext[newTableName] = [
72842
- ..._moveDataStatements(statement.tableName, json2, true)
72843
- ];
72844
- const tablesReferncingCurrent = [];
72845
- for (const table4 of Object.values(json1.tables)) {
72846
- const tablesRefs = Object.values(json1.tables[table4.name].foreignKeys).filter(
72847
- (t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === newTableName
72848
- ).map((t2) => SQLiteSquasher.unsquashPushFK(t2).tableFrom);
72849
- tablesReferncingCurrent.push(...tablesRefs);
72850
- }
72851
- const uniqueTableRefs = [...new Set(tablesReferncingCurrent)];
72852
- for (const table4 of uniqueTableRefs) {
72853
- if (typeof tablesContext[table4] === "undefined") {
72854
- tablesContext[table4] = [..._moveDataStatements(table4, json2)];
72855
- }
72856
- }
72857
- } else {
72858
- if (typeof tablesContext[newTableName] === "undefined") {
72859
- const stmnt = fromJson([statement], "sqlite")[0];
72860
- statementsToExecute.push(stmnt);
72861
- }
72862
- }
72863
- } else if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk") {
72864
- if (!(statement.type === "alter_table_alter_column_set_notnull" && statement.columnPk)) {
72865
- const newTableName = getOldTableName(statement.tableName, meta);
72866
- if (statement.type === "alter_table_alter_column_set_notnull" && typeof statement.columnDefault === "undefined") {
72867
- const res = await connection.query(
72868
- `select count(*) as count from \`${newTableName}\``
72869
- );
72870
- const count = Number(res[0].count);
72871
- if (count > 0) {
72872
- infoToPrint.push(
72873
- `\xB7 You're about to add not-null constraint to ${source_default.underline(
72874
- statement.columnName
72875
- )} column without default value, which contains ${count} items`
72876
- );
72877
- tablesToTruncate.push(newTableName);
72878
- shouldAskForApprove = true;
72879
- }
72880
- tablesContext[newTableName] = _moveDataStatements(
72881
- statement.tableName,
72882
- json1,
72883
- true
72884
- );
72885
- } else {
72886
- if (typeof tablesContext[newTableName] === "undefined") {
72887
- tablesContext[newTableName] = _moveDataStatements(
72888
- statement.tableName,
72889
- json1
72890
- );
72891
- }
72892
- }
72893
- const tablesReferncingCurrent = [];
72894
- for (const table4 of Object.values(json1.tables)) {
72895
- const tablesRefs = Object.values(json1.tables[table4.name].foreignKeys).filter(
72896
- (t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === newTableName
72897
- ).map((t2) => {
72898
- return getNewTableName(
72899
- SQLiteSquasher.unsquashPushFK(t2).tableFrom,
72900
- meta
72901
- );
72902
- });
72903
- tablesReferncingCurrent.push(...tablesRefs);
72904
- }
72905
- const uniqueTableRefs = [...new Set(tablesReferncingCurrent)];
72906
- for (const table4 of uniqueTableRefs) {
72907
- if (typeof tablesContext[table4] === "undefined") {
72908
- tablesContext[table4] = [..._moveDataStatements(table4, json1)];
72909
- }
72910
- }
72911
- }
72912
- } else if (statement.type === "create_reference" || statement.type === "delete_reference" || statement.type === "alter_reference") {
72913
- const fk4 = SQLiteSquasher.unsquashPushFK(statement.data);
72914
- if (typeof tablesContext[statement.tableName] === "undefined") {
72915
- tablesContext[statement.tableName] = _moveDataStatements(
72916
- statement.tableName,
72917
- json2
72918
- );
72919
- }
72920
- } else if (statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint") {
72921
- const newTableName = getOldTableName(statement.tableName, meta);
72922
- if (typeof tablesContext[newTableName] === "undefined") {
72923
- tablesContext[newTableName] = _moveDataStatements(
72924
- statement.tableName,
72925
- json2
72926
- );
72927
- }
72928
- } else {
72929
- const stmnt = fromJson([statement], "sqlite");
72930
- if (typeof stmnt !== "undefined") {
72931
- statementsToExecute.push(...stmnt);
72932
- }
72933
- }
72934
- }
72935
- for (const context of Object.values(tablesContext)) {
72936
- statementsToExecute.push(...context);
72937
- }
72938
- return {
72939
- statementsToExecute,
72940
- shouldAskForApprove,
72941
- infoToPrint,
72942
- columnsToRemove: [...new Set(columnsToRemove)],
72943
- schemasToRemove: [...new Set(schemasToRemove)],
72944
- tablesToTruncate: [...new Set(tablesToTruncate)],
72945
- tablesToRemove: [...new Set(tablesToRemove)]
72946
- };
72947
- };
72948
- }
72949
- });
72950
-
72951
74114
  // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
72952
74115
  var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
72953
74116
  var init_brace_expressions = __esm({
@@ -74510,11 +75673,12 @@ var init_sqliteIntrospect = __esm({
74510
75673
  // src/cli/commands/push.ts
74511
75674
  var push_exports = {};
74512
75675
  __export(push_exports, {
75676
+ libSQLPush: () => libSQLPush,
74513
75677
  mysqlPush: () => mysqlPush,
74514
75678
  pgPush: () => pgPush,
74515
75679
  sqlitePush: () => sqlitePush
74516
75680
  });
74517
- var import_hanji11, mysqlPush, pgPush, sqlitePush;
75681
+ var import_hanji11, mysqlPush, pgPush, sqlitePush, libSQLPush;
74518
75682
  var init_push = __esm({
74519
75683
  "src/cli/commands/push.ts"() {
74520
75684
  "use strict";
@@ -74523,6 +75687,7 @@ var init_push = __esm({
74523
75687
  init_sqlgenerator();
74524
75688
  init_selector_ui();
74525
75689
  init_outputs();
75690
+ init_libSqlPushUtils();
74526
75691
  init_mysqlPushUtils();
74527
75692
  init_pgPushUtils();
74528
75693
  init_sqlitePushUtils();
@@ -74550,7 +75715,7 @@ var init_push = __esm({
74550
75715
  tablesToTruncate,
74551
75716
  infoToPrint,
74552
75717
  schemasToRemove
74553
- } = await logSuggestionsAndReturn(
75718
+ } = await logSuggestionsAndReturn2(
74554
75719
  db,
74555
75720
  filteredStatements,
74556
75721
  statements.validatedCur
@@ -74569,7 +75734,6 @@ var init_push = __esm({
74569
75734
  }
74570
75735
  });
74571
75736
  if (verbose) {
74572
- console.log();
74573
75737
  console.log(
74574
75738
  withStyle.warning("You are about to execute current statements:")
74575
75739
  );
@@ -74720,11 +75884,100 @@ var init_push = __esm({
74720
75884
  tablesToTruncate,
74721
75885
  infoToPrint,
74722
75886
  schemasToRemove
74723
- } = await logSuggestionsAndReturn2(
75887
+ } = await logSuggestionsAndReturn(
74724
75888
  db,
74725
75889
  statements.statements,
75890
+ statements.squashedPrev,
74726
75891
  statements.squashedCur,
75892
+ statements.meta
75893
+ );
75894
+ if (verbose && statementsToExecute.length > 0) {
75895
+ console.log();
75896
+ console.log(
75897
+ withStyle.warning("You are about to execute current statements:")
75898
+ );
75899
+ console.log();
75900
+ console.log(statementsToExecute.map((s2) => source_default.blue(s2)).join("\n"));
75901
+ console.log();
75902
+ }
75903
+ if (!force && strict) {
75904
+ if (!shouldAskForApprove) {
75905
+ const { status, data } = await (0, import_hanji11.render)(
75906
+ new Select(["No, abort", `Yes, I want to execute all statements`])
75907
+ );
75908
+ if ((data == null ? void 0 : data.index) === 0) {
75909
+ (0, import_hanji11.render)(`[${source_default.red("x")}] All changes were aborted`);
75910
+ process.exit(0);
75911
+ }
75912
+ }
75913
+ }
75914
+ if (!force && shouldAskForApprove) {
75915
+ console.log(withStyle.warning("Found data-loss statements:"));
75916
+ console.log(infoToPrint.join("\n"));
75917
+ console.log();
75918
+ console.log(
75919
+ source_default.red.bold(
75920
+ "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
75921
+ )
75922
+ );
75923
+ console.log(source_default.white("Do you still want to push changes?"));
75924
+ const { status, data } = await (0, import_hanji11.render)(
75925
+ new Select([
75926
+ "No, abort",
75927
+ `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
75928
+ ])
75929
+ );
75930
+ if ((data == null ? void 0 : data.index) === 0) {
75931
+ (0, import_hanji11.render)(`[${source_default.red("x")}] All changes were aborted`);
75932
+ process.exit(0);
75933
+ }
75934
+ }
75935
+ if (statementsToExecute.length === 0) {
75936
+ (0, import_hanji11.render)(`
75937
+ [${source_default.blue("i")}] No changes detected`);
75938
+ } else {
75939
+ if (!("driver" in credentials2)) {
75940
+ await db.query("begin");
75941
+ try {
75942
+ for (const dStmnt of statementsToExecute) {
75943
+ await db.query(dStmnt);
75944
+ }
75945
+ await db.query("commit");
75946
+ } catch (e2) {
75947
+ console.error(e2);
75948
+ await db.query("rollback");
75949
+ process.exit(1);
75950
+ }
75951
+ } else if (credentials2.driver === "turso") {
75952
+ await db.batch(statementsToExecute.map((it) => ({ query: it })));
75953
+ }
75954
+ (0, import_hanji11.render)(`[${source_default.green("\u2713")}] Changes applied`);
75955
+ }
75956
+ }
75957
+ };
75958
+ libSQLPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force) => {
75959
+ const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
75960
+ const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
75961
+ const db = await connectToSQLite2(credentials2);
75962
+ const { schema: schema5 } = await sqlitePushIntrospect2(db, tablesFilter);
75963
+ const { prepareLibSQLPush: prepareLibSQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
75964
+ const statements = await prepareLibSQLPush2(schemaPath, schema5);
75965
+ if (statements.sqlStatements.length === 0) {
75966
+ (0, import_hanji11.render)(`
75967
+ [${source_default.blue("i")}] No changes detected`);
75968
+ } else {
75969
+ const {
75970
+ shouldAskForApprove,
75971
+ statementsToExecute,
75972
+ columnsToRemove,
75973
+ tablesToRemove,
75974
+ tablesToTruncate,
75975
+ infoToPrint
75976
+ } = await libSqlLogSuggestionsAndReturn(
75977
+ db,
75978
+ statements.statements,
74727
75979
  statements.squashedPrev,
75980
+ statements.squashedCur,
74728
75981
  statements.meta
74729
75982
  );
74730
75983
  if (verbose && statementsToExecute.length > 0) {
@@ -75265,6 +76518,7 @@ var init_introspect_mysql = __esm({
75265
76518
  patched = patched.startsWith("datetime(") ? "datetime" : patched;
75266
76519
  patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
75267
76520
  patched = patched.startsWith("int(") ? "int" : patched;
76521
+ patched = patched.startsWith("double(") ? "double" : patched;
75268
76522
  return patched;
75269
76523
  }).filter((type) => {
75270
76524
  return mysqlImportsList.has(type);
@@ -83076,7 +84330,7 @@ var push = command({
83076
84330
  schemasFilter,
83077
84331
  force
83078
84332
  );
83079
- } else if (dialect7 === "sqlite") {
84333
+ } else if (dialect7 === "sqlite" && !("driver" in credentials2)) {
83080
84334
  const { sqlitePush: sqlitePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
83081
84335
  await sqlitePush2(
83082
84336
  schemaPath,
@@ -83086,6 +84340,16 @@ var push = command({
83086
84340
  tablesFilter,
83087
84341
  force
83088
84342
  );
84343
+ } else if (dialect7 === "sqlite" && ("driver" in credentials2 && credentials2.driver === "turso")) {
84344
+ const { libSQLPush: libSQLPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
84345
+ await libSQLPush2(
84346
+ schemaPath,
84347
+ verbose,
84348
+ strict,
84349
+ credentials2,
84350
+ tablesFilter,
84351
+ force
84352
+ );
83089
84353
  } else {
83090
84354
  assertUnreachable(dialect7);
83091
84355
  }
@@ -83369,7 +84633,7 @@ init_utils2();
83369
84633
  var version2 = async () => {
83370
84634
  const { npmVersion } = await ormCoreVersions();
83371
84635
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
83372
- const envVersion = "0.23.2-eddab2e";
84636
+ const envVersion = "0.24.0-38d6dab";
83373
84637
  const kitVersion = envVersion ? `v${envVersion}` : "--";
83374
84638
  const versions = `drizzle-kit: ${kitVersion}
83375
84639
  ${ormVersion}`;