drizzle-kit 0.25.0-22c3e40 → 0.25.0-503ee01

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 +801 -0
  2. package/api.d.ts +801 -0
  3. package/api.js +2504 -385
  4. package/api.mjs +2504 -385
  5. package/bin.cjs +2613 -432
  6. package/package.json +1 -1
  7. package/utils.js +105 -18
  8. package/utils.mjs +105 -18
package/api.js CHANGED
@@ -562,7 +562,7 @@ function is(value, type) {
562
562
  `Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
563
563
  );
564
564
  }
565
- let cls = value.constructor;
565
+ let cls = Object.getPrototypeOf(value).constructor;
566
566
  if (cls) {
567
567
  while (cls) {
568
568
  if (entityKind in cls && cls[entityKind] === type[entityKind]) {
@@ -3410,8 +3410,8 @@ var require_hanji = __commonJS({
3410
3410
  };
3411
3411
  exports2.deferred = deferred;
3412
3412
  var Terminal = class {
3413
- constructor(view, stdin, stdout, closable) {
3414
- this.view = view;
3413
+ constructor(view4, stdin, stdout, closable) {
3414
+ this.view = view4;
3415
3415
  this.stdin = stdin;
3416
3416
  this.stdout = stdout;
3417
3417
  this.closable = closable;
@@ -3449,7 +3449,7 @@ var require_hanji = __commonJS({
3449
3449
  this.resolve({ status: "submitted", data: this.view.result() });
3450
3450
  return;
3451
3451
  }
3452
- view.input(str, key);
3452
+ view4.input(str, key);
3453
3453
  };
3454
3454
  this.stdin.on("keypress", keypress);
3455
3455
  this.view.attach(this);
@@ -3511,8 +3511,8 @@ var require_hanji = __commonJS({
3511
3511
  };
3512
3512
  exports2.TaskView = TaskView2;
3513
3513
  var TaskTerminal = class {
3514
- constructor(view, stdout) {
3515
- this.view = view;
3514
+ constructor(view4, stdout) {
3515
+ this.view = view4;
3516
3516
  this.stdout = stdout;
3517
3517
  this.text = "";
3518
3518
  this.view.attach(this);
@@ -3531,22 +3531,22 @@ var require_hanji = __commonJS({
3531
3531
  }
3532
3532
  };
3533
3533
  exports2.TaskTerminal = TaskTerminal;
3534
- function render6(view) {
3534
+ function render6(view4) {
3535
3535
  const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
3536
- if (view instanceof Prompt3) {
3537
- const terminal = new Terminal(view, stdin, stdout, closable);
3536
+ if (view4 instanceof Prompt3) {
3537
+ const terminal = new Terminal(view4, stdin, stdout, closable);
3538
3538
  terminal.requestLayout();
3539
3539
  return terminal.result();
3540
3540
  }
3541
- stdout.write(`${view}
3541
+ stdout.write(`${view4}
3542
3542
  `);
3543
3543
  closable.close();
3544
3544
  return;
3545
3545
  }
3546
3546
  exports2.render = render6;
3547
- function renderWithTask4(view, task) {
3547
+ function renderWithTask4(view4, task) {
3548
3548
  return __awaiter(this, void 0, void 0, function* () {
3549
- const terminal = new TaskTerminal(view, process.stdout);
3549
+ const terminal = new TaskTerminal(view4, process.stdout);
3550
3550
  terminal.requestLayout();
3551
3551
  const result = yield task;
3552
3552
  terminal.clear();
@@ -5873,8 +5873,8 @@ var init_lib = __esm({
5873
5873
  unknownKeys: "strict",
5874
5874
  ...message !== void 0 ? {
5875
5875
  errorMap: (issue, ctx) => {
5876
- var _a324, _b233, _c12, _d5;
5877
- const defaultError = (_c12 = (_b233 = (_a324 = this._def).errorMap) === null || _b233 === void 0 ? void 0 : _b233.call(_a324, issue, ctx).message) !== null && _c12 !== void 0 ? _c12 : ctx.defaultError;
5876
+ var _a324, _b233, _c11, _d5;
5877
+ const defaultError = (_c11 = (_b233 = (_a324 = this._def).errorMap) === null || _b233 === void 0 ? void 0 : _b233.call(_a324, issue, ctx).message) !== null && _c11 !== void 0 ? _c11 : ctx.defaultError;
5878
5878
  if (issue.code === "unrecognized_keys")
5879
5879
  return {
5880
5880
  message: (_d5 = errorUtil.errToObj(message).message) !== null && _d5 !== void 0 ? _d5 : defaultError
@@ -7376,7 +7376,7 @@ var init_lib = __esm({
7376
7376
  });
7377
7377
 
7378
7378
  // src/serializer/mysqlSchema.ts
7379
- var index, fk, column, tableV3, compositePK, uniqueConstraint, tableV4, table, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
7379
+ var index, fk, column, tableV3, compositePK, uniqueConstraint, checkConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
7380
7380
  var init_mysqlSchema = __esm({
7381
7381
  "src/serializer/mysqlSchema.ts"() {
7382
7382
  "use strict";
@@ -7426,6 +7426,10 @@ var init_mysqlSchema = __esm({
7426
7426
  name: stringType(),
7427
7427
  columns: stringType().array()
7428
7428
  }).strict();
7429
+ checkConstraint = objectType({
7430
+ name: stringType(),
7431
+ value: stringType()
7432
+ }).strict();
7429
7433
  tableV4 = objectType({
7430
7434
  name: stringType(),
7431
7435
  schema: stringType().optional(),
@@ -7439,8 +7443,20 @@ var init_mysqlSchema = __esm({
7439
7443
  indexes: recordType(stringType(), index),
7440
7444
  foreignKeys: recordType(stringType(), fk),
7441
7445
  compositePrimaryKeys: recordType(stringType(), compositePK),
7442
- uniqueConstraints: recordType(stringType(), uniqueConstraint).default({})
7446
+ uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
7447
+ checkConstraint: recordType(stringType(), checkConstraint).default({})
7448
+ }).strict();
7449
+ viewMeta = objectType({
7450
+ algorithm: enumType(["undefined", "merge", "temptable"]),
7451
+ sqlSecurity: enumType(["definer", "invoker"]),
7452
+ withCheckOption: enumType(["local", "cascaded"]).optional()
7443
7453
  }).strict();
7454
+ view = objectType({
7455
+ name: stringType(),
7456
+ columns: recordType(stringType(), column),
7457
+ definition: stringType().optional(),
7458
+ isExisting: booleanType()
7459
+ }).strict().merge(viewMeta);
7444
7460
  kitInternals = objectType({
7445
7461
  tables: recordType(
7446
7462
  stringType(),
@@ -7493,6 +7509,7 @@ var init_mysqlSchema = __esm({
7493
7509
  version: literalType("5"),
7494
7510
  dialect,
7495
7511
  tables: recordType(stringType(), table),
7512
+ views: recordType(stringType(), view),
7496
7513
  _meta: objectType({
7497
7514
  tables: recordType(stringType(), stringType()),
7498
7515
  columns: recordType(stringType(), stringType())
@@ -7516,12 +7533,19 @@ var init_mysqlSchema = __esm({
7516
7533
  indexes: recordType(stringType(), stringType()),
7517
7534
  foreignKeys: recordType(stringType(), stringType()),
7518
7535
  compositePrimaryKeys: recordType(stringType(), stringType()),
7519
- uniqueConstraints: recordType(stringType(), stringType()).default({})
7536
+ uniqueConstraints: recordType(stringType(), stringType()).default({}),
7537
+ checkConstraints: recordType(stringType(), stringType()).default({})
7520
7538
  }).strict();
7539
+ viewSquashed = view.omit({
7540
+ algorithm: true,
7541
+ sqlSecurity: true,
7542
+ withCheckOption: true
7543
+ }).extend({ meta: stringType() });
7521
7544
  schemaSquashed = objectType({
7522
7545
  version: literalType("5"),
7523
7546
  dialect,
7524
- tables: recordType(stringType(), tableSquashed)
7547
+ tables: recordType(stringType(), tableSquashed),
7548
+ views: recordType(stringType(), viewSquashed)
7525
7549
  }).strict();
7526
7550
  schemaSquashedV4 = objectType({
7527
7551
  version: literalType("4"),
@@ -7583,6 +7607,25 @@ var init_mysqlSchema = __esm({
7583
7607
  onDelete
7584
7608
  });
7585
7609
  return result;
7610
+ },
7611
+ squashCheck: (input) => {
7612
+ return `${input.name};${input.value}`;
7613
+ },
7614
+ unsquashCheck: (input) => {
7615
+ const [name2, value] = input.split(";");
7616
+ return { name: name2, value };
7617
+ },
7618
+ squashView: (view4) => {
7619
+ return `${view4.algorithm};${view4.sqlSecurity};${view4.withCheckOption}`;
7620
+ },
7621
+ unsquashView: (meta) => {
7622
+ const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
7623
+ const toReturn = {
7624
+ algorithm,
7625
+ sqlSecurity,
7626
+ withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
7627
+ };
7628
+ return viewMeta.parse(toReturn);
7586
7629
  }
7587
7630
  };
7588
7631
  squashMysqlScheme = (json3) => {
@@ -7603,6 +7646,9 @@ var init_mysqlSchema = __esm({
7603
7646
  return MySqlSquasher.squashUnique(unq);
7604
7647
  }
7605
7648
  );
7649
+ const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check) => {
7650
+ return MySqlSquasher.squashCheck(check);
7651
+ });
7606
7652
  return [
7607
7653
  it[0],
7608
7654
  {
@@ -7611,15 +7657,29 @@ var init_mysqlSchema = __esm({
7611
7657
  indexes: squashedIndexes,
7612
7658
  foreignKeys: squashedFKs,
7613
7659
  compositePrimaryKeys: squashedPKs,
7614
- uniqueConstraints: squashedUniqueConstraints
7660
+ uniqueConstraints: squashedUniqueConstraints,
7661
+ checkConstraints: squashedCheckConstraints
7615
7662
  }
7616
7663
  ];
7617
7664
  })
7618
7665
  );
7666
+ const mappedViews = Object.fromEntries(
7667
+ Object.entries(json3.views).map(([key, value]) => {
7668
+ const meta = MySqlSquasher.squashView(value);
7669
+ return [key, {
7670
+ name: value.name,
7671
+ isExisting: value.isExisting,
7672
+ columns: value.columns,
7673
+ definition: value.definition,
7674
+ meta
7675
+ }];
7676
+ })
7677
+ );
7619
7678
  return {
7620
7679
  version: "5",
7621
7680
  dialect: json3.dialect,
7622
- tables: mappedTables
7681
+ tables: mappedTables,
7682
+ views: mappedViews
7623
7683
  };
7624
7684
  };
7625
7685
  mysqlSchema = schema;
@@ -7633,6 +7693,7 @@ var init_mysqlSchema = __esm({
7633
7693
  prevId: "",
7634
7694
  tables: {},
7635
7695
  schemas: {},
7696
+ views: {},
7636
7697
  _meta: {
7637
7698
  schemas: {},
7638
7699
  tables: {},
@@ -7661,7 +7722,7 @@ var init_vector = __esm({
7661
7722
  });
7662
7723
 
7663
7724
  // src/serializer/pgSchema.ts
7664
- 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;
7725
+ var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, viewWithOption, matViewWithOption, mergedViewWithOption, view2, 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;
7665
7726
  var init_pgSchema = __esm({
7666
7727
  "src/serializer/pgSchema.ts"() {
7667
7728
  "use strict";
@@ -7825,6 +7886,10 @@ var init_pgSchema = __esm({
7825
7886
  }).optional(),
7826
7887
  identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
7827
7888
  }).strict();
7889
+ checkConstraint2 = objectType({
7890
+ name: stringType(),
7891
+ value: stringType()
7892
+ }).strict();
7828
7893
  columnSquashed = objectType({
7829
7894
  name: stringType(),
7830
7895
  type: stringType(),
@@ -7856,6 +7921,44 @@ var init_pgSchema = __esm({
7856
7921
  columns: stringType().array(),
7857
7922
  nullsNotDistinct: booleanType()
7858
7923
  }).strict();
7924
+ viewWithOption = objectType({
7925
+ checkOption: enumType(["local", "cascaded"]).optional(),
7926
+ securityBarrier: booleanType().optional(),
7927
+ securityInvoker: booleanType().optional()
7928
+ }).strict();
7929
+ matViewWithOption = objectType({
7930
+ fillfactor: numberType().optional(),
7931
+ toastTupleTarget: numberType().optional(),
7932
+ parallelWorkers: numberType().optional(),
7933
+ autovacuumEnabled: booleanType().optional(),
7934
+ vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
7935
+ vacuumTruncate: booleanType().optional(),
7936
+ autovacuumVacuumThreshold: numberType().optional(),
7937
+ autovacuumVacuumScaleFactor: numberType().optional(),
7938
+ autovacuumVacuumCostDelay: numberType().optional(),
7939
+ autovacuumVacuumCostLimit: numberType().optional(),
7940
+ autovacuumFreezeMinAge: numberType().optional(),
7941
+ autovacuumFreezeMaxAge: numberType().optional(),
7942
+ autovacuumFreezeTableAge: numberType().optional(),
7943
+ autovacuumMultixactFreezeMinAge: numberType().optional(),
7944
+ autovacuumMultixactFreezeMaxAge: numberType().optional(),
7945
+ autovacuumMultixactFreezeTableAge: numberType().optional(),
7946
+ logAutovacuumMinDuration: numberType().optional(),
7947
+ userCatalogTable: booleanType().optional()
7948
+ }).strict();
7949
+ mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
7950
+ view2 = objectType({
7951
+ name: stringType(),
7952
+ schema: stringType(),
7953
+ columns: recordType(stringType(), column2),
7954
+ definition: stringType().optional(),
7955
+ materialized: booleanType(),
7956
+ with: mergedViewWithOption.optional(),
7957
+ isExisting: booleanType(),
7958
+ withNoData: booleanType().optional(),
7959
+ using: stringType().optional(),
7960
+ tablespace: stringType().optional()
7961
+ }).strict();
7859
7962
  tableV42 = objectType({
7860
7963
  name: stringType(),
7861
7964
  schema: stringType(),
@@ -7897,7 +8000,8 @@ var init_pgSchema = __esm({
7897
8000
  indexes: recordType(stringType(), index2),
7898
8001
  foreignKeys: recordType(stringType(), fk2),
7899
8002
  compositePrimaryKeys: recordType(stringType(), compositePK2),
7900
- uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
8003
+ uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
8004
+ checkConstraints: recordType(stringType(), checkConstraint2).default({})
7901
8005
  }).strict();
7902
8006
  schemaHash2 = objectType({
7903
8007
  id: stringType(),
@@ -7990,6 +8094,7 @@ var init_pgSchema = __esm({
7990
8094
  tables: recordType(stringType(), table2),
7991
8095
  enums: recordType(stringType(), enumSchema),
7992
8096
  schemas: recordType(stringType(), stringType()),
8097
+ views: recordType(stringType(), view2).default({}),
7993
8098
  sequences: recordType(stringType(), sequenceSchema).default({}),
7994
8099
  _meta: objectType({
7995
8100
  schemas: recordType(stringType(), stringType()),
@@ -8005,7 +8110,8 @@ var init_pgSchema = __esm({
8005
8110
  indexes: recordType(stringType(), stringType()),
8006
8111
  foreignKeys: recordType(stringType(), stringType()),
8007
8112
  compositePrimaryKeys: recordType(stringType(), stringType()),
8008
- uniqueConstraints: recordType(stringType(), stringType())
8113
+ uniqueConstraints: recordType(stringType(), stringType()),
8114
+ checkConstraints: recordType(stringType(), stringType())
8009
8115
  }).strict();
8010
8116
  tableSquashedV42 = objectType({
8011
8117
  name: stringType(),
@@ -8034,6 +8140,7 @@ var init_pgSchema = __esm({
8034
8140
  tables: recordType(stringType(), tableSquashed2),
8035
8141
  enums: recordType(stringType(), enumSchema),
8036
8142
  schemas: recordType(stringType(), stringType()),
8143
+ views: recordType(stringType(), view2),
8037
8144
  sequences: recordType(stringType(), sequenceSquashed)
8038
8145
  }).strict();
8039
8146
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
@@ -8187,6 +8294,16 @@ var init_pgSchema = __esm({
8187
8294
  cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
8188
8295
  cycle: splitted[7] === "true"
8189
8296
  };
8297
+ },
8298
+ squashCheck: (check) => {
8299
+ return `${check.name};${check.value}`;
8300
+ },
8301
+ unsquashCheck: (input) => {
8302
+ const [
8303
+ name2,
8304
+ value
8305
+ ] = input.split(";");
8306
+ return { name: name2, value };
8190
8307
  }
8191
8308
  };
8192
8309
  squashPgScheme = (json3, action) => {
@@ -8219,6 +8336,12 @@ var init_pgSchema = __esm({
8219
8336
  return PgSquasher.squashUnique(unq);
8220
8337
  }
8221
8338
  );
8339
+ const squashedChecksContraints = mapValues(
8340
+ it[1].checkConstraints,
8341
+ (check) => {
8342
+ return PgSquasher.squashCheck(check);
8343
+ }
8344
+ );
8222
8345
  return [
8223
8346
  it[0],
8224
8347
  {
@@ -8228,7 +8351,8 @@ var init_pgSchema = __esm({
8228
8351
  indexes: squashedIndexes,
8229
8352
  foreignKeys: squashedFKs,
8230
8353
  compositePrimaryKeys: squashedPKs,
8231
- uniqueConstraints: squashedUniqueConstraints
8354
+ uniqueConstraints: squashedUniqueConstraints,
8355
+ checkConstraints: squashedChecksContraints
8232
8356
  }
8233
8357
  ];
8234
8358
  })
@@ -8251,6 +8375,7 @@ var init_pgSchema = __esm({
8251
8375
  tables: mappedTables,
8252
8376
  enums: json3.enums,
8253
8377
  schemas: json3.schemas,
8378
+ views: json3.views,
8254
8379
  sequences: mappedSequences
8255
8380
  };
8256
8381
  };
@@ -8273,7 +8398,7 @@ var init_pgSchema = __esm({
8273
8398
  });
8274
8399
 
8275
8400
  // src/serializer/sqliteSchema.ts
8276
- var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, table3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema2, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
8401
+ var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, checkConstraint3, table3, view3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema2, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
8277
8402
  var init_sqliteSchema = __esm({
8278
8403
  "src/serializer/sqliteSchema.ts"() {
8279
8404
  "use strict";
@@ -8320,13 +8445,24 @@ var init_sqliteSchema = __esm({
8320
8445
  name: stringType(),
8321
8446
  columns: stringType().array()
8322
8447
  }).strict();
8448
+ checkConstraint3 = objectType({
8449
+ name: stringType(),
8450
+ value: stringType()
8451
+ }).strict();
8323
8452
  table3 = objectType({
8324
8453
  name: stringType(),
8325
8454
  columns: recordType(stringType(), column3),
8326
8455
  indexes: recordType(stringType(), index3),
8327
8456
  foreignKeys: recordType(stringType(), fk3),
8328
8457
  compositePrimaryKeys: recordType(stringType(), compositePK3),
8329
- uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
8458
+ uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
8459
+ checkConstraints: recordType(stringType(), checkConstraint3).default({})
8460
+ }).strict();
8461
+ view3 = objectType({
8462
+ name: stringType(),
8463
+ columns: recordType(stringType(), column3),
8464
+ definition: stringType().optional(),
8465
+ isExisting: booleanType()
8330
8466
  }).strict();
8331
8467
  dialect2 = enumType(["sqlite"]);
8332
8468
  schemaHash3 = objectType({
@@ -8343,6 +8479,7 @@ var init_sqliteSchema = __esm({
8343
8479
  version: literalType("4"),
8344
8480
  dialect: dialect2,
8345
8481
  tables: recordType(stringType(), table3),
8482
+ views: recordType(stringType(), view3),
8346
8483
  enums: objectType({})
8347
8484
  }).strict();
8348
8485
  schemaInternalV52 = objectType({
@@ -8371,6 +8508,7 @@ var init_sqliteSchema = __esm({
8371
8508
  version: latestVersion,
8372
8509
  dialect: dialect2,
8373
8510
  tables: recordType(stringType(), table3),
8511
+ views: recordType(stringType(), view3),
8374
8512
  enums: objectType({}),
8375
8513
  _meta: objectType({
8376
8514
  tables: recordType(stringType(), stringType()),
@@ -8388,12 +8526,14 @@ var init_sqliteSchema = __esm({
8388
8526
  indexes: recordType(stringType(), stringType()),
8389
8527
  foreignKeys: recordType(stringType(), stringType()),
8390
8528
  compositePrimaryKeys: recordType(stringType(), stringType()),
8391
- uniqueConstraints: recordType(stringType(), stringType()).default({})
8529
+ uniqueConstraints: recordType(stringType(), stringType()).default({}),
8530
+ checkConstraints: recordType(stringType(), stringType()).default({})
8392
8531
  }).strict();
8393
8532
  schemaSquashed2 = objectType({
8394
8533
  version: latestVersion,
8395
8534
  dialect: dialect2,
8396
8535
  tables: recordType(stringType(), tableSquashed3),
8536
+ views: recordType(stringType(), view3),
8397
8537
  enums: anyType()
8398
8538
  }).strict();
8399
8539
  SQLiteSquasher = {
@@ -8470,6 +8610,16 @@ var init_sqliteSchema = __esm({
8470
8610
  },
8471
8611
  unsquashPK: (pk) => {
8472
8612
  return pk.split(",");
8613
+ },
8614
+ squashCheck: (check) => {
8615
+ return `${check.name};${check.value}`;
8616
+ },
8617
+ unsquashCheck: (input) => {
8618
+ const [
8619
+ name2,
8620
+ value
8621
+ ] = input.split(";");
8622
+ return { name: name2, value };
8473
8623
  }
8474
8624
  };
8475
8625
  squashSqliteScheme = (json3, action) => {
@@ -8496,6 +8646,12 @@ var init_sqliteSchema = __esm({
8496
8646
  return SQLiteSquasher.squashUnique(unq);
8497
8647
  }
8498
8648
  );
8649
+ const squashedCheckConstraints = mapValues(
8650
+ it[1].checkConstraints,
8651
+ (check) => {
8652
+ return SQLiteSquasher.squashCheck(check);
8653
+ }
8654
+ );
8499
8655
  return [
8500
8656
  it[0],
8501
8657
  {
@@ -8504,7 +8660,8 @@ var init_sqliteSchema = __esm({
8504
8660
  indexes: squashedIndexes,
8505
8661
  foreignKeys: squashedFKs,
8506
8662
  compositePrimaryKeys: squashedPKs,
8507
- uniqueConstraints: squashedUniqueConstraints
8663
+ uniqueConstraints: squashedUniqueConstraints,
8664
+ checkConstraints: squashedCheckConstraints
8508
8665
  }
8509
8666
  ];
8510
8667
  })
@@ -8513,6 +8670,7 @@ var init_sqliteSchema = __esm({
8513
8670
  version: "6",
8514
8671
  dialect: json3.dialect,
8515
8672
  tables: mappedTables,
8673
+ views: json3.views,
8516
8674
  enums: json3.enums
8517
8675
  };
8518
8676
  };
@@ -8522,6 +8680,7 @@ var init_sqliteSchema = __esm({
8522
8680
  id: originUUID,
8523
8681
  prevId: "",
8524
8682
  tables: {},
8683
+ views: {},
8525
8684
  enums: {},
8526
8685
  _meta: {
8527
8686
  tables: {},
@@ -11217,6 +11376,7 @@ function applyJsonDiff(json1, json22) {
11217
11376
  difference.tables = difference.tables || {};
11218
11377
  difference.enums = difference.enums || {};
11219
11378
  difference.sequences = difference.sequences || {};
11379
+ difference.views = difference.views || {};
11220
11380
  const schemaKeys = Object.keys(difference.schemas);
11221
11381
  for (let key of schemaKeys) {
11222
11382
  if (key.endsWith("__added") || key.endsWith("__deleted")) {
@@ -11272,6 +11432,70 @@ function applyJsonDiff(json1, json22) {
11272
11432
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
11273
11433
  return json22.sequences[it[0]];
11274
11434
  });
11435
+ const viewsEntries = Object.entries(difference.views);
11436
+ const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
11437
+ ([nameWithSchema, view4]) => {
11438
+ const deletedWithOption = view4.with__deleted;
11439
+ const addedWithOption = view4.with__added;
11440
+ const deletedWith = Object.fromEntries(
11441
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
11442
+ return [key.replace("__deleted", ""), value];
11443
+ })
11444
+ );
11445
+ const addedWith = Object.fromEntries(
11446
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
11447
+ return [key.replace("__added", ""), value];
11448
+ })
11449
+ );
11450
+ const alterWith = Object.fromEntries(
11451
+ Object.entries(view4.with || {}).filter(
11452
+ (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
11453
+ ).map(
11454
+ (it) => {
11455
+ return [it[0], it[1].__new];
11456
+ }
11457
+ )
11458
+ );
11459
+ const alteredSchema = view4.schema;
11460
+ const alteredDefinition = view4.definition;
11461
+ const alteredExisting = view4.isExisting;
11462
+ const addedTablespace = view4.tablespace__added;
11463
+ const droppedTablespace = view4.tablespace__deleted;
11464
+ const alterTablespaceTo = view4.tablespace;
11465
+ let alteredTablespace;
11466
+ if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
11467
+ if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
11468
+ if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
11469
+ const addedUsing = view4.using__added;
11470
+ const droppedUsing = view4.using__deleted;
11471
+ const alterUsingTo = view4.using;
11472
+ let alteredUsing;
11473
+ if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
11474
+ if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
11475
+ if (alterUsingTo) alteredUsing = alterUsingTo;
11476
+ const alteredMeta = view4.meta;
11477
+ return Object.fromEntries(
11478
+ Object.entries({
11479
+ name: json22.views[nameWithSchema].name,
11480
+ schema: json22.views[nameWithSchema].schema,
11481
+ // pg
11482
+ deletedWithOption,
11483
+ addedWithOption,
11484
+ deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
11485
+ addedWith: Object.keys(addedWith).length ? addedWith : void 0,
11486
+ alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
11487
+ alteredSchema,
11488
+ alteredTablespace,
11489
+ alteredUsing,
11490
+ // mysql
11491
+ alteredMeta,
11492
+ // common
11493
+ alteredDefinition,
11494
+ alteredExisting
11495
+ }).filter(([_2, value]) => value !== void 0)
11496
+ );
11497
+ }
11498
+ );
11275
11499
  const alteredTablesWithColumns = Object.values(difference.tables).map(
11276
11500
  (table4) => {
11277
11501
  return findAlternationsInTable(table4);
@@ -11280,7 +11504,8 @@ function applyJsonDiff(json1, json22) {
11280
11504
  return {
11281
11505
  alteredTablesWithColumns,
11282
11506
  alteredEnums,
11283
- alteredSequences
11507
+ alteredSequences,
11508
+ alteredViews
11284
11509
  };
11285
11510
  }
11286
11511
  var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
@@ -11385,6 +11610,21 @@ var init_jsonDiffer = __esm({
11385
11610
  return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
11386
11611
  })
11387
11612
  );
11613
+ const addedCheckConstraints = Object.fromEntries(
11614
+ Object.entries(table4.checkConstraints || {}).filter((it) => {
11615
+ return it[0].endsWith("__added");
11616
+ })
11617
+ );
11618
+ const deletedCheckConstraints = Object.fromEntries(
11619
+ Object.entries(table4.checkConstraints || {}).filter((it) => {
11620
+ return it[0].endsWith("__deleted");
11621
+ })
11622
+ );
11623
+ const alteredCheckConstraints = Object.fromEntries(
11624
+ Object.entries(table4.checkConstraints || {}).filter((it) => {
11625
+ return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
11626
+ })
11627
+ );
11388
11628
  const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
11389
11629
  return {
11390
11630
  name: table4.name,
@@ -11401,7 +11641,10 @@ var init_jsonDiffer = __esm({
11401
11641
  alteredCompositePKs,
11402
11642
  addedUniqueConstraints,
11403
11643
  deletedUniqueConstraints,
11404
- alteredUniqueConstraints
11644
+ alteredUniqueConstraints,
11645
+ addedCheckConstraints,
11646
+ deletedCheckConstraints,
11647
+ alteredCheckConstraints
11405
11648
  };
11406
11649
  };
11407
11650
  alternationsInColumn = (column4) => {
@@ -11655,6 +11898,32 @@ var init_jsonDiffer = __esm({
11655
11898
  };
11656
11899
  }
11657
11900
  return it;
11901
+ }).map((it) => {
11902
+ if ("" in it) {
11903
+ return {
11904
+ ...it,
11905
+ autoincrement: {
11906
+ type: "changed",
11907
+ old: it.autoincrement.__old,
11908
+ new: it.autoincrement.__new
11909
+ }
11910
+ };
11911
+ }
11912
+ if ("autoincrement__added" in it) {
11913
+ const { autoincrement__added, ...others } = it;
11914
+ return {
11915
+ ...others,
11916
+ autoincrement: { type: "added", value: it.autoincrement__added }
11917
+ };
11918
+ }
11919
+ if ("autoincrement__deleted" in it) {
11920
+ const { autoincrement__deleted, ...others } = it;
11921
+ return {
11922
+ ...others,
11923
+ autoincrement: { type: "deleted", value: it.autoincrement__deleted }
11924
+ };
11925
+ }
11926
+ return it;
11658
11927
  }).filter(Boolean);
11659
11928
  return result[0];
11660
11929
  };
@@ -11675,7 +11944,7 @@ function fromJson(statements, dialect4, action, json22) {
11675
11944
  }).filter((it) => it !== "");
11676
11945
  return result;
11677
11946
  }
11678
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
11947
+ var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
11679
11948
  var init_sqlgenerator = __esm({
11680
11949
  "src/sqlgenerator.ts"() {
11681
11950
  "use strict";
@@ -11736,7 +12005,7 @@ var init_sqlgenerator = __esm({
11736
12005
  return statement.type === "create_table" && dialect4 === "postgresql";
11737
12006
  }
11738
12007
  convert(st) {
11739
- const { tableName, schema: schema4, columns, compositePKs, uniqueConstraints } = st;
12008
+ const { tableName, schema: schema4, columns, compositePKs, uniqueConstraints, checkConstraints } = st;
11740
12009
  let statement = "";
11741
12010
  const name2 = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
11742
12011
  statement += `CREATE TABLE IF NOT EXISTS ${name2} (
@@ -11769,6 +12038,13 @@ var init_sqlgenerator = __esm({
11769
12038
  statement += ` CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
11770
12039
  }
11771
12040
  }
12041
+ if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
12042
+ for (const checkConstraint4 of checkConstraints) {
12043
+ statement += ",\n";
12044
+ const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint4);
12045
+ statement += ` CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
12046
+ }
12047
+ }
11772
12048
  statement += `
11773
12049
  );`;
11774
12050
  statement += `
@@ -11785,6 +12061,7 @@ var init_sqlgenerator = __esm({
11785
12061
  tableName,
11786
12062
  columns,
11787
12063
  schema: schema4,
12064
+ checkConstraints,
11788
12065
  compositePKs,
11789
12066
  uniqueConstraints,
11790
12067
  internals
@@ -11818,6 +12095,13 @@ var init_sqlgenerator = __esm({
11818
12095
  statement += ` CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
11819
12096
  }
11820
12097
  }
12098
+ if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
12099
+ for (const checkConstraint4 of checkConstraints) {
12100
+ statement += ",\n";
12101
+ const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint4);
12102
+ statement += ` CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`;
12103
+ }
12104
+ }
11821
12105
  statement += `
11822
12106
  );`;
11823
12107
  statement += `
@@ -11835,7 +12119,8 @@ var init_sqlgenerator = __esm({
11835
12119
  columns,
11836
12120
  referenceData,
11837
12121
  compositePKs,
11838
- uniqueConstraints
12122
+ uniqueConstraints,
12123
+ checkConstraints
11839
12124
  } = st;
11840
12125
  let statement = "";
11841
12126
  statement += `CREATE TABLE \`${tableName}\` (
@@ -11876,10 +12161,17 @@ var init_sqlgenerator = __esm({
11876
12161
  if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
11877
12162
  for (const uniqueConstraint4 of uniqueConstraints) {
11878
12163
  statement += ",\n";
11879
- const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint4);
12164
+ const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint4);
11880
12165
  statement += ` CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
11881
12166
  }
11882
12167
  }
12168
+ if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
12169
+ for (const check of checkConstraints) {
12170
+ statement += ",\n";
12171
+ const { value, name: name2 } = SQLiteSquasher.unsquashCheck(check);
12172
+ statement += ` CONSTRAINT "${name2}" CHECK(${value})`;
12173
+ }
12174
+ }
11883
12175
  statement += `
11884
12176
  `;
11885
12177
  statement += `);`;
@@ -11888,6 +12180,187 @@ var init_sqlgenerator = __esm({
11888
12180
  return statement;
11889
12181
  }
11890
12182
  };
12183
+ PgCreateViewConvertor = class extends Convertor {
12184
+ can(statement, dialect4) {
12185
+ return statement.type === "create_view" && dialect4 === "postgresql";
12186
+ }
12187
+ convert(st) {
12188
+ const { definition, name: viewName, schema: schema4, with: withOption, materialized, withNoData, tablespace, using } = st;
12189
+ const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
12190
+ let statement = materialized ? `CREATE MATERIALIZED VIEW ${name2}` : `CREATE VIEW ${name2}`;
12191
+ if (using) statement += ` USING "${using}"`;
12192
+ const options = [];
12193
+ if (withOption) {
12194
+ statement += ` WITH (`;
12195
+ Object.entries(withOption).forEach(([key, value]) => {
12196
+ if (typeof value === "undefined") return;
12197
+ options.push(`${key.snake_case()} = ${value}`);
12198
+ });
12199
+ statement += options.join(", ");
12200
+ statement += `)`;
12201
+ }
12202
+ if (tablespace) statement += ` TABLESPACE ${tablespace}`;
12203
+ statement += ` AS (${definition})`;
12204
+ if (withNoData) statement += ` WITH NO DATA`;
12205
+ statement += `;`;
12206
+ return statement;
12207
+ }
12208
+ };
12209
+ MySqlCreateViewConvertor = class extends Convertor {
12210
+ can(statement, dialect4) {
12211
+ return statement.type === "mysql_create_view" && dialect4 === "mysql";
12212
+ }
12213
+ convert(st) {
12214
+ const { definition, name: name2, algorithm, sqlSecurity, withCheckOption, replace } = st;
12215
+ let statement = `CREATE `;
12216
+ statement += replace ? `OR REPLACE ` : "";
12217
+ statement += algorithm ? `ALGORITHM = ${algorithm}
12218
+ ` : "";
12219
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
12220
+ ` : "";
12221
+ statement += `VIEW \`${name2}\` AS (${definition})`;
12222
+ statement += withCheckOption ? `
12223
+ WITH ${withCheckOption} CHECK OPTION` : "";
12224
+ statement += ";";
12225
+ return statement;
12226
+ }
12227
+ };
12228
+ SqliteCreateViewConvertor = class extends Convertor {
12229
+ can(statement, dialect4) {
12230
+ return statement.type === "sqlite_create_view" && (dialect4 === "sqlite" || dialect4 === "turso");
12231
+ }
12232
+ convert(st) {
12233
+ const { definition, name: name2 } = st;
12234
+ return `CREATE VIEW \`${name2}\` AS ${definition};`;
12235
+ }
12236
+ };
12237
+ PgDropViewConvertor = class extends Convertor {
12238
+ can(statement, dialect4) {
12239
+ return statement.type === "drop_view" && dialect4 === "postgresql";
12240
+ }
12241
+ convert(st) {
12242
+ const { name: viewName, schema: schema4, materialized } = st;
12243
+ const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
12244
+ return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name2};`;
12245
+ }
12246
+ };
12247
+ MySqlDropViewConvertor = class extends Convertor {
12248
+ can(statement, dialect4) {
12249
+ return statement.type === "drop_view" && dialect4 === "mysql";
12250
+ }
12251
+ convert(st) {
12252
+ const { name: name2 } = st;
12253
+ return `DROP VIEW \`${name2}\`;`;
12254
+ }
12255
+ };
12256
+ SqliteDropViewConvertor = class extends Convertor {
12257
+ can(statement, dialect4) {
12258
+ return statement.type === "drop_view" && (dialect4 === "sqlite" || dialect4 === "turso");
12259
+ }
12260
+ convert(st) {
12261
+ const { name: name2 } = st;
12262
+ return `DROP VIEW \`${name2}\`;`;
12263
+ }
12264
+ };
12265
+ MySqlAlterViewConvertor = class extends Convertor {
12266
+ can(statement, dialect4) {
12267
+ return statement.type === "alter_mysql_view" && dialect4 === "mysql";
12268
+ }
12269
+ convert(st) {
12270
+ const { name: name2, algorithm, definition, sqlSecurity, withCheckOption } = st;
12271
+ let statement = `ALTER `;
12272
+ statement += algorithm ? `ALGORITHM = ${algorithm}
12273
+ ` : "";
12274
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
12275
+ ` : "";
12276
+ statement += `VIEW \`${name2}\` AS ${definition}`;
12277
+ statement += withCheckOption ? `
12278
+ WITH ${withCheckOption} CHECK OPTION` : "";
12279
+ statement += ";";
12280
+ return statement;
12281
+ }
12282
+ };
12283
+ PgRenameViewConvertor = class extends Convertor {
12284
+ can(statement, dialect4) {
12285
+ return statement.type === "rename_view" && dialect4 === "postgresql";
12286
+ }
12287
+ convert(st) {
12288
+ const { nameFrom: from, nameTo: to, schema: schema4, materialized } = st;
12289
+ const nameFrom = `"${schema4}"."${from}"`;
12290
+ return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
12291
+ }
12292
+ };
12293
+ MySqlRenameViewConvertor = class extends Convertor {
12294
+ can(statement, dialect4) {
12295
+ return statement.type === "rename_view" && dialect4 === "mysql";
12296
+ }
12297
+ convert(st) {
12298
+ const { nameFrom: from, nameTo: to } = st;
12299
+ return `RENAME TABLE \`${from}\` RENAME TO \`${to}\`;`;
12300
+ }
12301
+ };
12302
+ PgAlterViewSchemaConvertor = class extends Convertor {
12303
+ can(statement, dialect4) {
12304
+ return statement.type === "alter_view_alter_schema" && dialect4 === "postgresql";
12305
+ }
12306
+ convert(st) {
12307
+ const { fromSchema, toSchema, name: name2, materialized } = st;
12308
+ const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name2}" SET SCHEMA "${toSchema}";`;
12309
+ return statement;
12310
+ }
12311
+ };
12312
+ PgAlterViewAddWithOptionConvertor = class extends Convertor {
12313
+ can(statement, dialect4) {
12314
+ return statement.type === "alter_view_add_with_option" && dialect4 === "postgresql";
12315
+ }
12316
+ convert(st) {
12317
+ const { schema: schema4, with: withOption, name: name2, materialized } = st;
12318
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${name2}" SET (`;
12319
+ const options = [];
12320
+ Object.entries(withOption).forEach(([key, value]) => {
12321
+ options.push(`${key.snake_case()} = ${value}`);
12322
+ });
12323
+ statement += options.join(", ");
12324
+ statement += `);`;
12325
+ return statement;
12326
+ }
12327
+ };
12328
+ PgAlterViewDropWithOptionConvertor = class extends Convertor {
12329
+ can(statement, dialect4) {
12330
+ return statement.type === "alter_view_drop_with_option" && dialect4 === "postgresql";
12331
+ }
12332
+ convert(st) {
12333
+ const { schema: schema4, name: name2, materialized, with: withOptions } = st;
12334
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${name2}" RESET (`;
12335
+ const options = [];
12336
+ Object.entries(withOptions).forEach(([key, value]) => {
12337
+ options.push(`${key.snake_case()}`);
12338
+ });
12339
+ statement += options.join(", ");
12340
+ statement += ");";
12341
+ return statement;
12342
+ }
12343
+ };
12344
+ PgAlterViewAlterTablespaceConvertor = class extends Convertor {
12345
+ can(statement, dialect4) {
12346
+ return statement.type === "alter_view_alter_tablespace" && dialect4 === "postgresql";
12347
+ }
12348
+ convert(st) {
12349
+ const { schema: schema4, name: name2, toTablespace } = st;
12350
+ const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET TABLESPACE ${toTablespace};`;
12351
+ return statement;
12352
+ }
12353
+ };
12354
+ PgAlterViewAlterUsingConvertor = class extends Convertor {
12355
+ can(statement, dialect4) {
12356
+ return statement.type === "alter_view_alter_using" && dialect4 === "postgresql";
12357
+ }
12358
+ convert(st) {
12359
+ const { schema: schema4, name: name2, toUsing } = st;
12360
+ const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET ACCESS METHOD "${toUsing}";`;
12361
+ return statement;
12362
+ }
12363
+ };
11891
12364
  PgAlterTableAlterColumnSetGenerated = class extends Convertor {
11892
12365
  can(statement, dialect4) {
11893
12366
  return statement.type === "alter_table_alter_column_set_identity" && dialect4 === "postgresql";
@@ -11979,6 +12452,25 @@ var init_sqlgenerator = __esm({
11979
12452
  return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`;
11980
12453
  }
11981
12454
  };
12455
+ PgAlterTableAddCheckConstraintConvertor = class extends Convertor {
12456
+ can(statement, dialect4) {
12457
+ return statement.type === "create_check_constraint" && dialect4 === "postgresql";
12458
+ }
12459
+ convert(statement) {
12460
+ const unsquashed = PgSquasher.unsquashCheck(statement.data);
12461
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
12462
+ return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`;
12463
+ }
12464
+ };
12465
+ PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
12466
+ can(statement, dialect4) {
12467
+ return statement.type === "delete_check_constraint" && dialect4 === "postgresql";
12468
+ }
12469
+ convert(statement) {
12470
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
12471
+ return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
12472
+ }
12473
+ };
11982
12474
  MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor {
11983
12475
  can(statement, dialect4) {
11984
12476
  return statement.type === "create_unique_constraint" && dialect4 === "mysql";
@@ -11997,6 +12489,25 @@ var init_sqlgenerator = __esm({
11997
12489
  return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
11998
12490
  }
11999
12491
  };
12492
+ MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
12493
+ can(statement, dialect4) {
12494
+ return statement.type === "create_check_constraint" && dialect4 === "mysql";
12495
+ }
12496
+ convert(statement) {
12497
+ const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
12498
+ const { tableName } = statement;
12499
+ return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
12500
+ }
12501
+ };
12502
+ MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
12503
+ can(statement, dialect4) {
12504
+ return statement.type === "delete_check_constraint" && dialect4 === "mysql";
12505
+ }
12506
+ convert(statement) {
12507
+ const { tableName } = statement;
12508
+ return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
12509
+ }
12510
+ };
12000
12511
  CreatePgSequenceConvertor = class extends Convertor {
12001
12512
  can(statement, dialect4) {
12002
12513
  return statement.type === "create_sequence" && dialect4 === "postgresql";
@@ -12600,7 +13111,7 @@ var init_sqlgenerator = __esm({
12600
13111
  };
12601
13112
  LibSQLModifyColumn = class extends Convertor {
12602
13113
  can(statement, dialect4) {
12603
- 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") && dialect4 === "turso";
13114
+ 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" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect4 === "turso";
12604
13115
  }
12605
13116
  convert(statement, json22) {
12606
13117
  const { tableName, columnName } = statement;
@@ -13187,18 +13698,22 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13187
13698
  return statement.type === "recreate_table" && dialect4 === "sqlite";
13188
13699
  }
13189
13700
  convert(statement) {
13190
- const { tableName, columns, compositePKs, referenceData } = statement;
13701
+ const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
13191
13702
  const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
13192
13703
  const newTableName = `__new_${tableName}`;
13193
13704
  const sqlStatements = [];
13194
13705
  sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
13706
+ const mappedCheckConstraints = checkConstraints.map(
13707
+ (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
13708
+ );
13195
13709
  sqlStatements.push(
13196
13710
  new SQLiteCreateTableConvertor().convert({
13197
13711
  type: "sqlite_create_table",
13198
13712
  tableName: newTableName,
13199
13713
  columns,
13200
13714
  referenceData,
13201
- compositePKs
13715
+ compositePKs,
13716
+ checkConstraints: mappedCheckConstraints
13202
13717
  })
13203
13718
  );
13204
13719
  sqlStatements.push(
@@ -13229,10 +13744,13 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13229
13744
  return statement.type === "recreate_table" && dialect4 === "turso";
13230
13745
  }
13231
13746
  convert(statement) {
13232
- const { tableName, columns, compositePKs, referenceData } = statement;
13747
+ const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
13233
13748
  const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
13234
13749
  const newTableName = `__new_${tableName}`;
13235
13750
  const sqlStatements = [];
13751
+ const mappedCheckConstraints = checkConstraints.map(
13752
+ (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
13753
+ );
13236
13754
  sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
13237
13755
  sqlStatements.push(
13238
13756
  new SQLiteCreateTableConvertor().convert({
@@ -13240,7 +13758,8 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13240
13758
  tableName: newTableName,
13241
13759
  columns,
13242
13760
  referenceData,
13243
- compositePKs
13761
+ compositePKs,
13762
+ checkConstraints: mappedCheckConstraints
13244
13763
  })
13245
13764
  );
13246
13765
  sqlStatements.push(
@@ -13272,6 +13791,20 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13272
13791
  convertors.push(new SQLiteCreateTableConvertor());
13273
13792
  convertors.push(new SQLiteRecreateTableConvertor());
13274
13793
  convertors.push(new LibSQLRecreateTableConvertor());
13794
+ convertors.push(new PgCreateViewConvertor());
13795
+ convertors.push(new PgDropViewConvertor());
13796
+ convertors.push(new PgRenameViewConvertor());
13797
+ convertors.push(new PgAlterViewSchemaConvertor());
13798
+ convertors.push(new PgAlterViewAddWithOptionConvertor());
13799
+ convertors.push(new PgAlterViewDropWithOptionConvertor());
13800
+ convertors.push(new PgAlterViewAlterTablespaceConvertor());
13801
+ convertors.push(new PgAlterViewAlterUsingConvertor());
13802
+ convertors.push(new MySqlCreateViewConvertor());
13803
+ convertors.push(new MySqlDropViewConvertor());
13804
+ convertors.push(new MySqlRenameViewConvertor());
13805
+ convertors.push(new MySqlAlterViewConvertor());
13806
+ convertors.push(new SqliteCreateViewConvertor());
13807
+ convertors.push(new SqliteDropViewConvertor());
13275
13808
  convertors.push(new CreateTypeEnumConvertor());
13276
13809
  convertors.push(new DropTypeEnumConvertor());
13277
13810
  convertors.push(new AlterTypeAddValueConvertor());
@@ -13301,6 +13834,10 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13301
13834
  convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
13302
13835
  convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
13303
13836
  convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
13837
+ convertors.push(new PgAlterTableAddCheckConstraintConvertor());
13838
+ convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
13839
+ convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
13840
+ convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
13304
13841
  convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
13305
13842
  convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
13306
13843
  convertors.push(new CreatePgIndexConvertor());
@@ -13390,6 +13927,10 @@ var init_sqlitePushUtils = __esm({
13390
13927
  const compositePKs = Object.values(
13391
13928
  json3.tables[tableName].compositePrimaryKeys
13392
13929
  ).map((it) => SQLiteSquasher.unsquashPK(it));
13930
+ const checkConstraints = Object.values(json3.tables[tableName].checkConstraints);
13931
+ const mappedCheckConstraints = checkConstraints.map(
13932
+ (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
13933
+ );
13393
13934
  const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
13394
13935
  statements.push(
13395
13936
  new SQLiteCreateTableConvertor().convert({
@@ -13397,7 +13938,8 @@ var init_sqlitePushUtils = __esm({
13397
13938
  tableName: newTableName,
13398
13939
  columns: tableColumns,
13399
13940
  referenceData: fks,
13400
- compositePKs
13941
+ compositePKs,
13942
+ checkConstraints: mappedCheckConstraints
13401
13943
  })
13402
13944
  );
13403
13945
  if (!dataLoss) {
@@ -13609,7 +14151,7 @@ var init_sqlitePushUtils = __esm({
13609
14151
  });
13610
14152
 
13611
14153
  // src/jsonStatements.ts
13612
- var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, 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;
14154
+ var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, 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, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
13613
14155
  var init_jsonStatements = __esm({
13614
14156
  "src/jsonStatements.ts"() {
13615
14157
  "use strict";
@@ -13620,7 +14162,7 @@ var init_jsonStatements = __esm({
13620
14162
  init_pgSchema();
13621
14163
  init_sqliteSchema();
13622
14164
  preparePgCreateTableJson = (table4, json22) => {
13623
- const { name: name2, schema: schema4, columns, compositePrimaryKeys, uniqueConstraints } = table4;
14165
+ const { name: name2, schema: schema4, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table4;
13624
14166
  const tableKey2 = `${schema4 || "public"}.${name2}`;
13625
14167
  const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json22.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
13626
14168
  return {
@@ -13630,11 +14172,12 @@ var init_jsonStatements = __esm({
13630
14172
  columns: Object.values(columns),
13631
14173
  compositePKs: Object.values(compositePrimaryKeys),
13632
14174
  compositePkName,
13633
- uniqueConstraints: Object.values(uniqueConstraints)
14175
+ uniqueConstraints: Object.values(uniqueConstraints),
14176
+ checkConstraints: Object.values(checkConstraints)
13634
14177
  };
13635
14178
  };
13636
14179
  prepareMySqlCreateTableJson = (table4, json22, internals) => {
13637
- const { name: name2, schema: schema4, columns, compositePrimaryKeys, uniqueConstraints } = table4;
14180
+ const { name: name2, schema: schema4, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table4;
13638
14181
  return {
13639
14182
  type: "create_table",
13640
14183
  tableName: name2,
@@ -13643,11 +14186,12 @@ var init_jsonStatements = __esm({
13643
14186
  compositePKs: Object.values(compositePrimaryKeys),
13644
14187
  compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json22.tables[name2].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
13645
14188
  uniqueConstraints: Object.values(uniqueConstraints),
13646
- internals
14189
+ internals,
14190
+ checkConstraints: Object.values(checkConstraints)
13647
14191
  };
13648
14192
  };
13649
14193
  prepareSQLiteCreateTable = (table4, action) => {
13650
- const { name: name2, columns, uniqueConstraints } = table4;
14194
+ const { name: name2, columns, uniqueConstraints, checkConstraints } = table4;
13651
14195
  const references2 = Object.values(table4.foreignKeys);
13652
14196
  const composites = Object.values(table4.compositePrimaryKeys).map(
13653
14197
  (it) => SQLiteSquasher.unsquashPK(it)
@@ -13661,7 +14205,8 @@ var init_jsonStatements = __esm({
13661
14205
  columns: Object.values(columns),
13662
14206
  referenceData: fks,
13663
14207
  compositePKs: composites,
13664
- uniqueConstraints: Object.values(uniqueConstraints)
14208
+ uniqueConstraints: Object.values(uniqueConstraints),
14209
+ checkConstraints: Object.values(checkConstraints)
13665
14210
  };
13666
14211
  };
13667
14212
  prepareDropTableJson = (table4) => {
@@ -14925,6 +15470,26 @@ var init_jsonStatements = __esm({
14925
15470
  };
14926
15471
  });
14927
15472
  };
15473
+ prepareAddCheckConstraint = (tableName, schema4, check) => {
15474
+ return Object.values(check).map((it) => {
15475
+ return {
15476
+ type: "create_check_constraint",
15477
+ tableName,
15478
+ data: it,
15479
+ schema: schema4
15480
+ };
15481
+ });
15482
+ };
15483
+ prepareDeleteCheckConstraint = (tableName, schema4, check) => {
15484
+ return Object.values(check).map((it) => {
15485
+ return {
15486
+ type: "delete_check_constraint",
15487
+ tableName,
15488
+ constraintName: PgSquasher.unsquashCheck(it).name,
15489
+ schema: schema4
15490
+ };
15491
+ });
15492
+ };
14928
15493
  prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json22) => {
14929
15494
  const res = [];
14930
15495
  for (const it of Object.values(pks)) {
@@ -14963,6 +15528,103 @@ var init_jsonStatements = __esm({
14963
15528
  };
14964
15529
  });
14965
15530
  };
15531
+ preparePgCreateViewJson = (name2, schema4, definition, materialized, withNoData = false, withOption, using, tablespace) => {
15532
+ return {
15533
+ type: "create_view",
15534
+ name: name2,
15535
+ schema: schema4,
15536
+ definition,
15537
+ with: withOption,
15538
+ materialized,
15539
+ withNoData,
15540
+ using,
15541
+ tablespace
15542
+ };
15543
+ };
15544
+ prepareMySqlCreateViewJson = (name2, definition, meta, replace = false) => {
15545
+ const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
15546
+ return {
15547
+ type: "mysql_create_view",
15548
+ name: name2,
15549
+ definition,
15550
+ algorithm,
15551
+ sqlSecurity,
15552
+ withCheckOption,
15553
+ replace
15554
+ };
15555
+ };
15556
+ prepareSqliteCreateViewJson = (name2, definition) => {
15557
+ return {
15558
+ type: "sqlite_create_view",
15559
+ name: name2,
15560
+ definition
15561
+ };
15562
+ };
15563
+ prepareDropViewJson = (name2, schema4, materialized) => {
15564
+ const resObject = { name: name2, type: "drop_view" };
15565
+ if (schema4) resObject["schema"] = schema4;
15566
+ if (materialized) resObject["materialized"] = materialized;
15567
+ return resObject;
15568
+ };
15569
+ prepareRenameViewJson = (to, from, schema4, materialized) => {
15570
+ const resObject = {
15571
+ type: "rename_view",
15572
+ nameTo: to,
15573
+ nameFrom: from
15574
+ };
15575
+ if (schema4) resObject["schema"] = schema4;
15576
+ if (materialized) resObject["materialized"] = materialized;
15577
+ return resObject;
15578
+ };
15579
+ preparePgAlterViewAlterSchemaJson = (to, from, name2, materialized) => {
15580
+ const returnObject = {
15581
+ type: "alter_view_alter_schema",
15582
+ fromSchema: from,
15583
+ toSchema: to,
15584
+ name: name2
15585
+ };
15586
+ if (materialized) returnObject["materialized"] = materialized;
15587
+ return returnObject;
15588
+ };
15589
+ preparePgAlterViewAddWithOptionJson = (name2, schema4, materialized, withOption) => {
15590
+ return {
15591
+ type: "alter_view_add_with_option",
15592
+ name: name2,
15593
+ schema: schema4,
15594
+ materialized,
15595
+ with: withOption
15596
+ };
15597
+ };
15598
+ preparePgAlterViewDropWithOptionJson = (name2, schema4, materialized, withOption) => {
15599
+ return {
15600
+ type: "alter_view_drop_with_option",
15601
+ name: name2,
15602
+ schema: schema4,
15603
+ materialized,
15604
+ with: withOption
15605
+ };
15606
+ };
15607
+ preparePgAlterViewAlterTablespaceJson = (name2, schema4, materialized, to) => {
15608
+ return {
15609
+ type: "alter_view_alter_tablespace",
15610
+ name: name2,
15611
+ schema: schema4,
15612
+ materialized,
15613
+ toTablespace: to
15614
+ };
15615
+ };
15616
+ preparePgAlterViewAlterUsingJson = (name2, schema4, materialized, to) => {
15617
+ return {
15618
+ type: "alter_view_alter_using",
15619
+ name: name2,
15620
+ schema: schema4,
15621
+ materialized,
15622
+ toUsing: to
15623
+ };
15624
+ };
15625
+ prepareMySqlAlterView = (view4) => {
15626
+ return { type: "alter_mysql_view", ...view4 };
15627
+ };
14966
15628
  }
14967
15629
  });
14968
15630
 
@@ -14974,7 +15636,7 @@ var init_statementCombiner = __esm({
14974
15636
  init_jsonStatements();
14975
15637
  init_sqliteSchema();
14976
15638
  prepareLibSQLRecreateTable = (table4, action) => {
14977
- const { name: name2, columns, uniqueConstraints, indexes } = table4;
15639
+ const { name: name2, columns, uniqueConstraints, indexes, checkConstraints } = table4;
14978
15640
  const composites = Object.values(table4.compositePrimaryKeys).map(
14979
15641
  (it) => SQLiteSquasher.unsquashPK(it)
14980
15642
  );
@@ -14989,7 +15651,8 @@ var init_statementCombiner = __esm({
14989
15651
  columns: Object.values(columns),
14990
15652
  compositePKs: composites,
14991
15653
  referenceData: fks,
14992
- uniqueConstraints: Object.values(uniqueConstraints)
15654
+ uniqueConstraints: Object.values(uniqueConstraints),
15655
+ checkConstraints: Object.values(checkConstraints)
14993
15656
  }
14994
15657
  ];
14995
15658
  if (Object.keys(indexes).length) {
@@ -14998,7 +15661,7 @@ var init_statementCombiner = __esm({
14998
15661
  return statements;
14999
15662
  };
15000
15663
  prepareSQLiteRecreateTable = (table4, action) => {
15001
- const { name: name2, columns, uniqueConstraints, indexes } = table4;
15664
+ const { name: name2, columns, uniqueConstraints, indexes, checkConstraints } = table4;
15002
15665
  const composites = Object.values(table4.compositePrimaryKeys).map(
15003
15666
  (it) => SQLiteSquasher.unsquashPK(it)
15004
15667
  );
@@ -15013,7 +15676,8 @@ var init_statementCombiner = __esm({
15013
15676
  columns: Object.values(columns),
15014
15677
  compositePKs: composites,
15015
15678
  referenceData: fks,
15016
- uniqueConstraints: Object.values(uniqueConstraints)
15679
+ uniqueConstraints: Object.values(uniqueConstraints),
15680
+ checkConstraints: Object.values(checkConstraints)
15017
15681
  }
15018
15682
  ];
15019
15683
  if (Object.keys(indexes).length) {
@@ -15024,7 +15688,7 @@ var init_statementCombiner = __esm({
15024
15688
  libSQLCombineStatements = (statements, json22, action) => {
15025
15689
  const newStatements = {};
15026
15690
  for (const statement of statements) {
15027
- 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") {
15691
+ 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" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
15028
15692
  const tableName2 = statement.tableName;
15029
15693
  const statementsForTable2 = newStatements[tableName2];
15030
15694
  if (!statementsForTable2) {
@@ -15165,16 +15829,16 @@ var init_statementCombiner = __esm({
15165
15829
  sqliteCombineStatements = (statements, json22, action) => {
15166
15830
  const newStatements = {};
15167
15831
  for (const statement of statements) {
15168
- 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") {
15832
+ 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" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
15169
15833
  const tableName2 = statement.tableName;
15170
15834
  const statementsForTable2 = newStatements[tableName2];
15171
15835
  if (!statementsForTable2) {
15172
- newStatements[tableName2] = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
15836
+ newStatements[tableName2] = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
15173
15837
  continue;
15174
15838
  }
15175
15839
  if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
15176
15840
  const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
15177
- const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
15841
+ const preparedStatements = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
15178
15842
  if (wasRename) {
15179
15843
  newStatements[tableName2].push(...preparedStatements);
15180
15844
  } else {
@@ -15188,12 +15852,12 @@ var init_statementCombiner = __esm({
15188
15852
  const tableName2 = statement.tableName;
15189
15853
  const statementsForTable2 = newStatements[tableName2];
15190
15854
  if (!statementsForTable2) {
15191
- newStatements[tableName2] = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
15855
+ newStatements[tableName2] = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
15192
15856
  continue;
15193
15857
  }
15194
15858
  if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
15195
15859
  const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
15196
- const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
15860
+ const preparedStatements = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
15197
15861
  if (wasRename) {
15198
15862
  newStatements[tableName2].push(...preparedStatements);
15199
15863
  } else {
@@ -15218,7 +15882,7 @@ var init_statementCombiner = __esm({
15218
15882
  }
15219
15883
  if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
15220
15884
  const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
15221
- const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
15885
+ const preparedStatements = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
15222
15886
  if (wasRename) {
15223
15887
  newStatements[tableName2].push(...preparedStatements);
15224
15888
  } else {
@@ -15250,6 +15914,7 @@ var init_statementCombiner = __esm({
15250
15914
  // src/snapshotsDiffer.ts
15251
15915
  var snapshotsDiffer_exports = {};
15252
15916
  __export(snapshotsDiffer_exports, {
15917
+ alteredPgViewSchema: () => alteredPgViewSchema,
15253
15918
  alteredTableScheme: () => alteredTableScheme,
15254
15919
  applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff,
15255
15920
  applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff,
@@ -15261,7 +15926,7 @@ __export(snapshotsDiffer_exports, {
15261
15926
  makePatched: () => makePatched,
15262
15927
  makeSelfOrPatched: () => makeSelfOrPatched
15263
15928
  });
15264
- var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
15929
+ var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
15265
15930
  var init_snapshotsDiffer = __esm({
15266
15931
  "src/snapshotsDiffer.ts"() {
15267
15932
  "use strict";
@@ -15387,7 +16052,8 @@ var init_snapshotsDiffer = __esm({
15387
16052
  indexes: recordType(stringType(), stringType()),
15388
16053
  foreignKeys: recordType(stringType(), stringType()),
15389
16054
  compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
15390
- uniqueConstraints: recordType(stringType(), stringType()).default({})
16055
+ uniqueConstraints: recordType(stringType(), stringType()).default({}),
16056
+ checkConstraints: recordType(stringType(), stringType()).default({})
15391
16057
  }).strict();
15392
16058
  alteredTableScheme = objectType({
15393
16059
  name: stringType(),
@@ -15428,20 +16094,79 @@ var init_snapshotsDiffer = __esm({
15428
16094
  __new: stringType(),
15429
16095
  __old: stringType()
15430
16096
  })
16097
+ ),
16098
+ addedCheckConstraints: recordType(
16099
+ stringType(),
16100
+ stringType()
16101
+ ),
16102
+ deletedCheckConstraints: recordType(
16103
+ stringType(),
16104
+ stringType()
16105
+ ),
16106
+ alteredCheckConstraints: recordType(
16107
+ stringType(),
16108
+ objectType({
16109
+ __new: stringType(),
16110
+ __old: stringType()
16111
+ })
15431
16112
  )
15432
16113
  }).strict();
16114
+ alteredViewCommon = objectType({
16115
+ name: stringType(),
16116
+ alteredDefinition: objectType({
16117
+ __old: stringType(),
16118
+ __new: stringType()
16119
+ }).strict().optional(),
16120
+ alteredExisting: objectType({
16121
+ __old: booleanType(),
16122
+ __new: booleanType()
16123
+ }).strict().optional()
16124
+ });
16125
+ alteredPgViewSchema = alteredViewCommon.merge(
16126
+ objectType({
16127
+ schema: stringType(),
16128
+ deletedWithOption: mergedViewWithOption.optional(),
16129
+ addedWithOption: mergedViewWithOption.optional(),
16130
+ addedWith: mergedViewWithOption.optional(),
16131
+ deletedWith: mergedViewWithOption.optional(),
16132
+ alteredWith: mergedViewWithOption.optional(),
16133
+ alteredSchema: objectType({
16134
+ __old: stringType(),
16135
+ __new: stringType()
16136
+ }).strict().optional(),
16137
+ alteredTablespace: objectType({
16138
+ __old: stringType(),
16139
+ __new: stringType()
16140
+ }).strict().optional(),
16141
+ alteredUsing: objectType({
16142
+ __old: stringType(),
16143
+ __new: stringType()
16144
+ }).strict().optional()
16145
+ }).strict()
16146
+ );
16147
+ alteredMySqlViewSchema = alteredViewCommon.merge(
16148
+ objectType({
16149
+ alteredMeta: objectType({
16150
+ __old: stringType(),
16151
+ __new: stringType()
16152
+ }).strict().optional()
16153
+ }).strict()
16154
+ );
15433
16155
  diffResultScheme = objectType({
15434
16156
  alteredTablesWithColumns: alteredTableScheme.array(),
15435
16157
  alteredEnums: changedEnumSchema.array(),
15436
- alteredSequences: sequenceSquashed.array()
16158
+ alteredSequences: sequenceSquashed.array(),
16159
+ alteredViews: alteredPgViewSchema.array()
15437
16160
  }).strict();
15438
16161
  diffResultSchemeMysql = objectType({
15439
16162
  alteredTablesWithColumns: alteredTableScheme.array(),
15440
- alteredEnums: neverType().array()
16163
+ alteredEnums: neverType().array(),
16164
+ alteredViews: alteredMySqlViewSchema.array()
15441
16165
  });
15442
16166
  diffResultSchemeSQLite = objectType({
15443
16167
  alteredTablesWithColumns: alteredTableScheme.array(),
15444
- alteredEnums: neverType().array()
16168
+ alteredEnums: neverType().array(),
16169
+ alteredViews: alteredViewCommon.array()
15445
16170
  });
15446
16171
  schemaChangeFor = (table4, renamedSchemas) => {
15447
16172
  for (let ren of renamedSchemas) {
@@ -15488,7 +16213,7 @@ var init_snapshotsDiffer = __esm({
15488
16213
  }
15489
16214
  return column4;
15490
16215
  };
15491
- applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
16216
+ applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
15492
16217
  const schemasDiff = diffSchemasOrTables(json1.schemas, json22.schemas);
15493
16218
  const {
15494
16219
  created: createdSchemas,
@@ -15716,7 +16441,39 @@ var init_snapshotsDiffer = __esm({
15716
16441
  return [tableKey2, tableValue];
15717
16442
  }
15718
16443
  );
15719
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
16444
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
16445
+ const {
16446
+ created: createdViews,
16447
+ deleted: deletedViews,
16448
+ renamed: renamedViews,
16449
+ moved: movedViews
16450
+ } = await viewsResolver2({
16451
+ created: viewsDiff.added,
16452
+ deleted: viewsDiff.deleted
16453
+ });
16454
+ const renamesViewDic = {};
16455
+ renamedViews.forEach((it) => {
16456
+ renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
16457
+ });
16458
+ const movedViewDic = {};
16459
+ movedViews.forEach((it) => {
16460
+ movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
16461
+ });
16462
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
16463
+ viewsPatchedSnap1.views = mapEntries(
16464
+ viewsPatchedSnap1.views,
16465
+ (viewKey, viewValue) => {
16466
+ const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
16467
+ const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
16468
+ if (rename) {
16469
+ viewValue.name = rename.to;
16470
+ viewKey = `${viewValue.schema}.${viewValue.name}`;
16471
+ }
16472
+ if (moved) viewKey = `${moved.to}.${viewValue.name}`;
16473
+ return [viewKey, viewValue];
16474
+ }
16475
+ );
16476
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
15720
16477
  const typedResult = diffResultScheme.parse(diffResult);
15721
16478
  const jsonStatements = [];
15722
16479
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -15768,6 +16525,8 @@ var init_snapshotsDiffer = __esm({
15768
16525
  schemaTo: it.schemaTo || "public"
15769
16526
  });
15770
16527
  }
16528
+ const jsonDeletedCheckConstraints = [];
16529
+ const jsonCreatedCheckConstraints = [];
15771
16530
  for (let it of alteredTables) {
15772
16531
  let addedColumns = [];
15773
16532
  for (const addedPkName of Object.keys(it.addedCompositePKs)) {
@@ -15807,6 +16566,8 @@ var init_snapshotsDiffer = __esm({
15807
16566
  let addedUniqueConstraints = [];
15808
16567
  let deletedUniqueConstraints = [];
15809
16568
  let alteredUniqueConstraints = [];
16569
+ let createCheckConstraints = [];
16570
+ let deleteCheckConstraints = [];
15810
16571
  addedUniqueConstraints = prepareAddUniqueConstraintPg(
15811
16572
  it.name,
15812
16573
  it.schema,
@@ -15831,6 +16592,24 @@ var init_snapshotsDiffer = __esm({
15831
16592
  ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
15832
16593
  );
15833
16594
  }
16595
+ createCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
16596
+ deleteCheckConstraints = prepareDeleteCheckConstraint(
16597
+ it.name,
16598
+ it.schema,
16599
+ it.deletedCheckConstraints
16600
+ );
16601
+ if (it.alteredCheckConstraints && action !== "push") {
16602
+ const added = {};
16603
+ const deleted = {};
16604
+ for (const k of Object.keys(it.alteredCheckConstraints)) {
16605
+ added[k] = it.alteredCheckConstraints[k].__new;
16606
+ deleted[k] = it.alteredCheckConstraints[k].__old;
16607
+ }
16608
+ createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
16609
+ deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
16610
+ }
16611
+ jsonCreatedCheckConstraints.push(...createCheckConstraints);
16612
+ jsonDeletedCheckConstraints.push(...deleteCheckConstraints);
15834
16613
  jsonAddedCompositePKs.push(...addedCompositePKs);
15835
16614
  jsonDeletedCompositePKs.push(...deletedCompositePKs);
15836
16615
  jsonAlteredCompositePKs.push(...alteredCompositePKs);
@@ -15971,6 +16750,137 @@ var init_snapshotsDiffer = __esm({
15971
16750
  const createTables = createdTables.map((it) => {
15972
16751
  return preparePgCreateTableJson(it, curFull);
15973
16752
  });
16753
+ const createViews = [];
16754
+ const dropViews = [];
16755
+ const renameViews = [];
16756
+ const alterViews = [];
16757
+ createViews.push(
16758
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
16759
+ return preparePgCreateViewJson(
16760
+ it.name,
16761
+ it.schema,
16762
+ it.definition,
16763
+ it.materialized,
16764
+ it.withNoData,
16765
+ it.with,
16766
+ it.using,
16767
+ it.tablespace
16768
+ );
16769
+ })
16770
+ );
16771
+ dropViews.push(
16772
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
16773
+ return prepareDropViewJson(it.name, it.schema, it.materialized);
16774
+ })
16775
+ );
16776
+ renameViews.push(
16777
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
16778
+ return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
16779
+ })
16780
+ );
16781
+ alterViews.push(
16782
+ ...movedViews.filter(
16783
+ (it) => !json22.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
16784
+ ).map((it) => {
16785
+ return preparePgAlterViewAlterSchemaJson(
16786
+ it.schemaTo,
16787
+ it.schemaFrom,
16788
+ it.name,
16789
+ json22.views[`${it.schemaTo}.${it.name}`].materialized
16790
+ );
16791
+ })
16792
+ );
16793
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[`${it.schema}.${it.name}`].isExisting);
16794
+ for (const alteredView of alteredViews) {
16795
+ const viewKey = `${alteredView.schema}.${alteredView.name}`;
16796
+ const { materialized, with: withOption, definition, withNoData, using, tablespace } = json22.views[viewKey];
16797
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
16798
+ dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
16799
+ createViews.push(
16800
+ preparePgCreateViewJson(
16801
+ alteredView.name,
16802
+ alteredView.schema,
16803
+ definition,
16804
+ materialized,
16805
+ withNoData,
16806
+ withOption,
16807
+ using,
16808
+ tablespace
16809
+ )
16810
+ );
16811
+ continue;
16812
+ }
16813
+ if (alteredView.addedWithOption) {
16814
+ alterViews.push(
16815
+ preparePgAlterViewAddWithOptionJson(
16816
+ alteredView.name,
16817
+ alteredView.schema,
16818
+ materialized,
16819
+ alteredView.addedWithOption
16820
+ )
16821
+ );
16822
+ }
16823
+ if (alteredView.deletedWithOption) {
16824
+ alterViews.push(
16825
+ preparePgAlterViewDropWithOptionJson(
16826
+ alteredView.name,
16827
+ alteredView.schema,
16828
+ materialized,
16829
+ alteredView.deletedWithOption
16830
+ )
16831
+ );
16832
+ }
16833
+ if (alteredView.addedWith) {
16834
+ alterViews.push(
16835
+ preparePgAlterViewAddWithOptionJson(
16836
+ alteredView.name,
16837
+ alteredView.schema,
16838
+ materialized,
16839
+ alteredView.addedWith
16840
+ )
16841
+ );
16842
+ }
16843
+ if (alteredView.deletedWith) {
16844
+ alterViews.push(
16845
+ preparePgAlterViewDropWithOptionJson(
16846
+ alteredView.name,
16847
+ alteredView.schema,
16848
+ materialized,
16849
+ alteredView.deletedWith
16850
+ )
16851
+ );
16852
+ }
16853
+ if (alteredView.alteredWith) {
16854
+ alterViews.push(
16855
+ preparePgAlterViewAddWithOptionJson(
16856
+ alteredView.name,
16857
+ alteredView.schema,
16858
+ materialized,
16859
+ alteredView.alteredWith
16860
+ )
16861
+ );
16862
+ }
16863
+ if (alteredView.alteredTablespace) {
16864
+ alterViews.push(
16865
+ preparePgAlterViewAlterTablespaceJson(
16866
+ alteredView.name,
16867
+ alteredView.schema,
16868
+ materialized,
16869
+ alteredView.alteredTablespace.__new
16870
+ )
16871
+ );
16872
+ }
16873
+ if (alteredView.alteredUsing) {
16874
+ alterViews.push(
16875
+ preparePgAlterViewAlterUsingJson(
16876
+ alteredView.name,
16877
+ alteredView.schema,
16878
+ materialized,
16879
+ alteredView.alteredUsing.__new
16880
+ )
16881
+ );
16882
+ }
16883
+ }
15974
16884
  jsonStatements.push(...createSchemas);
15975
16885
  jsonStatements.push(...renameSchemas);
15976
16886
  jsonStatements.push(...createEnums);
@@ -15982,11 +16892,15 @@ var init_snapshotsDiffer = __esm({
15982
16892
  jsonStatements.push(...renameSequences);
15983
16893
  jsonStatements.push(...jsonAlterSequences);
15984
16894
  jsonStatements.push(...createTables);
16895
+ jsonStatements.push(...dropViews);
16896
+ jsonStatements.push(...renameViews);
16897
+ jsonStatements.push(...alterViews);
15985
16898
  jsonStatements.push(...jsonDropTables);
15986
16899
  jsonStatements.push(...jsonSetTableSchemas);
15987
16900
  jsonStatements.push(...jsonRenameTables);
15988
16901
  jsonStatements.push(...jsonRenameColumnsStatements);
15989
16902
  jsonStatements.push(...jsonDeletedUniqueConstraints);
16903
+ jsonStatements.push(...jsonDeletedCheckConstraints);
15990
16904
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
15991
16905
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
15992
16906
  jsonStatements.push(...jsonDeletedCompositePKs);
@@ -16000,8 +16914,10 @@ var init_snapshotsDiffer = __esm({
16000
16914
  jsonStatements.push(...jsonDropColumnsStatemets);
16001
16915
  jsonStatements.push(...jsonAlteredCompositePKs);
16002
16916
  jsonStatements.push(...jsonAddedUniqueConstraints);
16917
+ jsonStatements.push(...jsonCreatedCheckConstraints);
16003
16918
  jsonStatements.push(...jsonAlteredUniqueConstraints);
16004
16919
  jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
16920
+ jsonStatements.push(...createViews);
16005
16921
  jsonStatements.push(...dropEnums);
16006
16922
  jsonStatements.push(...dropSequences);
16007
16923
  jsonStatements.push(...dropSchemas);
@@ -16053,7 +16969,7 @@ var init_snapshotsDiffer = __esm({
16053
16969
  _meta
16054
16970
  };
16055
16971
  };
16056
- applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
16972
+ applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16057
16973
  for (const tableName in json1.tables) {
16058
16974
  const table4 = json1.tables[tableName];
16059
16975
  for (const indexName2 in table4.indexes) {
@@ -16150,7 +17066,33 @@ var init_snapshotsDiffer = __esm({
16150
17066
  return [tableKey2, tableValue];
16151
17067
  }
16152
17068
  );
16153
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17069
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17070
+ const {
17071
+ created: createdViews,
17072
+ deleted: deletedViews,
17073
+ renamed: renamedViews
17074
+ // renamed or moved
17075
+ } = await viewsResolver2({
17076
+ created: viewsDiff.added,
17077
+ deleted: viewsDiff.deleted
17078
+ });
17079
+ const renamesViewDic = {};
17080
+ renamedViews.forEach((it) => {
17081
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17082
+ });
17083
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17084
+ viewsPatchedSnap1.views = mapEntries(
17085
+ viewsPatchedSnap1.views,
17086
+ (viewKey, viewValue) => {
17087
+ const rename = renamesViewDic[viewValue.name];
17088
+ if (rename) {
17089
+ viewValue.name = rename.to;
17090
+ viewKey = rename.to;
17091
+ }
17092
+ return [viewKey, viewValue];
17093
+ }
17094
+ );
17095
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16154
17096
  const typedResult = diffResultSchemeMysql.parse(diffResult);
16155
17097
  const jsonStatements = [];
16156
17098
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -16174,6 +17116,8 @@ var init_snapshotsDiffer = __esm({
16174
17116
  const jsonAddedUniqueConstraints = [];
16175
17117
  const jsonDeletedUniqueConstraints = [];
16176
17118
  const jsonAlteredUniqueConstraints = [];
17119
+ const jsonCreatedCheckConstraints = [];
17120
+ const jsonDeletedCheckConstraints = [];
16177
17121
  const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
16178
17122
  const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
16179
17123
  const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
@@ -16212,6 +17156,8 @@ var init_snapshotsDiffer = __esm({
16212
17156
  let addedUniqueConstraints = [];
16213
17157
  let deletedUniqueConstraints = [];
16214
17158
  let alteredUniqueConstraints = [];
17159
+ let createdCheckConstraints = [];
17160
+ let deletedCheckConstraints = [];
16215
17161
  addedUniqueConstraints = prepareAddUniqueConstraintPg(
16216
17162
  it.name,
16217
17163
  it.schema,
@@ -16236,12 +17182,30 @@ var init_snapshotsDiffer = __esm({
16236
17182
  ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
16237
17183
  );
16238
17184
  }
17185
+ createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
17186
+ deletedCheckConstraints = prepareDeleteCheckConstraint(
17187
+ it.name,
17188
+ it.schema,
17189
+ it.deletedCheckConstraints
17190
+ );
17191
+ if (it.alteredCheckConstraints && action !== "push") {
17192
+ const added = {};
17193
+ const deleted = {};
17194
+ for (const k of Object.keys(it.alteredCheckConstraints)) {
17195
+ added[k] = it.alteredCheckConstraints[k].__new;
17196
+ deleted[k] = it.alteredCheckConstraints[k].__old;
17197
+ }
17198
+ createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
17199
+ deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
17200
+ }
16239
17201
  jsonAddedCompositePKs.push(...addedCompositePKs);
16240
17202
  jsonDeletedCompositePKs.push(...deletedCompositePKs);
16241
17203
  jsonAlteredCompositePKs.push(...alteredCompositePKs);
16242
17204
  jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
16243
17205
  jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
16244
17206
  jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
17207
+ jsonCreatedCheckConstraints.push(...createdCheckConstraints);
17208
+ jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
16245
17209
  });
16246
17210
  const rColumns = jsonRenameColumnsStatements.map((it) => {
16247
17211
  const tableName = it.tableName;
@@ -16332,11 +17296,70 @@ var init_snapshotsDiffer = __esm({
16332
17296
  curFull.internal
16333
17297
  );
16334
17298
  });
17299
+ const createViews = [];
17300
+ const dropViews = [];
17301
+ const renameViews = [];
17302
+ const alterViews = [];
17303
+ createViews.push(
17304
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17305
+ return prepareMySqlCreateViewJson(
17306
+ it.name,
17307
+ it.definition,
17308
+ it.meta
17309
+ );
17310
+ })
17311
+ );
17312
+ dropViews.push(
17313
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17314
+ return prepareDropViewJson(it.name);
17315
+ })
17316
+ );
17317
+ renameViews.push(
17318
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
17319
+ return prepareRenameViewJson(it.to.name, it.from.name);
17320
+ })
17321
+ );
17322
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17323
+ for (const alteredView of alteredViews) {
17324
+ const { definition, meta } = json22.views[alteredView.name];
17325
+ if (alteredView.alteredExisting) {
17326
+ dropViews.push(prepareDropViewJson(alteredView.name));
17327
+ createViews.push(
17328
+ prepareMySqlCreateViewJson(
17329
+ alteredView.name,
17330
+ definition,
17331
+ meta
17332
+ )
17333
+ );
17334
+ continue;
17335
+ }
17336
+ if (alteredView.alteredDefinition && action !== "push") {
17337
+ createViews.push(
17338
+ prepareMySqlCreateViewJson(
17339
+ alteredView.name,
17340
+ definition,
17341
+ meta,
17342
+ true
17343
+ )
17344
+ );
17345
+ continue;
17346
+ }
17347
+ if (alteredView.alteredMeta) {
17348
+ const view4 = curFull["views"][alteredView.name];
17349
+ alterViews.push(
17350
+ prepareMySqlAlterView(view4)
17351
+ );
17352
+ }
17353
+ }
16335
17354
  jsonStatements.push(...jsonMySqlCreateTables);
16336
17355
  jsonStatements.push(...jsonDropTables);
16337
17356
  jsonStatements.push(...jsonRenameTables);
16338
17357
  jsonStatements.push(...jsonRenameColumnsStatements);
17358
+ jsonStatements.push(...dropViews);
17359
+ jsonStatements.push(...renameViews);
17360
+ jsonStatements.push(...alterViews);
16339
17361
  jsonStatements.push(...jsonDeletedUniqueConstraints);
17362
+ jsonStatements.push(...jsonDeletedCheckConstraints);
16340
17363
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
16341
17364
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
16342
17365
  jsonStatements.push(...jsonDeletedCompositePKs);
@@ -16347,11 +17370,12 @@ var init_snapshotsDiffer = __esm({
16347
17370
  jsonStatements.push(...jsonAddColumnsStatemets);
16348
17371
  jsonStatements.push(...jsonCreateReferencesForCreatedTables);
16349
17372
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
17373
+ jsonStatements.push(...jsonCreatedCheckConstraints);
16350
17374
  jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
16351
17375
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
16352
17376
  jsonStatements.push(...jsonDropColumnsStatemets);
16353
17377
  jsonStatements.push(...jsonAlteredCompositePKs);
16354
- jsonStatements.push(...jsonAddedUniqueConstraints);
17378
+ jsonStatements.push(...createViews);
16355
17379
  jsonStatements.push(...jsonAlteredUniqueConstraints);
16356
17380
  const sqlStatements = fromJson(jsonStatements, "mysql");
16357
17381
  const uniqueSqlStatements = [];
@@ -16370,7 +17394,7 @@ var init_snapshotsDiffer = __esm({
16370
17394
  _meta
16371
17395
  };
16372
17396
  };
16373
- applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
17397
+ applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16374
17398
  const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
16375
17399
  const {
16376
17400
  created: createdTables,
@@ -16440,7 +17464,32 @@ var init_snapshotsDiffer = __esm({
16440
17464
  return [tableKey2, tableValue];
16441
17465
  }
16442
17466
  );
16443
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17467
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17468
+ const {
17469
+ created: createdViews,
17470
+ deleted: deletedViews,
17471
+ renamed: renamedViews
17472
+ // renamed or moved
17473
+ } = await viewsResolver2({
17474
+ created: viewsDiff.added,
17475
+ deleted: viewsDiff.deleted
17476
+ });
17477
+ const renamesViewDic = {};
17478
+ renamedViews.forEach((it) => {
17479
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17480
+ });
17481
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17482
+ viewsPatchedSnap1.views = mapEntries(
17483
+ viewsPatchedSnap1.views,
17484
+ (viewKey, viewValue) => {
17485
+ const rename = renamesViewDic[viewValue.name];
17486
+ if (rename) {
17487
+ viewValue.name = rename.to;
17488
+ }
17489
+ return [viewKey, viewValue];
17490
+ }
17491
+ );
17492
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16444
17493
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
16445
17494
  const tablesMap = {};
16446
17495
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -16479,6 +17528,8 @@ var init_snapshotsDiffer = __esm({
16479
17528
  const jsonAddedUniqueConstraints = [];
16480
17529
  const jsonDeletedUniqueConstraints = [];
16481
17530
  const jsonAlteredUniqueConstraints = [];
17531
+ const jsonDeletedCheckConstraints = [];
17532
+ const jsonCreatedCheckConstraints = [];
16482
17533
  allAltered.forEach((it) => {
16483
17534
  let addedColumns = [];
16484
17535
  for (const addedPkName of Object.keys(it.addedCompositePKs)) {
@@ -16535,12 +17586,56 @@ var init_snapshotsDiffer = __esm({
16535
17586
  ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
16536
17587
  );
16537
17588
  }
17589
+ let createdCheckConstraints = [];
17590
+ let deletedCheckConstraints = [];
17591
+ addedUniqueConstraints = prepareAddUniqueConstraintPg(
17592
+ it.name,
17593
+ it.schema,
17594
+ it.addedUniqueConstraints
17595
+ );
17596
+ deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
17597
+ it.name,
17598
+ it.schema,
17599
+ it.deletedUniqueConstraints
17600
+ );
17601
+ if (it.alteredUniqueConstraints) {
17602
+ const added = {};
17603
+ const deleted = {};
17604
+ for (const k of Object.keys(it.alteredUniqueConstraints)) {
17605
+ added[k] = it.alteredUniqueConstraints[k].__new;
17606
+ deleted[k] = it.alteredUniqueConstraints[k].__old;
17607
+ }
17608
+ addedUniqueConstraints.push(
17609
+ ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
17610
+ );
17611
+ deletedUniqueConstraints.push(
17612
+ ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
17613
+ );
17614
+ }
17615
+ createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
17616
+ deletedCheckConstraints = prepareDeleteCheckConstraint(
17617
+ it.name,
17618
+ it.schema,
17619
+ it.deletedCheckConstraints
17620
+ );
17621
+ if (it.alteredCheckConstraints && action !== "push") {
17622
+ const added = {};
17623
+ const deleted = {};
17624
+ for (const k of Object.keys(it.alteredCheckConstraints)) {
17625
+ added[k] = it.alteredCheckConstraints[k].__new;
17626
+ deleted[k] = it.alteredCheckConstraints[k].__old;
17627
+ }
17628
+ createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
17629
+ deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
17630
+ }
16538
17631
  jsonAddedCompositePKs.push(...addedCompositePKs);
16539
17632
  jsonDeletedCompositePKs.push(...deletedCompositePKs);
16540
17633
  jsonAlteredCompositePKs.push(...alteredCompositePKs);
16541
17634
  jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
16542
17635
  jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
16543
17636
  jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
17637
+ jsonCreatedCheckConstraints.push(...createdCheckConstraints);
17638
+ jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
16544
17639
  });
16545
17640
  const rColumns = jsonRenameColumnsStatements.map((it) => {
16546
17641
  const tableName = it.tableName;
@@ -16619,12 +17714,51 @@ var init_snapshotsDiffer = __esm({
16619
17714
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
16620
17715
  (t) => t.type === "delete_reference"
16621
17716
  );
17717
+ const createViews = [];
17718
+ const dropViews = [];
17719
+ createViews.push(
17720
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17721
+ return prepareSqliteCreateViewJson(
17722
+ it.name,
17723
+ it.definition
17724
+ );
17725
+ })
17726
+ );
17727
+ dropViews.push(
17728
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17729
+ return prepareDropViewJson(it.name);
17730
+ })
17731
+ );
17732
+ dropViews.push(
17733
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17734
+ return prepareDropViewJson(it.from.name);
17735
+ })
17736
+ );
17737
+ createViews.push(
17738
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17739
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
17740
+ })
17741
+ );
17742
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17743
+ for (const alteredView of alteredViews) {
17744
+ const { definition } = json22.views[alteredView.name];
17745
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
17746
+ dropViews.push(prepareDropViewJson(alteredView.name));
17747
+ createViews.push(
17748
+ prepareSqliteCreateViewJson(
17749
+ alteredView.name,
17750
+ definition
17751
+ )
17752
+ );
17753
+ }
17754
+ }
16622
17755
  const jsonStatements = [];
16623
17756
  jsonStatements.push(...jsonCreateTables);
16624
17757
  jsonStatements.push(...jsonDropTables);
16625
17758
  jsonStatements.push(...jsonRenameTables);
16626
17759
  jsonStatements.push(...jsonRenameColumnsStatements);
16627
17760
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
17761
+ jsonStatements.push(...jsonDeletedCheckConstraints);
16628
17762
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
16629
17763
  jsonStatements.push(...jsonDeletedCompositePKs);
16630
17764
  jsonStatements.push(...jsonTableAlternations);
@@ -16632,10 +17766,13 @@ var init_snapshotsDiffer = __esm({
16632
17766
  jsonStatements.push(...jsonAddColumnsStatemets);
16633
17767
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
16634
17768
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
17769
+ jsonStatements.push(...jsonCreatedCheckConstraints);
16635
17770
  jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
16636
17771
  jsonStatements.push(...jsonDropColumnsStatemets);
16637
17772
  jsonStatements.push(...jsonAlteredCompositePKs);
16638
17773
  jsonStatements.push(...jsonAlteredUniqueConstraints);
17774
+ jsonStatements.push(...dropViews);
17775
+ jsonStatements.push(...createViews);
16639
17776
  const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json22, action);
16640
17777
  const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
16641
17778
  const uniqueSqlStatements = [];
@@ -16654,7 +17791,7 @@ var init_snapshotsDiffer = __esm({
16654
17791
  _meta
16655
17792
  };
16656
17793
  };
16657
- applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
17794
+ applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16658
17795
  const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
16659
17796
  const {
16660
17797
  created: createdTables,
@@ -16724,7 +17861,32 @@ var init_snapshotsDiffer = __esm({
16724
17861
  return [tableKey2, tableValue];
16725
17862
  }
16726
17863
  );
16727
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17864
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17865
+ const {
17866
+ created: createdViews,
17867
+ deleted: deletedViews,
17868
+ renamed: renamedViews
17869
+ // renamed or moved
17870
+ } = await viewsResolver2({
17871
+ created: viewsDiff.added,
17872
+ deleted: viewsDiff.deleted
17873
+ });
17874
+ const renamesViewDic = {};
17875
+ renamedViews.forEach((it) => {
17876
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17877
+ });
17878
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17879
+ viewsPatchedSnap1.views = mapEntries(
17880
+ viewsPatchedSnap1.views,
17881
+ (viewKey, viewValue) => {
17882
+ const rename = renamesViewDic[viewValue.name];
17883
+ if (rename) {
17884
+ viewValue.name = rename.to;
17885
+ }
17886
+ return [viewKey, viewValue];
17887
+ }
17888
+ );
17889
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16728
17890
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
16729
17891
  const tablesMap = {};
16730
17892
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -16775,6 +17937,8 @@ var init_snapshotsDiffer = __esm({
16775
17937
  const jsonAddedUniqueConstraints = [];
16776
17938
  const jsonDeletedUniqueConstraints = [];
16777
17939
  const jsonAlteredUniqueConstraints = [];
17940
+ const jsonDeletedCheckConstraints = [];
17941
+ const jsonCreatedCheckConstraints = [];
16778
17942
  allAltered.forEach((it) => {
16779
17943
  let addedColumns = [];
16780
17944
  for (const addedPkName of Object.keys(it.addedCompositePKs)) {
@@ -16807,6 +17971,8 @@ var init_snapshotsDiffer = __esm({
16807
17971
  let addedUniqueConstraints = [];
16808
17972
  let deletedUniqueConstraints = [];
16809
17973
  let alteredUniqueConstraints = [];
17974
+ let createdCheckConstraints = [];
17975
+ let deletedCheckConstraints = [];
16810
17976
  addedUniqueConstraints = prepareAddUniqueConstraintPg(
16811
17977
  it.name,
16812
17978
  it.schema,
@@ -16831,12 +17997,30 @@ var init_snapshotsDiffer = __esm({
16831
17997
  ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
16832
17998
  );
16833
17999
  }
18000
+ createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
18001
+ deletedCheckConstraints = prepareDeleteCheckConstraint(
18002
+ it.name,
18003
+ it.schema,
18004
+ it.deletedCheckConstraints
18005
+ );
18006
+ if (it.alteredCheckConstraints && action !== "push") {
18007
+ const added = {};
18008
+ const deleted = {};
18009
+ for (const k of Object.keys(it.alteredCheckConstraints)) {
18010
+ added[k] = it.alteredCheckConstraints[k].__new;
18011
+ deleted[k] = it.alteredCheckConstraints[k].__old;
18012
+ }
18013
+ createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
18014
+ deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
18015
+ }
16834
18016
  jsonAddedCompositePKs.push(...addedCompositePKs);
16835
18017
  jsonDeletedCompositePKs.push(...deletedCompositePKs);
16836
18018
  jsonAlteredCompositePKs.push(...alteredCompositePKs);
16837
18019
  jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
16838
18020
  jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
16839
18021
  jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
18022
+ jsonCreatedCheckConstraints.push(...createdCheckConstraints);
18023
+ jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
16840
18024
  });
16841
18025
  const jsonTableAlternations = allAltered.map((it) => {
16842
18026
  return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json22);
@@ -16908,12 +18092,51 @@ var init_snapshotsDiffer = __esm({
16908
18092
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
16909
18093
  (t) => t.type === "delete_reference"
16910
18094
  );
18095
+ const createViews = [];
18096
+ const dropViews = [];
18097
+ createViews.push(
18098
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
18099
+ return prepareSqliteCreateViewJson(
18100
+ it.name,
18101
+ it.definition
18102
+ );
18103
+ })
18104
+ );
18105
+ dropViews.push(
18106
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
18107
+ return prepareDropViewJson(it.name);
18108
+ })
18109
+ );
18110
+ dropViews.push(
18111
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
18112
+ return prepareDropViewJson(it.from.name);
18113
+ })
18114
+ );
18115
+ createViews.push(
18116
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
18117
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
18118
+ })
18119
+ );
18120
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
18121
+ for (const alteredView of alteredViews) {
18122
+ const { definition } = json22.views[alteredView.name];
18123
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
18124
+ dropViews.push(prepareDropViewJson(alteredView.name));
18125
+ createViews.push(
18126
+ prepareSqliteCreateViewJson(
18127
+ alteredView.name,
18128
+ definition
18129
+ )
18130
+ );
18131
+ }
18132
+ }
16911
18133
  const jsonStatements = [];
16912
18134
  jsonStatements.push(...jsonCreateTables);
16913
18135
  jsonStatements.push(...jsonDropTables);
16914
18136
  jsonStatements.push(...jsonRenameTables);
16915
18137
  jsonStatements.push(...jsonRenameColumnsStatements);
16916
18138
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
18139
+ jsonStatements.push(...jsonDeletedCheckConstraints);
16917
18140
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
16918
18141
  jsonStatements.push(...jsonDeletedCompositePKs);
16919
18142
  jsonStatements.push(...jsonTableAlternations);
@@ -16921,6 +18144,9 @@ var init_snapshotsDiffer = __esm({
16921
18144
  jsonStatements.push(...jsonAddColumnsStatemets);
16922
18145
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
16923
18146
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
18147
+ jsonStatements.push(...jsonCreatedCheckConstraints);
18148
+ jsonStatements.push(...dropViews);
18149
+ jsonStatements.push(...createViews);
16924
18150
  jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
16925
18151
  jsonStatements.push(...jsonDropColumnsStatemets);
16926
18152
  jsonStatements.push(...jsonAlteredCompositePKs);
@@ -17083,7 +18309,7 @@ var init_outputs = __esm({
17083
18309
  });
17084
18310
 
17085
18311
  // src/cli/commands/migrate.ts
17086
- var import_hanji2, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
18312
+ var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
17087
18313
  var init_migrate = __esm({
17088
18314
  "src/cli/commands/migrate.ts"() {
17089
18315
  "use strict";
@@ -17128,6 +18354,60 @@ var init_migrate = __esm({
17128
18354
  throw e;
17129
18355
  }
17130
18356
  };
18357
+ viewsResolver = async (input) => {
18358
+ try {
18359
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18360
+ input.created,
18361
+ input.deleted,
18362
+ "view"
18363
+ );
18364
+ return {
18365
+ created,
18366
+ deleted,
18367
+ moved,
18368
+ renamed
18369
+ };
18370
+ } catch (e) {
18371
+ console.error(e);
18372
+ throw e;
18373
+ }
18374
+ };
18375
+ mySqlViewsResolver = async (input) => {
18376
+ try {
18377
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18378
+ input.created,
18379
+ input.deleted,
18380
+ "view"
18381
+ );
18382
+ return {
18383
+ created,
18384
+ deleted,
18385
+ moved,
18386
+ renamed
18387
+ };
18388
+ } catch (e) {
18389
+ console.error(e);
18390
+ throw e;
18391
+ }
18392
+ };
18393
+ sqliteViewsResolver = async (input) => {
18394
+ try {
18395
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18396
+ input.created,
18397
+ input.deleted,
18398
+ "view"
18399
+ );
18400
+ return {
18401
+ created,
18402
+ deleted,
18403
+ moved,
18404
+ renamed
18405
+ };
18406
+ } catch (e) {
18407
+ console.error(e);
18408
+ throw e;
18409
+ }
18410
+ };
17131
18411
  sequencesResolver = async (input) => {
17132
18412
  try {
17133
18413
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -19203,7 +20483,7 @@ function fillPlaceholders(params, values) {
19203
20483
  return p;
19204
20484
  });
19205
20485
  }
19206
- var _a20, FakePrimitiveParam, _a21, StringChunk, _a22, _SQL, SQL, _a23, Name, noopDecoder, noopEncoder, noopMapper, _a24, Param, _a25, Placeholder, _a26, _b10, View;
20486
+ var _a20, FakePrimitiveParam, _a21, StringChunk, _a22, _SQL, SQL, _a23, Name, noopDecoder, noopEncoder, noopMapper, _a24, Param, _a25, Placeholder, _a26, _b10, View3;
19207
20487
  var init_sql = __esm({
19208
20488
  "../drizzle-orm/dist/sql/sql.js"() {
19209
20489
  "use strict";
@@ -19306,7 +20586,7 @@ var init_sql = __esm({
19306
20586
  }
19307
20587
  return { sql: escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), params: [] };
19308
20588
  }
19309
- if (is(chunk, View)) {
20589
+ if (is(chunk, View3)) {
19310
20590
  const schemaName = chunk[ViewBaseConfig].schema;
19311
20591
  const viewName = chunk[ViewBaseConfig].name;
19312
20592
  return {
@@ -19525,7 +20805,7 @@ var init_sql = __esm({
19525
20805
  };
19526
20806
  __publicField(Placeholder, _a25, "Placeholder");
19527
20807
  _b10 = entityKind, _a26 = ViewBaseConfig;
19528
- View = class {
20808
+ View3 = class {
19529
20809
  constructor({ name: name2, schema: schema4, selectedFields, query }) {
19530
20810
  /** @internal */
19531
20811
  __publicField(this, _a26);
@@ -19543,7 +20823,7 @@ var init_sql = __esm({
19543
20823
  return new SQL([this]);
19544
20824
  }
19545
20825
  };
19546
- __publicField(View, _b10, "View");
20826
+ __publicField(View3, _b10, "View");
19547
20827
  Column2.prototype.getSQL = function() {
19548
20828
  return new SQL([this]);
19549
20829
  };
@@ -19694,7 +20974,7 @@ var init_errors = __esm({
19694
20974
 
19695
20975
  // ../drizzle-orm/dist/sql/expressions/conditions.js
19696
20976
  function bindIfParam(value, column4) {
19697
- if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table) && !is(value, View)) {
20977
+ if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table) && !is(value, View3)) {
19698
20978
  return new Param(value, column4);
19699
20979
  }
19700
20980
  return value;
@@ -20065,7 +21345,7 @@ function getTableColumns(table4) {
20065
21345
  return table4[Table.Symbol.Columns];
20066
21346
  }
20067
21347
  function getTableLikeName(table4) {
20068
- return is(table4, Subquery) ? table4._.alias : is(table4, View) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : table4[Table.Symbol.IsAlias] ? table4[Table.Symbol.Name] : table4[Table.Symbol.BaseName];
21348
+ return is(table4, Subquery) ? table4._.alias : is(table4, View3) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : table4[Table.Symbol.IsAlias] ? table4[Table.Symbol.Name] : table4[Table.Symbol.BaseName];
20069
21349
  }
20070
21350
  function getColumnNameAndConfig(a, b) {
20071
21351
  return {
@@ -20983,23 +22263,23 @@ function hexToBytes(hex) {
20983
22263
  }
20984
22264
  function bytesToFloat64(bytes, offset) {
20985
22265
  const buffer = new ArrayBuffer(8);
20986
- const view = new DataView(buffer);
22266
+ const view4 = new DataView(buffer);
20987
22267
  for (let i = 0; i < 8; i++) {
20988
- view.setUint8(i, bytes[offset + i]);
22268
+ view4.setUint8(i, bytes[offset + i]);
20989
22269
  }
20990
- return view.getFloat64(0, true);
22270
+ return view4.getFloat64(0, true);
20991
22271
  }
20992
22272
  function parseEWKB(hex) {
20993
22273
  const bytes = hexToBytes(hex);
20994
22274
  let offset = 0;
20995
22275
  const byteOrder = bytes[offset];
20996
22276
  offset += 1;
20997
- const view = new DataView(bytes.buffer);
20998
- const geomType = view.getUint32(offset, byteOrder === 1);
22277
+ const view4 = new DataView(bytes.buffer);
22278
+ const geomType = view4.getUint32(offset, byteOrder === 1);
20999
22279
  offset += 4;
21000
22280
  let _srid;
21001
22281
  if (geomType & 536870912) {
21002
- _srid = view.getUint32(offset, byteOrder === 1);
22282
+ _srid = view4.getUint32(offset, byteOrder === 1);
21003
22283
  offset += 4;
21004
22284
  }
21005
22285
  if ((geomType & 65535) === 1) {
@@ -22222,7 +23502,7 @@ __export(dist_exports, {
22222
23502
  Table: () => Table,
22223
23503
  TableAliasProxyHandler: () => TableAliasProxyHandler,
22224
23504
  TransactionRollbackError: () => TransactionRollbackError,
22225
- View: () => View,
23505
+ View: () => View3,
22226
23506
  ViewBaseConfig: () => ViewBaseConfig,
22227
23507
  WithSubquery: () => WithSubquery,
22228
23508
  aliasedRelation: () => aliasedRelation,
@@ -22656,7 +23936,7 @@ var init_view_base = __esm({
22656
23936
  "use strict";
22657
23937
  init_entity();
22658
23938
  init_sql();
22659
- PgViewBase = class extends (_b99 = View, _a128 = entityKind, _b99) {
23939
+ PgViewBase = class extends (_b99 = View3, _a128 = entityKind, _b99) {
22660
23940
  };
22661
23941
  __publicField(PgViewBase, _a128, "PgViewBase");
22662
23942
  }
@@ -22879,7 +24159,7 @@ var init_dialect = __esm({
22879
24159
  joinsArray.push(
22880
24160
  sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
22881
24161
  );
22882
- } else if (is(table22, View)) {
24162
+ } else if (is(table22, View3)) {
22883
24163
  const viewName = table22[ViewBaseConfig].name;
22884
24164
  const viewSchema = table22[ViewBaseConfig].schema;
22885
24165
  const origViewName = table22[ViewBaseConfig].originalName;
@@ -23016,10 +24296,10 @@ var init_dialect = __esm({
23016
24296
  const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
23017
24297
  return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
23018
24298
  }
23019
- buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
24299
+ buildRefreshMaterializedViewQuery({ view: view4, concurrently, withNoData }) {
23020
24300
  const concurrentlySql = concurrently ? sql` concurrently` : void 0;
23021
24301
  const withNoDataSql = withNoData ? sql` with no data` : void 0;
23022
- return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
24302
+ return sql`refresh materialized view${concurrentlySql} ${view4}${withNoDataSql}`;
23023
24303
  }
23024
24304
  prepareTyping(encoder) {
23025
24305
  if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
@@ -23793,7 +25073,7 @@ var init_selection_proxy = __esm({
23793
25073
  if (typeof prop === "symbol") {
23794
25074
  return subquery[prop];
23795
25075
  }
23796
- const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
25076
+ const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View3) ? subquery[ViewBaseConfig].selectedFields : subquery;
23797
25077
  const value = columns[prop];
23798
25078
  if (is(value, SQL.Aliased)) {
23799
25079
  if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
@@ -24275,7 +25555,7 @@ var init_select2 = __esm({
24275
25555
  };
24276
25556
  }
24277
25557
  if (typeof tableName === "string" && !is(table4, SQL)) {
24278
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
25558
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
24279
25559
  this.config.fields[tableName] = selection;
24280
25560
  }
24281
25561
  }
@@ -24694,7 +25974,7 @@ var init_refresh_materialized_view = __esm({
24694
25974
  init_query_promise();
24695
25975
  init_tracing();
24696
25976
  PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
24697
- constructor(view, session, dialect4) {
25977
+ constructor(view4, session, dialect4) {
24698
25978
  super();
24699
25979
  __publicField(this, "config");
24700
25980
  __publicField(this, "execute", (placeholderValues) => {
@@ -24704,7 +25984,7 @@ var init_refresh_materialized_view = __esm({
24704
25984
  });
24705
25985
  this.session = session;
24706
25986
  this.dialect = dialect4;
24707
- this.config = { view };
25987
+ this.config = { view: view4 };
24708
25988
  }
24709
25989
  concurrently() {
24710
25990
  if (this.config.withNoData !== void 0) {
@@ -25335,8 +26615,8 @@ var init_db = __esm({
25335
26615
  delete(table4) {
25336
26616
  return new PgDeleteBase(table4, this.session, this.dialect);
25337
26617
  }
25338
- refreshMaterializedView(view) {
25339
- return new PgRefreshMaterializedView(view, this.session, this.dialect);
26618
+ refreshMaterializedView(view4) {
26619
+ return new PgRefreshMaterializedView(view4, this.session, this.dialect);
25340
26620
  }
25341
26621
  execute(query) {
25342
26622
  const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
@@ -25526,7 +26806,13 @@ function pgMaterializedViewWithSchema(name2, selection, schema4) {
25526
26806
  }
25527
26807
  return new MaterializedViewBuilder(name2, schema4);
25528
26808
  }
25529
- var _a148, DefaultViewBuilderCore, _a149, _b107, ViewBuilder, _a150, _b108, ManualViewBuilder, _a151, MaterializedViewBuilderCore, _a152, _b109, MaterializedViewBuilder, _a153, _b110, ManualMaterializedViewBuilder, _a154, _b111, _c4, PgView, PgMaterializedViewConfig, _a155, _b112, _c5, PgMaterializedView;
26809
+ function isPgView(obj) {
26810
+ return is(obj, PgView2);
26811
+ }
26812
+ function isPgMaterializedView(obj) {
26813
+ return is(obj, PgMaterializedView);
26814
+ }
26815
+ var _a148, DefaultViewBuilderCore, _a149, _b107, ViewBuilder, _a150, _b108, ManualViewBuilder, _a151, MaterializedViewBuilderCore, _a152, _b109, MaterializedViewBuilder, _a153, _b110, ManualMaterializedViewBuilder, _a154, _b111, _c4, PgView2, PgMaterializedViewConfig, _a155, _b112, _c5, PgMaterializedView;
25530
26816
  var init_view = __esm({
25531
26817
  "../drizzle-orm/dist/pg-core/view.js"() {
25532
26818
  "use strict";
@@ -25563,7 +26849,7 @@ var init_view = __esm({
25563
26849
  });
25564
26850
  const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
25565
26851
  return new Proxy(
25566
- new PgView({
26852
+ new PgView2({
25567
26853
  pgConfig: this.config,
25568
26854
  config: {
25569
26855
  name: this.name,
@@ -25585,7 +26871,7 @@ var init_view = __esm({
25585
26871
  }
25586
26872
  existing() {
25587
26873
  return new Proxy(
25588
- new PgView({
26874
+ new PgView2({
25589
26875
  pgConfig: void 0,
25590
26876
  config: {
25591
26877
  name: this.name,
@@ -25604,7 +26890,7 @@ var init_view = __esm({
25604
26890
  }
25605
26891
  as(query) {
25606
26892
  return new Proxy(
25607
- new PgView({
26893
+ new PgView2({
25608
26894
  pgConfig: this.config,
25609
26895
  config: {
25610
26896
  name: this.name,
@@ -25689,7 +26975,12 @@ var init_view = __esm({
25689
26975
  existing() {
25690
26976
  return new Proxy(
25691
26977
  new PgMaterializedView({
25692
- pgConfig: void 0,
26978
+ pgConfig: {
26979
+ tablespace: this.config.tablespace,
26980
+ using: this.config.using,
26981
+ with: this.config.with,
26982
+ withNoData: this.config.withNoData
26983
+ },
25693
26984
  config: {
25694
26985
  name: this.name,
25695
26986
  schema: this.schema,
@@ -25708,7 +26999,12 @@ var init_view = __esm({
25708
26999
  as(query) {
25709
27000
  return new Proxy(
25710
27001
  new PgMaterializedView({
25711
- pgConfig: void 0,
27002
+ pgConfig: {
27003
+ tablespace: this.config.tablespace,
27004
+ using: this.config.using,
27005
+ with: this.config.with,
27006
+ withNoData: this.config.withNoData
27007
+ },
25712
27008
  config: {
25713
27009
  name: this.name,
25714
27010
  schema: this.schema,
@@ -25726,7 +27022,7 @@ var init_view = __esm({
25726
27022
  }
25727
27023
  };
25728
27024
  __publicField(ManualMaterializedViewBuilder, _a153, "PgManualMaterializedViewBuilder");
25729
- PgView = class extends (_c4 = PgViewBase, _b111 = entityKind, _a154 = PgViewConfig, _c4) {
27025
+ PgView2 = class extends (_c4 = PgViewBase, _b111 = entityKind, _a154 = PgViewConfig, _c4) {
25730
27026
  constructor({ pgConfig, config }) {
25731
27027
  super(config);
25732
27028
  __publicField(this, _a154);
@@ -25737,7 +27033,7 @@ var init_view = __esm({
25737
27033
  }
25738
27034
  }
25739
27035
  };
25740
- __publicField(PgView, _b111, "PgView");
27036
+ __publicField(PgView2, _b111, "PgView");
25741
27037
  PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
25742
27038
  PgMaterializedView = class extends (_c5 = PgViewBase, _b112 = entityKind, _a155 = PgMaterializedViewConfig, _c5) {
25743
27039
  constructor({ pgConfig, config }) {
@@ -25932,17 +27228,32 @@ function getTableConfig(table4) {
25932
27228
  schema: schema4
25933
27229
  };
25934
27230
  }
27231
+ function getViewConfig(view4) {
27232
+ return {
27233
+ ...view4[ViewBaseConfig],
27234
+ ...view4[PgViewConfig]
27235
+ };
27236
+ }
27237
+ function getMaterializedViewConfig(view4) {
27238
+ return {
27239
+ ...view4[ViewBaseConfig],
27240
+ ...view4[PgMaterializedViewConfig]
27241
+ };
27242
+ }
25935
27243
  var init_utils4 = __esm({
25936
27244
  "../drizzle-orm/dist/pg-core/utils.js"() {
25937
27245
  "use strict";
25938
27246
  init_entity();
25939
27247
  init_table2();
25940
27248
  init_table();
27249
+ init_view_common();
25941
27250
  init_checks();
25942
27251
  init_foreign_keys();
25943
27252
  init_indexes();
25944
27253
  init_primary_keys();
25945
27254
  init_unique_constraint();
27255
+ init_view_common2();
27256
+ init_view();
25946
27257
  }
25947
27258
  });
25948
27259
 
@@ -26017,7 +27328,7 @@ function buildArrayString(array, sqlType) {
26017
27328
  }).join(",");
26018
27329
  return `{${values}}`;
26019
27330
  }
26020
- var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn;
27331
+ var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery;
26021
27332
  var init_pgSerializer = __esm({
26022
27333
  "src/serializer/pgSerializer.ts"() {
26023
27334
  "use strict";
@@ -26032,27 +27343,21 @@ var init_pgSerializer = __esm({
26032
27343
  indexName = (tableName, columns) => {
26033
27344
  return `${tableName}_${columns.join("_")}_index`;
26034
27345
  };
26035
- generatePgSnapshot = (tables, enums, schemas, sequences, casing2, schemaFilter) => {
27346
+ generatePgSnapshot = (tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter) => {
26036
27347
  const dialect4 = new PgDialect({ casing: casing2 });
26037
27348
  const result = {};
27349
+ const resultViews = {};
26038
27350
  const sequencesToReturn = {};
26039
27351
  const indexesInSchema = {};
26040
27352
  for (const table4 of tables) {
26041
- const {
26042
- name: tableName,
26043
- columns,
26044
- indexes,
26045
- foreignKeys,
26046
- checks,
26047
- schema: schema4,
26048
- primaryKeys,
26049
- uniqueConstraints
26050
- } = getTableConfig(table4);
27353
+ const checksInTable = {};
27354
+ const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema4, primaryKeys, uniqueConstraints } = getTableConfig(table4);
26051
27355
  if (schemaFilter && !schemaFilter.includes(schema4 ?? "public")) {
26052
27356
  continue;
26053
27357
  }
26054
27358
  const columnsObject = {};
26055
27359
  const indexesObject = {};
27360
+ const checksObject = {};
26056
27361
  const foreignKeysObject = {};
26057
27362
  const primaryKeysObject = {};
26058
27363
  const uniqueConstraintObject = {};
@@ -26103,7 +27408,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26103
27408
  column4.uniqueName
26104
27409
  )} on the ${source_default.underline.blue(
26105
27410
  name2
26106
- )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
27411
+ )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
26107
27412
  existingUnique.columns.join(",")
26108
27413
  )} columns
26109
27414
  `)}`
@@ -26124,9 +27429,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26124
27429
  columnToSet.default = `'${column4.default}'`;
26125
27430
  } else {
26126
27431
  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
26127
- columnToSet.default = `'${JSON.stringify(
26128
- column4.default
26129
- )}'::${sqlTypeLowered}`;
27432
+ columnToSet.default = `'${JSON.stringify(column4.default)}'::${sqlTypeLowered}`;
26130
27433
  } else if (column4.default instanceof Date) {
26131
27434
  if (sqlTypeLowered === "date") {
26132
27435
  columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
@@ -26136,10 +27439,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26136
27439
  columnToSet.default = `'${column4.default.toISOString()}'`;
26137
27440
  }
26138
27441
  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column4.default)) {
26139
- columnToSet.default = `'${buildArrayString(
26140
- column4.default,
26141
- sqlTypeLowered
26142
- )}'`;
27442
+ columnToSet.default = `'${buildArrayString(column4.default, sqlTypeLowered)}'`;
26143
27443
  } else {
26144
27444
  columnToSet.default = column4.default;
26145
27445
  }
@@ -26169,17 +27469,13 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26169
27469
  if (typeof existingUnique !== "undefined") {
26170
27470
  console.log(
26171
27471
  `
26172
- ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
26173
- tableName
26174
- )} table.
26175
- The unique constraint ${source_default.underline.blue(
26176
- name2
26177
- )} on the ${source_default.underline.blue(
26178
- columnNames.join(",")
26179
- )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
26180
- existingUnique.columns.join(",")
26181
- )} columns
26182
- `)}`
27472
+ ${withStyle.errorWarning(
27473
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table.
27474
+ The unique constraint ${source_default.underline.blue(name2)} on the ${source_default.underline.blue(
27475
+ columnNames.join(",")
27476
+ )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
27477
+ `
27478
+ )}`
26183
27479
  );
26184
27480
  process.exit(1);
26185
27481
  }
@@ -26232,9 +27528,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26232
27528
  console.log(
26233
27529
  `
26234
27530
  ${withStyle.errorWarning(
26235
- `Please specify an index name in ${getTableName(
26236
- value.config.table
26237
- )} table that has "${dialect4.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
27531
+ `Please specify an index name in ${getTableName(value.config.table)} table that has "${dialect4.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
26238
27532
  )}`
26239
27533
  );
26240
27534
  process.exit(1);
@@ -26252,9 +27546,7 @@ ${withStyle.errorWarning(
26252
27546
  tableName
26253
27547
  )} table with the ${source_default.blueBright(
26254
27548
  "vector"
26255
- )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(
26256
- ", "
26257
- )}].
27549
+ )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}].
26258
27550
 
26259
27551
  You can specify it using current syntax: ${source_default.underline(
26260
27552
  `index("${value.config.name}").using("${value.config.method}", table.${name3}.op("${vectorOps[0]}"))`
@@ -26295,9 +27587,7 @@ You can check the "pg_vector" docs for more info: https://github.com/pgvector/pg
26295
27587
  console.log(
26296
27588
  `
26297
27589
  ${withStyle.errorWarning(
26298
- `We've found duplicated index name across ${source_default.underline.blue(
26299
- schema4 ?? "public"
26300
- )} schema. Please rename your index in either the ${source_default.underline.blue(
27590
+ `We've found duplicated index name across ${source_default.underline.blue(schema4 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
26301
27591
  tableName
26302
27592
  )} table or the table with the duplicated index name`
26303
27593
  )}`
@@ -26318,6 +27608,33 @@ ${withStyle.errorWarning(
26318
27608
  with: value.config.with ?? {}
26319
27609
  };
26320
27610
  });
27611
+ checks.forEach((check) => {
27612
+ const checkName = check.name;
27613
+ if (typeof checksInTable[`"${schema4 ?? "public"}"."${tableName}"`] !== "undefined") {
27614
+ if (checksInTable[`"${schema4 ?? "public"}"."${tableName}"`].includes(check.name)) {
27615
+ console.log(
27616
+ `
27617
+ ${withStyle.errorWarning(
27618
+ `We've found duplicated check constraint name across ${source_default.underline.blue(
27619
+ schema4 ?? "public"
27620
+ )} schema in ${source_default.underline.blue(
27621
+ tableName
27622
+ )}. Please rename your check constraint in either the ${source_default.underline.blue(
27623
+ tableName
27624
+ )} table or the table with the duplicated check contraint name`
27625
+ )}`
27626
+ );
27627
+ process.exit(1);
27628
+ }
27629
+ checksInTable[`"${schema4 ?? "public"}"."${tableName}"`].push(checkName);
27630
+ } else {
27631
+ checksInTable[`"${schema4 ?? "public"}"."${tableName}"`] = [check.name];
27632
+ }
27633
+ checksObject[checkName] = {
27634
+ name: checkName,
27635
+ value: dialect4.sqlToQuery(check.value).sql
27636
+ };
27637
+ });
26321
27638
  const tableKey2 = `${schema4 ?? "public"}.${tableName}`;
26322
27639
  result[tableKey2] = {
26323
27640
  name: tableName,
@@ -26326,7 +27643,8 @@ ${withStyle.errorWarning(
26326
27643
  indexes: indexesObject,
26327
27644
  foreignKeys: foreignKeysObject,
26328
27645
  compositePrimaryKeys: primaryKeysObject,
26329
- uniqueConstraints: uniqueConstraintObject
27646
+ uniqueConstraints: uniqueConstraintObject,
27647
+ checkConstraints: checksObject
26330
27648
  };
26331
27649
  }
26332
27650
  for (const sequence of sequences) {
@@ -26350,6 +27668,136 @@ ${withStyle.errorWarning(
26350
27668
  } else {
26351
27669
  }
26352
27670
  }
27671
+ const combinedViews = [...views, ...matViews];
27672
+ for (const view4 of combinedViews) {
27673
+ let viewName;
27674
+ let schema4;
27675
+ let query;
27676
+ let selectedFields;
27677
+ let isExisting;
27678
+ let withOption;
27679
+ let tablespace;
27680
+ let using;
27681
+ let withNoData;
27682
+ let materialized = false;
27683
+ if (is(view4, PgView2)) {
27684
+ ({ name: viewName, schema: schema4, query, selectedFields, isExisting, with: withOption } = getViewConfig(view4));
27685
+ } else {
27686
+ ({ name: viewName, schema: schema4, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = getMaterializedViewConfig(view4));
27687
+ materialized = true;
27688
+ }
27689
+ const viewSchema = schema4 ?? "public";
27690
+ const viewKey = `${viewSchema}.${viewName}`;
27691
+ const columnsObject = {};
27692
+ const uniqueConstraintObject = {};
27693
+ const existingView = resultViews[viewKey];
27694
+ if (typeof existingView !== "undefined") {
27695
+ console.log(
27696
+ `
27697
+ ${withStyle.errorWarning(
27698
+ `We've found duplicated view name across ${source_default.underline.blue(schema4 ?? "public")} schema. Please rename your view`
27699
+ )}`
27700
+ );
27701
+ process.exit(1);
27702
+ }
27703
+ for (const key in selectedFields) {
27704
+ if (is(selectedFields[key], PgColumn)) {
27705
+ const column4 = selectedFields[key];
27706
+ const notNull = column4.notNull;
27707
+ const primaryKey = column4.primary;
27708
+ const sqlTypeLowered = column4.getSQLType().toLowerCase();
27709
+ const typeSchema = is(column4, PgEnumColumn) ? column4.enum.schema || "public" : void 0;
27710
+ const generated = column4.generated;
27711
+ const identity = column4.generatedIdentity;
27712
+ const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
27713
+ const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column4.columnType) : "1");
27714
+ const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column4.getSQLType()));
27715
+ const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
27716
+ const cache = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
27717
+ const columnToSet = {
27718
+ name: column4.name,
27719
+ type: column4.getSQLType(),
27720
+ typeSchema,
27721
+ primaryKey,
27722
+ notNull,
27723
+ generated: generated ? {
27724
+ as: is(generated.as, SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
27725
+ type: "stored"
27726
+ } : void 0,
27727
+ identity: identity ? {
27728
+ type: identity.type,
27729
+ name: identity.sequenceName ?? `${viewName}_${column4.name}_seq`,
27730
+ schema: schema4 ?? "public",
27731
+ increment,
27732
+ startWith,
27733
+ minValue,
27734
+ maxValue,
27735
+ cache,
27736
+ cycle: identity?.sequenceOptions?.cycle ?? false
27737
+ } : void 0
27738
+ };
27739
+ if (column4.isUnique) {
27740
+ const existingUnique = uniqueConstraintObject[column4.uniqueName];
27741
+ if (typeof existingUnique !== "undefined") {
27742
+ console.log(
27743
+ `
27744
+ ${withStyle.errorWarning(
27745
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table.
27746
+ The unique constraint ${source_default.underline.blue(column4.uniqueName)} on the ${source_default.underline.blue(
27747
+ column4.name
27748
+ )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
27749
+ `
27750
+ )}`
27751
+ );
27752
+ process.exit(1);
27753
+ }
27754
+ uniqueConstraintObject[column4.uniqueName] = {
27755
+ name: column4.uniqueName,
27756
+ nullsNotDistinct: column4.uniqueType === "not distinct",
27757
+ columns: [columnToSet.name]
27758
+ };
27759
+ }
27760
+ if (column4.default !== void 0) {
27761
+ if (is(column4.default, SQL)) {
27762
+ columnToSet.default = sqlToStr(column4.default, casing2);
27763
+ } else {
27764
+ if (typeof column4.default === "string") {
27765
+ columnToSet.default = `'${column4.default}'`;
27766
+ } else {
27767
+ if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
27768
+ columnToSet.default = `'${JSON.stringify(column4.default)}'::${sqlTypeLowered}`;
27769
+ } else if (column4.default instanceof Date) {
27770
+ if (sqlTypeLowered === "date") {
27771
+ columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
27772
+ } else if (sqlTypeLowered === "timestamp") {
27773
+ columnToSet.default = `'${column4.default.toISOString().replace("T", " ").slice(0, 23)}'`;
27774
+ } else {
27775
+ columnToSet.default = `'${column4.default.toISOString()}'`;
27776
+ }
27777
+ } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column4.default)) {
27778
+ columnToSet.default = `'${buildArrayString(column4.default, sqlTypeLowered)}'`;
27779
+ } else {
27780
+ columnToSet.default = column4.default;
27781
+ }
27782
+ }
27783
+ }
27784
+ }
27785
+ columnsObject[column4.name] = columnToSet;
27786
+ }
27787
+ }
27788
+ resultViews[viewKey] = {
27789
+ columns: columnsObject,
27790
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
27791
+ name: viewName,
27792
+ schema: viewSchema,
27793
+ isExisting,
27794
+ with: withOption,
27795
+ withNoData,
27796
+ materialized,
27797
+ tablespace,
27798
+ using
27799
+ };
27800
+ }
26353
27801
  const enumsToReturn = enums.reduce((map, obj) => {
26354
27802
  const enumSchema3 = obj.schema || "public";
26355
27803
  const key = `${enumSchema3}.${obj.enumName}`;
@@ -26376,6 +27824,7 @@ ${withStyle.errorWarning(
26376
27824
  enums: enumsToReturn,
26377
27825
  schemas: schemasObject,
26378
27826
  sequences: sequencesToReturn,
27827
+ views: resultViews,
26379
27828
  _meta: {
26380
27829
  schemas: {},
26381
27830
  tables: {},
@@ -26392,10 +27841,25 @@ ${withStyle.errorWarning(
26392
27841
  };
26393
27842
  fromDatabase = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
26394
27843
  const result = {};
27844
+ const views = {};
26395
27845
  const internals = { tables: {} };
26396
- const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
27846
+ const where = schemaFilters.map((t) => `n.nspname = '${t}'`).join(" or ");
26397
27847
  const allTables = await db.query(
26398
- `SELECT table_schema, table_name FROM information_schema.tables${where === "" ? "" : ` WHERE ${where}`};`
27848
+ `SELECT
27849
+ n.nspname AS table_schema,
27850
+ c.relname AS table_name,
27851
+ CASE
27852
+ WHEN c.relkind = 'r' THEN 'table'
27853
+ WHEN c.relkind = 'v' THEN 'view'
27854
+ WHEN c.relkind = 'm' THEN 'materialized_view'
27855
+ END AS type
27856
+ FROM
27857
+ pg_catalog.pg_class c
27858
+ JOIN
27859
+ pg_catalog.pg_namespace n ON n.oid = c.relnamespace
27860
+ WHERE
27861
+ c.relkind IN ('r', 'v', 'm')
27862
+ ${where === "" ? "" : ` AND ${where}`};`
26399
27863
  );
26400
27864
  const schemas = new Set(allTables.map((it) => it.table_schema));
26401
27865
  schemas.delete("public");
@@ -26415,6 +27879,8 @@ ${withStyle.errorWarning(
26415
27879
  let indexesCount = 0;
26416
27880
  let foreignKeysCount = 0;
26417
27881
  let tableCount = 0;
27882
+ let checksCount = 0;
27883
+ let viewsCount = 0;
26418
27884
  const sequencesToReturn = {};
26419
27885
  const seqWhere = schemaFilters.map((t) => `schemaname = '${t}'`).join(" or ");
26420
27886
  const allSequences = await db.query(
@@ -26473,7 +27939,7 @@ ${withStyle.errorWarning(
26473
27939
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
26474
27940
  }
26475
27941
  const sequencesInColumns = [];
26476
- const all = allTables.map((row) => {
27942
+ const all = allTables.filter((it) => it.type === "table").map((row) => {
26477
27943
  return new Promise(async (res, rej) => {
26478
27944
  const tableName = row.table_name;
26479
27945
  if (!tablesFilter(tableName)) return res("");
@@ -26485,42 +27951,8 @@ ${withStyle.errorWarning(
26485
27951
  const foreignKeysToReturn = {};
26486
27952
  const primaryKeys = {};
26487
27953
  const uniqueConstrains = {};
26488
- const tableResponse = await db.query(
26489
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
26490
- , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
26491
- AND EXISTS (
26492
- SELECT FROM pg_attrdef ad
26493
- WHERE ad.adrelid = a.attrelid
26494
- AND ad.adnum = a.attnum
26495
- AND pg_get_expr(ad.adbin, ad.adrelid)
26496
- = 'nextval('''
26497
- || (pg_get_serial_sequence (a.attrelid::regclass::text
26498
- , a.attname))::regclass
26499
- || '''::regclass)'
26500
- )
26501
- THEN CASE a.atttypid
26502
- WHEN 'int'::regtype THEN 'serial'
26503
- WHEN 'int8'::regtype THEN 'bigserial'
26504
- WHEN 'int2'::regtype THEN 'smallserial'
26505
- END
26506
- ELSE format_type(a.atttypid, a.atttypmod)
26507
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
26508
- pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
26509
- INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
26510
- INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
26511
- INFORMATION_SCHEMA.COLUMNS.is_generated, generation_expression,
26512
- INFORMATION_SCHEMA.COLUMNS.is_identity,INFORMATION_SCHEMA.COLUMNS.identity_generation,
26513
- INFORMATION_SCHEMA.COLUMNS.identity_start, INFORMATION_SCHEMA.COLUMNS.identity_increment,
26514
- INFORMATION_SCHEMA.COLUMNS.identity_maximum, INFORMATION_SCHEMA.COLUMNS.identity_minimum,
26515
- INFORMATION_SCHEMA.COLUMNS.identity_cycle
26516
- FROM pg_attribute a
26517
- JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
26518
- JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
26519
- WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
26520
- AND a.attnum > 0
26521
- AND NOT a.attisdropped
26522
- ORDER BY a.attnum;`
26523
- );
27954
+ const checkConstraints = {};
27955
+ const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
26524
27956
  const tableConstraints = await db.query(
26525
27957
  `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
26526
27958
  FROM information_schema.table_constraints tc
@@ -26529,6 +27961,28 @@ ${withStyle.errorWarning(
26529
27961
  AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
26530
27962
  WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
26531
27963
  );
27964
+ const tableChecks = await db.query(`SELECT
27965
+ tc.constraint_name,
27966
+ tc.constraint_type,
27967
+ pg_get_constraintdef(con.oid) AS constraint_definition
27968
+ FROM
27969
+ information_schema.table_constraints AS tc
27970
+ JOIN pg_constraint AS con
27971
+ ON tc.constraint_name = con.conname
27972
+ AND con.conrelid = (
27973
+ SELECT oid
27974
+ FROM pg_class
27975
+ WHERE relname = tc.table_name
27976
+ AND relnamespace = (
27977
+ SELECT oid
27978
+ FROM pg_namespace
27979
+ WHERE nspname = tc.constraint_schema
27980
+ )
27981
+ )
27982
+ WHERE
27983
+ tc.table_name = '${tableName}'
27984
+ AND tc.constraint_schema = '${tableSchema}'
27985
+ AND tc.constraint_type = 'CHECK';`);
26532
27986
  columnsCount += tableResponse.length;
26533
27987
  if (progressCallback) {
26534
27988
  progressCallback("columns", columnsCount, "fetching");
@@ -26602,13 +28056,9 @@ ${withStyle.errorWarning(
26602
28056
  foreignKeysToReturn[foreignKeyName].columnsFrom = [
26603
28057
  ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
26604
28058
  ];
26605
- foreignKeysToReturn[foreignKeyName].columnsTo = [
26606
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
26607
- ];
28059
+ foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
26608
28060
  }
26609
- const uniqueConstrainsRows = tableConstraints.filter(
26610
- (mapRow) => mapRow.constraint_type === "UNIQUE"
26611
- );
28061
+ const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
26612
28062
  for (const unqs of uniqueConstrainsRows) {
26613
28063
  const columnName = unqs.column_name;
26614
28064
  const constraintName = unqs.constraint_name;
@@ -26622,8 +28072,21 @@ ${withStyle.errorWarning(
26622
28072
  };
26623
28073
  }
26624
28074
  }
28075
+ checksCount += tableChecks.length;
28076
+ if (progressCallback) {
28077
+ progressCallback("checks", checksCount, "fetching");
28078
+ }
28079
+ for (const checks of tableChecks) {
28080
+ let checkValue = checks.constraint_definition;
28081
+ const constraintName = checks.constraint_name;
28082
+ checkValue = checkValue.replace(/^CHECK\s*\(\(/, "").replace(/\)\)\s*$/, "");
28083
+ checkConstraints[constraintName] = {
28084
+ name: constraintName,
28085
+ value: checkValue
28086
+ };
28087
+ }
26625
28088
  for (const columnResponse of tableResponse) {
26626
- const columnName = columnResponse.attname;
28089
+ const columnName = columnResponse.column_name;
26627
28090
  const columnAdditionalDT = columnResponse.additional_dt;
26628
28091
  const columnDimensions = columnResponse.array_dimensions;
26629
28092
  const enumType2 = columnResponse.enum_name;
@@ -26643,9 +28106,7 @@ ${withStyle.errorWarning(
26643
28106
  const primaryKey = tableConstraints.filter(
26644
28107
  (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
26645
28108
  );
26646
- const cprimaryKey = tableConstraints.filter(
26647
- (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
26648
- );
28109
+ const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
26649
28110
  if (cprimaryKey.length > 1) {
26650
28111
  const tableCompositePkName = await db.query(
26651
28112
  `SELECT conname AS primary_key
@@ -26668,10 +28129,7 @@ ${withStyle.errorWarning(
26668
28129
  [columnName]: {
26669
28130
  isArray: true,
26670
28131
  dimensions: columnDimensions,
26671
- rawType: columnTypeMapped.substring(
26672
- 0,
26673
- columnTypeMapped.length - 2
26674
- )
28132
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
26675
28133
  }
26676
28134
  }
26677
28135
  };
@@ -26680,19 +28138,12 @@ ${withStyle.errorWarning(
26680
28138
  internals.tables[tableName].columns[columnName] = {
26681
28139
  isArray: true,
26682
28140
  dimensions: columnDimensions,
26683
- rawType: columnTypeMapped.substring(
26684
- 0,
26685
- columnTypeMapped.length - 2
26686
- )
28141
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
26687
28142
  };
26688
28143
  }
26689
28144
  }
26690
28145
  }
26691
- const defaultValue = defaultForColumn(
26692
- columnResponse,
26693
- internals,
26694
- tableName
26695
- );
28146
+ const defaultValue = defaultForColumn(columnResponse, internals, tableName);
26696
28147
  if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
26697
28148
  if (typeof internals.tables[tableName] === "undefined") {
26698
28149
  internals.tables[tableName] = {
@@ -26805,7 +28256,9 @@ ${withStyle.errorWarning(
26805
28256
  WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
26806
28257
  group by index_name, table_name,schemaname, generated_by_constraint;`
26807
28258
  );
26808
- const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
28259
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
28260
+ (it) => it.index_name
28261
+ );
26809
28262
  for (const dbIndex of dbIndexes) {
26810
28263
  const indexName2 = dbIndex.indexname;
26811
28264
  const indexColumnName = dbIndex.column_name;
@@ -26865,7 +28318,8 @@ ${withStyle.errorWarning(
26865
28318
  indexes: indexToReturn,
26866
28319
  foreignKeys: foreignKeysToReturn,
26867
28320
  compositePrimaryKeys: primaryKeys,
26868
- uniqueConstraints: uniqueConstrains
28321
+ uniqueConstraints: uniqueConstrains,
28322
+ checkConstraints
26869
28323
  };
26870
28324
  } catch (e) {
26871
28325
  rej(e);
@@ -26879,10 +28333,181 @@ ${withStyle.errorWarning(
26879
28333
  }
26880
28334
  for await (const _2 of all) {
26881
28335
  }
28336
+ const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
28337
+ return new Promise(async (res, rej) => {
28338
+ const viewName = row.table_name;
28339
+ if (!tablesFilter(viewName)) return res("");
28340
+ tableCount += 1;
28341
+ const viewSchema = row.table_schema;
28342
+ try {
28343
+ const columnToReturn = {};
28344
+ const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
28345
+ for (const viewResponse of viewResponses) {
28346
+ const columnName = viewResponse.column_name;
28347
+ const columnAdditionalDT = viewResponse.additional_dt;
28348
+ const columnDimensions = viewResponse.array_dimensions;
28349
+ const enumType2 = viewResponse.enum_name;
28350
+ let columnType = viewResponse.data_type;
28351
+ const typeSchema = viewResponse.type_schema;
28352
+ const isGenerated = viewResponse.is_generated === "ALWAYS";
28353
+ const generationExpression = viewResponse.generation_expression;
28354
+ const isIdentity = viewResponse.is_identity === "YES";
28355
+ const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
28356
+ const identityStart = viewResponse.identity_start;
28357
+ const identityIncrement = viewResponse.identity_increment;
28358
+ const identityMaximum = viewResponse.identity_maximum;
28359
+ const identityMinimum = viewResponse.identity_minimum;
28360
+ const identityCycle = viewResponse.identity_cycle === "YES";
28361
+ const identityName = viewResponse.seq_name;
28362
+ const defaultValueRes = viewResponse.column_default;
28363
+ const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
28364
+ let columnTypeMapped = columnType;
28365
+ if (columnAdditionalDT === "ARRAY") {
28366
+ if (typeof internals.tables[viewName] === "undefined") {
28367
+ internals.tables[viewName] = {
28368
+ columns: {
28369
+ [columnName]: {
28370
+ isArray: true,
28371
+ dimensions: columnDimensions,
28372
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
28373
+ }
28374
+ }
28375
+ };
28376
+ } else {
28377
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
28378
+ internals.tables[viewName].columns[columnName] = {
28379
+ isArray: true,
28380
+ dimensions: columnDimensions,
28381
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
28382
+ };
28383
+ }
28384
+ }
28385
+ }
28386
+ const defaultValue = defaultForColumn(viewResponse, internals, viewName);
28387
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
28388
+ if (typeof internals.tables[viewName] === "undefined") {
28389
+ internals.tables[viewName] = {
28390
+ columns: {
28391
+ [columnName]: {
28392
+ isDefaultAnExpression: true
28393
+ }
28394
+ }
28395
+ };
28396
+ } else {
28397
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
28398
+ internals.tables[viewName].columns[columnName] = {
28399
+ isDefaultAnExpression: true
28400
+ };
28401
+ } else {
28402
+ internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
28403
+ }
28404
+ }
28405
+ }
28406
+ const isSerial = columnType === "serial";
28407
+ if (columnTypeMapped.startsWith("numeric(")) {
28408
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
28409
+ }
28410
+ if (columnAdditionalDT === "ARRAY") {
28411
+ for (let i = 1; i < Number(columnDimensions); i++) {
28412
+ columnTypeMapped += "[]";
28413
+ }
28414
+ }
28415
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
28416
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
28417
+ columnToReturn[columnName] = {
28418
+ name: columnName,
28419
+ type: (
28420
+ // filter vectors, but in future we should filter any extension that was installed by user
28421
+ columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
28422
+ ),
28423
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
28424
+ primaryKey,
28425
+ notNull: viewResponse.is_nullable === "NO",
28426
+ generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
28427
+ identity: isIdentity ? {
28428
+ type: identityGeneration,
28429
+ name: identityName,
28430
+ increment: stringFromDatabaseIdentityProperty(identityIncrement),
28431
+ minValue: stringFromDatabaseIdentityProperty(identityMinimum),
28432
+ maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
28433
+ startWith: stringFromDatabaseIdentityProperty(identityStart),
28434
+ cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${viewSchema}.${identityName}`]?.cache ? sequencesToReturn[`${viewSchema}.${identityName}`]?.cache : void 0,
28435
+ cycle: identityCycle,
28436
+ schema: viewSchema
28437
+ } : void 0
28438
+ };
28439
+ if (identityName) {
28440
+ delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
28441
+ delete sequencesToReturn[identityName];
28442
+ }
28443
+ if (!isSerial && typeof defaultValue !== "undefined") {
28444
+ columnToReturn[columnName].default = defaultValue;
28445
+ }
28446
+ }
28447
+ const [viewInfo] = await db.query(`
28448
+ SELECT
28449
+ c.relname AS view_name,
28450
+ n.nspname AS schema_name,
28451
+ pg_get_viewdef(c.oid, true) AS definition,
28452
+ ts.spcname AS tablespace_name,
28453
+ c.reloptions AS options,
28454
+ pg_tablespace_location(ts.oid) AS location
28455
+ FROM
28456
+ pg_class c
28457
+ JOIN
28458
+ pg_namespace n ON c.relnamespace = n.oid
28459
+ LEFT JOIN
28460
+ pg_tablespace ts ON c.reltablespace = ts.oid
28461
+ WHERE
28462
+ (c.relkind = 'm' OR c.relkind = 'v')
28463
+ AND n.nspname = '${viewSchema}'
28464
+ AND c.relname = '${viewName}';`);
28465
+ const resultWith = {};
28466
+ if (viewInfo.options) {
28467
+ viewInfo.options.forEach((pair) => {
28468
+ const splitted = pair.split("=");
28469
+ const key = splitted[0];
28470
+ const value = splitted[1];
28471
+ if (value === "true") {
28472
+ resultWith[key] = true;
28473
+ } else if (value === "false") {
28474
+ resultWith[key] = false;
28475
+ } else if (!isNaN(Number(value))) {
28476
+ resultWith[key] = Number(value);
28477
+ } else {
28478
+ resultWith[key] = value;
28479
+ }
28480
+ });
28481
+ }
28482
+ const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
28483
+ const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
28484
+ const materialized = row.type === "materialized_view";
28485
+ views[`${viewSchema}.${viewName}`] = {
28486
+ name: viewName,
28487
+ schema: viewSchema,
28488
+ columns: columnToReturn,
28489
+ isExisting: false,
28490
+ definition,
28491
+ materialized,
28492
+ with: withOption,
28493
+ tablespace: viewInfo.tablespace_name ?? void 0
28494
+ };
28495
+ } catch (e) {
28496
+ rej(e);
28497
+ return;
28498
+ }
28499
+ res("");
28500
+ });
28501
+ });
28502
+ viewsCount = allViews.length;
28503
+ for await (const _2 of allViews) {
28504
+ }
26882
28505
  if (progressCallback) {
26883
28506
  progressCallback("columns", columnsCount, "done");
26884
28507
  progressCallback("indexes", indexesCount, "done");
26885
28508
  progressCallback("fks", foreignKeysCount, "done");
28509
+ progressCallback("checks", checksCount, "done");
28510
+ progressCallback("views", viewsCount, "done");
26886
28511
  }
26887
28512
  const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
26888
28513
  return {
@@ -26892,6 +28517,7 @@ ${withStyle.errorWarning(
26892
28517
  enums: enumsToReturn,
26893
28518
  schemas: schemasObject,
26894
28519
  sequences: sequencesToReturn,
28520
+ views,
26895
28521
  _meta: {
26896
28522
  schemas: {},
26897
28523
  tables: {},
@@ -26901,7 +28527,7 @@ ${withStyle.errorWarning(
26901
28527
  };
26902
28528
  };
26903
28529
  defaultForColumn = (column4, internals, tableName) => {
26904
- const columnName = column4.attname;
28530
+ const columnName = column4.column_name;
26905
28531
  const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false;
26906
28532
  if (column4.column_default === null) {
26907
28533
  return void 0;
@@ -26954,6 +28580,8 @@ ${withStyle.errorWarning(
26954
28580
  }
26955
28581
  return columnDefaultAsString;
26956
28582
  }
28583
+ } else if (column4.data_type.includes("numeric")) {
28584
+ return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
26957
28585
  } else if (column4.data_type === "json" || column4.data_type === "jsonb") {
26958
28586
  const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
26959
28587
  return `'${jsonWithoutSpaces}'::${column4.data_type}`;
@@ -26967,6 +28595,75 @@ ${withStyle.errorWarning(
26967
28595
  return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
26968
28596
  }
26969
28597
  };
28598
+ getColumnsInfoQuery = ({ schema: schema4, table: table4, db }) => {
28599
+ return db.query(
28600
+ `SELECT
28601
+ a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
28602
+ a.attname AS column_name, -- Column name
28603
+ CASE
28604
+ WHEN NOT a.attisdropped THEN
28605
+ CASE
28606
+ WHEN a.attnotnull THEN 'NO'
28607
+ ELSE 'YES'
28608
+ END
28609
+ ELSE NULL
28610
+ END AS is_nullable, -- NULL or NOT NULL constraint
28611
+ a.attndims AS array_dimensions, -- Array dimensions
28612
+ CASE
28613
+ WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
28614
+ AND EXISTS (
28615
+ SELECT FROM pg_attrdef ad
28616
+ WHERE ad.adrelid = a.attrelid
28617
+ AND ad.adnum = a.attnum
28618
+ AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
28619
+ || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
28620
+ )
28621
+ THEN CASE a.atttypid
28622
+ WHEN 'int'::regtype THEN 'serial'
28623
+ WHEN 'int8'::regtype THEN 'bigserial'
28624
+ WHEN 'int2'::regtype THEN 'smallserial'
28625
+ END
28626
+ ELSE format_type(a.atttypid, a.atttypmod)
28627
+ END AS data_type, -- Column data type
28628
+ -- ns.nspname AS type_schema, -- Schema name
28629
+ pg_get_serial_sequence('"${schema4}"."${table4}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any)
28630
+ c.column_default, -- Column default value
28631
+ c.data_type AS additional_dt, -- Data type from information_schema
28632
+ c.udt_name AS enum_name, -- Enum type (if applicable)
28633
+ c.is_generated, -- Is it a generated column?
28634
+ c.generation_expression, -- Generation expression (if generated)
28635
+ c.is_identity, -- Is it an identity column?
28636
+ c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT)
28637
+ c.identity_start, -- Start value of identity column
28638
+ c.identity_increment, -- Increment for identity column
28639
+ c.identity_maximum, -- Maximum value for identity column
28640
+ c.identity_minimum, -- Minimum value for identity column
28641
+ c.identity_cycle, -- Does the identity column cycle?
28642
+ enum_ns.nspname AS type_schema -- Schema of the enum type
28643
+ FROM
28644
+ pg_attribute a
28645
+ JOIN
28646
+ pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
28647
+ JOIN
28648
+ pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
28649
+ LEFT JOIN
28650
+ information_schema.columns c ON c.column_name = a.attname
28651
+ AND c.table_schema = ns.nspname
28652
+ AND c.table_name = cls.relname -- Match schema and table/view name
28653
+ LEFT JOIN
28654
+ pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
28655
+ LEFT JOIN
28656
+ pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
28657
+ WHERE
28658
+ a.attnum > 0 -- Valid column numbers only
28659
+ AND NOT a.attisdropped -- Skip dropped columns
28660
+ AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
28661
+ AND ns.nspname = '${schema4}' -- Filter by schema
28662
+ AND cls.relname = '${table4}' -- Filter by table name
28663
+ ORDER BY
28664
+ a.attnum; -- Order by column number`
28665
+ );
28666
+ };
26970
28667
  }
26971
28668
  });
26972
28669
 
@@ -27721,7 +29418,9 @@ var init_delete2 = __esm({
27721
29418
  "use strict";
27722
29419
  init_entity();
27723
29420
  init_query_promise();
29421
+ init_selection_proxy();
27724
29422
  init_table3();
29423
+ init_table();
27725
29424
  init_utils2();
27726
29425
  SQLiteDeleteBase = class extends (_b141 = QueryPromise, _a194 = entityKind, _b141) {
27727
29426
  constructor(table4, session, dialect4, withList) {
@@ -27778,6 +29477,26 @@ var init_delete2 = __esm({
27778
29477
  this.config.where = where;
27779
29478
  return this;
27780
29479
  }
29480
+ orderBy(...columns) {
29481
+ if (typeof columns[0] === "function") {
29482
+ const orderBy = columns[0](
29483
+ new Proxy(
29484
+ this.config.table[Table.Symbol.Columns],
29485
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
29486
+ )
29487
+ );
29488
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
29489
+ this.config.orderBy = orderByArray;
29490
+ } else {
29491
+ const orderByArray = columns;
29492
+ this.config.orderBy = orderByArray;
29493
+ }
29494
+ return this;
29495
+ }
29496
+ limit(limit) {
29497
+ this.config.limit = limit;
29498
+ return this;
29499
+ }
27781
29500
  returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
27782
29501
  this.config.returning = orderSelectedFields(fields);
27783
29502
  return this;
@@ -27988,7 +29707,7 @@ var init_view_base2 = __esm({
27988
29707
  "use strict";
27989
29708
  init_entity();
27990
29709
  init_sql();
27991
- SQLiteViewBase = class extends (_b143 = View, _a197 = entityKind, _b143) {
29710
+ SQLiteViewBase = class extends (_b143 = View3, _a197 = entityKind, _b143) {
27992
29711
  };
27993
29712
  __publicField(SQLiteViewBase, _a197, "SQLiteViewBase");
27994
29713
  }
@@ -28043,11 +29762,13 @@ var init_dialect2 = __esm({
28043
29762
  withSqlChunks.push(sql` `);
28044
29763
  return sql.join(withSqlChunks);
28045
29764
  }
28046
- buildDeleteQuery({ table: table4, where, returning, withList }) {
29765
+ buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
28047
29766
  const withSql = this.buildWithCTE(withList);
28048
29767
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
28049
29768
  const whereSql = where ? sql` where ${where}` : void 0;
28050
- return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
29769
+ const orderBySql = this.buildOrderBy(orderBy);
29770
+ const limitSql = this.buildLimit(limit);
29771
+ return sql`${withSql}delete from ${table4}${whereSql}${returningSql}${orderBySql}${limitSql}`;
28051
29772
  }
28052
29773
  buildUpdateSet(table4, set) {
28053
29774
  const tableColumns = table4[Table.Symbol.Columns];
@@ -28065,12 +29786,14 @@ var init_dialect2 = __esm({
28065
29786
  return [res];
28066
29787
  }));
28067
29788
  }
28068
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
29789
+ buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
28069
29790
  const withSql = this.buildWithCTE(withList);
28070
29791
  const setSql = this.buildUpdateSet(table4, set);
28071
29792
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
28072
29793
  const whereSql = where ? sql` where ${where}` : void 0;
28073
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
29794
+ const orderBySql = this.buildOrderBy(orderBy);
29795
+ const limitSql = this.buildLimit(limit);
29796
+ return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
28074
29797
  }
28075
29798
  /**
28076
29799
  * Builds selection SQL with provided fields/expressions
@@ -28123,6 +29846,21 @@ var init_dialect2 = __esm({
28123
29846
  });
28124
29847
  return sql.join(chunks);
28125
29848
  }
29849
+ buildLimit(limit) {
29850
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
29851
+ }
29852
+ buildOrderBy(orderBy) {
29853
+ const orderByList = [];
29854
+ if (orderBy) {
29855
+ for (const [index4, orderByValue] of orderBy.entries()) {
29856
+ orderByList.push(orderByValue);
29857
+ if (index4 < orderBy.length - 1) {
29858
+ orderByList.push(sql`, `);
29859
+ }
29860
+ }
29861
+ }
29862
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
29863
+ }
28126
29864
  buildSelectQuery({
28127
29865
  withList,
28128
29866
  fields,
@@ -28187,15 +29925,6 @@ var init_dialect2 = __esm({
28187
29925
  const joinsSql = sql.join(joinsArray);
28188
29926
  const whereSql = where ? sql` where ${where}` : void 0;
28189
29927
  const havingSql = having ? sql` having ${having}` : void 0;
28190
- const orderByList = [];
28191
- if (orderBy) {
28192
- for (const [index4, orderByValue] of orderBy.entries()) {
28193
- orderByList.push(orderByValue);
28194
- if (index4 < orderBy.length - 1) {
28195
- orderByList.push(sql`, `);
28196
- }
28197
- }
28198
- }
28199
29928
  const groupByList = [];
28200
29929
  if (groupBy) {
28201
29930
  for (const [index4, groupByValue] of groupBy.entries()) {
@@ -28206,8 +29935,8 @@ var init_dialect2 = __esm({
28206
29935
  }
28207
29936
  }
28208
29937
  const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0;
28209
- const orderBySql = orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
28210
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
29938
+ const orderBySql = this.buildOrderBy(orderBy);
29939
+ const limitSql = this.buildLimit(limit);
28211
29940
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
28212
29941
  const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
28213
29942
  if (setOperators.length > 0) {
@@ -28926,7 +30655,7 @@ var init_select3 = __esm({
28926
30655
  };
28927
30656
  }
28928
30657
  if (typeof tableName === "string" && !is(table4, SQL)) {
28929
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
30658
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
28930
30659
  this.config.fields[tableName] = selection;
28931
30660
  }
28932
30661
  }
@@ -29318,7 +31047,9 @@ var init_update2 = __esm({
29318
31047
  "use strict";
29319
31048
  init_entity();
29320
31049
  init_query_promise();
31050
+ init_selection_proxy();
29321
31051
  init_table3();
31052
+ init_table();
29322
31053
  init_utils2();
29323
31054
  _a205 = entityKind;
29324
31055
  SQLiteUpdateBuilder = class {
@@ -29397,6 +31128,26 @@ var init_update2 = __esm({
29397
31128
  this.config.where = where;
29398
31129
  return this;
29399
31130
  }
31131
+ orderBy(...columns) {
31132
+ if (typeof columns[0] === "function") {
31133
+ const orderBy = columns[0](
31134
+ new Proxy(
31135
+ this.config.table[Table.Symbol.Columns],
31136
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
31137
+ )
31138
+ );
31139
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
31140
+ this.config.orderBy = orderByArray;
31141
+ } else {
31142
+ const orderByArray = columns;
31143
+ this.config.orderBy = orderByArray;
31144
+ }
31145
+ return this;
31146
+ }
31147
+ limit(limit) {
31148
+ this.config.limit = limit;
31149
+ return this;
31150
+ }
29400
31151
  returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
29401
31152
  this.config.returning = orderSelectedFields(fields);
29402
31153
  return this;
@@ -30212,15 +31963,6 @@ var init_subquery3 = __esm({
30212
31963
  }
30213
31964
  });
30214
31965
 
30215
- // ../drizzle-orm/dist/sqlite-core/view-common.js
30216
- var SQLiteViewConfig;
30217
- var init_view_common3 = __esm({
30218
- "../drizzle-orm/dist/sqlite-core/view-common.js"() {
30219
- "use strict";
30220
- SQLiteViewConfig = Symbol.for("drizzle:SQLiteViewConfig");
30221
- }
30222
- });
30223
-
30224
31966
  // ../drizzle-orm/dist/sqlite-core/utils.js
30225
31967
  function getTableConfig2(table4) {
30226
31968
  const columns = Object.values(table4[SQLiteTable.Symbol.Columns]);
@@ -30257,11 +31999,18 @@ function getTableConfig2(table4) {
30257
31999
  name: name2
30258
32000
  };
30259
32001
  }
32002
+ function getViewConfig2(view4) {
32003
+ return {
32004
+ ...view4[ViewBaseConfig]
32005
+ // ...view[SQLiteViewConfig],
32006
+ };
32007
+ }
30260
32008
  var init_utils6 = __esm({
30261
32009
  "../drizzle-orm/dist/sqlite-core/utils.js"() {
30262
32010
  "use strict";
30263
32011
  init_entity();
30264
32012
  init_table();
32013
+ init_view_common();
30265
32014
  init_checks2();
30266
32015
  init_foreign_keys2();
30267
32016
  init_indexes2();
@@ -30272,7 +32021,7 @@ var init_utils6 = __esm({
30272
32021
  });
30273
32022
 
30274
32023
  // ../drizzle-orm/dist/sqlite-core/view.js
30275
- var _a222, ViewBuilderCore, _a223, _b155, ViewBuilder2, _a224, _b156, ManualViewBuilder2, _a225, _b157, _c8, SQLiteView;
32024
+ var _a222, ViewBuilderCore, _a223, _b155, ViewBuilder2, _a224, _b156, ManualViewBuilder2, _a225, _b157, SQLiteView2;
30276
32025
  var init_view2 = __esm({
30277
32026
  "../drizzle-orm/dist/sqlite-core/view.js"() {
30278
32027
  "use strict";
@@ -30282,7 +32031,6 @@ var init_view2 = __esm({
30282
32031
  init_query_builder3();
30283
32032
  init_table3();
30284
32033
  init_view_base2();
30285
- init_view_common3();
30286
32034
  _a222 = entityKind;
30287
32035
  ViewBuilderCore = class {
30288
32036
  constructor(name2) {
@@ -30304,8 +32052,8 @@ var init_view2 = __esm({
30304
32052
  });
30305
32053
  const aliasedSelectedFields = qb.getSelectedFields();
30306
32054
  return new Proxy(
30307
- new SQLiteView({
30308
- sqliteConfig: this.config,
32055
+ new SQLiteView2({
32056
+ // sqliteConfig: this.config,
30309
32057
  config: {
30310
32058
  name: this.name,
30311
32059
  schema: void 0,
@@ -30326,8 +32074,7 @@ var init_view2 = __esm({
30326
32074
  }
30327
32075
  existing() {
30328
32076
  return new Proxy(
30329
- new SQLiteView({
30330
- sqliteConfig: void 0,
32077
+ new SQLiteView2({
30331
32078
  config: {
30332
32079
  name: this.name,
30333
32080
  schema: void 0,
@@ -30345,8 +32092,7 @@ var init_view2 = __esm({
30345
32092
  }
30346
32093
  as(query) {
30347
32094
  return new Proxy(
30348
- new SQLiteView({
30349
- sqliteConfig: this.config,
32095
+ new SQLiteView2({
30350
32096
  config: {
30351
32097
  name: this.name,
30352
32098
  schema: void 0,
@@ -30364,15 +32110,12 @@ var init_view2 = __esm({
30364
32110
  }
30365
32111
  };
30366
32112
  __publicField(ManualViewBuilder2, _a224, "SQLiteManualViewBuilder");
30367
- SQLiteView = class extends (_c8 = SQLiteViewBase, _b157 = entityKind, _a225 = SQLiteViewConfig, _c8) {
30368
- constructor({ sqliteConfig, config }) {
32113
+ SQLiteView2 = class extends (_b157 = SQLiteViewBase, _a225 = entityKind, _b157) {
32114
+ constructor({ config }) {
30369
32115
  super(config);
30370
- /** @internal */
30371
- __publicField(this, _a225);
30372
- this[SQLiteViewConfig] = sqliteConfig;
30373
32116
  }
30374
32117
  };
30375
- __publicField(SQLiteView, _b157, "SQLiteView");
32118
+ __publicField(SQLiteView2, _a225, "SQLiteView");
30376
32119
  }
30377
32120
  });
30378
32121
 
@@ -30470,9 +32213,10 @@ var init_sqliteSerializer = __esm({
30470
32213
  init_outputs();
30471
32214
  init_utils();
30472
32215
  init_serializer();
30473
- generateSqliteSnapshot = (tables, casing2) => {
32216
+ generateSqliteSnapshot = (tables, views, casing2) => {
30474
32217
  const dialect4 = new SQLiteSyncDialect({ casing: casing2 });
30475
32218
  const result = {};
32219
+ const resultViews = {};
30476
32220
  const internal = { indexes: {} };
30477
32221
  for (const table4 of tables) {
30478
32222
  const columnsObject = {};
@@ -30480,10 +32224,13 @@ var init_sqliteSerializer = __esm({
30480
32224
  const foreignKeysObject = {};
30481
32225
  const primaryKeysObject = {};
30482
32226
  const uniqueConstraintObject = {};
32227
+ const checkConstraintObject = {};
32228
+ const checksInTable = {};
30483
32229
  const {
30484
32230
  name: tableName,
30485
32231
  columns,
30486
32232
  indexes,
32233
+ checks,
30487
32234
  foreignKeys: tableForeignKeys,
30488
32235
  primaryKeys,
30489
32236
  uniqueConstraints
@@ -30659,19 +32406,95 @@ The unique constraint ${source_default.underline.blue(
30659
32406
  columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
30660
32407
  }
30661
32408
  });
32409
+ checks.forEach((check) => {
32410
+ const checkName = check.name;
32411
+ if (typeof checksInTable[tableName] !== "undefined") {
32412
+ if (checksInTable[tableName].includes(check.name)) {
32413
+ console.log(
32414
+ `
32415
+ ${withStyle.errorWarning(
32416
+ `We've found duplicated check constraint name in ${source_default.underline.blue(
32417
+ tableName
32418
+ )}. Please rename your check constraint in the ${source_default.underline.blue(
32419
+ tableName
32420
+ )} table`
32421
+ )}`
32422
+ );
32423
+ process.exit(1);
32424
+ }
32425
+ checksInTable[tableName].push(checkName);
32426
+ } else {
32427
+ checksInTable[tableName] = [check.name];
32428
+ }
32429
+ checkConstraintObject[checkName] = {
32430
+ name: checkName,
32431
+ value: dialect4.sqlToQuery(check.value).sql
32432
+ };
32433
+ });
30662
32434
  result[tableName] = {
30663
32435
  name: tableName,
30664
32436
  columns: columnsObject,
30665
32437
  indexes: indexesObject,
30666
32438
  foreignKeys: foreignKeysObject,
30667
32439
  compositePrimaryKeys: primaryKeysObject,
30668
- uniqueConstraints: uniqueConstraintObject
32440
+ uniqueConstraints: uniqueConstraintObject,
32441
+ checkConstraints: checkConstraintObject
32442
+ };
32443
+ }
32444
+ for (const view4 of views) {
32445
+ const { name: name2, isExisting, selectedFields, query, schema: schema4 } = getViewConfig2(view4);
32446
+ const columnsObject = {};
32447
+ const existingView = resultViews[name2];
32448
+ if (typeof existingView !== "undefined") {
32449
+ console.log(
32450
+ `
32451
+ ${withStyle.errorWarning(
32452
+ `We've found duplicated view name across ${source_default.underline.blue(
32453
+ schema4 ?? "public"
32454
+ )} schema. Please rename your view`
32455
+ )}`
32456
+ );
32457
+ process.exit(1);
32458
+ }
32459
+ for (const key in selectedFields) {
32460
+ if (is(selectedFields[key], SQLiteColumn)) {
32461
+ const column4 = selectedFields[key];
32462
+ const notNull = column4.notNull;
32463
+ const primaryKey = column4.primary;
32464
+ const generated = column4.generated;
32465
+ const columnToSet = {
32466
+ name: column4.name,
32467
+ type: column4.getSQLType(),
32468
+ primaryKey,
32469
+ notNull,
32470
+ autoincrement: is(column4, SQLiteBaseInteger) ? column4.autoIncrement : false,
32471
+ generated: generated ? {
32472
+ as: is(generated.as, SQL) ? `(${dialect4.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect4.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
32473
+ type: generated.mode ?? "virtual"
32474
+ } : void 0
32475
+ };
32476
+ if (column4.default !== void 0) {
32477
+ if (is(column4.default, SQL)) {
32478
+ columnToSet.default = sqlToStr(column4.default, casing2);
32479
+ } else {
32480
+ columnToSet.default = typeof column4.default === "string" ? `'${column4.default}'` : typeof column4.default === "object" || Array.isArray(column4.default) ? `'${JSON.stringify(column4.default)}'` : column4.default;
32481
+ }
32482
+ }
32483
+ columnsObject[column4.name] = columnToSet;
32484
+ }
32485
+ }
32486
+ resultViews[name2] = {
32487
+ columns: columnsObject,
32488
+ name: name2,
32489
+ isExisting,
32490
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql
30669
32491
  };
30670
32492
  }
30671
32493
  return {
30672
32494
  version: "6",
30673
32495
  dialect: "sqlite",
30674
32496
  tables: result,
32497
+ views: resultViews,
30675
32498
  enums: {},
30676
32499
  _meta: {
30677
32500
  tables: {},
@@ -30682,11 +32505,12 @@ The unique constraint ${source_default.underline.blue(
30682
32505
  };
30683
32506
  fromDatabase2 = async (db, tablesFilter = (table4) => true, progressCallback) => {
30684
32507
  const result = {};
32508
+ const resultViews = {};
30685
32509
  const columns = await db.query(
30686
32510
  `SELECT
30687
- m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk, p.hidden as hidden, m.sql
32511
+ m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk, p.hidden as hidden, m.sql, m.type as type
30688
32512
  FROM sqlite_master AS m JOIN pragma_table_xinfo(m.name) AS p
30689
- WHERE m.type = 'table'
32513
+ WHERE (m.type = 'table' OR m.type = 'view')
30690
32514
  and m.tbl_name != 'sqlite_sequence'
30691
32515
  and m.tbl_name != 'sqlite_stat1'
30692
32516
  and m.tbl_name != '_litestream_seq'
@@ -30712,11 +32536,15 @@ The unique constraint ${source_default.underline.blue(
30712
32536
  let tablesCount = /* @__PURE__ */ new Set();
30713
32537
  let indexesCount = 0;
30714
32538
  let foreignKeysCount = 0;
32539
+ let checksCount = 0;
32540
+ let viewsCount = 0;
30715
32541
  const tableToPk = {};
30716
32542
  let tableToGeneratedColumnsInfo = {};
30717
32543
  for (const column4 of columns) {
30718
32544
  if (!tablesFilter(column4.tableName)) continue;
30719
- columnsCount += 1;
32545
+ if (column4.type !== "view") {
32546
+ columnsCount += 1;
32547
+ }
30720
32548
  if (progressCallback) {
30721
32549
  progressCallback("columns", columnsCount, "fetching");
30722
32550
  }
@@ -30769,7 +32597,8 @@ The unique constraint ${source_default.underline.blue(
30769
32597
  compositePrimaryKeys: {},
30770
32598
  indexes: {},
30771
32599
  foreignKeys: {},
30772
- uniqueConstraints: {}
32600
+ uniqueConstraints: {},
32601
+ checkConstraints: {}
30773
32602
  };
30774
32603
  } else {
30775
32604
  result[tableName].columns[columnName] = newColumn;
@@ -30883,10 +32712,90 @@ WHERE
30883
32712
  progressCallback("indexes", indexesCount, "done");
30884
32713
  progressCallback("enums", 0, "done");
30885
32714
  }
32715
+ const views = await db.query(
32716
+ `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
32717
+ );
32718
+ viewsCount = views.length;
32719
+ if (progressCallback) {
32720
+ progressCallback("views", viewsCount, "fetching");
32721
+ }
32722
+ for (const view4 of views) {
32723
+ const viewName = view4["view_name"];
32724
+ const sql2 = view4["sql"];
32725
+ const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
32726
+ const match2 = sql2.match(regex);
32727
+ if (!match2) {
32728
+ console.log("Could not process view");
32729
+ process.exit(1);
32730
+ }
32731
+ const viewDefinition = match2[1];
32732
+ const columns2 = result[viewName].columns;
32733
+ delete result[viewName];
32734
+ resultViews[viewName] = {
32735
+ columns: columns2,
32736
+ isExisting: false,
32737
+ name: viewName,
32738
+ definition: viewDefinition
32739
+ };
32740
+ }
32741
+ if (progressCallback) {
32742
+ progressCallback("views", viewsCount, "done");
32743
+ }
32744
+ const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi;
32745
+ const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi;
32746
+ let checkCounter = 0;
32747
+ const checkConstraints = {};
32748
+ const checks = await db.query(`SELECT name as "tableName", sql as "sql"
32749
+ FROM sqlite_master
32750
+ WHERE type = 'table' AND name != 'sqlite_sequence';`);
32751
+ for (const check of checks) {
32752
+ if (!tablesFilter(check.tableName)) continue;
32753
+ const { tableName, sql: sql2 } = check;
32754
+ let namedChecks = [...sql2.matchAll(namedCheckPattern)];
32755
+ if (namedChecks.length > 0) {
32756
+ namedChecks.forEach(([_2, checkName, checkValue]) => {
32757
+ checkConstraints[checkName] = {
32758
+ name: checkName,
32759
+ value: checkValue.trim()
32760
+ };
32761
+ });
32762
+ } else {
32763
+ let unnamedChecks = [...sql2.matchAll(unnamedCheckPattern)];
32764
+ unnamedChecks.forEach(([_2, checkValue]) => {
32765
+ let checkName = `${tableName}_check_${++checkCounter}`;
32766
+ checkConstraints[checkName] = {
32767
+ name: checkName,
32768
+ value: checkValue.trim()
32769
+ };
32770
+ });
32771
+ }
32772
+ checksCount += Object.values(checkConstraints).length;
32773
+ if (progressCallback) {
32774
+ progressCallback("checks", checksCount, "fetching");
32775
+ }
32776
+ const table4 = result[tableName];
32777
+ if (!table4) {
32778
+ result[tableName] = {
32779
+ name: tableName,
32780
+ columns: {},
32781
+ compositePrimaryKeys: {},
32782
+ indexes: {},
32783
+ foreignKeys: {},
32784
+ uniqueConstraints: {},
32785
+ checkConstraints
32786
+ };
32787
+ } else {
32788
+ result[tableName].checkConstraints = checkConstraints;
32789
+ }
32790
+ }
32791
+ if (progressCallback) {
32792
+ progressCallback("checks", checksCount, "done");
32793
+ }
30886
32794
  return {
30887
32795
  version: "6",
30888
32796
  dialect: "sqlite",
30889
32797
  tables: result,
32798
+ views: resultViews,
30890
32799
  enums: {},
30891
32800
  _meta: {
30892
32801
  tables: {},
@@ -32275,13 +34184,13 @@ var init_columns3 = __esm({
32275
34184
  });
32276
34185
 
32277
34186
  // ../drizzle-orm/dist/mysql-core/query-builders/count.js
32278
- var _a295, _b220, _c9, _MySqlCountBuilder, MySqlCountBuilder;
34187
+ var _a295, _b220, _c8, _MySqlCountBuilder, MySqlCountBuilder;
32279
34188
  var init_count3 = __esm({
32280
34189
  "../drizzle-orm/dist/mysql-core/query-builders/count.js"() {
32281
34190
  "use strict";
32282
34191
  init_entity();
32283
34192
  init_sql();
32284
- _MySqlCountBuilder = class _MySqlCountBuilder extends (_c9 = SQL, _b220 = entityKind, _a295 = Symbol.toStringTag, _c9) {
34193
+ _MySqlCountBuilder = class _MySqlCountBuilder extends (_c8 = SQL, _b220 = entityKind, _a295 = Symbol.toStringTag, _c8) {
32285
34194
  constructor(params) {
32286
34195
  super(_MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
32287
34196
  __publicField(this, "sql");
@@ -32335,6 +34244,8 @@ var init_delete3 = __esm({
32335
34244
  "use strict";
32336
34245
  init_entity();
32337
34246
  init_query_promise();
34247
+ init_selection_proxy();
34248
+ init_table();
32338
34249
  MySqlDeleteBase = class extends (_b221 = QueryPromise, _a296 = entityKind, _b221) {
32339
34250
  constructor(table4, session, dialect4, withList) {
32340
34251
  super();
@@ -32387,6 +34298,26 @@ var init_delete3 = __esm({
32387
34298
  this.config.where = where;
32388
34299
  return this;
32389
34300
  }
34301
+ orderBy(...columns) {
34302
+ if (typeof columns[0] === "function") {
34303
+ const orderBy = columns[0](
34304
+ new Proxy(
34305
+ this.config.table[Table.Symbol.Columns],
34306
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
34307
+ )
34308
+ );
34309
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
34310
+ this.config.orderBy = orderByArray;
34311
+ } else {
34312
+ const orderByArray = columns;
34313
+ this.config.orderBy = orderByArray;
34314
+ }
34315
+ return this;
34316
+ }
34317
+ limit(limit) {
34318
+ this.config.limit = limit;
34319
+ return this;
34320
+ }
32390
34321
  /** @internal */
32391
34322
  getSQL() {
32392
34323
  return this.dialect.buildDeleteQuery(this.config);
@@ -32614,7 +34545,7 @@ function mysqlTableWithSchema(name2, columns, extraConfig, schema4, baseName = n
32614
34545
  }
32615
34546
  return table4;
32616
34547
  }
32617
- var InlineForeignKeys3, _a299, _b223, _c10, _d4, _e3, MySqlTable, mysqlTable;
34548
+ var InlineForeignKeys3, _a299, _b223, _c9, _d4, _e3, MySqlTable, mysqlTable;
32618
34549
  var init_table4 = __esm({
32619
34550
  "../drizzle-orm/dist/mysql-core/table.js"() {
32620
34551
  "use strict";
@@ -32622,11 +34553,11 @@ var init_table4 = __esm({
32622
34553
  init_table();
32623
34554
  init_all3();
32624
34555
  InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
32625
- MySqlTable = class extends (_e3 = Table, _d4 = entityKind, _c10 = Table.Symbol.Columns, _b223 = InlineForeignKeys3, _a299 = Table.Symbol.ExtraConfigBuilder, _e3) {
34556
+ MySqlTable = class extends (_e3 = Table, _d4 = entityKind, _c9 = Table.Symbol.Columns, _b223 = InlineForeignKeys3, _a299 = Table.Symbol.ExtraConfigBuilder, _e3) {
32626
34557
  constructor() {
32627
34558
  super(...arguments);
32628
34559
  /** @internal */
32629
- __publicField(this, _c10);
34560
+ __publicField(this, _c9);
32630
34561
  /** @internal */
32631
34562
  __publicField(this, _b223, []);
32632
34563
  /** @internal */
@@ -32651,7 +34582,7 @@ var init_view_base3 = __esm({
32651
34582
  "use strict";
32652
34583
  init_entity();
32653
34584
  init_sql();
32654
- MySqlViewBase = class extends (_b224 = View, _a300 = entityKind, _b224) {
34585
+ MySqlViewBase = class extends (_b224 = View3, _a300 = entityKind, _b224) {
32655
34586
  };
32656
34587
  __publicField(MySqlViewBase, _a300, "MySqlViewBase");
32657
34588
  }
@@ -32733,11 +34664,13 @@ var init_dialect3 = __esm({
32733
34664
  withSqlChunks.push(sql` `);
32734
34665
  return sql.join(withSqlChunks);
32735
34666
  }
32736
- buildDeleteQuery({ table: table4, where, returning, withList }) {
34667
+ buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
32737
34668
  const withSql = this.buildWithCTE(withList);
32738
34669
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32739
34670
  const whereSql = where ? sql` where ${where}` : void 0;
32740
- return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
34671
+ const orderBySql = this.buildOrderBy(orderBy);
34672
+ const limitSql = this.buildLimit(limit);
34673
+ return sql`${withSql}delete from ${table4}${whereSql}${orderBySql}${limitSql}${returningSql}`;
32741
34674
  }
32742
34675
  buildUpdateSet(table4, set) {
32743
34676
  const tableColumns = table4[Table.Symbol.Columns];
@@ -32755,12 +34688,14 @@ var init_dialect3 = __esm({
32755
34688
  return [res];
32756
34689
  }));
32757
34690
  }
32758
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
34691
+ buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
32759
34692
  const withSql = this.buildWithCTE(withList);
32760
34693
  const setSql = this.buildUpdateSet(table4, set);
32761
34694
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32762
34695
  const whereSql = where ? sql` where ${where}` : void 0;
32763
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
34696
+ const orderBySql = this.buildOrderBy(orderBy);
34697
+ const limitSql = this.buildLimit(limit);
34698
+ return sql`${withSql}update ${table4} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
32764
34699
  }
32765
34700
  /**
32766
34701
  * Builds selection SQL with provided fields/expressions
@@ -32812,6 +34747,12 @@ var init_dialect3 = __esm({
32812
34747
  });
32813
34748
  return sql.join(chunks);
32814
34749
  }
34750
+ buildLimit(limit) {
34751
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
34752
+ }
34753
+ buildOrderBy(orderBy) {
34754
+ return orderBy && orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0;
34755
+ }
32815
34756
  buildSelectQuery({
32816
34757
  withList,
32817
34758
  fields,
@@ -32865,7 +34806,7 @@ var init_dialect3 = __esm({
32865
34806
  joinsArray.push(
32866
34807
  sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
32867
34808
  );
32868
- } else if (is(table22, View)) {
34809
+ } else if (is(table22, View3)) {
32869
34810
  const viewName = table22[ViewBaseConfig].name;
32870
34811
  const viewSchema = table22[ViewBaseConfig].schema;
32871
34812
  const origViewName = table22[ViewBaseConfig].originalName;
@@ -32886,15 +34827,9 @@ var init_dialect3 = __esm({
32886
34827
  const joinsSql = sql.join(joinsArray);
32887
34828
  const whereSql = where ? sql` where ${where}` : void 0;
32888
34829
  const havingSql = having ? sql` having ${having}` : void 0;
32889
- let orderBySql;
32890
- if (orderBy && orderBy.length > 0) {
32891
- orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
32892
- }
32893
- let groupBySql;
32894
- if (groupBy && groupBy.length > 0) {
32895
- groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
32896
- }
32897
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
34830
+ const orderBySql = this.buildOrderBy(orderBy);
34831
+ const groupBySql = groupBy && groupBy.length > 0 ? sql` group by ${sql.join(groupBy, sql`, `)}` : void 0;
34832
+ const limitSql = this.buildLimit(limit);
32898
34833
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
32899
34834
  let lockingClausesSql;
32900
34835
  if (lockingClause) {
@@ -33881,7 +35816,7 @@ var init_select4 = __esm({
33881
35816
  };
33882
35817
  }
33883
35818
  if (typeof tableName === "string" && !is(table4, SQL)) {
33884
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
35819
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
33885
35820
  this.config.fields[tableName] = selection;
33886
35821
  }
33887
35822
  }
@@ -34277,6 +36212,8 @@ var init_update3 = __esm({
34277
36212
  "use strict";
34278
36213
  init_entity();
34279
36214
  init_query_promise();
36215
+ init_selection_proxy();
36216
+ init_table();
34280
36217
  init_utils2();
34281
36218
  _a306 = entityKind;
34282
36219
  MySqlUpdateBuilder = class {
@@ -34346,6 +36283,26 @@ var init_update3 = __esm({
34346
36283
  this.config.where = where;
34347
36284
  return this;
34348
36285
  }
36286
+ orderBy(...columns) {
36287
+ if (typeof columns[0] === "function") {
36288
+ const orderBy = columns[0](
36289
+ new Proxy(
36290
+ this.config.table[Table.Symbol.Columns],
36291
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
36292
+ )
36293
+ );
36294
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
36295
+ this.config.orderBy = orderByArray;
36296
+ } else {
36297
+ const orderByArray = columns;
36298
+ this.config.orderBy = orderByArray;
36299
+ }
36300
+ return this;
36301
+ }
36302
+ limit(limit) {
36303
+ this.config.limit = limit;
36304
+ return this;
36305
+ }
34349
36306
  /** @internal */
34350
36307
  getSQL() {
34351
36308
  return this.dialect.buildUpdateQuery(this.config);
@@ -34827,7 +36784,7 @@ var init_primary_keys3 = __esm({
34827
36784
 
34828
36785
  // ../drizzle-orm/dist/mysql-core/view-common.js
34829
36786
  var MySqlViewConfig;
34830
- var init_view_common4 = __esm({
36787
+ var init_view_common3 = __esm({
34831
36788
  "../drizzle-orm/dist/mysql-core/view-common.js"() {
34832
36789
  "use strict";
34833
36790
  MySqlViewConfig = Symbol.for("drizzle:MySqlViewConfig");
@@ -34841,7 +36798,7 @@ function mysqlViewWithSchema(name2, selection, schema4) {
34841
36798
  }
34842
36799
  return new ViewBuilder3(name2, schema4);
34843
36800
  }
34844
- var _a316, ViewBuilderCore2, _a317, _b229, ViewBuilder3, _a318, _b230, ManualViewBuilder3, _a319, _b231, _c11, MySqlView;
36801
+ var _a316, ViewBuilderCore2, _a317, _b229, ViewBuilder3, _a318, _b230, ManualViewBuilder3, _a319, _b231, _c10, MySqlView2;
34845
36802
  var init_view3 = __esm({
34846
36803
  "../drizzle-orm/dist/mysql-core/view.js"() {
34847
36804
  "use strict";
@@ -34851,7 +36808,7 @@ var init_view3 = __esm({
34851
36808
  init_query_builder4();
34852
36809
  init_table4();
34853
36810
  init_view_base3();
34854
- init_view_common4();
36811
+ init_view_common3();
34855
36812
  _a316 = entityKind;
34856
36813
  ViewBuilderCore2 = class {
34857
36814
  constructor(name2, schema4) {
@@ -34863,10 +36820,6 @@ var init_view3 = __esm({
34863
36820
  this.config.algorithm = algorithm;
34864
36821
  return this;
34865
36822
  }
34866
- definer(definer) {
34867
- this.config.definer = definer;
34868
- return this;
34869
- }
34870
36823
  sqlSecurity(sqlSecurity) {
34871
36824
  this.config.sqlSecurity = sqlSecurity;
34872
36825
  return this;
@@ -34890,7 +36843,7 @@ var init_view3 = __esm({
34890
36843
  });
34891
36844
  const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
34892
36845
  return new Proxy(
34893
- new MySqlView({
36846
+ new MySqlView2({
34894
36847
  mysqlConfig: this.config,
34895
36848
  config: {
34896
36849
  name: this.name,
@@ -34912,7 +36865,7 @@ var init_view3 = __esm({
34912
36865
  }
34913
36866
  existing() {
34914
36867
  return new Proxy(
34915
- new MySqlView({
36868
+ new MySqlView2({
34916
36869
  mysqlConfig: void 0,
34917
36870
  config: {
34918
36871
  name: this.name,
@@ -34931,7 +36884,7 @@ var init_view3 = __esm({
34931
36884
  }
34932
36885
  as(query) {
34933
36886
  return new Proxy(
34934
- new MySqlView({
36887
+ new MySqlView2({
34935
36888
  mysqlConfig: this.config,
34936
36889
  config: {
34937
36890
  name: this.name,
@@ -34950,14 +36903,14 @@ var init_view3 = __esm({
34950
36903
  }
34951
36904
  };
34952
36905
  __publicField(ManualViewBuilder3, _a318, "MySqlManualViewBuilder");
34953
- MySqlView = class extends (_c11 = MySqlViewBase, _b231 = entityKind, _a319 = MySqlViewConfig, _c11) {
36906
+ MySqlView2 = class extends (_c10 = MySqlViewBase, _b231 = entityKind, _a319 = MySqlViewConfig, _c10) {
34954
36907
  constructor({ mysqlConfig, config }) {
34955
36908
  super(config);
34956
36909
  __publicField(this, _a319);
34957
36910
  this[MySqlViewConfig] = mysqlConfig;
34958
36911
  }
34959
36912
  };
34960
- __publicField(MySqlView, _b231, "MySqlView");
36913
+ __publicField(MySqlView2, _b231, "MySqlView");
34961
36914
  }
34962
36915
  });
34963
36916
 
@@ -35099,17 +37052,25 @@ function getTableConfig3(table4) {
35099
37052
  baseName
35100
37053
  };
35101
37054
  }
37055
+ function getViewConfig3(view4) {
37056
+ return {
37057
+ ...view4[ViewBaseConfig],
37058
+ ...view4[MySqlViewConfig]
37059
+ };
37060
+ }
35102
37061
  var init_utils7 = __esm({
35103
37062
  "../drizzle-orm/dist/mysql-core/utils.js"() {
35104
37063
  "use strict";
35105
37064
  init_entity();
35106
37065
  init_table();
37066
+ init_view_common();
35107
37067
  init_checks3();
35108
37068
  init_foreign_keys3();
35109
37069
  init_indexes3();
35110
37070
  init_primary_keys3();
35111
37071
  init_table4();
35112
37072
  init_unique_constraint3();
37073
+ init_view_common3();
35113
37074
  }
35114
37075
  });
35115
37076
 
@@ -35132,7 +37093,7 @@ var init_mysql_core = __esm({
35132
37093
  init_table4();
35133
37094
  init_unique_constraint3();
35134
37095
  init_utils7();
35135
- init_view_common4();
37096
+ init_view_common3();
35136
37097
  init_view3();
35137
37098
  }
35138
37099
  });
@@ -35164,12 +37125,14 @@ var init_mysqlSerializer = __esm({
35164
37125
  init_dist();
35165
37126
  init_mysql_core();
35166
37127
  init_mysql_core();
37128
+ init_mysql_core();
35167
37129
  init_outputs();
35168
37130
  init_utils();
35169
37131
  init_serializer();
35170
- generateMySqlSnapshot = (tables, casing2) => {
37132
+ generateMySqlSnapshot = (tables, views, casing2) => {
35171
37133
  const dialect4 = new MySqlDialect({ casing: casing2 });
35172
37134
  const result = {};
37135
+ const resultViews = {};
35173
37136
  const internal = { tables: {}, indexes: {} };
35174
37137
  for (const table4 of tables) {
35175
37138
  const {
@@ -35178,6 +37141,7 @@ var init_mysqlSerializer = __esm({
35178
37141
  indexes,
35179
37142
  foreignKeys,
35180
37143
  schema: schema4,
37144
+ checks,
35181
37145
  primaryKeys,
35182
37146
  uniqueConstraints
35183
37147
  } = getTableConfig3(table4);
@@ -35186,6 +37150,8 @@ var init_mysqlSerializer = __esm({
35186
37150
  const foreignKeysObject = {};
35187
37151
  const primaryKeysObject = {};
35188
37152
  const uniqueConstraintObject = {};
37153
+ const checkConstraintObject = {};
37154
+ let checksInTable = {};
35189
37155
  columns.forEach((column4) => {
35190
37156
  const name2 = getColumnCasing(column4, casing2);
35191
37157
  const notNull = column4.notNull;
@@ -35416,6 +37382,32 @@ We have encountered a collision between the index name on columns ${source_defau
35416
37382
  lock: value.config.lock
35417
37383
  };
35418
37384
  });
37385
+ checks.forEach((check) => {
37386
+ check;
37387
+ const checkName = check.name;
37388
+ if (typeof checksInTable[tableName] !== "undefined") {
37389
+ if (checksInTable[tableName].includes(check.name)) {
37390
+ console.log(
37391
+ `
37392
+ ${withStyle.errorWarning(
37393
+ `We've found duplicated check constraint name in ${source_default.underline.blue(
37394
+ tableName
37395
+ )}. Please rename your check constraint in the ${source_default.underline.blue(
37396
+ tableName
37397
+ )} table`
37398
+ )}`
37399
+ );
37400
+ process.exit(1);
37401
+ }
37402
+ checksInTable[tableName].push(checkName);
37403
+ } else {
37404
+ checksInTable[tableName] = [check.name];
37405
+ }
37406
+ checkConstraintObject[checkName] = {
37407
+ name: checkName,
37408
+ value: dialect4.sqlToQuery(check.value).sql
37409
+ };
37410
+ });
35419
37411
  if (!schema4) {
35420
37412
  result[tableName] = {
35421
37413
  name: tableName,
@@ -35423,14 +37415,100 @@ We have encountered a collision between the index name on columns ${source_defau
35423
37415
  indexes: indexesObject,
35424
37416
  foreignKeys: foreignKeysObject,
35425
37417
  compositePrimaryKeys: primaryKeysObject,
35426
- uniqueConstraints: uniqueConstraintObject
37418
+ uniqueConstraints: uniqueConstraintObject,
37419
+ checkConstraint: checkConstraintObject
35427
37420
  };
35428
37421
  }
35429
37422
  }
37423
+ for (const view4 of views) {
37424
+ const {
37425
+ isExisting,
37426
+ name: name2,
37427
+ query,
37428
+ schema: schema4,
37429
+ selectedFields,
37430
+ algorithm,
37431
+ sqlSecurity,
37432
+ withCheckOption
37433
+ } = getViewConfig3(view4);
37434
+ const columnsObject = {};
37435
+ const existingView = resultViews[name2];
37436
+ if (typeof existingView !== "undefined") {
37437
+ console.log(
37438
+ `
37439
+ ${withStyle.errorWarning(
37440
+ `We've found duplicated view name across ${source_default.underline.blue(
37441
+ schema4 ?? "public"
37442
+ )} schema. Please rename your view`
37443
+ )}`
37444
+ );
37445
+ process.exit(1);
37446
+ }
37447
+ for (const key in selectedFields) {
37448
+ if (is(selectedFields[key], MySqlColumn)) {
37449
+ const column4 = selectedFields[key];
37450
+ const notNull = column4.notNull;
37451
+ const sqlTypeLowered = column4.getSQLType().toLowerCase();
37452
+ const autoIncrement = typeof column4.autoIncrement === "undefined" ? false : column4.autoIncrement;
37453
+ const generated = column4.generated;
37454
+ const columnToSet = {
37455
+ name: column4.name,
37456
+ type: column4.getSQLType(),
37457
+ primaryKey: false,
37458
+ // If field is autoincrement it's notNull by default
37459
+ // notNull: autoIncrement ? true : notNull,
37460
+ notNull,
37461
+ autoincrement: autoIncrement,
37462
+ onUpdate: column4.hasOnUpdateNow,
37463
+ generated: generated ? {
37464
+ as: is(generated.as, SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
37465
+ type: generated.mode ?? "stored"
37466
+ } : void 0
37467
+ };
37468
+ if (column4.default !== void 0) {
37469
+ if (is(column4.default, SQL)) {
37470
+ columnToSet.default = sqlToStr(column4.default, casing2);
37471
+ } else {
37472
+ if (typeof column4.default === "string") {
37473
+ columnToSet.default = `'${column4.default}'`;
37474
+ } else {
37475
+ if (sqlTypeLowered === "json") {
37476
+ columnToSet.default = `'${JSON.stringify(column4.default)}'`;
37477
+ } else if (column4.default instanceof Date) {
37478
+ if (sqlTypeLowered === "date") {
37479
+ columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
37480
+ } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
37481
+ columnToSet.default = `'${column4.default.toISOString().replace("T", " ").slice(0, 23)}'`;
37482
+ }
37483
+ } else {
37484
+ columnToSet.default = column4.default;
37485
+ }
37486
+ }
37487
+ if (["blob", "text", "json"].includes(column4.getSQLType())) {
37488
+ columnToSet.default = `(${columnToSet.default})`;
37489
+ }
37490
+ }
37491
+ }
37492
+ columnsObject[column4.name] = columnToSet;
37493
+ }
37494
+ }
37495
+ resultViews[name2] = {
37496
+ columns: columnsObject,
37497
+ name: name2,
37498
+ isExisting,
37499
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
37500
+ withCheckOption,
37501
+ algorithm: algorithm ?? "undefined",
37502
+ // set default values
37503
+ sqlSecurity: sqlSecurity ?? "definer"
37504
+ // set default values
37505
+ };
37506
+ }
35430
37507
  return {
35431
37508
  version: "5",
35432
37509
  dialect: "mysql",
35433
37510
  tables: result,
37511
+ views: resultViews,
35434
37512
  _meta: {
35435
37513
  tables: {},
35436
37514
  columns: {}
@@ -35450,6 +37528,8 @@ We have encountered a collision between the index name on columns ${source_defau
35450
37528
  let tablesCount = /* @__PURE__ */ new Set();
35451
37529
  let indexesCount = 0;
35452
37530
  let foreignKeysCount = 0;
37531
+ let checksCount = 0;
37532
+ let viewsCount = 0;
35453
37533
  const idxs = await db.query(
35454
37534
  `select * from INFORMATION_SCHEMA.STATISTICS
35455
37535
  WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
@@ -35544,7 +37624,8 @@ We have encountered a collision between the index name on columns ${source_defau
35544
37624
  compositePrimaryKeys: {},
35545
37625
  indexes: {},
35546
37626
  foreignKeys: {},
35547
- uniqueConstraints: {}
37627
+ uniqueConstraints: {},
37628
+ checkConstraint: {}
35548
37629
  };
35549
37630
  } else {
35550
37631
  result[tableName].columns[columnName] = newColumn;
@@ -35689,14 +37770,76 @@ We have encountered a collision between the index name on columns ${source_defau
35689
37770
  }
35690
37771
  }
35691
37772
  }
37773
+ const views = await db.query(
37774
+ `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
37775
+ );
37776
+ const resultViews = {};
37777
+ viewsCount = views.length;
37778
+ if (progressCallback) {
37779
+ progressCallback("views", viewsCount, "fetching");
37780
+ }
37781
+ for await (const view4 of views) {
37782
+ const viewName = view4["TABLE_NAME"];
37783
+ const definition = view4["VIEW_DEFINITION"];
37784
+ const withCheckOption = view4["CHECK_OPTION"] === "NONE" ? void 0 : view4["CHECK_OPTION"].toLowerCase();
37785
+ const sqlSecurity = view4["SECURITY_TYPE"].toLowerCase();
37786
+ const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
37787
+ const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
37788
+ const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
37789
+ const columns2 = result[viewName].columns;
37790
+ delete result[viewName];
37791
+ resultViews[viewName] = {
37792
+ columns: columns2,
37793
+ isExisting: false,
37794
+ name: viewName,
37795
+ algorithm,
37796
+ definition,
37797
+ sqlSecurity,
37798
+ withCheckOption
37799
+ };
37800
+ }
35692
37801
  if (progressCallback) {
35693
37802
  progressCallback("indexes", indexesCount, "done");
35694
37803
  progressCallback("enums", 0, "done");
37804
+ progressCallback("views", viewsCount, "done");
37805
+ }
37806
+ const checkConstraints = await db.query(
37807
+ `SELECT
37808
+ tc.table_name,
37809
+ tc.constraint_name,
37810
+ cc.check_clause
37811
+ FROM
37812
+ information_schema.table_constraints tc
37813
+ JOIN
37814
+ information_schema.check_constraints cc
37815
+ ON tc.constraint_name = cc.constraint_name
37816
+ WHERE
37817
+ tc.constraint_schema = '${inputSchema}'
37818
+ AND
37819
+ tc.constraint_type = 'CHECK';`
37820
+ );
37821
+ checksCount += checkConstraints.length;
37822
+ if (progressCallback) {
37823
+ progressCallback("checks", checksCount, "fetching");
37824
+ }
37825
+ for (const checkConstraintRow of checkConstraints) {
37826
+ const constraintName = checkConstraintRow["CONSTRAINT_NAME"];
37827
+ const constraintValue = checkConstraintRow["CHECK_CLAUSE"];
37828
+ const tableName = checkConstraintRow["TABLE_NAME"];
37829
+ const tableInResult = result[tableName];
37830
+ tableInResult.checkConstraint[constraintName] = {
37831
+ name: constraintName,
37832
+ value: constraintValue
37833
+ };
37834
+ }
37835
+ if (progressCallback) {
37836
+ progressCallback("checks", checksCount, "done");
35695
37837
  }
35696
37838
  return {
35697
37839
  version: "5",
35698
37840
  dialect: "mysql",
35699
37841
  tables: result,
37842
+ views: resultViews,
35700
37843
  _meta: {
35701
37844
  tables: {},
35702
37845
  columns: {}
@@ -36012,6 +38155,8 @@ var init_pgImports = __esm({
36012
38155
  const enums = [];
36013
38156
  const schemas = [];
36014
38157
  const sequences = [];
38158
+ const views = [];
38159
+ const matViews = [];
36015
38160
  const i0values = Object.values(exports2);
36016
38161
  i0values.forEach((t) => {
36017
38162
  if (isPgEnum(t)) {
@@ -36024,11 +38169,17 @@ var init_pgImports = __esm({
36024
38169
  if (is(t, PgSchema5)) {
36025
38170
  schemas.push(t);
36026
38171
  }
38172
+ if (isPgView(t)) {
38173
+ views.push(t);
38174
+ }
38175
+ if (isPgMaterializedView(t)) {
38176
+ matViews.push(t);
38177
+ }
36027
38178
  if (isPgSequence(t)) {
36028
38179
  sequences.push(t);
36029
38180
  }
36030
38181
  });
36031
- return { tables, enums, schemas, sequences };
38182
+ return { tables, enums, schemas, sequences, views, matViews };
36032
38183
  };
36033
38184
  }
36034
38185
  });
@@ -36048,25 +38199,31 @@ var init_sqliteImports = __esm({
36048
38199
  init_utils8();
36049
38200
  prepareFromExports2 = (exports2) => {
36050
38201
  const tables = [];
38202
+ const views = [];
36051
38203
  const i0values = Object.values(exports2);
36052
38204
  i0values.forEach((t) => {
36053
38205
  if (is(t, SQLiteTable)) {
36054
38206
  tables.push(t);
36055
38207
  }
38208
+ if (is(t, SQLiteView2)) {
38209
+ views.push(t);
38210
+ }
36056
38211
  });
36057
- return { tables };
38212
+ return { tables, views };
36058
38213
  };
36059
38214
  prepareFromSqliteImports = async (imports) => {
36060
38215
  const tables = [];
38216
+ const views = [];
36061
38217
  const { unregister } = await safeRegister();
36062
38218
  for (let i = 0; i < imports.length; i++) {
36063
38219
  const it = imports[i];
36064
38220
  const i0 = require(`${it}`);
36065
38221
  const prepared = prepareFromExports2(i0);
36066
38222
  tables.push(...prepared.tables);
38223
+ views.push(...prepared.views);
36067
38224
  }
36068
38225
  unregister();
36069
- return { tables: Array.from(new Set(tables)) };
38226
+ return { tables: Array.from(new Set(tables)), views };
36070
38227
  };
36071
38228
  }
36072
38229
  });
@@ -36086,25 +38243,31 @@ var init_mysqlImports = __esm({
36086
38243
  init_utils8();
36087
38244
  prepareFromExports3 = (exports2) => {
36088
38245
  const tables = [];
38246
+ const views = [];
36089
38247
  const i0values = Object.values(exports2);
36090
38248
  i0values.forEach((t) => {
36091
38249
  if (is(t, MySqlTable)) {
36092
38250
  tables.push(t);
36093
38251
  }
38252
+ if (is(t, MySqlView2)) {
38253
+ views.push(t);
38254
+ }
36094
38255
  });
36095
- return { tables };
38256
+ return { tables, views };
36096
38257
  };
36097
38258
  prepareFromMySqlImports = async (imports) => {
36098
38259
  const tables = [];
38260
+ const views = [];
36099
38261
  const { unregister } = await safeRegister();
36100
38262
  for (let i = 0; i < imports.length; i++) {
36101
38263
  const it = imports[i];
36102
38264
  const i0 = require(`${it}`);
36103
38265
  const prepared = prepareFromExports3(i0);
36104
38266
  tables.push(...prepared.tables);
38267
+ views.push(...prepared.views);
36105
38268
  }
36106
38269
  unregister();
36107
- return { tables: Array.from(new Set(tables)) };
38270
+ return { tables: Array.from(new Set(tables)), views };
36108
38271
  };
36109
38272
  }
36110
38273
  });
@@ -36493,6 +38656,7 @@ var pgSuggestions = async (db, statements) => {
36493
38656
  const columnsToRemove = [];
36494
38657
  const schemasToRemove = [];
36495
38658
  const tablesToTruncate = [];
38659
+ const matViewsToRemove = [];
36496
38660
  let renamedSchemas = {};
36497
38661
  let renamedTables = {};
36498
38662
  for (const statement of statements) {
@@ -36502,38 +38666,32 @@ var pgSuggestions = async (db, statements) => {
36502
38666
  renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
36503
38667
  } else if (statement.type === "drop_table") {
36504
38668
  const res = await db.query(
36505
- `select count(*) as count from ${tableNameWithSchemaFrom(
36506
- statement.schema,
36507
- statement.tableName,
36508
- renamedSchemas,
36509
- renamedTables
36510
- )}`
38669
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36511
38670
  );
36512
38671
  const count2 = Number(res[0].count);
38672
+ if (count2 > 0) {
38673
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count2} items`);
38674
+ tablesToRemove.push(statement.tableName);
38675
+ shouldAskForApprove = true;
38676
+ }
38677
+ } else if (statement.type === "drop_view" && statement.materialized) {
38678
+ const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
38679
+ const count2 = Number(res[0].count);
36513
38680
  if (count2 > 0) {
36514
38681
  infoToPrint.push(
36515
- `\xB7 You're about to delete ${source_default.underline(
36516
- statement.tableName
36517
- )} table with ${count2} items`
38682
+ `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count2} items`
36518
38683
  );
36519
- tablesToRemove.push(statement.tableName);
38684
+ matViewsToRemove.push(statement.name);
36520
38685
  shouldAskForApprove = true;
36521
38686
  }
36522
38687
  } else if (statement.type === "alter_table_drop_column") {
36523
38688
  const res = await db.query(
36524
- `select count(*) as count from ${tableNameWithSchemaFrom(
36525
- statement.schema,
36526
- statement.tableName,
36527
- renamedSchemas,
36528
- renamedTables
36529
- )}`
38689
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36530
38690
  );
36531
38691
  const count2 = Number(res[0].count);
36532
38692
  if (count2 > 0) {
36533
38693
  infoToPrint.push(
36534
- `\xB7 You're about to delete ${source_default.underline(
36535
- statement.columnName
36536
- )} column in ${statement.tableName} table with ${count2} items`
38694
+ `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count2} items`
36537
38695
  );
36538
38696
  columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
36539
38697
  shouldAskForApprove = true;
@@ -36544,58 +38702,35 @@ var pgSuggestions = async (db, statements) => {
36544
38702
  );
36545
38703
  const count2 = Number(res[0].count);
36546
38704
  if (count2 > 0) {
36547
- infoToPrint.push(
36548
- `\xB7 You're about to delete ${source_default.underline(
36549
- statement.name
36550
- )} schema with ${count2} tables`
36551
- );
38705
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count2} tables`);
36552
38706
  schemasToRemove.push(statement.name);
36553
38707
  shouldAskForApprove = true;
36554
38708
  }
36555
38709
  } else if (statement.type === "alter_table_alter_column_set_type") {
36556
38710
  const res = await db.query(
36557
- `select count(*) as count from ${tableNameWithSchemaFrom(
36558
- statement.schema,
36559
- statement.tableName,
36560
- renamedSchemas,
36561
- renamedTables
36562
- )}`
38711
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36563
38712
  );
36564
38713
  const count2 = Number(res[0].count);
36565
38714
  if (count2 > 0) {
36566
38715
  infoToPrint.push(
36567
- `\xB7 You're about to change ${source_default.underline(
36568
- statement.columnName
36569
- )} column type from ${source_default.underline(
36570
- statement.oldDataType
36571
- )} to ${source_default.underline(statement.newDataType)} with ${count2} items`
38716
+ `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
38717
+ statement.newDataType
38718
+ )} with ${count2} items`
36572
38719
  );
36573
38720
  statementsToExecute.push(
36574
- `truncate table ${tableNameWithSchemaFrom(
36575
- statement.schema,
36576
- statement.tableName,
36577
- renamedSchemas,
36578
- renamedTables
36579
- )} cascade;`
38721
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36580
38722
  );
36581
38723
  tablesToTruncate.push(statement.tableName);
36582
38724
  shouldAskForApprove = true;
36583
38725
  }
36584
38726
  } else if (statement.type === "alter_table_alter_column_drop_pk") {
36585
38727
  const res = await db.query(
36586
- `select count(*) as count from ${tableNameWithSchemaFrom(
36587
- statement.schema,
36588
- statement.tableName,
36589
- renamedSchemas,
36590
- renamedTables
36591
- )}`
38728
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36592
38729
  );
36593
38730
  const count2 = Number(res[0].count);
36594
38731
  if (count2 > 0) {
36595
38732
  infoToPrint.push(
36596
- `\xB7 You're about to change ${source_default.underline(
36597
- statement.tableName
36598
- )} primary key. This statements may fail and you table may left without primary key`
38733
+ `\xB7 You're about to change ${source_default.underline(statement.tableName)} primary key. This statements may fail and you table may left without primary key`
36599
38734
  );
36600
38735
  tablesToTruncate.push(statement.tableName);
36601
38736
  shouldAskForApprove = true;
@@ -36619,40 +38754,23 @@ var pgSuggestions = async (db, statements) => {
36619
38754
  } else if (statement.type === "alter_table_add_column") {
36620
38755
  if (statement.column.notNull && typeof statement.column.default === "undefined") {
36621
38756
  const res = await db.query(
36622
- `select count(*) as count from ${tableNameWithSchemaFrom(
36623
- statement.schema,
36624
- statement.tableName,
36625
- renamedSchemas,
36626
- renamedTables
36627
- )}`
38757
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36628
38758
  );
36629
38759
  const count2 = Number(res[0].count);
36630
38760
  if (count2 > 0) {
36631
38761
  infoToPrint.push(
36632
- `\xB7 You're about to add not-null ${source_default.underline(
36633
- statement.column.name
36634
- )} column without default value, which contains ${count2} items`
38762
+ `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count2} items`
36635
38763
  );
36636
38764
  tablesToTruncate.push(statement.tableName);
36637
38765
  statementsToExecute.push(
36638
- `truncate table ${tableNameWithSchemaFrom(
36639
- statement.schema,
36640
- statement.tableName,
36641
- renamedSchemas,
36642
- renamedTables
36643
- )} cascade;`
38766
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36644
38767
  );
36645
38768
  shouldAskForApprove = true;
36646
38769
  }
36647
38770
  }
36648
38771
  } else if (statement.type === "create_unique_constraint") {
36649
38772
  const res = await db.query(
36650
- `select count(*) as count from ${tableNameWithSchemaFrom(
36651
- statement.schema,
36652
- statement.tableName,
36653
- renamedSchemas,
36654
- renamedTables
36655
- )}`
38773
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36656
38774
  );
36657
38775
  const count2 = Number(res[0].count);
36658
38776
  if (count2 > 0) {
@@ -36666,20 +38784,12 @@ var pgSuggestions = async (db, statements) => {
36666
38784
  `
36667
38785
  );
36668
38786
  const { status, data } = await (0, import_hanji5.render)(
36669
- new Select([
36670
- "No, add the constraint without truncating the table",
36671
- `Yes, truncate the table`
36672
- ])
38787
+ new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
36673
38788
  );
36674
38789
  if (data?.index === 1) {
36675
38790
  tablesToTruncate.push(statement.tableName);
36676
38791
  statementsToExecute.push(
36677
- `truncate table ${tableNameWithSchemaFrom(
36678
- statement.schema,
36679
- statement.tableName,
36680
- renamedSchemas,
36681
- renamedTables
36682
- )} cascade;`
38792
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36683
38793
  );
36684
38794
  shouldAskForApprove = true;
36685
38795
  }
@@ -36689,10 +38799,7 @@ var pgSuggestions = async (db, statements) => {
36689
38799
  if (typeof stmnt !== "undefined") {
36690
38800
  if (statement.type === "drop_table") {
36691
38801
  statementsToExecute.push(
36692
- `DROP TABLE ${concatSchemaAndTableName(
36693
- statement.schema,
36694
- statement.tableName
36695
- )} CASCADE;`
38802
+ `DROP TABLE ${concatSchemaAndTableName(statement.schema, statement.tableName)} CASCADE;`
36696
38803
  );
36697
38804
  } else {
36698
38805
  statementsToExecute.push(...stmnt);
@@ -36703,6 +38810,7 @@ var pgSuggestions = async (db, statements) => {
36703
38810
  statementsToExecute,
36704
38811
  shouldAskForApprove,
36705
38812
  infoToPrint,
38813
+ matViewsToRemove: [...new Set(matViewsToRemove)],
36706
38814
  columnsToRemove: [...new Set(columnsToRemove)],
36707
38815
  schemasToRemove: [...new Set(schemasToRemove)],
36708
38816
  tablesToTruncate: [...new Set(tablesToTruncate)],
@@ -36882,6 +38990,9 @@ String.prototype.capitalise = function() {
36882
38990
  String.prototype.concatIf = function(it, condition) {
36883
38991
  return condition ? `${this}${it}` : String(this);
36884
38992
  };
38993
+ String.prototype.snake_case = function() {
38994
+ return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
38995
+ };
36885
38996
  Array.prototype.random = function() {
36886
38997
  return this[~~(Math.random() * this.length)];
36887
38998
  };
@@ -36942,6 +39053,8 @@ var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
36942
39053
  prepared.enums,
36943
39054
  prepared.schemas,
36944
39055
  prepared.sequences,
39056
+ prepared.views,
39057
+ prepared.matViews,
36945
39058
  casing2,
36946
39059
  schemaFilters
36947
39060
  );
@@ -36965,6 +39078,7 @@ var generateMigration = async (prev, cur) => {
36965
39078
  sequencesResolver,
36966
39079
  tablesResolver,
36967
39080
  columnsResolver,
39081
+ viewsResolver,
36968
39082
  validatedPrev,
36969
39083
  validatedCur
36970
39084
  );
@@ -36997,6 +39111,7 @@ var pushSchema = async (imports, drizzleInstance, schemaFilters) => {
36997
39111
  sequencesResolver,
36998
39112
  tablesResolver,
36999
39113
  columnsResolver,
39114
+ viewsResolver,
37000
39115
  validatedPrev,
37001
39116
  validatedCur,
37002
39117
  "push"
@@ -37017,7 +39132,7 @@ var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
37017
39132
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
37018
39133
  const prepared = prepareFromExports4(imports);
37019
39134
  const id = (0, import_crypto.randomUUID)();
37020
- const snapshot = generateSqliteSnapshot(prepared.tables, casing2);
39135
+ const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
37021
39136
  return {
37022
39137
  ...snapshot,
37023
39138
  id,
@@ -37035,6 +39150,7 @@ var generateSQLiteMigration = async (prev, cur) => {
37035
39150
  squashedCur,
37036
39151
  tablesResolver,
37037
39152
  columnsResolver,
39153
+ sqliteViewsResolver,
37038
39154
  validatedPrev,
37039
39155
  validatedCur
37040
39156
  );
@@ -37066,6 +39182,7 @@ var pushSQLiteSchema = async (imports, drizzleInstance) => {
37066
39182
  squashedCur,
37067
39183
  tablesResolver,
37068
39184
  columnsResolver,
39185
+ sqliteViewsResolver,
37069
39186
  validatedPrev,
37070
39187
  validatedCur,
37071
39188
  "push"
@@ -37092,7 +39209,7 @@ var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
37092
39209
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
37093
39210
  const prepared = prepareFromExports4(imports);
37094
39211
  const id = (0, import_crypto.randomUUID)();
37095
- const snapshot = generateMySqlSnapshot(prepared.tables, casing2);
39212
+ const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
37096
39213
  return {
37097
39214
  ...snapshot,
37098
39215
  id,
@@ -37110,6 +39227,7 @@ var generateMySQLMigration = async (prev, cur) => {
37110
39227
  squashedCur,
37111
39228
  tablesResolver,
37112
39229
  columnsResolver,
39230
+ mySqlViewsResolver,
37113
39231
  validatedPrev,
37114
39232
  validatedCur
37115
39233
  );
@@ -37137,6 +39255,7 @@ var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
37137
39255
  squashedCur,
37138
39256
  tablesResolver,
37139
39257
  columnsResolver,
39258
+ mySqlViewsResolver,
37140
39259
  validatedPrev,
37141
39260
  validatedCur,
37142
39261
  "push"