drizzle-kit 0.24.0-38d6dab → 0.24.0-5df8253

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 +10 -0
  2. package/api.d.ts +10 -0
  3. package/api.js +501 -1280
  4. package/api.mjs +501 -1280
  5. package/bin.cjs +756 -1832
  6. package/package.json +2 -1
  7. package/utils.js +2 -10
  8. package/utils.mjs +2 -9
package/bin.cjs CHANGED
@@ -5687,11 +5687,30 @@ var init_mysqlSchema = __esm({
5687
5687
  }
5688
5688
  });
5689
5689
 
5690
+ // src/extensions/vector.ts
5691
+ var vectorOps;
5692
+ var init_vector = __esm({
5693
+ "src/extensions/vector.ts"() {
5694
+ "use strict";
5695
+ vectorOps = [
5696
+ "vector_l2_ops",
5697
+ "vector_ip_ops",
5698
+ "vector_cosine_ops",
5699
+ "vector_l1_ops",
5700
+ "bit_hamming_ops",
5701
+ "bit_jaccard_ops",
5702
+ "halfvec_l2_ops",
5703
+ "sparsevec_l2_ops"
5704
+ ];
5705
+ }
5706
+ });
5707
+
5690
5708
  // src/serializer/pgSchema.ts
5691
5709
  var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5692
5710
  var init_pgSchema = __esm({
5693
5711
  "src/serializer/pgSchema.ts"() {
5694
5712
  "use strict";
5713
+ init_vector();
5695
5714
  init_global();
5696
5715
  init_lib();
5697
5716
  indexV2 = objectType({
@@ -5938,7 +5957,8 @@ var init_pgSchema = __esm({
5938
5957
  objectType({
5939
5958
  isArray: booleanType().optional(),
5940
5959
  dimensions: numberType().optional(),
5941
- rawType: stringType().optional()
5960
+ rawType: stringType().optional(),
5961
+ isDefaultAnExpression: booleanType().optional()
5942
5962
  }).optional()
5943
5963
  )
5944
5964
  }).optional()
@@ -6076,7 +6096,7 @@ var init_pgSchema = __esm({
6076
6096
  squashIdx: (idx) => {
6077
6097
  index2.parse(idx);
6078
6098
  return `${idx.name};${idx.columns.map(
6079
- (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass}`
6099
+ (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass && vectorOps.includes(c.opclass) ? c.opclass : ""}`
6080
6100
  ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
6081
6101
  },
6082
6102
  unsquashIdx: (input) => {
@@ -6564,13 +6584,6 @@ var init_sqliteSchema = __esm({
6564
6584
  function isPgArrayType(sqlType) {
6565
6585
  return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
6566
6586
  }
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
- }
6574
6587
  var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl;
6575
6588
  var init_utils = __esm({
6576
6589
  "src/utils.ts"() {
@@ -11368,8 +11381,7 @@ var init_cli = __esm({
11368
11381
  schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
11369
11382
  extensionsFilters: literalType("postgis").array().optional(),
11370
11383
  verbose: booleanType().optional(),
11371
- strict: booleanType().optional(),
11372
- driver: driver.optional()
11384
+ strict: booleanType().optional()
11373
11385
  }).passthrough();
11374
11386
  pullParams = objectType({
11375
11387
  config: stringType().optional(),
@@ -11380,7 +11392,7 @@ var init_cli = __esm({
11380
11392
  extensionsFilters: literalType("postgis").array().optional(),
11381
11393
  introspectCasing: casing,
11382
11394
  breakpoints: booleanType().optional().default(true),
11383
- database: objectType({
11395
+ migrations: objectType({
11384
11396
  prefix: prefix.optional().default("index")
11385
11397
  }).optional()
11386
11398
  }).passthrough();
@@ -17373,8 +17385,7 @@ var init_utils4 = __esm({
17373
17385
  breakpoints: breakpoints || true,
17374
17386
  schema: schema5,
17375
17387
  out: out || "drizzle",
17376
- bundle: driver2 === "expo",
17377
- driver: driver2
17388
+ bundle: driver2 === "expo"
17378
17389
  };
17379
17390
  };
17380
17391
  flattenDatabaseCredentials = (config) => {
@@ -17402,7 +17413,6 @@ var init_utils4 = __esm({
17402
17413
  const raw2 = flattenDatabaseCredentials(
17403
17414
  from === "config" ? await drizzleConfigFromFile(options.config) : options
17404
17415
  );
17405
- raw2.driver ||= options.driver;
17406
17416
  raw2.verbose ||= options.verbose;
17407
17417
  raw2.strict ||= options.strict;
17408
17418
  const parsed = pushParams.safeParse(raw2);
@@ -17477,8 +17487,7 @@ var init_utils4 = __esm({
17477
17487
  force: options.force ?? false,
17478
17488
  credentials: parsed2.data,
17479
17489
  tablesFilter,
17480
- schemasFilter,
17481
- driver: config.driver
17490
+ schemasFilter
17482
17491
  };
17483
17492
  }
17484
17493
  assertUnreachable(config.dialect);
@@ -17521,7 +17530,7 @@ var init_utils4 = __esm({
17521
17530
  credentials: parsed2.data,
17522
17531
  tablesFilter,
17523
17532
  schemasFilter,
17524
- prefix: ((_a = config.database) == null ? void 0 : _a.prefix) || "index"
17533
+ prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index"
17525
17534
  };
17526
17535
  }
17527
17536
  if (dialect7 === "mysql") {
@@ -17538,7 +17547,7 @@ var init_utils4 = __esm({
17538
17547
  credentials: parsed2.data,
17539
17548
  tablesFilter,
17540
17549
  schemasFilter,
17541
- prefix: ((_b = config.database) == null ? void 0 : _b.prefix) || "index"
17550
+ prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index"
17542
17551
  };
17543
17552
  }
17544
17553
  if (dialect7 === "sqlite") {
@@ -17555,7 +17564,7 @@ var init_utils4 = __esm({
17555
17564
  credentials: parsed2.data,
17556
17565
  tablesFilter,
17557
17566
  schemasFilter,
17558
- prefix: ((_c = config.database) == null ? void 0 : _c.prefix) || "index"
17567
+ prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index"
17559
17568
  };
17560
17569
  }
17561
17570
  assertUnreachable(dialect7);
@@ -18383,24 +18392,6 @@ var init_pgImports = __esm({
18383
18392
  }
18384
18393
  });
18385
18394
 
18386
- // src/extensions/vector.ts
18387
- var vectorOps;
18388
- var init_vector = __esm({
18389
- "src/extensions/vector.ts"() {
18390
- "use strict";
18391
- vectorOps = [
18392
- "vector_l2_ops",
18393
- "vector_ip_ops",
18394
- "vector_cosine_ops",
18395
- "vector_l1_ops",
18396
- "bit_hamming_ops",
18397
- "bit_jaccard_ops",
18398
- "halfvec_l2_ops",
18399
- "sparsevec_l2_ops"
18400
- ];
18401
- }
18402
- });
18403
-
18404
18395
  // src/serializer/pgSerializer.ts
18405
18396
  var pgSerializer_exports = {};
18406
18397
  __export(pgSerializer_exports, {
@@ -18444,7 +18435,7 @@ function buildArrayString(array, sqlType) {
18444
18435
  }).join(",");
18445
18436
  return `{${values}}`;
18446
18437
  }
18447
- var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, columnToDefault, defaultForColumn;
18438
+ var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn;
18448
18439
  var init_pgSerializer = __esm({
18449
18440
  "src/serializer/pgSerializer.ts"() {
18450
18441
  "use strict";
@@ -18567,7 +18558,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18567
18558
  columnToSet.default = `'${buildArrayString(
18568
18559
  column7.default,
18569
18560
  sqlTypeLowered
18570
- )}'::${sqlTypeLowered}`;
18561
+ )}'`;
18571
18562
  } else {
18572
18563
  columnToSet.default = column7.default;
18573
18564
  }
@@ -18919,7 +18910,7 @@ ${withStyle.errorWarning(
18919
18910
  WHEN 'int2'::regtype THEN 'smallserial'
18920
18911
  END
18921
18912
  ELSE format_type(a.atttypid, a.atttypmod)
18922
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name,
18913
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
18923
18914
  pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
18924
18915
  INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
18925
18916
  INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
@@ -18930,6 +18921,7 @@ ${withStyle.errorWarning(
18930
18921
  INFORMATION_SCHEMA.COLUMNS.identity_cycle
18931
18922
  FROM pg_attribute a
18932
18923
  JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
18924
+ JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
18933
18925
  WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
18934
18926
  AND a.attnum > 0
18935
18927
  AND NOT a.attisdropped
@@ -18949,30 +18941,42 @@ ${withStyle.errorWarning(
18949
18941
  }
18950
18942
  const tableForeignKeys = await db.query(
18951
18943
  `SELECT
18952
- tc.table_schema,
18953
- tc.constraint_name,
18954
- tc.table_name,
18955
- kcu.column_name,
18956
- (
18957
- SELECT ccu.table_schema
18958
- FROM information_schema.constraint_column_usage ccu
18959
- WHERE ccu.constraint_name = tc.constraint_name
18960
- LIMIT 1
18961
- ) AS foreign_table_schema,
18962
- ccu.table_name AS foreign_table_name,
18963
- ccu.column_name AS foreign_column_name,
18964
- rc.delete_rule,
18965
- rc.update_rule
18966
- FROM
18967
- information_schema.table_constraints AS tc
18968
- JOIN information_schema.key_column_usage AS kcu
18969
- ON tc.constraint_name = kcu.constraint_name
18970
- AND tc.table_schema = kcu.table_schema
18971
- JOIN information_schema.constraint_column_usage AS ccu
18972
- ON ccu.constraint_name = tc.constraint_name
18973
- JOIN information_schema.referential_constraints AS rc
18974
- ON ccu.constraint_name = rc.constraint_name
18975
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
18944
+ con.contype AS constraint_type,
18945
+ nsp.nspname AS constraint_schema,
18946
+ con.conname AS constraint_name,
18947
+ rel.relname AS table_name,
18948
+ att.attname AS column_name,
18949
+ fnsp.nspname AS foreign_table_schema,
18950
+ frel.relname AS foreign_table_name,
18951
+ fatt.attname AS foreign_column_name,
18952
+ CASE con.confupdtype
18953
+ WHEN 'a' THEN 'NO ACTION'
18954
+ WHEN 'r' THEN 'RESTRICT'
18955
+ WHEN 'n' THEN 'SET NULL'
18956
+ WHEN 'c' THEN 'CASCADE'
18957
+ WHEN 'd' THEN 'SET DEFAULT'
18958
+ END AS update_rule,
18959
+ CASE con.confdeltype
18960
+ WHEN 'a' THEN 'NO ACTION'
18961
+ WHEN 'r' THEN 'RESTRICT'
18962
+ WHEN 'n' THEN 'SET NULL'
18963
+ WHEN 'c' THEN 'CASCADE'
18964
+ WHEN 'd' THEN 'SET DEFAULT'
18965
+ END AS delete_rule
18966
+ FROM
18967
+ pg_catalog.pg_constraint con
18968
+ JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
18969
+ JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
18970
+ LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
18971
+ AND att.attrelid = con.conrelid
18972
+ LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
18973
+ LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
18974
+ LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
18975
+ AND fatt.attrelid = con.confrelid
18976
+ WHERE
18977
+ nsp.nspname = '${tableSchema}'
18978
+ AND rel.relname = '${tableName}'
18979
+ AND con.contype IN ('f');`
18976
18980
  );
18977
18981
  foreignKeysCount += tableForeignKeys.length;
18978
18982
  if (progressCallback) {
@@ -19030,6 +19034,8 @@ ${withStyle.errorWarning(
19030
19034
  const columnDimensions = columnResponse.array_dimensions;
19031
19035
  const enumType2 = columnResponse.enum_name;
19032
19036
  let columnType = columnResponse.data_type;
19037
+ const typeSchema = columnResponse.type_schema;
19038
+ const defaultValueRes = columnResponse.column_default;
19033
19039
  const isGenerated = columnResponse.is_generated === "ALWAYS";
19034
19040
  const generationExpression = columnResponse.generation_expression;
19035
19041
  const isIdentity = columnResponse.is_identity === "YES";
@@ -19060,12 +19066,7 @@ ${withStyle.errorWarning(
19060
19066
  columns: cprimaryKey.map((c) => c.column_name)
19061
19067
  };
19062
19068
  }
19063
- const defaultValue = defaultForColumn(columnResponse);
19064
- const isSerial = columnType === "serial";
19065
19069
  let columnTypeMapped = columnType;
19066
- if (columnTypeMapped.startsWith("numeric(")) {
19067
- columnTypeMapped = columnTypeMapped.replace(",", ", ");
19068
- }
19069
19070
  if (columnAdditionalDT === "ARRAY") {
19070
19071
  if (typeof internals.tables[tableName] === "undefined") {
19071
19072
  internals.tables[tableName] = {
@@ -19093,6 +19094,34 @@ ${withStyle.errorWarning(
19093
19094
  }
19094
19095
  }
19095
19096
  }
19097
+ const defaultValue = defaultForColumn(
19098
+ columnResponse,
19099
+ internals,
19100
+ tableName
19101
+ );
19102
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
19103
+ if (typeof internals.tables[tableName] === "undefined") {
19104
+ internals.tables[tableName] = {
19105
+ columns: {
19106
+ [columnName]: {
19107
+ isDefaultAnExpression: true
19108
+ }
19109
+ }
19110
+ };
19111
+ } else {
19112
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
19113
+ internals.tables[tableName].columns[columnName] = {
19114
+ isDefaultAnExpression: true
19115
+ };
19116
+ } else {
19117
+ internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
19118
+ }
19119
+ }
19120
+ }
19121
+ const isSerial = columnType === "serial";
19122
+ if (columnTypeMapped.startsWith("numeric(")) {
19123
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
19124
+ }
19096
19125
  if (columnAdditionalDT === "ARRAY") {
19097
19126
  for (let i2 = 1; i2 < Number(columnDimensions); i2++) {
19098
19127
  columnTypeMapped += "[]";
@@ -19106,7 +19135,7 @@ ${withStyle.errorWarning(
19106
19135
  // filter vectors, but in future we should filter any extension that was installed by user
19107
19136
  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
19108
19137
  ),
19109
- typeSchema: enumsToReturn[`${tableSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${tableSchema}.${enumType2}`].schema : void 0,
19138
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
19110
19139
  primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
19111
19140
  // default: isSerial ? undefined : defaultValue,
19112
19141
  notNull: columnResponse.is_nullable === "NO",
@@ -19278,59 +19307,72 @@ ${withStyle.errorWarning(
19278
19307
  internal: internals
19279
19308
  };
19280
19309
  };
19281
- columnToDefault = {
19282
- "numeric(": "::numeric",
19283
- // text: "::text",
19284
- // "character varying": "::character varying",
19285
- // "double precision": "::double precision",
19286
- // "time with time zone": "::time with time zone",
19287
- "time without time zone": "::time without time zone",
19288
- // "timestamp with time zone": "::timestamp with time zone",
19289
- "timestamp without time zone": "::timestamp without time zone",
19290
- "timestamp(": "::timestamp without time zone",
19291
- // date: "::date",
19292
- // interval: "::interval",
19293
- // character: "::bpchar",
19294
- // macaddr8: "::macaddr8",
19295
- // macaddr: "::macaddr",
19296
- // inet: "::inet",
19297
- // cidr: "::cidr",
19298
- // jsonb: "::jsonb",
19299
- // json: "::json",
19300
- "character(": "::bpchar"
19301
- };
19302
- defaultForColumn = (column7) => {
19310
+ defaultForColumn = (column7, internals, tableName) => {
19311
+ var _a, _b;
19312
+ const columnName = column7.attname;
19313
+ const isArray3 = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
19303
19314
  if (column7.column_default === null) {
19304
19315
  return void 0;
19305
19316
  }
19306
19317
  if (column7.data_type === "serial" || column7.data_type === "smallserial" || column7.data_type === "bigserial") {
19307
19318
  return void 0;
19308
19319
  }
19309
- const hasDifferentDefaultCast = Object.keys(columnToDefault).find((it) => column7.data_type.startsWith(it));
19320
+ if (column7.column_default.endsWith("[]")) {
19321
+ column7.column_default = column7.column_default.slice(0, -2);
19322
+ }
19323
+ column7.column_default = column7.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
19310
19324
  const columnDefaultAsString = column7.column_default.toString();
19311
- if (columnDefaultAsString.endsWith(
19312
- hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column7.data_type
19313
- )) {
19314
- const nonPrefixPart = column7.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column7.data_type}`).length - 1;
19315
- const rt = column7.column_default.toString().substring(1, nonPrefixPart);
19316
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column7.data_type.startsWith("numeric")) {
19317
- return Number(rt);
19318
- } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19319
- const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
19320
- return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column7.data_type}`}`;
19321
- } else if (column7.data_type === "boolean") {
19322
- return column7.column_default === "true";
19323
- } else {
19324
- return `'${rt}'`;
19325
- }
19326
- } else {
19327
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column7.data_type.startsWith("numeric")) {
19325
+ if (isArray3) {
19326
+ return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
19327
+ if (["integer", "smallint", "bigint", "double precision", "real"].includes(column7.data_type.slice(0, -2))) {
19328
+ return value;
19329
+ } else if (column7.data_type.startsWith("timestamp")) {
19330
+ return `${value}`;
19331
+ } else if (column7.data_type.slice(0, -2) === "interval") {
19332
+ return value.replaceAll('"', `"`);
19333
+ } else if (column7.data_type.slice(0, -2) === "boolean") {
19334
+ return value === "t" ? "true" : "false";
19335
+ } else if (["json", "jsonb"].includes(column7.data_type.slice(0, -2))) {
19336
+ return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
19337
+ } else {
19338
+ return `"${value}"`;
19339
+ }
19340
+ }).join(",")}}'`;
19341
+ }
19342
+ if (["integer", "smallint", "bigint", "double precision", "real"].includes(column7.data_type)) {
19343
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
19328
19344
  return Number(columnDefaultAsString);
19329
- } else if (column7.data_type === "boolean") {
19330
- return column7.column_default === "true";
19331
19345
  } else {
19332
- return `${columnDefaultAsString}`;
19346
+ if (typeof internals.tables[tableName] === "undefined") {
19347
+ internals.tables[tableName] = {
19348
+ columns: {
19349
+ [columnName]: {
19350
+ isDefaultAnExpression: true
19351
+ }
19352
+ }
19353
+ };
19354
+ } else {
19355
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
19356
+ internals.tables[tableName].columns[columnName] = {
19357
+ isDefaultAnExpression: true
19358
+ };
19359
+ } else {
19360
+ internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
19361
+ }
19362
+ }
19363
+ return columnDefaultAsString;
19333
19364
  }
19365
+ } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19366
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
19367
+ return `'${jsonWithoutSpaces}'::${column7.data_type}`;
19368
+ } else if (column7.data_type === "boolean") {
19369
+ return column7.column_default === "true";
19370
+ } else if (columnDefaultAsString === "NULL") {
19371
+ return `NULL`;
19372
+ } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
19373
+ return columnDefaultAsString;
19374
+ } else {
19375
+ return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
19334
19376
  }
19335
19377
  };
19336
19378
  }
@@ -22863,20 +22905,7 @@ var init_jsonDiffer = __esm({
22863
22905
  });
22864
22906
 
22865
22907
  // src/sqlgenerator.ts
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;
22908
+ 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;
22880
22909
  var init_sqlgenerator = __esm({
22881
22910
  "src/sqlgenerator.ts"() {
22882
22911
  "use strict";
@@ -22929,7 +22958,7 @@ var init_sqlgenerator = __esm({
22929
22958
  if (pgNativeTypes.has(it))
22930
22959
  return true;
22931
22960
  const toCheck = it.replace(/ /g, "");
22932
- return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
22961
+ return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("doubleprecision[") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
22933
22962
  };
22934
22963
  Convertor = class {
22935
22964
  };
@@ -23395,7 +23424,7 @@ var init_sqlgenerator = __esm({
23395
23424
  }
23396
23425
  convert(statement) {
23397
23426
  const { tableName, oldColumnName, newColumnName } = statement;
23398
- return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
23427
+ return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
23399
23428
  }
23400
23429
  };
23401
23430
  PgAlterTableDropColumnConvertor = class extends Convertor {
@@ -23497,8 +23526,8 @@ var init_sqlgenerator = __esm({
23497
23526
  }
23498
23527
  };
23499
23528
  SQLiteAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
23500
- can(statement, dialect7, driver2) {
23501
- return statement.type === "alter_table_alter_column_set_type" && dialect7 === "sqlite" && !driver2;
23529
+ can(statement, dialect7) {
23530
+ return statement.type === "alter_table_alter_column_set_type" && dialect7 === "sqlite";
23502
23531
  }
23503
23532
  convert(statement) {
23504
23533
  return `/*
@@ -23809,46 +23838,6 @@ var init_sqlgenerator = __esm({
23809
23838
  return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
23810
23839
  }
23811
23840
  };
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
- };
23852
23841
  MySqlModifyColumn = class extends Convertor {
23853
23842
  can(statement, dialect7) {
23854
23843
  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";
@@ -24190,8 +24179,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24190
24179
  }
24191
24180
  };
24192
24181
  SqliteAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
24193
- can(statement, dialect7, driver2) {
24194
- return statement.type === "alter_table_alter_column_set_notnull" && dialect7 === "sqlite" && !driver2;
24182
+ can(statement, dialect7) {
24183
+ return statement.type === "alter_table_alter_column_set_notnull" && dialect7 === "sqlite";
24195
24184
  }
24196
24185
  convert(statement) {
24197
24186
  return `/*
@@ -24205,8 +24194,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24205
24194
  }
24206
24195
  };
24207
24196
  SqliteAlterTableAlterColumnSetAutoincrementConvertor = class extends Convertor {
24208
- can(statement, dialect7, driver2) {
24209
- return statement.type === "alter_table_alter_column_set_autoincrement" && dialect7 === "sqlite" && !driver2;
24197
+ can(statement, dialect7) {
24198
+ return statement.type === "alter_table_alter_column_set_autoincrement" && dialect7 === "sqlite";
24210
24199
  }
24211
24200
  convert(statement) {
24212
24201
  return `/*
@@ -24220,8 +24209,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24220
24209
  }
24221
24210
  };
24222
24211
  SqliteAlterTableAlterColumnDropAutoincrementConvertor = class extends Convertor {
24223
- can(statement, dialect7, driver2) {
24224
- return statement.type === "alter_table_alter_column_drop_autoincrement" && dialect7 === "sqlite" && !driver2;
24212
+ can(statement, dialect7) {
24213
+ return statement.type === "alter_table_alter_column_drop_autoincrement" && dialect7 === "sqlite";
24225
24214
  }
24226
24215
  convert(statement) {
24227
24216
  return `/*
@@ -24245,8 +24234,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24245
24234
  }
24246
24235
  };
24247
24236
  SqliteAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
24248
- can(statement, dialect7, driver2) {
24249
- return statement.type === "alter_table_alter_column_drop_notnull" && dialect7 === "sqlite" && !driver2;
24237
+ can(statement, dialect7) {
24238
+ return statement.type === "alter_table_alter_column_drop_notnull" && dialect7 === "sqlite";
24250
24239
  }
24251
24240
  convert(statement) {
24252
24241
  return `/*
@@ -24290,8 +24279,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24290
24279
  }
24291
24280
  };
24292
24281
  SqliteCreateForeignKeyConvertor = class extends Convertor {
24293
- can(statement, dialect7, driver2) {
24294
- return statement.type === "create_reference" && dialect7 === "sqlite" && !driver2;
24282
+ can(statement, dialect7) {
24283
+ return statement.type === "create_reference" && dialect7 === "sqlite";
24295
24284
  }
24296
24285
  convert(statement) {
24297
24286
  return `/*
@@ -24303,32 +24292,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24303
24292
  */`;
24304
24293
  }
24305
24294
  };
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
- };
24332
24295
  MySqlCreateForeignKeyConvertor = class extends Convertor {
24333
24296
  can(statement, dialect7) {
24334
24297
  return statement.type === "create_reference" && dialect7 === "mysql";
@@ -24402,8 +24365,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24402
24365
  }
24403
24366
  };
24404
24367
  SqliteDeleteForeignKeyConvertor = class extends Convertor {
24405
- can(statement, dialect7, driver2) {
24406
- return statement.type === "delete_reference" && dialect7 === "sqlite" && !driver2;
24368
+ can(statement, dialect7) {
24369
+ return statement.type === "delete_reference" && dialect7 === "sqlite";
24407
24370
  }
24408
24371
  convert(statement) {
24409
24372
  return `/*
@@ -24415,29 +24378,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24415
24378
  */`;
24416
24379
  }
24417
24380
  };
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
- };
24441
24381
  MySqlDeleteForeignKeyConvertor = class extends Convertor {
24442
24382
  can(statement, dialect7) {
24443
24383
  return statement.type === "delete_reference" && dialect7 === "mysql";
@@ -24603,90 +24543,10 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24603
24543
  return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
24604
24544
  }
24605
24545
  };
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
- };
24684
24546
  convertors = [];
24685
24547
  convertors.push(new PgCreateTableConvertor());
24686
24548
  convertors.push(new MySqlCreateTableConvertor());
24687
24549
  convertors.push(new SQLiteCreateTableConvertor());
24688
- convertors.push(new SQLiteRecreateTableConvertor());
24689
- convertors.push(new LibSQLRecreateTableConvertor());
24690
24550
  convertors.push(new CreateTypeEnumConvertor());
24691
24551
  convertors.push(new CreatePgSequenceConvertor());
24692
24552
  convertors.push(new DropPgSequenceConvertor());
@@ -24734,7 +24594,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24734
24594
  convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
24735
24595
  convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
24736
24596
  convertors.push(new MySqlModifyColumn());
24737
- convertors.push(new LibSQLModifyColumn());
24738
24597
  convertors.push(new PgCreateForeignKeyConvertor());
24739
24598
  convertors.push(new MySqlCreateForeignKeyConvertor());
24740
24599
  convertors.push(new PgAlterForeignKeyConvertor());
@@ -24749,9 +24608,7 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24749
24608
  convertors.push(new SQLiteAlterTableAlterColumnSetTypeConvertor());
24750
24609
  convertors.push(new SqliteAlterForeignKeyConvertor());
24751
24610
  convertors.push(new SqliteDeleteForeignKeyConvertor());
24752
- convertors.push(new LibSQLDeleteForeignKeyConvertor());
24753
24611
  convertors.push(new SqliteCreateForeignKeyConvertor());
24754
- convertors.push(new LibSQLCreateForeignKeyConvertor());
24755
24612
  convertors.push(new SQLiteAlterTableAddUniqueConstraintConvertor());
24756
24613
  convertors.push(new SQLiteAlterTableDropUniqueConstraintConvertor());
24757
24614
  convertors.push(new PgAlterTableAlterColumnDropGenerated());
@@ -24774,6 +24631,19 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24774
24631
  convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
24775
24632
  convertors.push(new MySqlAlterTableAddPk());
24776
24633
  convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
24634
+ fromJson = (statements, dialect7) => {
24635
+ const result = statements.flatMap((statement) => {
24636
+ const filtered = convertors.filter((it) => {
24637
+ return it.can(statement, dialect7);
24638
+ });
24639
+ const convertor = filtered.length === 1 ? filtered[0] : void 0;
24640
+ if (!convertor) {
24641
+ return "";
24642
+ }
24643
+ return convertor.convert(statement);
24644
+ }).filter((it) => it !== "");
24645
+ return result;
24646
+ };
24777
24647
  https:
24778
24648
  `
24779
24649
  create table users (
@@ -24801,237 +24671,12 @@ drop type __venum;
24801
24671
  }
24802
24672
  });
24803
24673
 
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
-
25028
24674
  // src/jsonStatements.ts
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;
24675
+ 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;
25030
24676
  var init_jsonStatements = __esm({
25031
24677
  "src/jsonStatements.ts"() {
25032
24678
  "use strict";
25033
24679
  init_source();
25034
- init_sqlitePushUtils();
25035
24680
  init_views();
25036
24681
  init_mysqlSchema();
25037
24682
  init_pgSchema();
@@ -25805,7 +25450,7 @@ var init_jsonStatements = __esm({
25805
25450
  return [...dropPkStatements, ...setPkStatements, ...statements];
25806
25451
  };
25807
25452
  prepareSqliteAlterColumns = (tableName, schema5, columns, json2) => {
25808
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
25453
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
25809
25454
  let statements = [];
25810
25455
  let dropPkStatements = [];
25811
25456
  let setPkStatements = [];
@@ -25819,49 +25464,6 @@ var init_jsonStatements = __esm({
25819
25464
  const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
25820
25465
  const columnGenerated = json2.tables[tableName].columns[columnName].generated;
25821
25466
  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
- }
25865
25467
  if (typeof column7.name !== "string") {
25866
25468
  statements.push({
25867
25469
  type: "alter_table_rename_column",
@@ -25871,7 +25473,7 @@ var init_jsonStatements = __esm({
25871
25473
  schema: schema5
25872
25474
  });
25873
25475
  }
25874
- if (((_d = column7.type) == null ? void 0 : _d.type) === "changed") {
25476
+ if (((_a = column7.type) == null ? void 0 : _a.type) === "changed") {
25875
25477
  statements.push({
25876
25478
  type: "alter_table_alter_column_set_type",
25877
25479
  tableName,
@@ -25886,7 +25488,7 @@ var init_jsonStatements = __esm({
25886
25488
  columnPk
25887
25489
  });
25888
25490
  }
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") {
25491
+ 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") {
25890
25492
  dropPkStatements.push({
25891
25493
  ////
25892
25494
  type: "alter_table_alter_column_drop_pk",
@@ -25895,7 +25497,7 @@ var init_jsonStatements = __esm({
25895
25497
  schema: schema5
25896
25498
  });
25897
25499
  }
25898
- if (((_g = column7.default) == null ? void 0 : _g.type) === "added") {
25500
+ if (((_d = column7.default) == null ? void 0 : _d.type) === "added") {
25899
25501
  statements.push({
25900
25502
  type: "alter_table_alter_column_set_default",
25901
25503
  tableName,
@@ -25909,7 +25511,7 @@ var init_jsonStatements = __esm({
25909
25511
  columnPk
25910
25512
  });
25911
25513
  }
25912
- if (((_h = column7.default) == null ? void 0 : _h.type) === "changed") {
25514
+ if (((_e = column7.default) == null ? void 0 : _e.type) === "changed") {
25913
25515
  statements.push({
25914
25516
  type: "alter_table_alter_column_set_default",
25915
25517
  tableName,
@@ -25924,7 +25526,7 @@ var init_jsonStatements = __esm({
25924
25526
  columnPk
25925
25527
  });
25926
25528
  }
25927
- if (((_i = column7.default) == null ? void 0 : _i.type) === "deleted") {
25529
+ if (((_f = column7.default) == null ? void 0 : _f.type) === "deleted") {
25928
25530
  statements.push({
25929
25531
  type: "alter_table_alter_column_drop_default",
25930
25532
  tableName,
@@ -25938,7 +25540,7 @@ var init_jsonStatements = __esm({
25938
25540
  columnPk
25939
25541
  });
25940
25542
  }
25941
- if (((_j = column7.notNull) == null ? void 0 : _j.type) === "added") {
25543
+ if (((_g = column7.notNull) == null ? void 0 : _g.type) === "added") {
25942
25544
  statements.push({
25943
25545
  type: "alter_table_alter_column_set_notnull",
25944
25546
  tableName,
@@ -25952,7 +25554,7 @@ var init_jsonStatements = __esm({
25952
25554
  columnPk
25953
25555
  });
25954
25556
  }
25955
- if (((_k = column7.notNull) == null ? void 0 : _k.type) === "changed") {
25557
+ if (((_h = column7.notNull) == null ? void 0 : _h.type) === "changed") {
25956
25558
  const type = column7.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
25957
25559
  statements.push({
25958
25560
  type,
@@ -25967,7 +25569,7 @@ var init_jsonStatements = __esm({
25967
25569
  columnPk
25968
25570
  });
25969
25571
  }
25970
- if (((_l = column7.notNull) == null ? void 0 : _l.type) === "deleted") {
25572
+ if (((_i = column7.notNull) == null ? void 0 : _i.type) === "deleted") {
25971
25573
  statements.push({
25972
25574
  type: "alter_table_alter_column_drop_notnull",
25973
25575
  tableName,
@@ -25981,7 +25583,7 @@ var init_jsonStatements = __esm({
25981
25583
  columnPk
25982
25584
  });
25983
25585
  }
25984
- if (((_m = column7.generated) == null ? void 0 : _m.type) === "added") {
25586
+ if (((_j = column7.generated) == null ? void 0 : _j.type) === "added") {
25985
25587
  if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
25986
25588
  statements.push({
25987
25589
  type: "alter_table_alter_column_set_generated",
@@ -26002,7 +25604,7 @@ var init_jsonStatements = __esm({
26002
25604
  );
26003
25605
  }
26004
25606
  }
26005
- if (((_n = column7.generated) == null ? void 0 : _n.type) === "changed") {
25607
+ if (((_k = column7.generated) == null ? void 0 : _k.type) === "changed") {
26006
25608
  if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
26007
25609
  statements.push({
26008
25610
  type: "alter_table_alter_column_alter_generated",
@@ -26023,7 +25625,7 @@ var init_jsonStatements = __esm({
26023
25625
  );
26024
25626
  }
26025
25627
  }
26026
- if (((_o = column7.generated) == null ? void 0 : _o.type) === "deleted") {
25628
+ if (((_l = column7.generated) == null ? void 0 : _l.type) === "deleted") {
26027
25629
  statements.push({
26028
25630
  type: "alter_table_alter_column_drop_generated",
26029
25631
  tableName,
@@ -26038,7 +25640,7 @@ var init_jsonStatements = __esm({
26038
25640
  columnGenerated
26039
25641
  });
26040
25642
  }
26041
- if (((_p = column7.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column7.primaryKey) == null ? void 0 : _q.type) === "changed" && column7.primaryKey.new) {
25643
+ if (((_m = column7.primaryKey) == null ? void 0 : _m.type) === "added" || ((_n = column7.primaryKey) == null ? void 0 : _n.type) === "changed" && column7.primaryKey.new) {
26042
25644
  const wasAutoincrement = statements.filter(
26043
25645
  (it) => it.type === "alter_table_alter_column_set_autoincrement"
26044
25646
  );
@@ -26051,7 +25653,7 @@ var init_jsonStatements = __esm({
26051
25653
  });
26052
25654
  }
26053
25655
  }
26054
- if (((_r = column7.onUpdate) == null ? void 0 : _r.type) === "added") {
25656
+ if (((_o = column7.onUpdate) == null ? void 0 : _o.type) === "added") {
26055
25657
  statements.push({
26056
25658
  type: "alter_table_alter_column_set_on_update",
26057
25659
  tableName,
@@ -26065,7 +25667,7 @@ var init_jsonStatements = __esm({
26065
25667
  columnPk
26066
25668
  });
26067
25669
  }
26068
- if (((_s = column7.onUpdate) == null ? void 0 : _s.type) === "deleted") {
25670
+ if (((_p = column7.onUpdate) == null ? void 0 : _p.type) === "deleted") {
26069
25671
  statements.push({
26070
25672
  type: "alter_table_alter_column_drop_on_update",
26071
25673
  tableName,
@@ -26125,37 +25727,6 @@ var init_jsonStatements = __esm({
26125
25727
  };
26126
25728
  });
26127
25729
  };
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
- };
26159
25730
  prepareDropReferencesJson = (tableName, schema5, foreignKeys) => {
26160
25731
  return Object.values(foreignKeys).map((fkData) => {
26161
25732
  return {
@@ -26166,54 +25737,6 @@ var init_jsonStatements = __esm({
26166
25737
  };
26167
25738
  });
26168
25739
  };
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
- };
26217
25740
  prepareAlterReferencesJson = (tableName, schema5, foreignKeys) => {
26218
25741
  const stmts = [];
26219
25742
  Object.values(foreignKeys).map((val2) => {
@@ -26368,295 +25891,8 @@ var init_jsonStatements = __esm({
26368
25891
  }
26369
25892
  });
26370
25893
 
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
-
26658
25894
  // src/snapshotsDiffer.ts
26659
- var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
25895
+ var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff;
26660
25896
  var init_snapshotsDiffer = __esm({
26661
25897
  "src/snapshotsDiffer.ts"() {
26662
25898
  "use strict";
@@ -26668,7 +25904,6 @@ var init_snapshotsDiffer = __esm({
26668
25904
  init_mysqlSchema();
26669
25905
  init_pgSchema();
26670
25906
  init_sqliteSchema();
26671
- init_statementCombiner();
26672
25907
  init_utils();
26673
25908
  makeChanged = (schema5) => {
26674
25909
  return objectType({
@@ -27996,8 +27231,7 @@ var init_snapshotsDiffer = __esm({
27996
27231
  jsonStatements.push(...jsonDropColumnsStatemets);
27997
27232
  jsonStatements.push(...jsonAlteredCompositePKs);
27998
27233
  jsonStatements.push(...jsonAlteredUniqueConstraints);
27999
- const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
28000
- const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
27234
+ const sqlStatements = fromJson(jsonStatements, "sqlite");
28001
27235
  const uniqueSqlStatements = [];
28002
27236
  sqlStatements.forEach((ss) => {
28003
27237
  if (!uniqueSqlStatements.includes(ss)) {
@@ -28009,298 +27243,7 @@ var init_snapshotsDiffer = __esm({
28009
27243
  });
28010
27244
  const _meta = prepareMigrationMeta([], rTables, rColumns);
28011
27245
  return {
28012
- statements: combinedJsonStatements,
28013
- sqlStatements: uniqueSqlStatements,
28014
- _meta
28015
- };
28016
- };
28017
- applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
28018
- const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
28019
- const {
28020
- created: createdTables,
28021
- deleted: deletedTables,
28022
- renamed: renamedTables
28023
- } = await tablesResolver2({
28024
- created: tablesDiff.added,
28025
- deleted: tablesDiff.deleted
28026
- });
28027
- const tablesPatchedSnap1 = copy(json1);
28028
- tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
28029
- const { name } = nameChangeFor(it, renamedTables);
28030
- it.name = name;
28031
- return [name, it];
28032
- });
28033
- const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
28034
- const columnRenames = [];
28035
- const columnCreates = [];
28036
- const columnDeletes = [];
28037
- for (let entry of Object.values(res)) {
28038
- const { renamed, created, deleted } = await columnsResolver2({
28039
- tableName: entry.name,
28040
- schema: entry.schema,
28041
- deleted: entry.columns.deleted,
28042
- created: entry.columns.added
28043
- });
28044
- if (created.length > 0) {
28045
- columnCreates.push({
28046
- table: entry.name,
28047
- columns: created
28048
- });
28049
- }
28050
- if (deleted.length > 0) {
28051
- columnDeletes.push({
28052
- table: entry.name,
28053
- columns: deleted
28054
- });
28055
- }
28056
- if (renamed.length > 0) {
28057
- columnRenames.push({
28058
- table: entry.name,
28059
- renames: renamed
28060
- });
28061
- }
28062
- }
28063
- const columnRenamesDict = columnRenames.reduce(
28064
- (acc, it) => {
28065
- acc[it.table] = it.renames;
28066
- return acc;
28067
- },
28068
- {}
28069
- );
28070
- const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
28071
- columnsPatchedSnap1.tables = mapEntries(
28072
- columnsPatchedSnap1.tables,
28073
- (tableKey2, tableValue) => {
28074
- const patchedColumns = mapKeys(
28075
- tableValue.columns,
28076
- (columnKey, column7) => {
28077
- const rens = columnRenamesDict[tableValue.name] || [];
28078
- const newName = columnChangeFor(columnKey, rens);
28079
- column7.name = newName;
28080
- return newName;
28081
- }
28082
- );
28083
- tableValue.columns = patchedColumns;
28084
- return [tableKey2, tableValue];
28085
- }
28086
- );
28087
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
28088
- const typedResult = diffResultSchemeSQLite.parse(diffResult);
28089
- const tablesMap = {};
28090
- typedResult.alteredTablesWithColumns.forEach((obj) => {
28091
- tablesMap[obj.name] = obj;
28092
- });
28093
- const jsonCreateTables = createdTables.map((it) => {
28094
- return prepareSQLiteCreateTable(it, action);
28095
- });
28096
- const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
28097
- return prepareCreateIndexesJson(
28098
- it.name,
28099
- it.schema,
28100
- it.indexes,
28101
- curFull.internal
28102
- );
28103
- }).flat();
28104
- const jsonDropTables = deletedTables.map((it) => {
28105
- return prepareDropTableJson(it);
28106
- });
28107
- const jsonRenameTables = renamedTables.map((it) => {
28108
- return prepareRenameTableJson(it.from, it.to);
28109
- });
28110
- const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
28111
- const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
28112
- const jsonAddColumnsStatemets = columnCreates.map((it) => {
28113
- return _prepareSqliteAddColumns(
28114
- it.table,
28115
- it.columns,
28116
- tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
28117
- );
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);
28131
- const allAltered = typedResult.alteredTablesWithColumns;
28132
- const jsonAddedCompositePKs = [];
28133
- const jsonDeletedCompositePKs = [];
28134
- const jsonAlteredCompositePKs = [];
28135
- const jsonAddedUniqueConstraints = [];
28136
- const jsonDeletedUniqueConstraints = [];
28137
- const jsonAlteredUniqueConstraints = [];
28138
- allAltered.forEach((it) => {
28139
- let addedColumns = [];
28140
- for (const addedPkName of Object.keys(it.addedCompositePKs)) {
28141
- const addedPkColumns = it.addedCompositePKs[addedPkName];
28142
- addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
28143
- }
28144
- let deletedColumns = [];
28145
- for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
28146
- const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
28147
- deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
28148
- }
28149
- const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
28150
- let addedCompositePKs = [];
28151
- let deletedCompositePKs = [];
28152
- let alteredCompositePKs = [];
28153
- if (doPerformDeleteAndCreate) {
28154
- addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
28155
- it.name,
28156
- it.addedCompositePKs
28157
- );
28158
- deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
28159
- it.name,
28160
- it.deletedCompositePKs
28161
- );
28162
- }
28163
- alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
28164
- it.name,
28165
- it.alteredCompositePKs
28166
- );
28167
- let addedUniqueConstraints = [];
28168
- let deletedUniqueConstraints = [];
28169
- let alteredUniqueConstraints = [];
28170
- addedUniqueConstraints = prepareAddUniqueConstraintPg(
28171
- it.name,
28172
- it.schema,
28173
- it.addedUniqueConstraints
28174
- );
28175
- deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
28176
- it.name,
28177
- it.schema,
28178
- it.deletedUniqueConstraints
28179
- );
28180
- if (it.alteredUniqueConstraints) {
28181
- const added = {};
28182
- const deleted = {};
28183
- for (const k of Object.keys(it.alteredUniqueConstraints)) {
28184
- added[k] = it.alteredUniqueConstraints[k].__new;
28185
- deleted[k] = it.alteredUniqueConstraints[k].__old;
28186
- }
28187
- addedUniqueConstraints.push(
28188
- ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
28189
- );
28190
- deletedUniqueConstraints.push(
28191
- ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
28192
- );
28193
- }
28194
- jsonAddedCompositePKs.push(...addedCompositePKs);
28195
- jsonDeletedCompositePKs.push(...deletedCompositePKs);
28196
- jsonAlteredCompositePKs.push(...alteredCompositePKs);
28197
- jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
28198
- jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
28199
- jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
28200
- });
28201
- const jsonTableAlternations = allAltered.map((it) => {
28202
- return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
28203
- }).flat();
28204
- const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
28205
- return prepareCreateIndexesJson(
28206
- it.name,
28207
- it.schema,
28208
- it.addedIndexes || {},
28209
- curFull.internal
28210
- );
28211
- }).flat();
28212
- const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
28213
- return prepareDropIndexesJson(
28214
- it.name,
28215
- it.schema,
28216
- it.deletedIndexes || {}
28217
- );
28218
- }).flat();
28219
- allAltered.forEach((it) => {
28220
- const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
28221
- (current, item) => {
28222
- current[item] = it.alteredIndexes[item].__old;
28223
- return current;
28224
- },
28225
- {}
28226
- );
28227
- const createdIndexes = Object.keys(it.alteredIndexes).reduce(
28228
- (current, item) => {
28229
- current[item] = it.alteredIndexes[item].__new;
28230
- return current;
28231
- },
28232
- {}
28233
- );
28234
- jsonCreateIndexesForAllAlteredTables.push(
28235
- ...prepareCreateIndexesJson(
28236
- it.name,
28237
- it.schema,
28238
- createdIndexes || {},
28239
- curFull.internal
28240
- )
28241
- );
28242
- jsonDropIndexesForAllAlteredTables.push(
28243
- ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
28244
- );
28245
- });
28246
- const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
28247
- const forAdded = prepareLibSQLCreateReferencesJson(
28248
- it.name,
28249
- it.schema,
28250
- it.addedForeignKeys,
28251
- json2,
28252
- action
28253
- );
28254
- const forAltered = prepareLibSQLDropReferencesJson(
28255
- it.name,
28256
- it.schema,
28257
- it.deletedForeignKeys,
28258
- json2,
28259
- _meta,
28260
- action
28261
- );
28262
- const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
28263
- return [...forAdded, ...forAltered, ...alteredFKs];
28264
- }).flat();
28265
- const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
28266
- (t2) => t2.type === "create_reference"
28267
- );
28268
- const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
28269
- (t2) => t2.type === "delete_reference"
28270
- );
28271
- const jsonStatements = [];
28272
- jsonStatements.push(...jsonCreateTables);
28273
- jsonStatements.push(...jsonDropTables);
28274
- jsonStatements.push(...jsonRenameTables);
28275
- jsonStatements.push(...jsonRenameColumnsStatements);
28276
- jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
28277
- jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
28278
- jsonStatements.push(...jsonDeletedCompositePKs);
28279
- jsonStatements.push(...jsonTableAlternations);
28280
- jsonStatements.push(...jsonAddedCompositePKs);
28281
- jsonStatements.push(...jsonAddColumnsStatemets);
28282
- jsonStatements.push(...jsonCreateIndexesForCreatedTables);
28283
- jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
28284
- jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
28285
- jsonStatements.push(...jsonDropColumnsStatemets);
28286
- jsonStatements.push(...jsonAlteredCompositePKs);
28287
- jsonStatements.push(...jsonAlteredUniqueConstraints);
28288
- const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action);
28289
- const sqlStatements = fromJson(
28290
- combinedJsonStatements,
28291
- "sqlite",
28292
- action,
28293
- "turso",
28294
- json2
28295
- );
28296
- const uniqueSqlStatements = [];
28297
- sqlStatements.forEach((ss) => {
28298
- if (!uniqueSqlStatements.includes(ss)) {
28299
- uniqueSqlStatements.push(ss);
28300
- }
28301
- });
28302
- return {
28303
- statements: combinedJsonStatements,
27246
+ statements: jsonStatements,
28304
27247
  sqlStatements: uniqueSqlStatements,
28305
27248
  _meta
28306
27249
  };
@@ -29639,7 +28582,6 @@ __export(migrate_exports, {
29639
28582
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
29640
28583
  prepareAndMigratePg: () => prepareAndMigratePg,
29641
28584
  prepareAndMigrateSqlite: () => prepareAndMigrateSqlite,
29642
- prepareLibSQLPush: () => prepareLibSQLPush,
29643
28585
  prepareMySQLPush: () => prepareMySQLPush,
29644
28586
  preparePgPush: () => preparePgPush,
29645
28587
  prepareSQLitePush: () => prepareSQLitePush,
@@ -29652,7 +28594,7 @@ __export(migrate_exports, {
29652
28594
  tablesResolver: () => tablesResolver,
29653
28595
  writeResult: () => writeResult
29654
28596
  });
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;
28597
+ 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;
29656
28598
  var init_migrate = __esm({
29657
28599
  "src/cli/commands/migrate.ts"() {
29658
28600
  "use strict";
@@ -29904,7 +28846,6 @@ var init_migrate = __esm({
29904
28846
  prepareAndMigrateSqlite = async (config) => {
29905
28847
  const outFolder = config.out;
29906
28848
  const schemaPath = config.schema;
29907
- const driver2 = config.driver;
29908
28849
  try {
29909
28850
  assertV1OutFolder(outFolder);
29910
28851
  const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
@@ -29930,27 +28871,14 @@ var init_migrate = __esm({
29930
28871
  }
29931
28872
  const squashedPrev = squashSqliteScheme(validatedPrev);
29932
28873
  const squashedCur = squashSqliteScheme(validatedCur);
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
- }
28874
+ const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
28875
+ squashedPrev,
28876
+ squashedCur,
28877
+ tablesResolver,
28878
+ columnsResolver,
28879
+ validatedPrev,
28880
+ validatedCur
28881
+ );
29954
28882
  writeResult({
29955
28883
  cur,
29956
28884
  sqlStatements,
@@ -29966,51 +28894,13 @@ var init_migrate = __esm({
29966
28894
  console.error(e2);
29967
28895
  }
29968
28896
  };
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) => {
28897
+ prepareSQLitePush = async (schemaPath, snapshot) => {
30008
28898
  const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath);
30009
28899
  const validatedPrev = sqliteSchema.parse(prev);
30010
28900
  const validatedCur = sqliteSchema.parse(cur);
30011
28901
  const squashedPrev = squashSqliteScheme(validatedPrev, "push");
30012
28902
  const squashedCur = squashSqliteScheme(validatedCur, "push");
30013
- const { sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
28903
+ const { sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
30014
28904
  squashedPrev,
30015
28905
  squashedCur,
30016
28906
  tablesResolver,
@@ -73368,259 +72258,8 @@ var init_selector_ui = __esm({
73368
72258
  }
73369
72259
  });
73370
72260
 
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
-
73622
72261
  // src/cli/commands/mysqlPushUtils.ts
73623
- var import_hanji6, filterStatements, logSuggestionsAndReturn2;
72262
+ var import_hanji6, filterStatements, logSuggestionsAndReturn;
73624
72263
  var init_mysqlPushUtils = __esm({
73625
72264
  "src/cli/commands/mysqlPushUtils.ts"() {
73626
72265
  "use strict";
@@ -73670,7 +72309,7 @@ var init_mysqlPushUtils = __esm({
73670
72309
  return true;
73671
72310
  });
73672
72311
  };
73673
- logSuggestionsAndReturn2 = async (db, statements, json2) => {
72312
+ logSuggestionsAndReturn = async (db, statements, json2) => {
73674
72313
  let shouldAskForApprove = false;
73675
72314
  const statementsToExecute = [];
73676
72315
  const infoToPrint = [];
@@ -74111,6 +72750,289 @@ var init_pgPushUtils = __esm({
74111
72750
  }
74112
72751
  });
74113
72752
 
72753
+ // src/cli/commands/sqlitePushUtils.ts
72754
+ var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn2;
72755
+ var init_sqlitePushUtils = __esm({
72756
+ "src/cli/commands/sqlitePushUtils.ts"() {
72757
+ "use strict";
72758
+ init_source();
72759
+ init_sqliteSchema();
72760
+ init_sqlgenerator();
72761
+ _moveDataStatements = (tableName, json, dataLoss = false) => {
72762
+ const statements = [];
72763
+ statements.push(
72764
+ new SqliteRenameTableConvertor().convert({
72765
+ type: "rename_table",
72766
+ tableNameFrom: tableName,
72767
+ tableNameTo: `__old_push_${tableName}`,
72768
+ fromSchema: "",
72769
+ toSchema: ""
72770
+ })
72771
+ );
72772
+ const tableColumns = Object.values(json.tables[tableName].columns);
72773
+ const referenceData = Object.values(json.tables[tableName].foreignKeys);
72774
+ const compositePKs = Object.values(
72775
+ json.tables[tableName].compositePrimaryKeys
72776
+ ).map((it) => SQLiteSquasher.unsquashPK(it));
72777
+ const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
72778
+ statements.push(
72779
+ new SQLiteCreateTableConvertor().convert({
72780
+ type: "sqlite_create_table",
72781
+ tableName,
72782
+ columns: tableColumns,
72783
+ referenceData: fks,
72784
+ compositePKs
72785
+ })
72786
+ );
72787
+ if (!dataLoss) {
72788
+ statements.push(
72789
+ `INSERT INTO "${tableName}" SELECT * FROM "__old_push_${tableName}";`
72790
+ );
72791
+ }
72792
+ statements.push(
72793
+ new SQLiteDropTableConvertor().convert({
72794
+ type: "drop_table",
72795
+ tableName: `__old_push_${tableName}`,
72796
+ schema: ""
72797
+ })
72798
+ );
72799
+ for (const idx of Object.values(json.tables[tableName].indexes)) {
72800
+ statements.push(
72801
+ new CreateSqliteIndexConvertor().convert({
72802
+ type: "create_index",
72803
+ tableName,
72804
+ schema: "",
72805
+ data: idx
72806
+ })
72807
+ );
72808
+ }
72809
+ return statements;
72810
+ };
72811
+ getOldTableName = (tableName, meta) => {
72812
+ for (const key of Object.keys(meta.tables)) {
72813
+ const value = meta.tables[key];
72814
+ if (`"${tableName}"` === value) {
72815
+ return key.substring(1, key.length - 1);
72816
+ }
72817
+ }
72818
+ return tableName;
72819
+ };
72820
+ getNewTableName = (tableName, meta) => {
72821
+ if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
72822
+ return meta.tables[`"${tableName}"`].substring(
72823
+ 1,
72824
+ meta.tables[`"${tableName}"`].length - 1
72825
+ );
72826
+ }
72827
+ return tableName;
72828
+ };
72829
+ logSuggestionsAndReturn2 = async (connection, statements, json1, json2, meta) => {
72830
+ let shouldAskForApprove = false;
72831
+ const statementsToExecute = [];
72832
+ const infoToPrint = [];
72833
+ const tablesToRemove = [];
72834
+ const columnsToRemove = [];
72835
+ const schemasToRemove = [];
72836
+ const tablesToTruncate = [];
72837
+ const tablesContext = {};
72838
+ for (const statement of statements) {
72839
+ if (statement.type === "drop_table") {
72840
+ const res = await connection.query(
72841
+ `select count(*) as count from \`${statement.tableName}\``
72842
+ );
72843
+ const count = Number(res[0].count);
72844
+ if (count > 0) {
72845
+ infoToPrint.push(
72846
+ `\xB7 You're about to delete ${source_default.underline(
72847
+ statement.tableName
72848
+ )} table with ${count} items`
72849
+ );
72850
+ tablesToRemove.push(statement.tableName);
72851
+ shouldAskForApprove = true;
72852
+ }
72853
+ const stmnt = fromJson([statement], "sqlite")[0];
72854
+ statementsToExecute.push(stmnt);
72855
+ } else if (statement.type === "alter_table_drop_column") {
72856
+ const newTableName = getOldTableName(statement.tableName, meta);
72857
+ const columnIsPartOfPk = Object.values(
72858
+ json1.tables[newTableName].compositePrimaryKeys
72859
+ ).find((c) => SQLiteSquasher.unsquashPK(c).includes(statement.columnName));
72860
+ const columnIsPartOfIndex = Object.values(
72861
+ json1.tables[newTableName].indexes
72862
+ ).find((c) => SQLiteSquasher.unsquashIdx(c).columns.includes(statement.columnName));
72863
+ const columnIsPk = json1.tables[newTableName].columns[statement.columnName].primaryKey;
72864
+ const columnIsPartOfFk = Object.values(
72865
+ json1.tables[newTableName].foreignKeys
72866
+ ).find(
72867
+ (t2) => SQLiteSquasher.unsquashPushFK(t2).columnsFrom.includes(
72868
+ statement.columnName
72869
+ )
72870
+ );
72871
+ const res = await connection.query(
72872
+ `select count(*) as count from \`${newTableName}\``
72873
+ );
72874
+ const count = Number(res[0].count);
72875
+ if (count > 0) {
72876
+ infoToPrint.push(
72877
+ `\xB7 You're about to delete ${source_default.underline(
72878
+ statement.columnName
72879
+ )} column in ${newTableName} table with ${count} items`
72880
+ );
72881
+ columnsToRemove.push(`${newTableName}_${statement.columnName}`);
72882
+ shouldAskForApprove = true;
72883
+ }
72884
+ if (columnIsPk || columnIsPartOfPk || columnIsPartOfIndex || columnIsPartOfFk) {
72885
+ tablesContext[newTableName] = [
72886
+ ..._moveDataStatements(statement.tableName, json2, true)
72887
+ ];
72888
+ const tablesReferncingCurrent = [];
72889
+ for (const table4 of Object.values(json1.tables)) {
72890
+ const tablesRefs = Object.values(json1.tables[table4.name].foreignKeys).filter(
72891
+ (t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === newTableName
72892
+ ).map((t2) => SQLiteSquasher.unsquashPushFK(t2).tableFrom);
72893
+ tablesReferncingCurrent.push(...tablesRefs);
72894
+ }
72895
+ const uniqueTableRefs = [...new Set(tablesReferncingCurrent)];
72896
+ for (const table4 of uniqueTableRefs) {
72897
+ if (typeof tablesContext[table4] === "undefined") {
72898
+ tablesContext[table4] = [..._moveDataStatements(table4, json2)];
72899
+ }
72900
+ }
72901
+ } else {
72902
+ if (typeof tablesContext[newTableName] === "undefined") {
72903
+ const stmnt = fromJson([statement], "sqlite")[0];
72904
+ statementsToExecute.push(stmnt);
72905
+ }
72906
+ }
72907
+ } else if (statement.type === "sqlite_alter_table_add_column") {
72908
+ const newTableName = getOldTableName(statement.tableName, meta);
72909
+ if (statement.column.notNull && !statement.column.default) {
72910
+ const res = await connection.query(
72911
+ `select count(*) as count from \`${newTableName}\``
72912
+ );
72913
+ const count = Number(res[0].count);
72914
+ if (count > 0) {
72915
+ infoToPrint.push(
72916
+ `\xB7 You're about to add not-null ${source_default.underline(
72917
+ statement.column.name
72918
+ )} column without default value, which contains ${count} items`
72919
+ );
72920
+ tablesToTruncate.push(newTableName);
72921
+ statementsToExecute.push(`delete from ${newTableName};`);
72922
+ shouldAskForApprove = true;
72923
+ }
72924
+ }
72925
+ if (statement.column.primaryKey) {
72926
+ tablesContext[newTableName] = [
72927
+ ..._moveDataStatements(statement.tableName, json2, true)
72928
+ ];
72929
+ const tablesReferncingCurrent = [];
72930
+ for (const table4 of Object.values(json1.tables)) {
72931
+ const tablesRefs = Object.values(json1.tables[table4.name].foreignKeys).filter(
72932
+ (t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === newTableName
72933
+ ).map((t2) => SQLiteSquasher.unsquashPushFK(t2).tableFrom);
72934
+ tablesReferncingCurrent.push(...tablesRefs);
72935
+ }
72936
+ const uniqueTableRefs = [...new Set(tablesReferncingCurrent)];
72937
+ for (const table4 of uniqueTableRefs) {
72938
+ if (typeof tablesContext[table4] === "undefined") {
72939
+ tablesContext[table4] = [..._moveDataStatements(table4, json2)];
72940
+ }
72941
+ }
72942
+ } else {
72943
+ if (typeof tablesContext[newTableName] === "undefined") {
72944
+ const stmnt = fromJson([statement], "sqlite")[0];
72945
+ statementsToExecute.push(stmnt);
72946
+ }
72947
+ }
72948
+ } 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") {
72949
+ if (!(statement.type === "alter_table_alter_column_set_notnull" && statement.columnPk)) {
72950
+ const newTableName = getOldTableName(statement.tableName, meta);
72951
+ if (statement.type === "alter_table_alter_column_set_notnull" && typeof statement.columnDefault === "undefined") {
72952
+ const res = await connection.query(
72953
+ `select count(*) as count from \`${newTableName}\``
72954
+ );
72955
+ const count = Number(res[0].count);
72956
+ if (count > 0) {
72957
+ infoToPrint.push(
72958
+ `\xB7 You're about to add not-null constraint to ${source_default.underline(
72959
+ statement.columnName
72960
+ )} column without default value, which contains ${count} items`
72961
+ );
72962
+ tablesToTruncate.push(newTableName);
72963
+ shouldAskForApprove = true;
72964
+ }
72965
+ tablesContext[newTableName] = _moveDataStatements(
72966
+ statement.tableName,
72967
+ json1,
72968
+ true
72969
+ );
72970
+ } else {
72971
+ if (typeof tablesContext[newTableName] === "undefined") {
72972
+ tablesContext[newTableName] = _moveDataStatements(
72973
+ statement.tableName,
72974
+ json1
72975
+ );
72976
+ }
72977
+ }
72978
+ const tablesReferncingCurrent = [];
72979
+ for (const table4 of Object.values(json1.tables)) {
72980
+ const tablesRefs = Object.values(json1.tables[table4.name].foreignKeys).filter(
72981
+ (t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === newTableName
72982
+ ).map((t2) => {
72983
+ return getNewTableName(
72984
+ SQLiteSquasher.unsquashPushFK(t2).tableFrom,
72985
+ meta
72986
+ );
72987
+ });
72988
+ tablesReferncingCurrent.push(...tablesRefs);
72989
+ }
72990
+ const uniqueTableRefs = [...new Set(tablesReferncingCurrent)];
72991
+ for (const table4 of uniqueTableRefs) {
72992
+ if (typeof tablesContext[table4] === "undefined") {
72993
+ tablesContext[table4] = [..._moveDataStatements(table4, json1)];
72994
+ }
72995
+ }
72996
+ }
72997
+ } else if (statement.type === "create_reference" || statement.type === "delete_reference" || statement.type === "alter_reference") {
72998
+ const fk4 = SQLiteSquasher.unsquashPushFK(statement.data);
72999
+ if (typeof tablesContext[statement.tableName] === "undefined") {
73000
+ tablesContext[statement.tableName] = _moveDataStatements(
73001
+ statement.tableName,
73002
+ json2
73003
+ );
73004
+ }
73005
+ } 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") {
73006
+ const newTableName = getOldTableName(statement.tableName, meta);
73007
+ if (typeof tablesContext[newTableName] === "undefined") {
73008
+ tablesContext[newTableName] = _moveDataStatements(
73009
+ statement.tableName,
73010
+ json2
73011
+ );
73012
+ }
73013
+ } else {
73014
+ const stmnt = fromJson([statement], "sqlite");
73015
+ if (typeof stmnt !== "undefined") {
73016
+ statementsToExecute.push(...stmnt);
73017
+ }
73018
+ }
73019
+ }
73020
+ for (const context of Object.values(tablesContext)) {
73021
+ statementsToExecute.push(...context);
73022
+ }
73023
+ return {
73024
+ statementsToExecute,
73025
+ shouldAskForApprove,
73026
+ infoToPrint,
73027
+ columnsToRemove: [...new Set(columnsToRemove)],
73028
+ schemasToRemove: [...new Set(schemasToRemove)],
73029
+ tablesToTruncate: [...new Set(tablesToTruncate)],
73030
+ tablesToRemove: [...new Set(tablesToRemove)]
73031
+ };
73032
+ };
73033
+ }
73034
+ });
73035
+
74114
73036
  // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
74115
73037
  var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
74116
73038
  var init_brace_expressions = __esm({
@@ -75285,7 +74207,7 @@ var init_pgIntrospect = __esm({
75285
74207
  });
75286
74208
 
75287
74209
  // src/introspect-sqlite.ts
75288
- var sqliteImportsList, indexName3, objToStatement2, relations, withCasing, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column4, createTableColumns, createTableIndexes, createTableUniques, createTablePKs, createTableFKs;
74210
+ var sqliteImportsList, indexName3, objToStatement2, relations, escapeColumnKey, withCasing, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column4, createTableColumns, createTableIndexes, createTableUniques, createTablePKs, createTableFKs;
75289
74211
  var init_introspect_sqlite = __esm({
75290
74212
  "src/introspect-sqlite.ts"() {
75291
74213
  "use strict";
@@ -75312,12 +74234,18 @@ var init_introspect_sqlite = __esm({
75312
74234
  return statement;
75313
74235
  };
75314
74236
  relations = /* @__PURE__ */ new Set();
74237
+ escapeColumnKey = (value) => {
74238
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
74239
+ return `"${value}"`;
74240
+ }
74241
+ return value;
74242
+ };
75315
74243
  withCasing = (value, casing2) => {
75316
- if (typeof casing2 === "undefined") {
75317
- return value;
74244
+ if (casing2 === "preserve") {
74245
+ return escapeColumnKey(value);
75318
74246
  }
75319
74247
  if (casing2 === "camel") {
75320
- return value.camelCase();
74248
+ return escapeColumnKey(value.camelCase());
75321
74249
  }
75322
74250
  return value;
75323
74251
  };
@@ -75673,12 +74601,11 @@ var init_sqliteIntrospect = __esm({
75673
74601
  // src/cli/commands/push.ts
75674
74602
  var push_exports = {};
75675
74603
  __export(push_exports, {
75676
- libSQLPush: () => libSQLPush,
75677
74604
  mysqlPush: () => mysqlPush,
75678
74605
  pgPush: () => pgPush,
75679
74606
  sqlitePush: () => sqlitePush
75680
74607
  });
75681
- var import_hanji11, mysqlPush, pgPush, sqlitePush, libSQLPush;
74608
+ var import_hanji11, mysqlPush, pgPush, sqlitePush;
75682
74609
  var init_push = __esm({
75683
74610
  "src/cli/commands/push.ts"() {
75684
74611
  "use strict";
@@ -75687,7 +74614,6 @@ var init_push = __esm({
75687
74614
  init_sqlgenerator();
75688
74615
  init_selector_ui();
75689
74616
  init_outputs();
75690
- init_libSqlPushUtils();
75691
74617
  init_mysqlPushUtils();
75692
74618
  init_pgPushUtils();
75693
74619
  init_sqlitePushUtils();
@@ -75715,7 +74641,7 @@ var init_push = __esm({
75715
74641
  tablesToTruncate,
75716
74642
  infoToPrint,
75717
74643
  schemasToRemove
75718
- } = await logSuggestionsAndReturn2(
74644
+ } = await logSuggestionsAndReturn(
75719
74645
  db,
75720
74646
  filteredStatements,
75721
74647
  statements.validatedCur
@@ -75734,6 +74660,7 @@ var init_push = __esm({
75734
74660
  }
75735
74661
  });
75736
74662
  if (verbose) {
74663
+ console.log();
75737
74664
  console.log(
75738
74665
  withStyle.warning("You are about to execute current statements:")
75739
74666
  );
@@ -75884,100 +74811,11 @@ var init_push = __esm({
75884
74811
  tablesToTruncate,
75885
74812
  infoToPrint,
75886
74813
  schemasToRemove
75887
- } = await logSuggestionsAndReturn(
74814
+ } = await logSuggestionsAndReturn2(
75888
74815
  db,
75889
74816
  statements.statements,
75890
- statements.squashedPrev,
75891
74817
  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,
75979
74818
  statements.squashedPrev,
75980
- statements.squashedCur,
75981
74819
  statements.meta
75982
74820
  );
75983
74821
  if (verbose && statementsToExecute.length > 0) {
@@ -76405,7 +75243,7 @@ var require_pluralize = __commonJS({
76405
75243
  });
76406
75244
 
76407
75245
  // src/introspect-mysql.ts
76408
- var mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, prepareCasing, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTableUniques2, createTablePKs2, createTableFKs2;
75246
+ var mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, escapeColumnKey2, prepareCasing, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTableUniques2, createTablePKs2, createTableFKs2;
76409
75247
  var init_introspect_mysql = __esm({
76410
75248
  "src/introspect-mysql.ts"() {
76411
75249
  "use strict";
@@ -76476,14 +75314,20 @@ var init_introspect_mysql = __esm({
76476
75314
  "timestamp without time zone": "timestamp"
76477
75315
  };
76478
75316
  relations2 = /* @__PURE__ */ new Set();
75317
+ escapeColumnKey2 = (value) => {
75318
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
75319
+ return `"${value}"`;
75320
+ }
75321
+ return value;
75322
+ };
76479
75323
  prepareCasing = (casing2) => (value) => {
76480
- if (typeof casing2 === "undefined") {
76481
- return value;
75324
+ if (casing2 === "preserve") {
75325
+ return escapeColumnKey2(value);
76482
75326
  }
76483
75327
  if (casing2 === "camel") {
76484
- return value.camelCase();
75328
+ return escapeColumnKey2(value.camelCase());
76485
75329
  }
76486
- return value;
75330
+ return escapeColumnKey2(value);
76487
75331
  };
76488
75332
  schemaToTypeScript2 = (schema5, casing2) => {
76489
75333
  const withCasing4 = prepareCasing(casing2);
@@ -76949,7 +75793,33 @@ import { sql } from "drizzle-orm"
76949
75793
  });
76950
75794
 
76951
75795
  // src/introspect-pg.ts
76952
- var import_drizzle_orm8, import_relations, pgImportsList, objToStatement23, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, importsPatch2, relations3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
75796
+ function generateIdentityParams(identity) {
75797
+ let paramsObj = `{ name: "${identity.name}"`;
75798
+ if (identity == null ? void 0 : identity.startWith) {
75799
+ paramsObj += `, startWith: ${identity.startWith}`;
75800
+ }
75801
+ if (identity == null ? void 0 : identity.increment) {
75802
+ paramsObj += `, increment: ${identity.increment}`;
75803
+ }
75804
+ if (identity == null ? void 0 : identity.minValue) {
75805
+ paramsObj += `, minValue: ${identity.minValue}`;
75806
+ }
75807
+ if (identity == null ? void 0 : identity.maxValue) {
75808
+ paramsObj += `, maxValue: ${identity.maxValue}`;
75809
+ }
75810
+ if (identity == null ? void 0 : identity.cache) {
75811
+ paramsObj += `, cache: ${identity.cache}`;
75812
+ }
75813
+ if (identity == null ? void 0 : identity.cycle) {
75814
+ paramsObj += `, cycle: true`;
75815
+ }
75816
+ paramsObj += " }";
75817
+ if ((identity == null ? void 0 : identity.type) === "always") {
75818
+ return `.generatedAlwaysAsIdentity(${paramsObj})`;
75819
+ }
75820
+ return `.generatedByDefaultAsIdentity(${paramsObj})`;
75821
+ }
75822
+ var import_drizzle_orm8, import_relations, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
76953
75823
  var init_introspect_pg = __esm({
76954
75824
  "src/introspect-pg.ts"() {
76955
75825
  "use strict";
@@ -76993,16 +75863,6 @@ var init_introspect_pg = __esm({
76993
75863
  "line",
76994
75864
  "geometry"
76995
75865
  ]);
76996
- objToStatement23 = (json) => {
76997
- json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
76998
- const keys = Object.keys(json);
76999
- if (keys.length === 0)
77000
- return;
77001
- let statement = "{ ";
77002
- statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
77003
- statement += " }";
77004
- return statement;
77005
- };
77006
75866
  timeConfig2 = (json) => {
77007
75867
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
77008
75868
  const keys = Object.keys(json);
@@ -77062,6 +75922,12 @@ var init_introspect_pg = __esm({
77062
75922
  statement += " }";
77063
75923
  return statement;
77064
75924
  };
75925
+ mapColumnDefault3 = (defaultValue, isExpression) => {
75926
+ if (isExpression) {
75927
+ return `sql\`${defaultValue}\``;
75928
+ }
75929
+ return defaultValue;
75930
+ };
77065
75931
  importsPatch2 = {
77066
75932
  "double precision": "doublePrecision",
77067
75933
  "timestamp without time zone": "timestamp",
@@ -77070,12 +75936,18 @@ var init_introspect_pg = __esm({
77070
75936
  "time with time zone": "time"
77071
75937
  };
77072
75938
  relations3 = /* @__PURE__ */ new Set();
75939
+ escapeColumnKey3 = (value) => {
75940
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
75941
+ return `"${value}"`;
75942
+ }
75943
+ return value;
75944
+ };
77073
75945
  withCasing2 = (value, casing2) => {
77074
75946
  if (casing2 === "preserve") {
77075
- return value;
75947
+ return escapeColumnKey3(value);
77076
75948
  }
77077
75949
  if (casing2 === "camel") {
77078
- return value.camelCase();
75950
+ return escapeColumnKey3(value.camelCase());
77079
75951
  }
77080
75952
  assertUnreachable(casing2);
77081
75953
  };
@@ -77095,7 +75967,13 @@ var init_introspect_pg = __esm({
77095
75967
  return [it[0], withCasing2(it[1], casing2)];
77096
75968
  })
77097
75969
  );
77098
- const enumTypes = new Set(Object.values(schema5.enums).map((it) => it.name));
75970
+ const enumTypes = Object.values(schema5.enums).reduce(
75971
+ (acc, cur) => {
75972
+ acc.add(`${cur.schema}.${cur.name}`);
75973
+ return acc;
75974
+ },
75975
+ /* @__PURE__ */ new Set()
75976
+ );
77099
75977
  const imports = Object.values(schema5.tables).reduce(
77100
75978
  (res, it) => {
77101
75979
  const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
@@ -77116,11 +75994,9 @@ var init_introspect_pg = __esm({
77116
75994
  res.pg.push(...fkImpots);
77117
75995
  res.pg.push(...pkImports);
77118
75996
  res.pg.push(...uniqueImports);
77119
- if (enumTypes.size > 0) {
77120
- res.pg.push("pgEnum");
77121
- }
77122
75997
  const columnImports = Object.values(it.columns).map((col) => {
77123
- let patched = importsPatch2[col.type] || col.type;
75998
+ let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
75999
+ patched = patched === "double precision" ? "doublePrecision" : patched;
77124
76000
  patched = patched.startsWith("varchar(") ? "varchar" : patched;
77125
76001
  patched = patched.startsWith("char(") ? "char" : patched;
77126
76002
  patched = patched.startsWith("numeric(") ? "numeric" : patched;
@@ -77137,12 +76013,54 @@ var init_introspect_pg = __esm({
77137
76013
  },
77138
76014
  { pg: [] }
77139
76015
  );
76016
+ Object.values(schema5.sequences).forEach((it) => {
76017
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
76018
+ imports.pg.push("pgSchema");
76019
+ } else if (it.schema === "public") {
76020
+ imports.pg.push("pgSequence");
76021
+ }
76022
+ });
76023
+ Object.values(schema5.enums).forEach((it) => {
76024
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
76025
+ imports.pg.push("pgSchema");
76026
+ } else if (it.schema === "public") {
76027
+ imports.pg.push("pgEnum");
76028
+ }
76029
+ });
77140
76030
  const enumStatements = Object.values(schema5.enums).map((it) => {
77141
76031
  const enumSchema3 = schemas[it.schema];
77142
76032
  const paramName = paramNameFor(it.name, enumSchema3);
77143
76033
  const func = enumSchema3 ? `${enumSchema3}.enum` : "pgEnum";
77144
76034
  const values = Object.values(it.values).map((it2) => `'${it2}'`).join(", ");
77145
76035
  return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", [${values}])
76036
+ `;
76037
+ }).join("").concat("\n");
76038
+ const sequencesStatements = Object.values(schema5.sequences).map((it) => {
76039
+ const seqSchema = schemas[it.schema];
76040
+ const paramName = paramNameFor(it.name, seqSchema);
76041
+ const func = seqSchema ? `${seqSchema}.sequence` : "pgSequence";
76042
+ let params = "";
76043
+ if (it.startWith) {
76044
+ params += `, startWith: "${it.startWith}"`;
76045
+ }
76046
+ if (it.increment) {
76047
+ params += `, increment: "${it.increment}"`;
76048
+ }
76049
+ if (it.minValue) {
76050
+ params += `, minValue: "${it.minValue}"`;
76051
+ }
76052
+ if (it.maxValue) {
76053
+ params += `, maxValue: "${it.maxValue}"`;
76054
+ }
76055
+ if (it.cache) {
76056
+ params += `, cache: "${it.cache}"`;
76057
+ }
76058
+ if (it.cycle) {
76059
+ params += `, cycle: true`;
76060
+ } else {
76061
+ params += `, cycle: false`;
76062
+ }
76063
+ return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
77146
76064
  `;
77147
76065
  }).join("").concat("\n");
77148
76066
  const schemaStatements = Object.entries(schemas).map((it) => {
@@ -77165,10 +76083,7 @@ var init_introspect_pg = __esm({
77165
76083
  schema5.internal
77166
76084
  );
77167
76085
  statement += "}";
77168
- const filteredFKs = Object.values(table4.foreignKeys).filter((it) => {
77169
- return it.columnsFrom.length > 1 || isSelf3(it);
77170
- });
77171
- if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
76086
+ if (Object.keys(table4.indexes).length > 0 || Object.values(table4.foreignKeys).length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
77172
76087
  statement += ",\n";
77173
76088
  statement += "(table) => {\n";
77174
76089
  statement += " return {\n";
@@ -77177,7 +76092,7 @@ var init_introspect_pg = __esm({
77177
76092
  Object.values(table4.indexes),
77178
76093
  casing2
77179
76094
  );
77180
- statement += createTableFKs3(Object.values(filteredFKs), schemas, casing2);
76095
+ statement += createTableFKs3(Object.values(table4.foreignKeys), schemas, casing2);
77181
76096
  statement += createTablePKs3(
77182
76097
  Object.values(table4.compositePrimaryKeys),
77183
76098
  casing2
@@ -77201,6 +76116,7 @@ var init_introspect_pg = __esm({
77201
76116
  `;
77202
76117
  let decalrations = schemaStatements;
77203
76118
  decalrations += enumStatements;
76119
+ decalrations += sequencesStatements;
77204
76120
  decalrations += "\n";
77205
76121
  decalrations += tableStatements.join("\n\n");
77206
76122
  const file = importsTs + decalrations;
@@ -77219,9 +76135,120 @@ var init_introspect_pg = __esm({
77219
76135
  isSelf3 = (fk4) => {
77220
76136
  return fk4.tableFrom === fk4.tableTo;
77221
76137
  };
77222
- column6 = (tableName, type, name, enumTypes, casing2, defaultValue, internals) => {
77223
- var _a;
77224
- const lowered = type.toLowerCase();
76138
+ buildArrayDefault = (defaultValue, typeName) => {
76139
+ if (typeof defaultValue === "string" && !(defaultValue.startsWith("{") || defaultValue.startsWith("'{"))) {
76140
+ return `sql\`${defaultValue}\``;
76141
+ }
76142
+ defaultValue = defaultValue.substring(2, defaultValue.length - 2);
76143
+ return `[${defaultValue.split(/\s*,\s*/g).map((value) => {
76144
+ if (typeName === "json" || typeName === "jsonb") {
76145
+ return value.substring(1, value.length - 1).replaceAll("\\", "");
76146
+ }
76147
+ return value;
76148
+ }).join(", ")}]`;
76149
+ };
76150
+ mapDefault = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
76151
+ var _a, _b, _c, _d;
76152
+ const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
76153
+ const isArray3 = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
76154
+ const lowered = type.toLowerCase().replace("[]", "");
76155
+ if (isArray3) {
76156
+ return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault(defaultValue, lowered)})` : "";
76157
+ }
76158
+ if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
76159
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76160
+ }
76161
+ if (lowered.startsWith("integer")) {
76162
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76163
+ }
76164
+ if (lowered.startsWith("smallint")) {
76165
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76166
+ }
76167
+ if (lowered.startsWith("bigint")) {
76168
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76169
+ }
76170
+ if (lowered.startsWith("boolean")) {
76171
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76172
+ }
76173
+ if (lowered.startsWith("double precision")) {
76174
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76175
+ }
76176
+ if (lowered.startsWith("real")) {
76177
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76178
+ }
76179
+ if (lowered.startsWith("uuid")) {
76180
+ return defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
76181
+ }
76182
+ if (lowered.startsWith("numeric")) {
76183
+ defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
76184
+ return defaultValue ? `.default('${mapColumnDefault3(defaultValue, isExpression)}')` : "";
76185
+ }
76186
+ if (lowered.startsWith("timestamp")) {
76187
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_TIMESTAMP" ? ".default(sql`CURRENT_TIMESTAMP`)" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76188
+ }
76189
+ if (lowered.startsWith("time")) {
76190
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76191
+ }
76192
+ if (lowered.startsWith("interval")) {
76193
+ return defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76194
+ }
76195
+ if (lowered === "date") {
76196
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_DATE" ? `.default(sql\`${defaultValue}\`)` : defaultValue ? `.default(${defaultValue})` : "";
76197
+ }
76198
+ if (lowered.startsWith("text")) {
76199
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76200
+ }
76201
+ if (lowered.startsWith("jsonb")) {
76202
+ const def = typeof defaultValue !== "undefined" ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
76203
+ return defaultValue ? `.default(${def})` : "";
76204
+ }
76205
+ if (lowered.startsWith("json")) {
76206
+ const def = defaultValue ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
76207
+ return typeof defaultValue !== "undefined" ? `.default(${def})` : "";
76208
+ }
76209
+ if (lowered.startsWith("inet")) {
76210
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76211
+ }
76212
+ if (lowered.startsWith("cidr")) {
76213
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76214
+ }
76215
+ if (lowered.startsWith("macaddr8")) {
76216
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76217
+ }
76218
+ if (lowered.startsWith("macaddr")) {
76219
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76220
+ }
76221
+ if (lowered.startsWith("varchar")) {
76222
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76223
+ }
76224
+ if (lowered.startsWith("point")) {
76225
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76226
+ }
76227
+ if (lowered.startsWith("line")) {
76228
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76229
+ }
76230
+ if (lowered.startsWith("geometry")) {
76231
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76232
+ }
76233
+ if (lowered.startsWith("vector")) {
76234
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76235
+ }
76236
+ if (lowered.startsWith("char")) {
76237
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76238
+ }
76239
+ return "";
76240
+ };
76241
+ column6 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
76242
+ var _a, _b;
76243
+ const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
76244
+ const lowered = type.toLowerCase().replace("[]", "");
76245
+ if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
76246
+ let out = `${withCasing2(name, casing2)}: ${withCasing2(
76247
+ paramNameFor(type.replace("[]", ""), typeSchema),
76248
+ casing2
76249
+ )}("${name}")`;
76250
+ return out;
76251
+ }
77225
76252
  if (lowered.startsWith("serial")) {
77226
76253
  return `${withCasing2(name, casing2)}: serial("${name}")`;
77227
76254
  }
@@ -77236,39 +76263,32 @@ var init_introspect_pg = __esm({
77236
76263
  }
77237
76264
  if (lowered.startsWith("integer")) {
77238
76265
  let out = `${withCasing2(name, casing2)}: integer("${name}")`;
77239
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77240
76266
  return out;
77241
76267
  }
77242
76268
  if (lowered.startsWith("smallint")) {
77243
76269
  let out = `${withCasing2(name, casing2)}: smallint("${name}")`;
77244
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77245
76270
  return out;
77246
76271
  }
77247
76272
  if (lowered.startsWith("bigint")) {
77248
76273
  let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
77249
76274
  `;
77250
76275
  out += `${withCasing2(name, casing2)}: bigint("${name}", { mode: "number" })`;
77251
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77252
76276
  return out;
77253
76277
  }
77254
76278
  if (lowered.startsWith("boolean")) {
77255
76279
  let out = `${withCasing2(name, casing2)}: boolean("${name}")`;
77256
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77257
76280
  return out;
77258
76281
  }
77259
76282
  if (lowered.startsWith("double precision")) {
77260
76283
  let out = `${withCasing2(name, casing2)}: doublePrecision("${name}")`;
77261
- out += defaultValue ? `.default(${defaultValue})` : "";
77262
76284
  return out;
77263
76285
  }
77264
76286
  if (lowered.startsWith("real")) {
77265
76287
  let out = `${withCasing2(name, casing2)}: real("${name}")`;
77266
- out += defaultValue ? `.default(${defaultValue})` : "";
77267
76288
  return out;
77268
76289
  }
77269
76290
  if (lowered.startsWith("uuid")) {
77270
76291
  let out = `${withCasing2(name, casing2)}: uuid("${name}")`;
77271
- out += defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
77272
76292
  return out;
77273
76293
  }
77274
76294
  if (lowered.startsWith("numeric")) {
@@ -77278,8 +76298,6 @@ var init_introspect_pg = __esm({
77278
76298
  params = { precision, scale };
77279
76299
  }
77280
76300
  let out = params ? `${withCasing2(name, casing2)}: numeric("${name}", ${timeConfig2(params)})` : `${withCasing2(name, casing2)}: numeric("${name}")`;
77281
- defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
77282
- out += defaultValue ? `.default('${defaultValue}')` : "";
77283
76301
  return out;
77284
76302
  }
77285
76303
  if (lowered.startsWith("timestamp")) {
@@ -77294,8 +76312,6 @@ var init_introspect_pg = __esm({
77294
76312
  mode: "'string'"
77295
76313
  });
77296
76314
  let out = params ? `${withCasing2(name, casing2)}: timestamp("${name}", ${params})` : `${withCasing2(name, casing2)}: timestamp("${name}")`;
77297
- defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
77298
- out += defaultValue;
77299
76315
  return out;
77300
76316
  }
77301
76317
  if (lowered.startsWith("time")) {
@@ -77306,63 +76322,46 @@ var init_introspect_pg = __esm({
77306
76322
  precision = precision ? precision : null;
77307
76323
  const params = timeConfig2({ precision, withTimezone });
77308
76324
  let out = params ? `${withCasing2(name, casing2)}: time("${name}", ${params})` : `${withCasing2(name, casing2)}: time("${name}")`;
77309
- defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
77310
- out += defaultValue;
77311
76325
  return out;
77312
76326
  }
77313
76327
  if (lowered.startsWith("interval")) {
77314
76328
  const params = intervalConfig(lowered);
77315
76329
  let out = params ? `${withCasing2(name, casing2)}: interval("${name}", ${params})` : `${withCasing2(name, casing2)}: interval("${name}")`;
77316
- out += defaultValue ? `.default(${defaultValue})` : "";
77317
76330
  return out;
77318
76331
  }
77319
76332
  if (lowered === "date") {
77320
76333
  let out = `${withCasing2(name, casing2)}: date("${name}")`;
77321
- defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_DATE" ? `.default(sql\`${defaultValue}\`)` : defaultValue ? `.default(${defaultValue})` : "";
77322
- out += defaultValue;
77323
76334
  return out;
77324
76335
  }
77325
76336
  if (lowered.startsWith("text")) {
77326
76337
  let out = `${withCasing2(name, casing2)}: text("${name}")`;
77327
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77328
76338
  return out;
77329
76339
  }
77330
- if (lowered === "json") {
77331
- let out = `${withCasing2(name, casing2)}: json("${name}")`;
77332
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::json")) ? defaultValue.substring(1, defaultValue.length - 7) : defaultValue;
77333
- const def = defaultValue ? defaultValue : null;
77334
- out += typeof defaultValue !== "undefined" ? `.default(${def})` : "";
76340
+ if (lowered.startsWith("jsonb")) {
76341
+ let out = `${withCasing2(name, casing2)}: jsonb("${name}")`;
77335
76342
  return out;
77336
76343
  }
77337
- if (lowered === "jsonb") {
77338
- let out = `${withCasing2(name, casing2)}: jsonb("${name}")`;
77339
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::jsonb")) ? defaultValue.substring(1, defaultValue.length - 8) : defaultValue;
77340
- const def = typeof defaultValue !== "undefined" ? defaultValue : null;
77341
- out += defaultValue ? `.default(${def})` : "";
76344
+ if (lowered.startsWith("json")) {
76345
+ let out = `${withCasing2(name, casing2)}: json("${name}")`;
77342
76346
  return out;
77343
76347
  }
77344
76348
  if (lowered.startsWith("inet")) {
77345
76349
  let out = `${withCasing2(name, casing2)}: inet("${name}")`;
77346
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77347
76350
  return out;
77348
76351
  }
77349
76352
  if (lowered.startsWith("cidr")) {
77350
76353
  let out = `${withCasing2(name, casing2)}: cidr("${name}")`;
77351
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77352
- return out;
77353
- }
77354
- if (lowered.startsWith("macaddr")) {
77355
- let out = `${withCasing2(name, casing2)}: macaddr("${name}")`;
77356
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77357
76354
  return out;
77358
76355
  }
77359
76356
  if (lowered.startsWith("macaddr8")) {
77360
76357
  let out = `${withCasing2(name, casing2)}: macaddr8("${name}")`;
77361
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76358
+ return out;
76359
+ }
76360
+ if (lowered.startsWith("macaddr")) {
76361
+ let out = `${withCasing2(name, casing2)}: macaddr("${name}")`;
77362
76362
  return out;
77363
76363
  }
77364
76364
  if (lowered.startsWith("varchar")) {
77365
- const split = lowered.split(" ");
77366
76365
  let out;
77367
76366
  if (lowered.length !== 7) {
77368
76367
  out = `${withCasing2(
@@ -77375,17 +76374,14 @@ var init_introspect_pg = __esm({
77375
76374
  } else {
77376
76375
  out = `${withCasing2(name, casing2)}: varchar("${name}")`;
77377
76376
  }
77378
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77379
76377
  return out;
77380
76378
  }
77381
76379
  if (lowered.startsWith("point")) {
77382
76380
  let out = `${withCasing2(name, casing2)}: point("${name}")`;
77383
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77384
76381
  return out;
77385
76382
  }
77386
76383
  if (lowered.startsWith("line")) {
77387
76384
  let out = `${withCasing2(name, casing2)}: point("${name}")`;
77388
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77389
76385
  return out;
77390
76386
  }
77391
76387
  if (lowered.startsWith("geometry")) {
@@ -77403,7 +76399,6 @@ var init_introspect_pg = __esm({
77403
76399
  } else {
77404
76400
  out = `${withCasing2(name, casing2)}: geometry("${name}")`;
77405
76401
  }
77406
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77407
76402
  if (isGeoUnknown) {
77408
76403
  let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
77409
76404
  // Introspect is currently supporting only type and srid options
@@ -77414,7 +76409,6 @@ var init_introspect_pg = __esm({
77414
76409
  return out;
77415
76410
  }
77416
76411
  if (lowered.startsWith("vector")) {
77417
- const split = lowered.split(" ");
77418
76412
  let out;
77419
76413
  if (lowered.length !== 6) {
77420
76414
  out = `${withCasing2(
@@ -77427,7 +76421,6 @@ var init_introspect_pg = __esm({
77427
76421
  } else {
77428
76422
  out = `${withCasing2(name, casing2)}: vector("${name}")`;
77429
76423
  }
77430
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77431
76424
  return out;
77432
76425
  }
77433
76426
  if (lowered.startsWith("char")) {
@@ -77443,26 +76436,6 @@ var init_introspect_pg = __esm({
77443
76436
  } else {
77444
76437
  out = `${withCasing2(name, casing2)}: char("${name}")`;
77445
76438
  }
77446
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77447
- return out;
77448
- }
77449
- const columnInternals = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name];
77450
- if (typeof columnInternals !== "undefined") {
77451
- if (columnInternals.isArray && columnInternals.rawType && enumTypes.has(columnInternals.rawType)) {
77452
- let out = `${withCasing2(columnInternals.rawType, casing2)}: ${withCasing2(
77453
- columnInternals.rawType,
77454
- casing2
77455
- )}("${name}")`;
77456
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77457
- return out;
77458
- }
77459
- }
77460
- if (enumTypes.has(type)) {
77461
- let out = `${withCasing2(name, casing2)}: ${withCasing2(
77462
- type,
77463
- casing2
77464
- )}("${name}")`;
77465
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
77466
76439
  return out;
77467
76440
  }
77468
76441
  let unknown = `// TODO: failed to parse database type '${type}'
@@ -77497,6 +76470,7 @@ var init_introspect_pg = __esm({
77497
76470
  it.type,
77498
76471
  it.name,
77499
76472
  enumTypes,
76473
+ it.typeSchema ?? "public",
77500
76474
  casing2,
77501
76475
  it.default,
77502
76476
  internals
@@ -77508,59 +76482,19 @@ var init_introspect_pg = __esm({
77508
76482
  (_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions
77509
76483
  );
77510
76484
  }
76485
+ statement += mapDefault(
76486
+ tableName,
76487
+ it.type,
76488
+ it.name,
76489
+ enumTypes,
76490
+ it.typeSchema ?? "public",
76491
+ it.default,
76492
+ internals
76493
+ );
77511
76494
  statement += it.primaryKey ? ".primaryKey()" : "";
77512
76495
  statement += it.notNull && !it.identity ? ".notNull()" : "";
77513
- function generateIdentityParams(identity) {
77514
- let paramsObj = `{ name: "${identity.name}"`;
77515
- if (identity == null ? void 0 : identity.startWith) {
77516
- paramsObj += `, startWith: ${identity.startWith}`;
77517
- }
77518
- if (identity == null ? void 0 : identity.increment) {
77519
- paramsObj += `, increment: ${identity.increment}`;
77520
- }
77521
- if (identity == null ? void 0 : identity.minValue) {
77522
- paramsObj += `, minValue: ${identity.minValue}`;
77523
- }
77524
- if (identity == null ? void 0 : identity.maxValue) {
77525
- paramsObj += `, maxValue: ${identity.maxValue}`;
77526
- }
77527
- if (identity == null ? void 0 : identity.cache) {
77528
- paramsObj += `, cache: ${identity.cache}`;
77529
- }
77530
- if (identity == null ? void 0 : identity.cycle) {
77531
- paramsObj += `, cycle: true`;
77532
- }
77533
- paramsObj += " }";
77534
- if ((identity == null ? void 0 : identity.type) === "always") {
77535
- return `.generatedAlwaysAsIdentity(${paramsObj})`;
77536
- }
77537
- return `.generatedByDefaultAsIdentity(${paramsObj})`;
77538
- }
77539
76496
  statement += it.identity ? generateIdentityParams(it.identity) : "";
77540
76497
  statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
77541
- const fks2 = fkByColumnName[it.name];
77542
- if (fks2) {
77543
- const fksStatement = fks2.map((it2) => {
77544
- const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
77545
- const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
77546
- const params = { onDelete, onUpdate };
77547
- const typeSuffix = isCyclic3(it2) ? ": AnyPgColumn" : "";
77548
- const paramsStr = objToStatement23(params);
77549
- const tableSchema = schemas[it2.schemaTo || ""];
77550
- const paramName = paramNameFor(it2.tableTo, tableSchema);
77551
- if (paramsStr) {
77552
- return `.references(()${typeSuffix} => ${withCasing2(
77553
- paramName,
77554
- casing2
77555
- )}.${withCasing2(it2.columnsTo[0], casing2)}, ${paramsStr} )`;
77556
- }
77557
- return `.references(()${typeSuffix} => ${withCasing2(
77558
- paramName,
77559
- casing2
77560
- )}.${withCasing2(it2.columnsTo[0], casing2)})`;
77561
- }).join("");
77562
- statement += fksStatement;
77563
- }
77564
76498
  statement += ",\n";
77565
76499
  });
77566
76500
  return statement;
@@ -77584,7 +76518,7 @@ var init_introspect_pg = __esm({
77584
76518
  if (it2.isExpression) {
77585
76519
  return `sql\`${it2.expression}\``;
77586
76520
  } else {
77587
- return `table.${withCasing2(it2.expression, casing2)}${it2.opclass && vectorOps.includes(it2.opclass) ? `.op("${it2.opclass}")` : ""}`;
76521
+ return `table.${withCasing2(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass && vectorOps.includes(it2.opclass) ? `.op("${it2.opclass}")` : ""}`;
77588
76522
  }
77589
76523
  }).join(", ")})`;
77590
76524
  statement += it.where ? `.where(sql\`${it.where}\`)` : "";
@@ -84330,7 +83264,7 @@ var push = command({
84330
83264
  schemasFilter,
84331
83265
  force
84332
83266
  );
84333
- } else if (dialect7 === "sqlite" && !("driver" in credentials2)) {
83267
+ } else if (dialect7 === "sqlite") {
84334
83268
  const { sqlitePush: sqlitePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
84335
83269
  await sqlitePush2(
84336
83270
  schemaPath,
@@ -84340,16 +83274,6 @@ var push = command({
84340
83274
  tablesFilter,
84341
83275
  force
84342
83276
  );
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
- );
84353
83277
  } else {
84354
83278
  assertUnreachable(dialect7);
84355
83279
  }
@@ -84633,7 +83557,7 @@ init_utils2();
84633
83557
  var version2 = async () => {
84634
83558
  const { npmVersion } = await ormCoreVersions();
84635
83559
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
84636
- const envVersion = "0.24.0-38d6dab";
83560
+ const envVersion = "0.24.0-5df8253";
84637
83561
  const kitVersion = envVersion ? `v${envVersion}` : "--";
84638
83562
  const versions = `drizzle-kit: ${kitVersion}
84639
83563
  ${ormVersion}`;