drizzle-kit 0.25.0-746aeed → 0.25.0-8c3e1b5

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 +719 -0
  2. package/api.d.ts +719 -0
  3. package/api.js +2007 -359
  4. package/api.mjs +2007 -359
  5. package/bin.cjs +2037 -407
  6. package/package.json +1 -1
  7. package/utils.js +81 -12
  8. package/utils.mjs +81 -12
package/bin.cjs CHANGED
@@ -922,8 +922,8 @@ var require_hanji = __commonJS({
922
922
  };
923
923
  exports2.deferred = deferred;
924
924
  var Terminal = class {
925
- constructor(view, stdin, stdout, closable) {
926
- this.view = view;
925
+ constructor(view4, stdin, stdout, closable) {
926
+ this.view = view4;
927
927
  this.stdin = stdin;
928
928
  this.stdout = stdout;
929
929
  this.closable = closable;
@@ -961,7 +961,7 @@ var require_hanji = __commonJS({
961
961
  this.resolve({ status: "submitted", data: this.view.result() });
962
962
  return;
963
963
  }
964
- view.input(str, key);
964
+ view4.input(str, key);
965
965
  };
966
966
  this.stdin.on("keypress", keypress);
967
967
  this.view.attach(this);
@@ -1023,8 +1023,8 @@ var require_hanji = __commonJS({
1023
1023
  };
1024
1024
  exports2.TaskView = TaskView2;
1025
1025
  var TaskTerminal = class {
1026
- constructor(view, stdout) {
1027
- this.view = view;
1026
+ constructor(view4, stdout) {
1027
+ this.view = view4;
1028
1028
  this.stdout = stdout;
1029
1029
  this.text = "";
1030
1030
  this.view.attach(this);
@@ -1043,22 +1043,22 @@ var require_hanji = __commonJS({
1043
1043
  }
1044
1044
  };
1045
1045
  exports2.TaskTerminal = TaskTerminal;
1046
- function render9(view) {
1046
+ function render9(view4) {
1047
1047
  const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
1048
- if (view instanceof Prompt3) {
1049
- const terminal = new Terminal(view, stdin, stdout, closable);
1048
+ if (view4 instanceof Prompt3) {
1049
+ const terminal = new Terminal(view4, stdin, stdout, closable);
1050
1050
  terminal.requestLayout();
1051
1051
  return terminal.result();
1052
1052
  }
1053
- stdout.write(`${view}
1053
+ stdout.write(`${view4}
1054
1054
  `);
1055
1055
  closable.close();
1056
1056
  return;
1057
1057
  }
1058
1058
  exports2.render = render9;
1059
- function renderWithTask6(view, task) {
1059
+ function renderWithTask6(view4, task) {
1060
1060
  return __awaiter2(this, void 0, void 0, function* () {
1061
- const terminal = new TaskTerminal(view, process.stdout);
1061
+ const terminal = new TaskTerminal(view4, process.stdout);
1062
1062
  terminal.requestLayout();
1063
1063
  const result = yield task;
1064
1064
  terminal.clear();
@@ -1315,6 +1315,11 @@ Is ${source_default.bold.blue(
1315
1315
  count: 0,
1316
1316
  name: "foreign keys",
1317
1317
  status: "fetching"
1318
+ },
1319
+ views: {
1320
+ count: 0,
1321
+ name: "views",
1322
+ status: "fetching"
1318
1323
  }
1319
1324
  };
1320
1325
  this.formatCount = (count) => {
@@ -1352,6 +1357,7 @@ Is ${source_default.bold.blue(
1352
1357
  info2 += this.hasEnums ? this.statusText(spin, this.state.enums) : "";
1353
1358
  info2 += this.statusText(spin, this.state.indexes);
1354
1359
  info2 += this.statusText(spin, this.state.fks);
1360
+ info2 += this.statusText(spin, this.state.views);
1355
1361
  return info2;
1356
1362
  }
1357
1363
  };
@@ -5421,7 +5427,7 @@ var init_lib = __esm({
5421
5427
  });
5422
5428
 
5423
5429
  // src/serializer/mysqlSchema.ts
5424
- var index, fk, column, tableV3, compositePK, uniqueConstraint, tableV4, table, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema2, tableSquashedV4, tableSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
5430
+ var index, fk, column, tableV3, compositePK, uniqueConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema2, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
5425
5431
  var init_mysqlSchema = __esm({
5426
5432
  "src/serializer/mysqlSchema.ts"() {
5427
5433
  "use strict";
@@ -5486,6 +5492,17 @@ var init_mysqlSchema = __esm({
5486
5492
  compositePrimaryKeys: recordType(stringType(), compositePK),
5487
5493
  uniqueConstraints: recordType(stringType(), uniqueConstraint).default({})
5488
5494
  }).strict();
5495
+ viewMeta = objectType({
5496
+ algorithm: enumType(["undefined", "merge", "temptable"]),
5497
+ sqlSecurity: enumType(["definer", "invoker"]),
5498
+ withCheckOption: enumType(["local", "cascaded"]).optional()
5499
+ }).strict();
5500
+ view = objectType({
5501
+ name: stringType(),
5502
+ columns: recordType(stringType(), column),
5503
+ definition: stringType().optional(),
5504
+ isExisting: booleanType()
5505
+ }).strict().merge(viewMeta);
5489
5506
  kitInternals = objectType({
5490
5507
  tables: recordType(
5491
5508
  stringType(),
@@ -5538,6 +5555,7 @@ var init_mysqlSchema = __esm({
5538
5555
  version: literalType("5"),
5539
5556
  dialect,
5540
5557
  tables: recordType(stringType(), table),
5558
+ views: recordType(stringType(), view),
5541
5559
  _meta: objectType({
5542
5560
  tables: recordType(stringType(), stringType()),
5543
5561
  columns: recordType(stringType(), stringType())
@@ -5563,10 +5581,16 @@ var init_mysqlSchema = __esm({
5563
5581
  compositePrimaryKeys: recordType(stringType(), stringType()),
5564
5582
  uniqueConstraints: recordType(stringType(), stringType()).default({})
5565
5583
  }).strict();
5584
+ viewSquashed = view.omit({
5585
+ algorithm: true,
5586
+ sqlSecurity: true,
5587
+ withCheckOption: true
5588
+ }).extend({ meta: stringType() });
5566
5589
  schemaSquashed = objectType({
5567
5590
  version: literalType("5"),
5568
5591
  dialect,
5569
- tables: recordType(stringType(), tableSquashed)
5592
+ tables: recordType(stringType(), tableSquashed),
5593
+ views: recordType(stringType(), viewSquashed)
5570
5594
  }).strict();
5571
5595
  schemaSquashedV4 = objectType({
5572
5596
  version: literalType("4"),
@@ -5628,6 +5652,18 @@ var init_mysqlSchema = __esm({
5628
5652
  onDelete
5629
5653
  });
5630
5654
  return result;
5655
+ },
5656
+ squashView: (view4) => {
5657
+ return `${view4.algorithm};${view4.sqlSecurity};${view4.withCheckOption}`;
5658
+ },
5659
+ unsquashView: (meta) => {
5660
+ const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
5661
+ const toReturn = {
5662
+ algorithm,
5663
+ sqlSecurity,
5664
+ withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
5665
+ };
5666
+ return viewMeta.parse(toReturn);
5631
5667
  }
5632
5668
  };
5633
5669
  squashMysqlScheme = (json) => {
@@ -5661,10 +5697,23 @@ var init_mysqlSchema = __esm({
5661
5697
  ];
5662
5698
  })
5663
5699
  );
5700
+ const mappedViews = Object.fromEntries(
5701
+ Object.entries(json.views).map(([key, value]) => {
5702
+ const meta = MySqlSquasher.squashView(value);
5703
+ return [key, {
5704
+ name: value.name,
5705
+ isExisting: value.isExisting,
5706
+ columns: value.columns,
5707
+ definition: value.definition,
5708
+ meta
5709
+ }];
5710
+ })
5711
+ );
5664
5712
  return {
5665
5713
  version: "5",
5666
5714
  dialect: json.dialect,
5667
- tables: mappedTables
5715
+ tables: mappedTables,
5716
+ views: mappedViews
5668
5717
  };
5669
5718
  };
5670
5719
  mysqlSchema = schema2;
@@ -5678,6 +5727,7 @@ var init_mysqlSchema = __esm({
5678
5727
  prevId: "",
5679
5728
  tables: {},
5680
5729
  schemas: {},
5730
+ views: {},
5681
5731
  _meta: {
5682
5732
  schemas: {},
5683
5733
  tables: {},
@@ -5706,7 +5756,7 @@ var init_vector = __esm({
5706
5756
  });
5707
5757
 
5708
5758
  // src/serializer/pgSchema.ts
5709
- var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5759
+ 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, 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;
5710
5760
  var init_pgSchema = __esm({
5711
5761
  "src/serializer/pgSchema.ts"() {
5712
5762
  "use strict";
@@ -5901,6 +5951,44 @@ var init_pgSchema = __esm({
5901
5951
  columns: stringType().array(),
5902
5952
  nullsNotDistinct: booleanType()
5903
5953
  }).strict();
5954
+ viewWithOption = objectType({
5955
+ checkOption: enumType(["local", "cascaded"]).optional(),
5956
+ securityBarrier: booleanType().optional(),
5957
+ securityInvoker: booleanType().optional()
5958
+ }).strict();
5959
+ matViewWithOption = objectType({
5960
+ fillfactor: numberType().optional(),
5961
+ toastTupleTarget: numberType().optional(),
5962
+ parallelWorkers: numberType().optional(),
5963
+ autovacuumEnabled: booleanType().optional(),
5964
+ vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
5965
+ vacuumTruncate: booleanType().optional(),
5966
+ autovacuumVacuumThreshold: numberType().optional(),
5967
+ autovacuumVacuumScaleFactor: numberType().optional(),
5968
+ autovacuumVacuumCostDelay: numberType().optional(),
5969
+ autovacuumVacuumCostLimit: numberType().optional(),
5970
+ autovacuumFreezeMinAge: numberType().optional(),
5971
+ autovacuumFreezeMaxAge: numberType().optional(),
5972
+ autovacuumFreezeTableAge: numberType().optional(),
5973
+ autovacuumMultixactFreezeMinAge: numberType().optional(),
5974
+ autovacuumMultixactFreezeMaxAge: numberType().optional(),
5975
+ autovacuumMultixactFreezeTableAge: numberType().optional(),
5976
+ logAutovacuumMinDuration: numberType().optional(),
5977
+ userCatalogTable: booleanType().optional()
5978
+ }).strict();
5979
+ mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
5980
+ view2 = objectType({
5981
+ name: stringType(),
5982
+ schema: stringType(),
5983
+ columns: recordType(stringType(), column2),
5984
+ definition: stringType().optional(),
5985
+ materialized: booleanType(),
5986
+ with: mergedViewWithOption.optional(),
5987
+ isExisting: booleanType(),
5988
+ withNoData: booleanType().optional(),
5989
+ using: stringType().optional(),
5990
+ tablespace: stringType().optional()
5991
+ }).strict();
5904
5992
  tableV42 = objectType({
5905
5993
  name: stringType(),
5906
5994
  schema: stringType(),
@@ -6035,6 +6123,7 @@ var init_pgSchema = __esm({
6035
6123
  tables: recordType(stringType(), table2),
6036
6124
  enums: recordType(stringType(), enumSchema),
6037
6125
  schemas: recordType(stringType(), stringType()),
6126
+ views: recordType(stringType(), view2).default({}),
6038
6127
  sequences: recordType(stringType(), sequenceSchema).default({}),
6039
6128
  _meta: objectType({
6040
6129
  schemas: recordType(stringType(), stringType()),
@@ -6079,6 +6168,7 @@ var init_pgSchema = __esm({
6079
6168
  tables: recordType(stringType(), tableSquashed2),
6080
6169
  enums: recordType(stringType(), enumSchema),
6081
6170
  schemas: recordType(stringType(), stringType()),
6171
+ views: recordType(stringType(), view2),
6082
6172
  sequences: recordType(stringType(), sequenceSquashed)
6083
6173
  }).strict();
6084
6174
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
@@ -6296,6 +6386,7 @@ var init_pgSchema = __esm({
6296
6386
  tables: mappedTables,
6297
6387
  enums: json.enums,
6298
6388
  schemas: json.schemas,
6389
+ views: json.views,
6299
6390
  sequences: mappedSequences
6300
6391
  };
6301
6392
  };
@@ -6318,7 +6409,7 @@ var init_pgSchema = __esm({
6318
6409
  });
6319
6410
 
6320
6411
  // src/serializer/sqliteSchema.ts
6321
- var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, table3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema3, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
6412
+ var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, table3, view3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema3, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
6322
6413
  var init_sqliteSchema = __esm({
6323
6414
  "src/serializer/sqliteSchema.ts"() {
6324
6415
  "use strict";
@@ -6373,6 +6464,12 @@ var init_sqliteSchema = __esm({
6373
6464
  compositePrimaryKeys: recordType(stringType(), compositePK3),
6374
6465
  uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
6375
6466
  }).strict();
6467
+ view3 = objectType({
6468
+ name: stringType(),
6469
+ columns: recordType(stringType(), column3),
6470
+ definition: stringType().optional(),
6471
+ isExisting: booleanType()
6472
+ }).strict();
6376
6473
  dialect2 = enumType(["sqlite"]);
6377
6474
  schemaHash3 = objectType({
6378
6475
  id: stringType(),
@@ -6388,6 +6485,7 @@ var init_sqliteSchema = __esm({
6388
6485
  version: literalType("4"),
6389
6486
  dialect: dialect2,
6390
6487
  tables: recordType(stringType(), table3),
6488
+ views: recordType(stringType(), view3),
6391
6489
  enums: objectType({})
6392
6490
  }).strict();
6393
6491
  schemaInternalV52 = objectType({
@@ -6416,6 +6514,7 @@ var init_sqliteSchema = __esm({
6416
6514
  version: latestVersion,
6417
6515
  dialect: dialect2,
6418
6516
  tables: recordType(stringType(), table3),
6517
+ views: recordType(stringType(), view3),
6419
6518
  enums: objectType({}),
6420
6519
  _meta: objectType({
6421
6520
  tables: recordType(stringType(), stringType()),
@@ -6439,6 +6538,7 @@ var init_sqliteSchema = __esm({
6439
6538
  version: latestVersion,
6440
6539
  dialect: dialect2,
6441
6540
  tables: recordType(stringType(), tableSquashed3),
6541
+ views: recordType(stringType(), view3),
6442
6542
  enums: anyType()
6443
6543
  }).strict();
6444
6544
  SQLiteSquasher = {
@@ -6558,6 +6658,7 @@ var init_sqliteSchema = __esm({
6558
6658
  version: "6",
6559
6659
  dialect: json.dialect,
6560
6660
  tables: mappedTables,
6661
+ views: json.views,
6561
6662
  enums: json.enums
6562
6663
  };
6563
6664
  };
@@ -6567,6 +6668,7 @@ var init_sqliteSchema = __esm({
6567
6668
  id: originUUID,
6568
6669
  prevId: "",
6569
6670
  tables: {},
6671
+ views: {},
6570
6672
  enums: {},
6571
6673
  _meta: {
6572
6674
  tables: {},
@@ -8817,6 +8919,9 @@ var init_utils3 = __esm({
8817
8919
  String.prototype.concatIf = function(it, condition) {
8818
8920
  return condition ? `${this}${it}` : String(this);
8819
8921
  };
8922
+ String.prototype.snake_case = function() {
8923
+ return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
8924
+ };
8820
8925
  Array.prototype.random = function() {
8821
8926
  return this[~~(Math.random() * this.length)];
8822
8927
  };
@@ -12517,11 +12622,11 @@ var require_node2 = __commonJS({
12517
12622
  };
12518
12623
  var require_base64 = __commonJS3((exports3) => {
12519
12624
  var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
12520
- exports3.encode = function(number3) {
12521
- if (0 <= number3 && number3 < intToCharMap.length) {
12522
- return intToCharMap[number3];
12625
+ exports3.encode = function(number2) {
12626
+ if (0 <= number2 && number2 < intToCharMap.length) {
12627
+ return intToCharMap[number2];
12523
12628
  }
12524
- throw new TypeError("Must be between 0 and 63: " + number3);
12629
+ throw new TypeError("Must be between 0 and 63: " + number2);
12525
12630
  };
12526
12631
  exports3.decode = function(charCode) {
12527
12632
  var bigA = 65;
@@ -17875,25 +17980,31 @@ var init_mysqlImports = __esm({
17875
17980
  init_utils4();
17876
17981
  prepareFromExports = (exports2) => {
17877
17982
  const tables = [];
17983
+ const views = [];
17878
17984
  const i0values = Object.values(exports2);
17879
17985
  i0values.forEach((t2) => {
17880
17986
  if ((0, import_drizzle_orm.is)(t2, import_mysql_core.MySqlTable)) {
17881
17987
  tables.push(t2);
17882
17988
  }
17989
+ if ((0, import_drizzle_orm.is)(t2, import_mysql_core.MySqlView)) {
17990
+ views.push(t2);
17991
+ }
17883
17992
  });
17884
- return { tables };
17993
+ return { tables, views };
17885
17994
  };
17886
17995
  prepareFromMySqlImports = async (imports) => {
17887
17996
  const tables = [];
17997
+ const views = [];
17888
17998
  const { unregister } = await safeRegister();
17889
17999
  for (let i2 = 0; i2 < imports.length; i2++) {
17890
18000
  const it = imports[i2];
17891
18001
  const i0 = require(`${it}`);
17892
18002
  const prepared = prepareFromExports(i0);
17893
18003
  tables.push(...prepared.tables);
18004
+ views.push(...prepared.views);
17894
18005
  }
17895
18006
  unregister();
17896
- return { tables: Array.from(new Set(tables)) };
18007
+ return { tables: Array.from(new Set(tables)), views };
17897
18008
  };
17898
18009
  }
17899
18010
  });
@@ -17922,7 +18033,7 @@ function clearDefaults(defaultValue, collate) {
17922
18033
  return `(${resultDefault})`;
17923
18034
  }
17924
18035
  }
17925
- var import_drizzle_orm2, import_drizzle_orm3, import_mysql_core2, import_mysql_core3, indexName, generateMySqlSnapshot, fromDatabase;
18036
+ var import_drizzle_orm2, import_drizzle_orm3, import_mysql_core2, import_mysql_core3, import_mysql_core4, indexName, generateMySqlSnapshot, fromDatabase;
17926
18037
  var init_mysqlSerializer = __esm({
17927
18038
  "src/serializer/mysqlSerializer.ts"() {
17928
18039
  "use strict";
@@ -17931,15 +18042,17 @@ var init_mysqlSerializer = __esm({
17931
18042
  import_drizzle_orm3 = require("drizzle-orm");
17932
18043
  import_mysql_core2 = require("drizzle-orm/mysql-core");
17933
18044
  import_mysql_core3 = require("drizzle-orm/mysql-core");
18045
+ import_mysql_core4 = require("drizzle-orm/mysql-core");
17934
18046
  init_outputs();
17935
18047
  init_utils();
17936
18048
  init_serializer();
17937
18049
  indexName = (tableName, columns) => {
17938
18050
  return `${tableName}_${columns.join("_")}_index`;
17939
18051
  };
17940
- generateMySqlSnapshot = (tables, casing2) => {
17941
- const dialect4 = new import_mysql_core2.MySqlDialect({ casing: casing2 });
18052
+ generateMySqlSnapshot = (tables, views, casing2) => {
18053
+ const dialect4 = new import_mysql_core3.MySqlDialect({ casing: casing2 });
17942
18054
  const result = {};
18055
+ const resultViews = {};
17943
18056
  const internal = { tables: {}, indexes: {} };
17944
18057
  for (const table4 of tables) {
17945
18058
  const {
@@ -17950,7 +18063,7 @@ var init_mysqlSerializer = __esm({
17950
18063
  schema: schema5,
17951
18064
  primaryKeys,
17952
18065
  uniqueConstraints
17953
- } = (0, import_mysql_core3.getTableConfig)(table4);
18066
+ } = (0, import_mysql_core4.getTableConfig)(table4);
17954
18067
  const columnsObject = {};
17955
18068
  const indexesObject = {};
17956
18069
  const foreignKeysObject = {};
@@ -18051,7 +18164,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18051
18164
  });
18052
18165
  uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
18053
18166
  const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
18054
- const name = unq.name ?? (0, import_mysql_core2.uniqueKeyName)(table4, columnNames);
18167
+ const name = unq.name ?? (0, import_mysql_core3.uniqueKeyName)(table4, columnNames);
18055
18168
  const existingUnique = uniqueConstraintObject[name];
18056
18169
  if (typeof existingUnique !== "undefined") {
18057
18170
  console.log(
@@ -18198,10 +18311,95 @@ We have encountered a collision between the index name on columns ${source_defau
18198
18311
  };
18199
18312
  }
18200
18313
  }
18314
+ for (const view4 of views) {
18315
+ const {
18316
+ isExisting,
18317
+ name,
18318
+ query,
18319
+ schema: schema5,
18320
+ selectedFields,
18321
+ algorithm,
18322
+ sqlSecurity,
18323
+ withCheckOption
18324
+ } = (0, import_mysql_core2.getViewConfig)(view4);
18325
+ const columnsObject = {};
18326
+ const existingView = resultViews[name];
18327
+ if (typeof existingView !== "undefined") {
18328
+ console.log(
18329
+ `
18330
+ ${withStyle.errorWarning(
18331
+ `We've found duplicated view name across ${source_default.underline.blue(
18332
+ schema5 ?? "public"
18333
+ )} schema. Please rename your view`
18334
+ )}`
18335
+ );
18336
+ process.exit(1);
18337
+ }
18338
+ for (const key in selectedFields) {
18339
+ if ((0, import_drizzle_orm2.is)(selectedFields[key], import_mysql_core2.MySqlColumn)) {
18340
+ const column7 = selectedFields[key];
18341
+ const notNull = column7.notNull;
18342
+ const sqlTypeLowered = column7.getSQLType().toLowerCase();
18343
+ const autoIncrement = typeof column7.autoIncrement === "undefined" ? false : column7.autoIncrement;
18344
+ const generated = column7.generated;
18345
+ const columnToSet = {
18346
+ name: column7.name,
18347
+ type: column7.getSQLType(),
18348
+ primaryKey: false,
18349
+ // If field is autoincrement it's notNull by default
18350
+ // notNull: autoIncrement ? true : notNull,
18351
+ notNull,
18352
+ autoincrement: autoIncrement,
18353
+ onUpdate: column7.hasOnUpdateNow,
18354
+ generated: generated ? {
18355
+ as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm3.SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
18356
+ type: generated.mode ?? "stored"
18357
+ } : void 0
18358
+ };
18359
+ if (column7.default !== void 0) {
18360
+ if ((0, import_drizzle_orm2.is)(column7.default, import_drizzle_orm3.SQL)) {
18361
+ columnToSet.default = sqlToStr(column7.default, casing2);
18362
+ } else {
18363
+ if (typeof column7.default === "string") {
18364
+ columnToSet.default = `'${column7.default}'`;
18365
+ } else {
18366
+ if (sqlTypeLowered === "json") {
18367
+ columnToSet.default = `'${JSON.stringify(column7.default)}'`;
18368
+ } else if (column7.default instanceof Date) {
18369
+ if (sqlTypeLowered === "date") {
18370
+ columnToSet.default = `'${column7.default.toISOString().split("T")[0]}'`;
18371
+ } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
18372
+ columnToSet.default = `'${column7.default.toISOString().replace("T", " ").slice(0, 23)}'`;
18373
+ }
18374
+ } else {
18375
+ columnToSet.default = column7.default;
18376
+ }
18377
+ }
18378
+ if (["blob", "text", "json"].includes(column7.getSQLType())) {
18379
+ columnToSet.default = `(${columnToSet.default})`;
18380
+ }
18381
+ }
18382
+ }
18383
+ columnsObject[column7.name] = columnToSet;
18384
+ }
18385
+ }
18386
+ resultViews[name] = {
18387
+ columns: columnsObject,
18388
+ name,
18389
+ isExisting,
18390
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
18391
+ withCheckOption,
18392
+ algorithm: algorithm ?? "undefined",
18393
+ // set default values
18394
+ sqlSecurity: sqlSecurity ?? "definer"
18395
+ // set default values
18396
+ };
18397
+ }
18201
18398
  return {
18202
18399
  version: "5",
18203
18400
  dialect: "mysql",
18204
18401
  tables: result,
18402
+ views: resultViews,
18205
18403
  _meta: {
18206
18404
  tables: {},
18207
18405
  columns: {}
@@ -18221,6 +18419,7 @@ We have encountered a collision between the index name on columns ${source_defau
18221
18419
  let tablesCount = /* @__PURE__ */ new Set();
18222
18420
  let indexesCount = 0;
18223
18421
  let foreignKeysCount = 0;
18422
+ let viewsCount = 0;
18224
18423
  const idxs = await db.query(
18225
18424
  `select * from INFORMATION_SCHEMA.STATISTICS
18226
18425
  WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
@@ -18463,14 +18662,44 @@ We have encountered a collision between the index name on columns ${source_defau
18463
18662
  }
18464
18663
  }
18465
18664
  }
18665
+ const views = await db.query(
18666
+ `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
18667
+ );
18668
+ const resultViews = {};
18669
+ viewsCount = views.length;
18670
+ if (progressCallback) {
18671
+ progressCallback("views", viewsCount, "fetching");
18672
+ }
18673
+ for await (const view4 of views) {
18674
+ const viewName = view4["TABLE_NAME"];
18675
+ const definition = view4["VIEW_DEFINITION"];
18676
+ const withCheckOption = view4["CHECK_OPTION"] === "NONE" ? void 0 : view4["CHECK_OPTION"].toLowerCase();
18677
+ const sqlSecurity = view4["SECURITY_TYPE"].toLowerCase();
18678
+ const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
18679
+ const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
18680
+ const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
18681
+ const columns2 = result[viewName].columns;
18682
+ delete result[viewName];
18683
+ resultViews[viewName] = {
18684
+ columns: columns2,
18685
+ isExisting: false,
18686
+ name: viewName,
18687
+ algorithm,
18688
+ definition,
18689
+ sqlSecurity,
18690
+ withCheckOption
18691
+ };
18692
+ }
18466
18693
  if (progressCallback) {
18467
18694
  progressCallback("indexes", indexesCount, "done");
18468
18695
  progressCallback("enums", 0, "done");
18696
+ progressCallback("views", viewsCount, "done");
18469
18697
  }
18470
18698
  return {
18471
18699
  version: "5",
18472
18700
  dialect: "mysql",
18473
18701
  tables: result,
18702
+ views: resultViews,
18474
18703
  _meta: {
18475
18704
  tables: {},
18476
18705
  columns: {}
@@ -18499,6 +18728,8 @@ var init_pgImports = __esm({
18499
18728
  const enums = [];
18500
18729
  const schemas = [];
18501
18730
  const sequences = [];
18731
+ const views = [];
18732
+ const matViews = [];
18502
18733
  const i0values = Object.values(exports2);
18503
18734
  i0values.forEach((t2) => {
18504
18735
  if ((0, import_pg_core.isPgEnum)(t2)) {
@@ -18511,17 +18742,25 @@ var init_pgImports = __esm({
18511
18742
  if ((0, import_drizzle_orm4.is)(t2, import_pg_core.PgSchema)) {
18512
18743
  schemas.push(t2);
18513
18744
  }
18745
+ if ((0, import_pg_core.isPgView)(t2)) {
18746
+ views.push(t2);
18747
+ }
18748
+ if ((0, import_pg_core.isPgMaterializedView)(t2)) {
18749
+ matViews.push(t2);
18750
+ }
18514
18751
  if ((0, import_pg_core.isPgSequence)(t2)) {
18515
18752
  sequences.push(t2);
18516
18753
  }
18517
18754
  });
18518
- return { tables, enums, schemas, sequences };
18755
+ return { tables, enums, schemas, sequences, views, matViews };
18519
18756
  };
18520
18757
  prepareFromPgImports = async (imports) => {
18521
- let tables = [];
18522
- let enums = [];
18523
- let schemas = [];
18524
- let sequences = [];
18758
+ const tables = [];
18759
+ const enums = [];
18760
+ const schemas = [];
18761
+ const sequences = [];
18762
+ const views = [];
18763
+ const matViews = [];
18525
18764
  const { unregister } = await safeRegister();
18526
18765
  for (let i2 = 0; i2 < imports.length; i2++) {
18527
18766
  const it = imports[i2];
@@ -18531,9 +18770,11 @@ var init_pgImports = __esm({
18531
18770
  enums.push(...prepared.enums);
18532
18771
  schemas.push(...prepared.schemas);
18533
18772
  sequences.push(...prepared.sequences);
18773
+ views.push(...prepared.views);
18774
+ matViews.push(...prepared.matViews);
18534
18775
  }
18535
18776
  unregister();
18536
- return { tables: Array.from(new Set(tables)), enums, schemas, sequences };
18777
+ return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews };
18537
18778
  };
18538
18779
  }
18539
18780
  });
@@ -18581,7 +18822,7 @@ function buildArrayString(array, sqlType) {
18581
18822
  }).join(",");
18582
18823
  return `{${values}}`;
18583
18824
  }
18584
- var import_drizzle_orm5, import_pg_core2, import_pg_core3, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn;
18825
+ var import_drizzle_orm5, import_pg_core2, import_pg_core3, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn, getColumnsInfoQuery;
18585
18826
  var init_pgSerializer = __esm({
18586
18827
  "src/serializer/pgSerializer.ts"() {
18587
18828
  "use strict";
@@ -18596,23 +18837,15 @@ var init_pgSerializer = __esm({
18596
18837
  indexName2 = (tableName, columns) => {
18597
18838
  return `${tableName}_${columns.join("_")}_index`;
18598
18839
  };
18599
- generatePgSnapshot = (tables, enums, schemas, sequences, casing2, schemaFilter) => {
18600
- var _a, _b, _c, _d, _e, _f;
18840
+ generatePgSnapshot = (tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter) => {
18841
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
18601
18842
  const dialect4 = new import_pg_core2.PgDialect({ casing: casing2 });
18602
18843
  const result = {};
18844
+ const resultViews = {};
18603
18845
  const sequencesToReturn = {};
18604
18846
  const indexesInSchema = {};
18605
18847
  for (const table4 of tables) {
18606
- const {
18607
- name: tableName,
18608
- columns,
18609
- indexes,
18610
- foreignKeys,
18611
- checks,
18612
- schema: schema5,
18613
- primaryKeys,
18614
- uniqueConstraints
18615
- } = (0, import_pg_core3.getTableConfig)(table4);
18848
+ const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema5, primaryKeys, uniqueConstraints } = (0, import_pg_core3.getTableConfig)(table4);
18616
18849
  if (schemaFilter && !schemaFilter.includes(schema5 ?? "public")) {
18617
18850
  continue;
18618
18851
  }
@@ -18669,7 +18902,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18669
18902
  column7.uniqueName
18670
18903
  )} on the ${source_default.underline.blue(
18671
18904
  name
18672
- )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
18905
+ )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
18673
18906
  existingUnique.columns.join(",")
18674
18907
  )} columns
18675
18908
  `)}`
@@ -18690,9 +18923,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18690
18923
  columnToSet.default = `'${column7.default}'`;
18691
18924
  } else {
18692
18925
  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
18693
- columnToSet.default = `'${JSON.stringify(
18694
- column7.default
18695
- )}'::${sqlTypeLowered}`;
18926
+ columnToSet.default = `'${JSON.stringify(column7.default)}'::${sqlTypeLowered}`;
18696
18927
  } else if (column7.default instanceof Date) {
18697
18928
  if (sqlTypeLowered === "date") {
18698
18929
  columnToSet.default = `'${column7.default.toISOString().split("T")[0]}'`;
@@ -18702,10 +18933,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18702
18933
  columnToSet.default = `'${column7.default.toISOString()}'`;
18703
18934
  }
18704
18935
  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column7.default)) {
18705
- columnToSet.default = `'${buildArrayString(
18706
- column7.default,
18707
- sqlTypeLowered
18708
- )}'`;
18936
+ columnToSet.default = `'${buildArrayString(column7.default, sqlTypeLowered)}'`;
18709
18937
  } else {
18710
18938
  columnToSet.default = column7.default;
18711
18939
  }
@@ -18735,17 +18963,13 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18735
18963
  if (typeof existingUnique !== "undefined") {
18736
18964
  console.log(
18737
18965
  `
18738
- ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
18739
- tableName
18740
- )} table.
18741
- The unique constraint ${source_default.underline.blue(
18742
- name
18743
- )} on the ${source_default.underline.blue(
18744
- columnNames.join(",")
18745
- )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
18746
- existingUnique.columns.join(",")
18747
- )} columns
18748
- `)}`
18966
+ ${withStyle.errorWarning(
18967
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table.
18968
+ The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue(
18969
+ columnNames.join(",")
18970
+ )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
18971
+ `
18972
+ )}`
18749
18973
  );
18750
18974
  process.exit(1);
18751
18975
  }
@@ -18798,9 +19022,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18798
19022
  console.log(
18799
19023
  `
18800
19024
  ${withStyle.errorWarning(
18801
- `Please specify an index name in ${(0, import_drizzle_orm5.getTableName)(
18802
- value.config.table
18803
- )} 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.`
19025
+ `Please specify an index name in ${(0, import_drizzle_orm5.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.`
18804
19026
  )}`
18805
19027
  );
18806
19028
  process.exit(1);
@@ -18818,9 +19040,7 @@ ${withStyle.errorWarning(
18818
19040
  tableName
18819
19041
  )} table with the ${source_default.blueBright(
18820
19042
  "vector"
18821
- )} 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(
18822
- ", "
18823
- )}].
19043
+ )} 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(", ")}].
18824
19044
 
18825
19045
  You can specify it using current syntax: ${source_default.underline(
18826
19046
  `index("${value.config.name}").using("${value.config.method}", table.${name2}.op("${vectorOps[0]}"))`
@@ -18862,9 +19082,7 @@ You can check the "pg_vector" docs for more info: https://github.com/pgvector/pg
18862
19082
  console.log(
18863
19083
  `
18864
19084
  ${withStyle.errorWarning(
18865
- `We've found duplicated index name across ${source_default.underline.blue(
18866
- schema5 ?? "public"
18867
- )} schema. Please rename your index in either the ${source_default.underline.blue(
19085
+ `We've found duplicated index name across ${source_default.underline.blue(schema5 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
18868
19086
  tableName
18869
19087
  )} table or the table with the duplicated index name`
18870
19088
  )}`
@@ -18917,6 +19135,136 @@ ${withStyle.errorWarning(
18917
19135
  } else {
18918
19136
  }
18919
19137
  }
19138
+ const combinedViews = [...views, ...matViews];
19139
+ for (const view4 of combinedViews) {
19140
+ let viewName;
19141
+ let schema5;
19142
+ let query;
19143
+ let selectedFields;
19144
+ let isExisting;
19145
+ let withOption;
19146
+ let tablespace;
19147
+ let using;
19148
+ let withNoData;
19149
+ let materialized = false;
19150
+ if ((0, import_drizzle_orm5.is)(view4, import_pg_core2.PgView)) {
19151
+ ({ name: viewName, schema: schema5, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core2.getViewConfig)(view4));
19152
+ } else {
19153
+ ({ name: viewName, schema: schema5, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core2.getMaterializedViewConfig)(view4));
19154
+ materialized = true;
19155
+ }
19156
+ const viewSchema = schema5 ?? "public";
19157
+ const viewKey = `${viewSchema}.${viewName}`;
19158
+ const columnsObject = {};
19159
+ const uniqueConstraintObject = {};
19160
+ const existingView = resultViews[viewKey];
19161
+ if (typeof existingView !== "undefined") {
19162
+ console.log(
19163
+ `
19164
+ ${withStyle.errorWarning(
19165
+ `We've found duplicated view name across ${source_default.underline.blue(schema5 ?? "public")} schema. Please rename your view`
19166
+ )}`
19167
+ );
19168
+ process.exit(1);
19169
+ }
19170
+ for (const key in selectedFields) {
19171
+ if ((0, import_drizzle_orm5.is)(selectedFields[key], import_pg_core2.PgColumn)) {
19172
+ const column7 = selectedFields[key];
19173
+ const notNull = column7.notNull;
19174
+ const primaryKey = column7.primary;
19175
+ const sqlTypeLowered = column7.getSQLType().toLowerCase();
19176
+ const typeSchema = (0, import_drizzle_orm5.is)(column7, import_pg_core2.PgEnumColumn) ? column7.enum.schema || "public" : void 0;
19177
+ const generated = column7.generated;
19178
+ const identity = column7.generatedIdentity;
19179
+ const increment = stringFromIdentityProperty((_g = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _g.increment) ?? "1";
19180
+ const minValue = stringFromIdentityProperty((_h = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _h.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column7.columnType) : "1");
19181
+ const maxValue = stringFromIdentityProperty((_i = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _i.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column7.getSQLType()));
19182
+ const startWith = stringFromIdentityProperty((_j = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _j.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
19183
+ const cache = stringFromIdentityProperty((_k = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _k.cache) ?? "1";
19184
+ const columnToSet = {
19185
+ name: column7.name,
19186
+ type: column7.getSQLType(),
19187
+ typeSchema,
19188
+ primaryKey,
19189
+ notNull,
19190
+ generated: generated ? {
19191
+ as: (0, import_drizzle_orm5.is)(generated.as, import_drizzle_orm5.SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
19192
+ type: "stored"
19193
+ } : void 0,
19194
+ identity: identity ? {
19195
+ type: identity.type,
19196
+ name: identity.sequenceName ?? `${viewName}_${column7.name}_seq`,
19197
+ schema: schema5 ?? "public",
19198
+ increment,
19199
+ startWith,
19200
+ minValue,
19201
+ maxValue,
19202
+ cache,
19203
+ cycle: ((_l = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _l.cycle) ?? false
19204
+ } : void 0
19205
+ };
19206
+ if (column7.isUnique) {
19207
+ const existingUnique = uniqueConstraintObject[column7.uniqueName];
19208
+ if (typeof existingUnique !== "undefined") {
19209
+ console.log(
19210
+ `
19211
+ ${withStyle.errorWarning(
19212
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table.
19213
+ The unique constraint ${source_default.underline.blue(column7.uniqueName)} on the ${source_default.underline.blue(
19214
+ column7.name
19215
+ )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
19216
+ `
19217
+ )}`
19218
+ );
19219
+ process.exit(1);
19220
+ }
19221
+ uniqueConstraintObject[column7.uniqueName] = {
19222
+ name: column7.uniqueName,
19223
+ nullsNotDistinct: column7.uniqueType === "not distinct",
19224
+ columns: [columnToSet.name]
19225
+ };
19226
+ }
19227
+ if (column7.default !== void 0) {
19228
+ if ((0, import_drizzle_orm5.is)(column7.default, import_drizzle_orm5.SQL)) {
19229
+ columnToSet.default = sqlToStr(column7.default, casing2);
19230
+ } else {
19231
+ if (typeof column7.default === "string") {
19232
+ columnToSet.default = `'${column7.default}'`;
19233
+ } else {
19234
+ if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
19235
+ columnToSet.default = `'${JSON.stringify(column7.default)}'::${sqlTypeLowered}`;
19236
+ } else if (column7.default instanceof Date) {
19237
+ if (sqlTypeLowered === "date") {
19238
+ columnToSet.default = `'${column7.default.toISOString().split("T")[0]}'`;
19239
+ } else if (sqlTypeLowered === "timestamp") {
19240
+ columnToSet.default = `'${column7.default.toISOString().replace("T", " ").slice(0, 23)}'`;
19241
+ } else {
19242
+ columnToSet.default = `'${column7.default.toISOString()}'`;
19243
+ }
19244
+ } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column7.default)) {
19245
+ columnToSet.default = `'${buildArrayString(column7.default, sqlTypeLowered)}'`;
19246
+ } else {
19247
+ columnToSet.default = column7.default;
19248
+ }
19249
+ }
19250
+ }
19251
+ }
19252
+ columnsObject[column7.name] = columnToSet;
19253
+ }
19254
+ }
19255
+ resultViews[viewKey] = {
19256
+ columns: columnsObject,
19257
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
19258
+ name: viewName,
19259
+ schema: viewSchema,
19260
+ isExisting,
19261
+ with: withOption,
19262
+ withNoData,
19263
+ materialized,
19264
+ tablespace,
19265
+ using
19266
+ };
19267
+ }
18920
19268
  const enumsToReturn = enums.reduce((map, obj) => {
18921
19269
  const enumSchema3 = obj.schema || "public";
18922
19270
  const key = `${enumSchema3}.${obj.enumName}`;
@@ -18943,6 +19291,7 @@ ${withStyle.errorWarning(
18943
19291
  enums: enumsToReturn,
18944
19292
  schemas: schemasObject,
18945
19293
  sequences: sequencesToReturn,
19294
+ views: resultViews,
18946
19295
  _meta: {
18947
19296
  schemas: {},
18948
19297
  tables: {},
@@ -18961,10 +19310,25 @@ ${withStyle.errorWarning(
18961
19310
  };
18962
19311
  fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
18963
19312
  const result = {};
19313
+ const views = {};
18964
19314
  const internals = { tables: {} };
18965
- const where = schemaFilters.map((t2) => `table_schema = '${t2}'`).join(" or ");
19315
+ const where = schemaFilters.map((t2) => `n.nspname = '${t2}'`).join(" or ");
18966
19316
  const allTables = await db.query(
18967
- `SELECT table_schema, table_name FROM information_schema.tables${where === "" ? "" : ` WHERE ${where}`};`
19317
+ `SELECT
19318
+ n.nspname AS table_schema,
19319
+ c.relname AS table_name,
19320
+ CASE
19321
+ WHEN c.relkind = 'r' THEN 'table'
19322
+ WHEN c.relkind = 'v' THEN 'view'
19323
+ WHEN c.relkind = 'm' THEN 'materialized_view'
19324
+ END AS type
19325
+ FROM
19326
+ pg_catalog.pg_class c
19327
+ JOIN
19328
+ pg_catalog.pg_namespace n ON n.oid = c.relnamespace
19329
+ WHERE
19330
+ c.relkind IN ('r', 'v', 'm')
19331
+ ${where === "" ? "" : ` AND ${where}`};`
18968
19332
  );
18969
19333
  const schemas = new Set(allTables.map((it) => it.table_schema));
18970
19334
  schemas.delete("public");
@@ -18984,6 +19348,7 @@ ${withStyle.errorWarning(
18984
19348
  let indexesCount = 0;
18985
19349
  let foreignKeysCount = 0;
18986
19350
  let tableCount = 0;
19351
+ let viewsCount = 0;
18987
19352
  const sequencesToReturn = {};
18988
19353
  const seqWhere = schemaFilters.map((t2) => `schemaname = '${t2}'`).join(" or ");
18989
19354
  const allSequences = await db.query(
@@ -19042,7 +19407,7 @@ ${withStyle.errorWarning(
19042
19407
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
19043
19408
  }
19044
19409
  const sequencesInColumns = [];
19045
- const all = allTables.map((row) => {
19410
+ const all = allTables.filter((it) => it.type === "table").map((row) => {
19046
19411
  return new Promise(async (res, rej) => {
19047
19412
  var _a, _b, _c, _d, _e, _f;
19048
19413
  const tableName = row.table_name;
@@ -19056,42 +19421,7 @@ ${withStyle.errorWarning(
19056
19421
  const foreignKeysToReturn = {};
19057
19422
  const primaryKeys = {};
19058
19423
  const uniqueConstrains = {};
19059
- const tableResponse = await db.query(
19060
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
19061
- , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
19062
- AND EXISTS (
19063
- SELECT FROM pg_attrdef ad
19064
- WHERE ad.adrelid = a.attrelid
19065
- AND ad.adnum = a.attnum
19066
- AND pg_get_expr(ad.adbin, ad.adrelid)
19067
- = 'nextval('''
19068
- || (pg_get_serial_sequence (a.attrelid::regclass::text
19069
- , a.attname))::regclass
19070
- || '''::regclass)'
19071
- )
19072
- THEN CASE a.atttypid
19073
- WHEN 'int'::regtype THEN 'serial'
19074
- WHEN 'int8'::regtype THEN 'bigserial'
19075
- WHEN 'int2'::regtype THEN 'smallserial'
19076
- END
19077
- ELSE format_type(a.atttypid, a.atttypmod)
19078
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
19079
- pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
19080
- INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
19081
- INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
19082
- INFORMATION_SCHEMA.COLUMNS.is_generated, generation_expression,
19083
- INFORMATION_SCHEMA.COLUMNS.is_identity,INFORMATION_SCHEMA.COLUMNS.identity_generation,
19084
- INFORMATION_SCHEMA.COLUMNS.identity_start, INFORMATION_SCHEMA.COLUMNS.identity_increment,
19085
- INFORMATION_SCHEMA.COLUMNS.identity_maximum, INFORMATION_SCHEMA.COLUMNS.identity_minimum,
19086
- INFORMATION_SCHEMA.COLUMNS.identity_cycle
19087
- FROM pg_attribute a
19088
- JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
19089
- JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
19090
- WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
19091
- AND a.attnum > 0
19092
- AND NOT a.attisdropped
19093
- ORDER BY a.attnum;`
19094
- );
19424
+ const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
19095
19425
  const tableConstraints = await db.query(
19096
19426
  `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
19097
19427
  FROM information_schema.table_constraints tc
@@ -19173,13 +19503,9 @@ ${withStyle.errorWarning(
19173
19503
  foreignKeysToReturn[foreignKeyName].columnsFrom = [
19174
19504
  ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
19175
19505
  ];
19176
- foreignKeysToReturn[foreignKeyName].columnsTo = [
19177
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
19178
- ];
19506
+ foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
19179
19507
  }
19180
- const uniqueConstrainsRows = tableConstraints.filter(
19181
- (mapRow) => mapRow.constraint_type === "UNIQUE"
19182
- );
19508
+ const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
19183
19509
  for (const unqs of uniqueConstrainsRows) {
19184
19510
  const columnName = unqs.column_name;
19185
19511
  const constraintName = unqs.constraint_name;
@@ -19194,7 +19520,7 @@ ${withStyle.errorWarning(
19194
19520
  }
19195
19521
  }
19196
19522
  for (const columnResponse of tableResponse) {
19197
- const columnName = columnResponse.attname;
19523
+ const columnName = columnResponse.column_name;
19198
19524
  const columnAdditionalDT = columnResponse.additional_dt;
19199
19525
  const columnDimensions = columnResponse.array_dimensions;
19200
19526
  const enumType2 = columnResponse.enum_name;
@@ -19214,9 +19540,7 @@ ${withStyle.errorWarning(
19214
19540
  const primaryKey = tableConstraints.filter(
19215
19541
  (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
19216
19542
  );
19217
- const cprimaryKey = tableConstraints.filter(
19218
- (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
19219
- );
19543
+ const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
19220
19544
  if (cprimaryKey.length > 1) {
19221
19545
  const tableCompositePkName = await db.query(
19222
19546
  `SELECT conname AS primary_key
@@ -19239,10 +19563,7 @@ ${withStyle.errorWarning(
19239
19563
  [columnName]: {
19240
19564
  isArray: true,
19241
19565
  dimensions: columnDimensions,
19242
- rawType: columnTypeMapped.substring(
19243
- 0,
19244
- columnTypeMapped.length - 2
19245
- )
19566
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
19246
19567
  }
19247
19568
  }
19248
19569
  };
@@ -19251,19 +19572,12 @@ ${withStyle.errorWarning(
19251
19572
  internals.tables[tableName].columns[columnName] = {
19252
19573
  isArray: true,
19253
19574
  dimensions: columnDimensions,
19254
- rawType: columnTypeMapped.substring(
19255
- 0,
19256
- columnTypeMapped.length - 2
19257
- )
19575
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
19258
19576
  };
19259
19577
  }
19260
19578
  }
19261
19579
  }
19262
- const defaultValue = defaultForColumn(
19263
- columnResponse,
19264
- internals,
19265
- tableName
19266
- );
19580
+ const defaultValue = defaultForColumn(columnResponse, internals, tableName);
19267
19581
  if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
19268
19582
  if (typeof internals.tables[tableName] === "undefined") {
19269
19583
  internals.tables[tableName] = {
@@ -19376,7 +19690,9 @@ ${withStyle.errorWarning(
19376
19690
  WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
19377
19691
  group by index_name, table_name,schemaname, generated_by_constraint;`
19378
19692
  );
19379
- const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
19693
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
19694
+ (it) => it.index_name
19695
+ );
19380
19696
  for (const dbIndex of dbIndexes) {
19381
19697
  const indexName4 = dbIndex.indexname;
19382
19698
  const indexColumnName = dbIndex.column_name;
@@ -19451,10 +19767,182 @@ ${withStyle.errorWarning(
19451
19767
  }
19452
19768
  for await (const _2 of all) {
19453
19769
  }
19770
+ const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
19771
+ return new Promise(async (res, rej) => {
19772
+ var _a, _b, _c, _d;
19773
+ const viewName = row.table_name;
19774
+ if (!tablesFilter(viewName))
19775
+ return res("");
19776
+ tableCount += 1;
19777
+ const viewSchema = row.table_schema;
19778
+ try {
19779
+ const columnToReturn = {};
19780
+ const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
19781
+ for (const viewResponse of viewResponses) {
19782
+ const columnName = viewResponse.column_name;
19783
+ const columnAdditionalDT = viewResponse.additional_dt;
19784
+ const columnDimensions = viewResponse.array_dimensions;
19785
+ const enumType2 = viewResponse.enum_name;
19786
+ let columnType = viewResponse.data_type;
19787
+ const typeSchema = viewResponse.type_schema;
19788
+ const isGenerated = viewResponse.is_generated === "ALWAYS";
19789
+ const generationExpression = viewResponse.generation_expression;
19790
+ const isIdentity = viewResponse.is_identity === "YES";
19791
+ const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
19792
+ const identityStart = viewResponse.identity_start;
19793
+ const identityIncrement = viewResponse.identity_increment;
19794
+ const identityMaximum = viewResponse.identity_maximum;
19795
+ const identityMinimum = viewResponse.identity_minimum;
19796
+ const identityCycle = viewResponse.identity_cycle === "YES";
19797
+ const identityName = viewResponse.seq_name;
19798
+ const defaultValueRes = viewResponse.column_default;
19799
+ const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
19800
+ let columnTypeMapped = columnType;
19801
+ if (columnAdditionalDT === "ARRAY") {
19802
+ if (typeof internals.tables[viewName] === "undefined") {
19803
+ internals.tables[viewName] = {
19804
+ columns: {
19805
+ [columnName]: {
19806
+ isArray: true,
19807
+ dimensions: columnDimensions,
19808
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
19809
+ }
19810
+ }
19811
+ };
19812
+ } else {
19813
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
19814
+ internals.tables[viewName].columns[columnName] = {
19815
+ isArray: true,
19816
+ dimensions: columnDimensions,
19817
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
19818
+ };
19819
+ }
19820
+ }
19821
+ }
19822
+ const defaultValue = defaultForColumn(viewResponse, internals, viewName);
19823
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
19824
+ if (typeof internals.tables[viewName] === "undefined") {
19825
+ internals.tables[viewName] = {
19826
+ columns: {
19827
+ [columnName]: {
19828
+ isDefaultAnExpression: true
19829
+ }
19830
+ }
19831
+ };
19832
+ } else {
19833
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
19834
+ internals.tables[viewName].columns[columnName] = {
19835
+ isDefaultAnExpression: true
19836
+ };
19837
+ } else {
19838
+ internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
19839
+ }
19840
+ }
19841
+ }
19842
+ const isSerial = columnType === "serial";
19843
+ if (columnTypeMapped.startsWith("numeric(")) {
19844
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
19845
+ }
19846
+ if (columnAdditionalDT === "ARRAY") {
19847
+ for (let i2 = 1; i2 < Number(columnDimensions); i2++) {
19848
+ columnTypeMapped += "[]";
19849
+ }
19850
+ }
19851
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
19852
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
19853
+ columnToReturn[columnName] = {
19854
+ name: columnName,
19855
+ type: (
19856
+ // filter vectors, but in future we should filter any extension that was installed by user
19857
+ columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
19858
+ ),
19859
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
19860
+ primaryKey,
19861
+ notNull: viewResponse.is_nullable === "NO",
19862
+ generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
19863
+ identity: isIdentity ? {
19864
+ type: identityGeneration,
19865
+ name: identityName,
19866
+ increment: stringFromDatabaseIdentityProperty(identityIncrement),
19867
+ minValue: stringFromDatabaseIdentityProperty(identityMinimum),
19868
+ maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
19869
+ startWith: stringFromDatabaseIdentityProperty(identityStart),
19870
+ cache: ((_a = sequencesToReturn[identityName]) == null ? void 0 : _a.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _d.cache : void 0,
19871
+ cycle: identityCycle,
19872
+ schema: viewSchema
19873
+ } : void 0
19874
+ };
19875
+ if (identityName) {
19876
+ delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
19877
+ delete sequencesToReturn[identityName];
19878
+ }
19879
+ if (!isSerial && typeof defaultValue !== "undefined") {
19880
+ columnToReturn[columnName].default = defaultValue;
19881
+ }
19882
+ }
19883
+ const [viewInfo] = await db.query(`
19884
+ SELECT
19885
+ c.relname AS view_name,
19886
+ n.nspname AS schema_name,
19887
+ pg_get_viewdef(c.oid, true) AS definition,
19888
+ ts.spcname AS tablespace_name,
19889
+ c.reloptions AS options,
19890
+ pg_tablespace_location(ts.oid) AS location
19891
+ FROM
19892
+ pg_class c
19893
+ JOIN
19894
+ pg_namespace n ON c.relnamespace = n.oid
19895
+ LEFT JOIN
19896
+ pg_tablespace ts ON c.reltablespace = ts.oid
19897
+ WHERE
19898
+ (c.relkind = 'm' OR c.relkind = 'v')
19899
+ AND n.nspname = '${viewSchema}'
19900
+ AND c.relname = '${viewName}';`);
19901
+ const resultWith = {};
19902
+ if (viewInfo.options) {
19903
+ viewInfo.options.forEach((pair) => {
19904
+ const splitted = pair.split("=");
19905
+ const key = splitted[0];
19906
+ const value = splitted[1];
19907
+ if (value === "true") {
19908
+ resultWith[key] = true;
19909
+ } else if (value === "false") {
19910
+ resultWith[key] = false;
19911
+ } else if (!isNaN(Number(value))) {
19912
+ resultWith[key] = Number(value);
19913
+ } else {
19914
+ resultWith[key] = value;
19915
+ }
19916
+ });
19917
+ }
19918
+ const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
19919
+ const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
19920
+ const materialized = row.type === "materialized_view";
19921
+ views[`${viewSchema}.${viewName}`] = {
19922
+ name: viewName,
19923
+ schema: viewSchema,
19924
+ columns: columnToReturn,
19925
+ isExisting: false,
19926
+ definition,
19927
+ materialized,
19928
+ with: withOption,
19929
+ tablespace: viewInfo.tablespace_name ?? void 0
19930
+ };
19931
+ } catch (e2) {
19932
+ rej(e2);
19933
+ return;
19934
+ }
19935
+ res("");
19936
+ });
19937
+ });
19938
+ viewsCount = allViews.length;
19939
+ for await (const _2 of allViews) {
19940
+ }
19454
19941
  if (progressCallback) {
19455
19942
  progressCallback("columns", columnsCount, "done");
19456
19943
  progressCallback("indexes", indexesCount, "done");
19457
19944
  progressCallback("fks", foreignKeysCount, "done");
19945
+ progressCallback("views", viewsCount, "done");
19458
19946
  }
19459
19947
  const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
19460
19948
  return {
@@ -19464,6 +19952,7 @@ ${withStyle.errorWarning(
19464
19952
  enums: enumsToReturn,
19465
19953
  schemas: schemasObject,
19466
19954
  sequences: sequencesToReturn,
19955
+ views,
19467
19956
  _meta: {
19468
19957
  schemas: {},
19469
19958
  tables: {},
@@ -19474,7 +19963,7 @@ ${withStyle.errorWarning(
19474
19963
  };
19475
19964
  defaultForColumn = (column7, internals, tableName) => {
19476
19965
  var _a, _b;
19477
- const columnName = column7.attname;
19966
+ const columnName = column7.column_name;
19478
19967
  const isArray3 = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
19479
19968
  if (column7.column_default === null) {
19480
19969
  return void 0;
@@ -19527,6 +20016,8 @@ ${withStyle.errorWarning(
19527
20016
  }
19528
20017
  return columnDefaultAsString;
19529
20018
  }
20019
+ } else if (column7.data_type.includes("numeric")) {
20020
+ return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
19530
20021
  } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19531
20022
  const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
19532
20023
  return `'${jsonWithoutSpaces}'::${column7.data_type}`;
@@ -19540,6 +20031,75 @@ ${withStyle.errorWarning(
19540
20031
  return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
19541
20032
  }
19542
20033
  };
20034
+ getColumnsInfoQuery = ({ schema: schema5, table: table4, db }) => {
20035
+ return db.query(
20036
+ `SELECT
20037
+ a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
20038
+ a.attname AS column_name, -- Column name
20039
+ CASE
20040
+ WHEN NOT a.attisdropped THEN
20041
+ CASE
20042
+ WHEN a.attnotnull THEN 'NO'
20043
+ ELSE 'YES'
20044
+ END
20045
+ ELSE NULL
20046
+ END AS is_nullable, -- NULL or NOT NULL constraint
20047
+ a.attndims AS array_dimensions, -- Array dimensions
20048
+ CASE
20049
+ WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
20050
+ AND EXISTS (
20051
+ SELECT FROM pg_attrdef ad
20052
+ WHERE ad.adrelid = a.attrelid
20053
+ AND ad.adnum = a.attnum
20054
+ AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
20055
+ || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
20056
+ )
20057
+ THEN CASE a.atttypid
20058
+ WHEN 'int'::regtype THEN 'serial'
20059
+ WHEN 'int8'::regtype THEN 'bigserial'
20060
+ WHEN 'int2'::regtype THEN 'smallserial'
20061
+ END
20062
+ ELSE format_type(a.atttypid, a.atttypmod)
20063
+ END AS data_type, -- Column data type
20064
+ -- ns.nspname AS type_schema, -- Schema name
20065
+ pg_get_serial_sequence('"${schema5}"."${table4}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any)
20066
+ c.column_default, -- Column default value
20067
+ c.data_type AS additional_dt, -- Data type from information_schema
20068
+ c.udt_name AS enum_name, -- Enum type (if applicable)
20069
+ c.is_generated, -- Is it a generated column?
20070
+ c.generation_expression, -- Generation expression (if generated)
20071
+ c.is_identity, -- Is it an identity column?
20072
+ c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT)
20073
+ c.identity_start, -- Start value of identity column
20074
+ c.identity_increment, -- Increment for identity column
20075
+ c.identity_maximum, -- Maximum value for identity column
20076
+ c.identity_minimum, -- Minimum value for identity column
20077
+ c.identity_cycle, -- Does the identity column cycle?
20078
+ enum_ns.nspname AS type_schema -- Schema of the enum type
20079
+ FROM
20080
+ pg_attribute a
20081
+ JOIN
20082
+ pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
20083
+ JOIN
20084
+ pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
20085
+ LEFT JOIN
20086
+ information_schema.columns c ON c.column_name = a.attname
20087
+ AND c.table_schema = ns.nspname
20088
+ AND c.table_name = cls.relname -- Match schema and table/view name
20089
+ LEFT JOIN
20090
+ pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
20091
+ LEFT JOIN
20092
+ pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
20093
+ WHERE
20094
+ a.attnum > 0 -- Valid column numbers only
20095
+ AND NOT a.attisdropped -- Skip dropped columns
20096
+ AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
20097
+ AND ns.nspname = '${schema5}' -- Filter by schema
20098
+ AND cls.relname = '${table4}' -- Filter by table name
20099
+ ORDER BY
20100
+ a.attnum; -- Order by column number`
20101
+ );
20102
+ };
19543
20103
  }
19544
20104
  });
19545
20105
 
@@ -19558,25 +20118,31 @@ var init_sqliteImports = __esm({
19558
20118
  init_utils4();
19559
20119
  prepareFromExports3 = (exports2) => {
19560
20120
  const tables = [];
20121
+ const views = [];
19561
20122
  const i0values = Object.values(exports2);
19562
20123
  i0values.forEach((t2) => {
19563
20124
  if ((0, import_drizzle_orm6.is)(t2, import_sqlite_core.SQLiteTable)) {
19564
20125
  tables.push(t2);
19565
20126
  }
20127
+ if ((0, import_drizzle_orm6.is)(t2, import_sqlite_core.SQLiteView)) {
20128
+ views.push(t2);
20129
+ }
19566
20130
  });
19567
- return { tables };
20131
+ return { tables, views };
19568
20132
  };
19569
20133
  prepareFromSqliteImports = async (imports) => {
19570
20134
  const tables = [];
20135
+ const views = [];
19571
20136
  const { unregister } = await safeRegister();
19572
20137
  for (let i2 = 0; i2 < imports.length; i2++) {
19573
20138
  const it = imports[i2];
19574
20139
  const i0 = require(`${it}`);
19575
20140
  const prepared = prepareFromExports3(i0);
19576
20141
  tables.push(...prepared.tables);
20142
+ views.push(...prepared.views);
19577
20143
  }
19578
20144
  unregister();
19579
- return { tables: Array.from(new Set(tables)) };
20145
+ return { tables: Array.from(new Set(tables)), views };
19580
20146
  };
19581
20147
  }
19582
20148
  });
@@ -19658,9 +20224,10 @@ var init_sqliteSerializer = __esm({
19658
20224
  init_outputs();
19659
20225
  init_utils();
19660
20226
  init_serializer();
19661
- generateSqliteSnapshot = (tables, casing2) => {
20227
+ generateSqliteSnapshot = (tables, views, casing2) => {
19662
20228
  const dialect4 = new import_sqlite_core2.SQLiteSyncDialect({ casing: casing2 });
19663
20229
  const result = {};
20230
+ const resultViews = {};
19664
20231
  const internal = { indexes: {} };
19665
20232
  for (const table4 of tables) {
19666
20233
  const columnsObject = {};
@@ -19857,10 +20424,60 @@ The unique constraint ${source_default.underline.blue(
19857
20424
  uniqueConstraints: uniqueConstraintObject
19858
20425
  };
19859
20426
  }
20427
+ for (const view4 of views) {
20428
+ const { name, isExisting, selectedFields, query, schema: schema5 } = (0, import_sqlite_core2.getViewConfig)(view4);
20429
+ const columnsObject = {};
20430
+ const existingView = resultViews[name];
20431
+ if (typeof existingView !== "undefined") {
20432
+ console.log(
20433
+ `
20434
+ ${withStyle.errorWarning(
20435
+ `We've found duplicated view name across ${source_default.underline.blue(
20436
+ schema5 ?? "public"
20437
+ )} schema. Please rename your view`
20438
+ )}`
20439
+ );
20440
+ process.exit(1);
20441
+ }
20442
+ for (const key in selectedFields) {
20443
+ if ((0, import_drizzle_orm7.is)(selectedFields[key], import_sqlite_core2.SQLiteColumn)) {
20444
+ const column7 = selectedFields[key];
20445
+ const notNull = column7.notNull;
20446
+ const primaryKey = column7.primary;
20447
+ const generated = column7.generated;
20448
+ const columnToSet = {
20449
+ name: column7.name,
20450
+ type: column7.getSQLType(),
20451
+ primaryKey,
20452
+ notNull,
20453
+ autoincrement: (0, import_drizzle_orm7.is)(column7, import_sqlite_core2.SQLiteBaseInteger) ? column7.autoIncrement : false,
20454
+ generated: generated ? {
20455
+ as: (0, import_drizzle_orm7.is)(generated.as, import_drizzle_orm7.SQL) ? `(${dialect4.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect4.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
20456
+ type: generated.mode ?? "virtual"
20457
+ } : void 0
20458
+ };
20459
+ if (column7.default !== void 0) {
20460
+ if ((0, import_drizzle_orm7.is)(column7.default, import_drizzle_orm7.SQL)) {
20461
+ columnToSet.default = sqlToStr(column7.default, casing2);
20462
+ } else {
20463
+ columnToSet.default = typeof column7.default === "string" ? `'${column7.default}'` : typeof column7.default === "object" || Array.isArray(column7.default) ? `'${JSON.stringify(column7.default)}'` : column7.default;
20464
+ }
20465
+ }
20466
+ columnsObject[column7.name] = columnToSet;
20467
+ }
20468
+ }
20469
+ resultViews[name] = {
20470
+ columns: columnsObject,
20471
+ name,
20472
+ isExisting,
20473
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql
20474
+ };
20475
+ }
19860
20476
  return {
19861
20477
  version: "6",
19862
20478
  dialect: "sqlite",
19863
20479
  tables: result,
20480
+ views: resultViews,
19864
20481
  enums: {},
19865
20482
  _meta: {
19866
20483
  tables: {},
@@ -19871,11 +20488,12 @@ The unique constraint ${source_default.underline.blue(
19871
20488
  };
19872
20489
  fromDatabase3 = async (db, tablesFilter = (table4) => true, progressCallback) => {
19873
20490
  const result = {};
20491
+ const resultViews = {};
19874
20492
  const columns = await db.query(
19875
20493
  `SELECT
19876
- 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
20494
+ 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
19877
20495
  FROM sqlite_master AS m JOIN pragma_table_xinfo(m.name) AS p
19878
- WHERE m.type = 'table'
20496
+ WHERE (m.type = 'table' OR m.type = 'view')
19879
20497
  and m.tbl_name != 'sqlite_sequence'
19880
20498
  and m.tbl_name != 'sqlite_stat1'
19881
20499
  and m.tbl_name != '_litestream_seq'
@@ -19901,12 +20519,15 @@ The unique constraint ${source_default.underline.blue(
19901
20519
  let tablesCount = /* @__PURE__ */ new Set();
19902
20520
  let indexesCount = 0;
19903
20521
  let foreignKeysCount = 0;
20522
+ let viewsCount = 0;
19904
20523
  const tableToPk = {};
19905
20524
  let tableToGeneratedColumnsInfo = {};
19906
20525
  for (const column7 of columns) {
19907
20526
  if (!tablesFilter(column7.tableName))
19908
20527
  continue;
19909
- columnsCount += 1;
20528
+ if (column7.type !== "view") {
20529
+ columnsCount += 1;
20530
+ }
19910
20531
  if (progressCallback) {
19911
20532
  progressCallback("columns", columnsCount, "fetching");
19912
20533
  }
@@ -20075,10 +20696,40 @@ WHERE
20075
20696
  progressCallback("indexes", indexesCount, "done");
20076
20697
  progressCallback("enums", 0, "done");
20077
20698
  }
20699
+ const views = await db.query(
20700
+ `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
20701
+ );
20702
+ viewsCount = views.length;
20703
+ if (progressCallback) {
20704
+ progressCallback("views", viewsCount, "fetching");
20705
+ }
20706
+ for (const view4 of views) {
20707
+ const viewName = view4["view_name"];
20708
+ const sql = view4["sql"];
20709
+ const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
20710
+ const match2 = sql.match(regex);
20711
+ if (!match2) {
20712
+ console.log("Could not process view");
20713
+ process.exit(1);
20714
+ }
20715
+ const viewDefinition = match2[1];
20716
+ const columns2 = result[viewName].columns;
20717
+ delete result[viewName];
20718
+ resultViews[viewName] = {
20719
+ columns: columns2,
20720
+ isExisting: false,
20721
+ name: viewName,
20722
+ definition: viewDefinition
20723
+ };
20724
+ }
20725
+ if (progressCallback) {
20726
+ progressCallback("views", viewsCount, "done");
20727
+ }
20078
20728
  return {
20079
20729
  version: "6",
20080
20730
  dialect: "sqlite",
20081
20731
  tables: result,
20732
+ views: resultViews,
20082
20733
  enums: {},
20083
20734
  _meta: {
20084
20735
  tables: {},
@@ -20121,24 +20772,24 @@ ${filenames.join("\n")}
20121
20772
  `));
20122
20773
  const { prepareFromMySqlImports: prepareFromMySqlImports2 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
20123
20774
  const { generateMySqlSnapshot: generateMySqlSnapshot2 } = await Promise.resolve().then(() => (init_mysqlSerializer(), mysqlSerializer_exports));
20124
- const { tables } = await prepareFromMySqlImports2(filenames);
20125
- return generateMySqlSnapshot2(tables, casing2);
20775
+ const { tables, views } = await prepareFromMySqlImports2(filenames);
20776
+ return generateMySqlSnapshot2(tables, views, casing2);
20126
20777
  };
20127
20778
  serializePg = async (path5, casing2, schemaFilter) => {
20128
20779
  const filenames = prepareFilenames(path5);
20129
20780
  const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
20130
20781
  const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
20131
- const { tables, enums, schemas, sequences } = await prepareFromPgImports2(
20782
+ const { tables, enums, schemas, sequences, views, matViews } = await prepareFromPgImports2(
20132
20783
  filenames
20133
20784
  );
20134
- return generatePgSnapshot2(tables, enums, schemas, sequences, casing2, schemaFilter);
20785
+ return generatePgSnapshot2(tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter);
20135
20786
  };
20136
20787
  serializeSQLite = async (path5, casing2) => {
20137
20788
  const filenames = prepareFilenames(path5);
20138
20789
  const { prepareFromSqliteImports: prepareFromSqliteImports2 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
20139
20790
  const { generateSqliteSnapshot: generateSqliteSnapshot2 } = await Promise.resolve().then(() => (init_sqliteSerializer(), sqliteSerializer_exports));
20140
- const { tables } = await prepareFromSqliteImports2(filenames);
20141
- return generateSqliteSnapshot2(tables, casing2);
20791
+ const { tables, views } = await prepareFromSqliteImports2(filenames);
20792
+ return generateSqliteSnapshot2(tables, views, casing2);
20142
20793
  };
20143
20794
  prepareFilenames = (path5) => {
20144
20795
  if (typeof path5 === "string") {
@@ -22647,6 +23298,7 @@ function applyJsonDiff(json1, json2) {
22647
23298
  difference.tables = difference.tables || {};
22648
23299
  difference.enums = difference.enums || {};
22649
23300
  difference.sequences = difference.sequences || {};
23301
+ difference.views = difference.views || {};
22650
23302
  const schemaKeys = Object.keys(difference.schemas);
22651
23303
  for (let key of schemaKeys) {
22652
23304
  if (key.endsWith("__added") || key.endsWith("__deleted")) {
@@ -22702,6 +23354,76 @@ function applyJsonDiff(json1, json2) {
22702
23354
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
22703
23355
  return json2.sequences[it[0]];
22704
23356
  });
23357
+ const viewsEntries = Object.entries(difference.views);
23358
+ const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
23359
+ ([nameWithSchema, view4]) => {
23360
+ const deletedWithOption = view4.with__deleted;
23361
+ const addedWithOption = view4.with__added;
23362
+ const deletedWith = Object.fromEntries(
23363
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
23364
+ return [key.replace("__deleted", ""), value];
23365
+ })
23366
+ );
23367
+ const addedWith = Object.fromEntries(
23368
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
23369
+ return [key.replace("__added", ""), value];
23370
+ })
23371
+ );
23372
+ const alterWith = Object.fromEntries(
23373
+ Object.entries(view4.with || {}).filter(
23374
+ (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
23375
+ ).map(
23376
+ (it) => {
23377
+ return [it[0], it[1].__new];
23378
+ }
23379
+ )
23380
+ );
23381
+ const alteredSchema = view4.schema;
23382
+ const alteredDefinition = view4.definition;
23383
+ const alteredExisting = view4.isExisting;
23384
+ const addedTablespace = view4.tablespace__added;
23385
+ const droppedTablespace = view4.tablespace__deleted;
23386
+ const alterTablespaceTo = view4.tablespace;
23387
+ let alteredTablespace;
23388
+ if (addedTablespace)
23389
+ alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
23390
+ if (droppedTablespace)
23391
+ alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
23392
+ if (alterTablespaceTo)
23393
+ alteredTablespace = alterTablespaceTo;
23394
+ const addedUsing = view4.using__added;
23395
+ const droppedUsing = view4.using__deleted;
23396
+ const alterUsingTo = view4.using;
23397
+ let alteredUsing;
23398
+ if (addedUsing)
23399
+ alteredUsing = { __new: addedUsing, __old: "heap" };
23400
+ if (droppedUsing)
23401
+ alteredUsing = { __new: "heap", __old: droppedUsing };
23402
+ if (alterUsingTo)
23403
+ alteredUsing = alterUsingTo;
23404
+ const alteredMeta = view4.meta;
23405
+ return Object.fromEntries(
23406
+ Object.entries({
23407
+ name: json2.views[nameWithSchema].name,
23408
+ schema: json2.views[nameWithSchema].schema,
23409
+ // pg
23410
+ deletedWithOption,
23411
+ addedWithOption,
23412
+ deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
23413
+ addedWith: Object.keys(addedWith).length ? addedWith : void 0,
23414
+ alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
23415
+ alteredSchema,
23416
+ alteredTablespace,
23417
+ alteredUsing,
23418
+ // mysql
23419
+ alteredMeta,
23420
+ // common
23421
+ alteredDefinition,
23422
+ alteredExisting
23423
+ }).filter(([_2, value]) => value !== void 0)
23424
+ );
23425
+ }
23426
+ );
22705
23427
  const alteredTablesWithColumns = Object.values(difference.tables).map(
22706
23428
  (table4) => {
22707
23429
  return findAlternationsInTable(table4);
@@ -22710,7 +23432,8 @@ function applyJsonDiff(json1, json2) {
22710
23432
  return {
22711
23433
  alteredTablesWithColumns,
22712
23434
  alteredEnums,
22713
- alteredSequences
23435
+ alteredSequences,
23436
+ alteredViews
22714
23437
  };
22715
23438
  }
22716
23439
  var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
@@ -23105,7 +23828,7 @@ function fromJson(statements, dialect4, action, json2) {
23105
23828
  }).filter((it) => it !== "");
23106
23829
  return result;
23107
23830
  }
23108
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, AlterTypeAddValueConvertor, 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;
23831
+ 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, 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;
23109
23832
  var init_sqlgenerator = __esm({
23110
23833
  "src/sqlgenerator.ts"() {
23111
23834
  "use strict";
@@ -23321,6 +24044,191 @@ var init_sqlgenerator = __esm({
23321
24044
  return statement;
23322
24045
  }
23323
24046
  };
24047
+ PgCreateViewConvertor = class extends Convertor {
24048
+ can(statement, dialect4) {
24049
+ return statement.type === "create_view" && dialect4 === "postgresql";
24050
+ }
24051
+ convert(st) {
24052
+ const { definition, name: viewName, schema: schema5, with: withOption, materialized, withNoData, tablespace, using } = st;
24053
+ const name = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
24054
+ let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`;
24055
+ if (using)
24056
+ statement += ` USING "${using}"`;
24057
+ const options = [];
24058
+ if (withOption) {
24059
+ statement += ` WITH (`;
24060
+ Object.entries(withOption).forEach(([key, value]) => {
24061
+ if (typeof value === "undefined")
24062
+ return;
24063
+ options.push(`${key.snake_case()} = ${value}`);
24064
+ });
24065
+ statement += options.join(", ");
24066
+ statement += `)`;
24067
+ }
24068
+ if (tablespace)
24069
+ statement += ` TABLESPACE ${tablespace}`;
24070
+ statement += ` AS (${definition})`;
24071
+ if (withNoData)
24072
+ statement += ` WITH NO DATA`;
24073
+ statement += `;`;
24074
+ return statement;
24075
+ }
24076
+ };
24077
+ MySqlCreateViewConvertor = class extends Convertor {
24078
+ can(statement, dialect4) {
24079
+ return statement.type === "mysql_create_view" && dialect4 === "mysql";
24080
+ }
24081
+ convert(st) {
24082
+ const { definition, name, algorithm, sqlSecurity, withCheckOption, replace } = st;
24083
+ let statement = `CREATE `;
24084
+ statement += replace ? `OR REPLACE ` : "";
24085
+ statement += algorithm ? `ALGORITHM = ${algorithm}
24086
+ ` : "";
24087
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
24088
+ ` : "";
24089
+ statement += `VIEW \`${name}\` AS (${definition})`;
24090
+ statement += withCheckOption ? `
24091
+ WITH ${withCheckOption} CHECK OPTION` : "";
24092
+ statement += ";";
24093
+ return statement;
24094
+ }
24095
+ };
24096
+ SqliteCreateViewConvertor = class extends Convertor {
24097
+ can(statement, dialect4) {
24098
+ return statement.type === "sqlite_create_view" && (dialect4 === "sqlite" || dialect4 === "turso");
24099
+ }
24100
+ convert(st) {
24101
+ const { definition, name } = st;
24102
+ return `CREATE VIEW \`${name}\` AS ${definition};`;
24103
+ }
24104
+ };
24105
+ PgDropViewConvertor = class extends Convertor {
24106
+ can(statement, dialect4) {
24107
+ return statement.type === "drop_view" && dialect4 === "postgresql";
24108
+ }
24109
+ convert(st) {
24110
+ const { name: viewName, schema: schema5, materialized } = st;
24111
+ const name = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
24112
+ return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`;
24113
+ }
24114
+ };
24115
+ MySqlDropViewConvertor = class extends Convertor {
24116
+ can(statement, dialect4) {
24117
+ return statement.type === "drop_view" && dialect4 === "mysql";
24118
+ }
24119
+ convert(st) {
24120
+ const { name } = st;
24121
+ return `DROP VIEW \`${name}\`;`;
24122
+ }
24123
+ };
24124
+ SqliteDropViewConvertor = class extends Convertor {
24125
+ can(statement, dialect4) {
24126
+ return statement.type === "drop_view" && (dialect4 === "sqlite" || dialect4 === "turso");
24127
+ }
24128
+ convert(st) {
24129
+ const { name } = st;
24130
+ return `DROP VIEW \`${name}\`;`;
24131
+ }
24132
+ };
24133
+ MySqlAlterViewConvertor = class extends Convertor {
24134
+ can(statement, dialect4) {
24135
+ return statement.type === "alter_mysql_view" && dialect4 === "mysql";
24136
+ }
24137
+ convert(st) {
24138
+ const { name, algorithm, definition, sqlSecurity, withCheckOption } = st;
24139
+ let statement = `ALTER `;
24140
+ statement += algorithm ? `ALGORITHM = ${algorithm}
24141
+ ` : "";
24142
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
24143
+ ` : "";
24144
+ statement += `VIEW \`${name}\` AS ${definition}`;
24145
+ statement += withCheckOption ? `
24146
+ WITH ${withCheckOption} CHECK OPTION` : "";
24147
+ statement += ";";
24148
+ return statement;
24149
+ }
24150
+ };
24151
+ PgRenameViewConvertor = class extends Convertor {
24152
+ can(statement, dialect4) {
24153
+ return statement.type === "rename_view" && dialect4 === "postgresql";
24154
+ }
24155
+ convert(st) {
24156
+ const { nameFrom: from, nameTo: to, schema: schema5, materialized } = st;
24157
+ const nameFrom = `"${schema5}"."${from}"`;
24158
+ return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
24159
+ }
24160
+ };
24161
+ MySqlRenameViewConvertor = class extends Convertor {
24162
+ can(statement, dialect4) {
24163
+ return statement.type === "rename_view" && dialect4 === "mysql";
24164
+ }
24165
+ convert(st) {
24166
+ const { nameFrom: from, nameTo: to } = st;
24167
+ return `RENAME TABLE \`${from}\` RENAME TO \`${to}\`;`;
24168
+ }
24169
+ };
24170
+ PgAlterViewSchemaConvertor = class extends Convertor {
24171
+ can(statement, dialect4) {
24172
+ return statement.type === "alter_view_alter_schema" && dialect4 === "postgresql";
24173
+ }
24174
+ convert(st) {
24175
+ const { fromSchema, toSchema, name, materialized } = st;
24176
+ const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`;
24177
+ return statement;
24178
+ }
24179
+ };
24180
+ PgAlterViewAddWithOptionConvertor = class extends Convertor {
24181
+ can(statement, dialect4) {
24182
+ return statement.type === "alter_view_add_with_option" && dialect4 === "postgresql";
24183
+ }
24184
+ convert(st) {
24185
+ const { schema: schema5, with: withOption, name, materialized } = st;
24186
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name}" SET (`;
24187
+ const options = [];
24188
+ Object.entries(withOption).forEach(([key, value]) => {
24189
+ options.push(`${key.snake_case()} = ${value}`);
24190
+ });
24191
+ statement += options.join(", ");
24192
+ statement += `);`;
24193
+ return statement;
24194
+ }
24195
+ };
24196
+ PgAlterViewDropWithOptionConvertor = class extends Convertor {
24197
+ can(statement, dialect4) {
24198
+ return statement.type === "alter_view_drop_with_option" && dialect4 === "postgresql";
24199
+ }
24200
+ convert(st) {
24201
+ const { schema: schema5, name, materialized, with: withOptions } = st;
24202
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name}" RESET (`;
24203
+ const options = [];
24204
+ Object.entries(withOptions).forEach(([key, value]) => {
24205
+ options.push(`${key.snake_case()}`);
24206
+ });
24207
+ statement += options.join(", ");
24208
+ statement += ");";
24209
+ return statement;
24210
+ }
24211
+ };
24212
+ PgAlterViewAlterTablespaceConvertor = class extends Convertor {
24213
+ can(statement, dialect4) {
24214
+ return statement.type === "alter_view_alter_tablespace" && dialect4 === "postgresql";
24215
+ }
24216
+ convert(st) {
24217
+ const { schema: schema5, name, toTablespace } = st;
24218
+ const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name}" SET TABLESPACE ${toTablespace};`;
24219
+ return statement;
24220
+ }
24221
+ };
24222
+ PgAlterViewAlterUsingConvertor = class extends Convertor {
24223
+ can(statement, dialect4) {
24224
+ return statement.type === "alter_view_alter_using" && dialect4 === "postgresql";
24225
+ }
24226
+ convert(st) {
24227
+ const { schema: schema5, name, toUsing } = st;
24228
+ const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name}" SET ACCESS METHOD "${toUsing}";`;
24229
+ return statement;
24230
+ }
24231
+ };
23324
24232
  PgAlterTableAlterColumnSetGenerated = class extends Convertor {
23325
24233
  can(statement, dialect4) {
23326
24234
  return statement.type === "alter_table_alter_column_set_identity" && dialect4 === "postgresql";
@@ -23489,20 +24397,22 @@ var init_sqlgenerator = __esm({
23489
24397
  }
23490
24398
  convert(st) {
23491
24399
  const { name, values, schema: schema5 } = st;
23492
- const tableNameWithSchema = schema5 ? `"${schema5}"."${name}"` : `"${name}"`;
24400
+ const enumNameWithSchema = schema5 ? `"${schema5}"."${name}"` : `"${name}"`;
23493
24401
  let valuesStatement = "(";
23494
24402
  valuesStatement += values.map((it) => `'${it}'`).join(", ");
23495
24403
  valuesStatement += ")";
23496
- let statement = "DO $$ BEGIN";
23497
- statement += "\n";
23498
- statement += ` CREATE TYPE ${tableNameWithSchema} AS ENUM${valuesStatement};`;
23499
- statement += "\n";
23500
- statement += "EXCEPTION";
23501
- statement += "\n";
23502
- statement += " WHEN duplicate_object THEN null;";
23503
- statement += "\n";
23504
- statement += "END $$;";
23505
- statement += "\n";
24404
+ let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
24405
+ return statement;
24406
+ }
24407
+ };
24408
+ DropTypeEnumConvertor = class extends Convertor {
24409
+ can(statement) {
24410
+ return statement.type === "drop_type_enum";
24411
+ }
24412
+ convert(st) {
24413
+ const { name, schema: schema5 } = st;
24414
+ const enumNameWithSchema = schema5 ? `"${schema5}"."${name}"` : `"${name}"`;
24415
+ let statement = `DROP TYPE ${enumNameWithSchema};`;
23506
24416
  return statement;
23507
24417
  }
23508
24418
  };
@@ -23511,9 +24421,56 @@ var init_sqlgenerator = __esm({
23511
24421
  return statement.type === "alter_type_add_value";
23512
24422
  }
23513
24423
  convert(st) {
23514
- const { name, schema: schema5, value } = st;
23515
- const schemaPrefix = schema5 && schema5 !== "public" ? `"${schema5}".` : "";
23516
- return `ALTER TYPE ${schemaPrefix}"${name}" ADD VALUE '${value}';`;
24424
+ const { name, schema: schema5, value, before } = st;
24425
+ const enumNameWithSchema = schema5 ? `"${schema5}"."${name}"` : `"${name}"`;
24426
+ return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
24427
+ }
24428
+ };
24429
+ AlterTypeSetSchemaConvertor = class extends Convertor {
24430
+ can(statement) {
24431
+ return statement.type === "move_type_enum";
24432
+ }
24433
+ convert(st) {
24434
+ const { name, schemaFrom, schemaTo } = st;
24435
+ const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
24436
+ return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
24437
+ }
24438
+ };
24439
+ AlterRenameTypeConvertor = class extends Convertor {
24440
+ can(statement) {
24441
+ return statement.type === "rename_type_enum";
24442
+ }
24443
+ convert(st) {
24444
+ const { nameTo, nameFrom, schema: schema5 } = st;
24445
+ const enumNameWithSchema = schema5 ? `"${schema5}"."${nameFrom}"` : `"${nameFrom}"`;
24446
+ return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
24447
+ }
24448
+ };
24449
+ AlterTypeDropValueConvertor = class extends Convertor {
24450
+ can(statement) {
24451
+ return statement.type === "alter_type_drop_value";
24452
+ }
24453
+ convert(st) {
24454
+ const { columnsWithEnum, name, newValues, schema: schema5 } = st;
24455
+ const statements = [];
24456
+ for (const withEnum of columnsWithEnum) {
24457
+ statements.push(
24458
+ `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
24459
+ );
24460
+ }
24461
+ statements.push(new DropTypeEnumConvertor().convert({ name, schema: schema5, type: "drop_type_enum" }));
24462
+ statements.push(new CreateTypeEnumConvertor().convert({
24463
+ name,
24464
+ schema: schema5,
24465
+ values: newValues,
24466
+ type: "create_type_enum"
24467
+ }));
24468
+ for (const withEnum of columnsWithEnum) {
24469
+ statements.push(
24470
+ `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE "${schema5}"."${name}" USING "${withEnum.column}"::"${schema5}"."${name}";`
24471
+ );
24472
+ }
24473
+ return statements;
23517
24474
  }
23518
24475
  };
23519
24476
  PgDropTableConvertor = class extends Convertor {
@@ -24659,7 +25616,26 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24659
25616
  convertors.push(new SQLiteCreateTableConvertor());
24660
25617
  convertors.push(new SQLiteRecreateTableConvertor());
24661
25618
  convertors.push(new LibSQLRecreateTableConvertor());
25619
+ convertors.push(new PgCreateViewConvertor());
25620
+ convertors.push(new PgDropViewConvertor());
25621
+ convertors.push(new PgRenameViewConvertor());
25622
+ convertors.push(new PgAlterViewSchemaConvertor());
25623
+ convertors.push(new PgAlterViewAddWithOptionConvertor());
25624
+ convertors.push(new PgAlterViewDropWithOptionConvertor());
25625
+ convertors.push(new PgAlterViewAlterTablespaceConvertor());
25626
+ convertors.push(new PgAlterViewAlterUsingConvertor());
25627
+ convertors.push(new MySqlCreateViewConvertor());
25628
+ convertors.push(new MySqlDropViewConvertor());
25629
+ convertors.push(new MySqlRenameViewConvertor());
25630
+ convertors.push(new MySqlAlterViewConvertor());
25631
+ convertors.push(new SqliteCreateViewConvertor());
25632
+ convertors.push(new SqliteDropViewConvertor());
24662
25633
  convertors.push(new CreateTypeEnumConvertor());
25634
+ convertors.push(new DropTypeEnumConvertor());
25635
+ convertors.push(new AlterTypeAddValueConvertor());
25636
+ convertors.push(new AlterTypeSetSchemaConvertor());
25637
+ convertors.push(new AlterRenameTypeConvertor());
25638
+ convertors.push(new AlterTypeDropValueConvertor());
24663
25639
  convertors.push(new CreatePgSequenceConvertor());
24664
25640
  convertors.push(new DropPgSequenceConvertor());
24665
25641
  convertors.push(new RenamePgSequenceConvertor());
@@ -24691,7 +25667,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24691
25667
  convertors.push(new PgDropIndexConvertor());
24692
25668
  convertors.push(new SqliteDropIndexConvertor());
24693
25669
  convertors.push(new MySqlDropIndexConvertor());
24694
- convertors.push(new AlterTypeAddValueConvertor());
24695
25670
  convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
24696
25671
  convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
24697
25672
  convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
@@ -24993,7 +25968,7 @@ var init_sqlitePushUtils = __esm({
24993
25968
  });
24994
25969
 
24995
25970
  // src/jsonStatements.ts
24996
- var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql;
25971
+ 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, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
24997
25972
  var init_jsonStatements = __esm({
24998
25973
  "src/jsonStatements.ts"() {
24999
25974
  "use strict";
@@ -25083,6 +26058,28 @@ var init_jsonStatements = __esm({
25083
26058
  };
25084
26059
  });
25085
26060
  };
26061
+ prepareDropEnumValues = (name, schema5, removedValues, json2) => {
26062
+ if (!removedValues.length)
26063
+ return [];
26064
+ const affectedColumns = [];
26065
+ for (const tableKey2 in json2.tables) {
26066
+ const table4 = json2.tables[tableKey2];
26067
+ for (const columnKey in table4.columns) {
26068
+ const column7 = table4.columns[columnKey];
26069
+ if (column7.type === name && column7.typeSchema === schema5) {
26070
+ affectedColumns.push({ schema: table4.schema || "public", table: table4.name, column: column7.name });
26071
+ }
26072
+ }
26073
+ }
26074
+ return [{
26075
+ type: "alter_type_drop_value",
26076
+ name,
26077
+ schema: schema5,
26078
+ deletedValues: removedValues,
26079
+ newValues: json2.enums[`${schema5}.${name}`].values,
26080
+ columnsWithEnum: affectedColumns
26081
+ }];
26082
+ };
25086
26083
  prepareDropEnumJson = (name, schema5) => {
25087
26084
  return {
25088
26085
  type: "drop_type_enum",
@@ -26332,6 +27329,108 @@ var init_jsonStatements = __esm({
26332
27329
  };
26333
27330
  });
26334
27331
  };
27332
+ preparePgCreateViewJson = (name, schema5, definition, materialized, withNoData = false, withOption, using, tablespace) => {
27333
+ return {
27334
+ type: "create_view",
27335
+ name,
27336
+ schema: schema5,
27337
+ definition,
27338
+ with: withOption,
27339
+ materialized,
27340
+ withNoData,
27341
+ using,
27342
+ tablespace
27343
+ };
27344
+ };
27345
+ prepareMySqlCreateViewJson = (name, definition, meta, replace = false) => {
27346
+ const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
27347
+ return {
27348
+ type: "mysql_create_view",
27349
+ name,
27350
+ definition,
27351
+ algorithm,
27352
+ sqlSecurity,
27353
+ withCheckOption,
27354
+ replace
27355
+ };
27356
+ };
27357
+ prepareSqliteCreateViewJson = (name, definition) => {
27358
+ return {
27359
+ type: "sqlite_create_view",
27360
+ name,
27361
+ definition
27362
+ };
27363
+ };
27364
+ prepareDropViewJson = (name, schema5, materialized) => {
27365
+ const resObject = { name, type: "drop_view" };
27366
+ if (schema5)
27367
+ resObject["schema"] = schema5;
27368
+ if (materialized)
27369
+ resObject["materialized"] = materialized;
27370
+ return resObject;
27371
+ };
27372
+ prepareRenameViewJson = (to, from, schema5, materialized) => {
27373
+ const resObject = {
27374
+ type: "rename_view",
27375
+ nameTo: to,
27376
+ nameFrom: from
27377
+ };
27378
+ if (schema5)
27379
+ resObject["schema"] = schema5;
27380
+ if (materialized)
27381
+ resObject["materialized"] = materialized;
27382
+ return resObject;
27383
+ };
27384
+ preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => {
27385
+ const returnObject = {
27386
+ type: "alter_view_alter_schema",
27387
+ fromSchema: from,
27388
+ toSchema: to,
27389
+ name
27390
+ };
27391
+ if (materialized)
27392
+ returnObject["materialized"] = materialized;
27393
+ return returnObject;
27394
+ };
27395
+ preparePgAlterViewAddWithOptionJson = (name, schema5, materialized, withOption) => {
27396
+ return {
27397
+ type: "alter_view_add_with_option",
27398
+ name,
27399
+ schema: schema5,
27400
+ materialized,
27401
+ with: withOption
27402
+ };
27403
+ };
27404
+ preparePgAlterViewDropWithOptionJson = (name, schema5, materialized, withOption) => {
27405
+ return {
27406
+ type: "alter_view_drop_with_option",
27407
+ name,
27408
+ schema: schema5,
27409
+ materialized,
27410
+ with: withOption
27411
+ };
27412
+ };
27413
+ preparePgAlterViewAlterTablespaceJson = (name, schema5, materialized, to) => {
27414
+ return {
27415
+ type: "alter_view_alter_tablespace",
27416
+ name,
27417
+ schema: schema5,
27418
+ materialized,
27419
+ toTablespace: to
27420
+ };
27421
+ };
27422
+ preparePgAlterViewAlterUsingJson = (name, schema5, materialized, to) => {
27423
+ return {
27424
+ type: "alter_view_alter_using",
27425
+ name,
27426
+ schema: schema5,
27427
+ materialized,
27428
+ toUsing: to
27429
+ };
27430
+ };
27431
+ prepareMySqlAlterView = (view4) => {
27432
+ return { type: "alter_mysql_view", ...view4 };
27433
+ };
26335
27434
  }
26336
27435
  });
26337
27436
 
@@ -26617,7 +27716,7 @@ var init_statementCombiner = __esm({
26617
27716
  });
26618
27717
 
26619
27718
  // src/snapshotsDiffer.ts
26620
- var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
27719
+ var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
26621
27720
  var init_snapshotsDiffer = __esm({
26622
27721
  "src/snapshotsDiffer.ts"() {
26623
27722
  "use strict";
@@ -26765,18 +27864,62 @@ var init_snapshotsDiffer = __esm({
26765
27864
  })
26766
27865
  )
26767
27866
  }).strict();
27867
+ alteredViewCommon = objectType({
27868
+ name: stringType(),
27869
+ alteredDefinition: objectType({
27870
+ __old: stringType(),
27871
+ __new: stringType()
27872
+ }).strict().optional(),
27873
+ alteredExisting: objectType({
27874
+ __old: booleanType(),
27875
+ __new: booleanType()
27876
+ }).strict().optional()
27877
+ });
27878
+ alteredPgViewSchema = alteredViewCommon.merge(
27879
+ objectType({
27880
+ schema: stringType(),
27881
+ deletedWithOption: mergedViewWithOption.optional(),
27882
+ addedWithOption: mergedViewWithOption.optional(),
27883
+ addedWith: mergedViewWithOption.optional(),
27884
+ deletedWith: mergedViewWithOption.optional(),
27885
+ alteredWith: mergedViewWithOption.optional(),
27886
+ alteredSchema: objectType({
27887
+ __old: stringType(),
27888
+ __new: stringType()
27889
+ }).strict().optional(),
27890
+ alteredTablespace: objectType({
27891
+ __old: stringType(),
27892
+ __new: stringType()
27893
+ }).strict().optional(),
27894
+ alteredUsing: objectType({
27895
+ __old: stringType(),
27896
+ __new: stringType()
27897
+ }).strict().optional()
27898
+ }).strict()
27899
+ );
27900
+ alteredMySqlViewSchema = alteredViewCommon.merge(
27901
+ objectType({
27902
+ alteredMeta: objectType({
27903
+ __old: stringType(),
27904
+ __new: stringType()
27905
+ }).strict().optional()
27906
+ }).strict()
27907
+ );
26768
27908
  diffResultScheme = objectType({
26769
27909
  alteredTablesWithColumns: alteredTableScheme.array(),
26770
27910
  alteredEnums: changedEnumSchema.array(),
26771
- alteredSequences: sequenceSquashed.array()
27911
+ alteredSequences: sequenceSquashed.array(),
27912
+ alteredViews: alteredPgViewSchema.array()
26772
27913
  }).strict();
26773
27914
  diffResultSchemeMysql = objectType({
26774
27915
  alteredTablesWithColumns: alteredTableScheme.array(),
26775
- alteredEnums: neverType().array()
27916
+ alteredEnums: neverType().array(),
27917
+ alteredViews: alteredMySqlViewSchema.array()
26776
27918
  });
26777
27919
  diffResultSchemeSQLite = objectType({
26778
27920
  alteredTablesWithColumns: alteredTableScheme.array(),
26779
- alteredEnums: neverType().array()
27921
+ alteredEnums: neverType().array(),
27922
+ alteredViews: alteredViewCommon.array()
26780
27923
  });
26781
27924
  schemaChangeFor = (table4, renamedSchemas) => {
26782
27925
  for (let ren of renamedSchemas) {
@@ -26823,7 +27966,7 @@ var init_snapshotsDiffer = __esm({
26823
27966
  }
26824
27967
  return column7;
26825
27968
  };
26826
- applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
27969
+ applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
26827
27970
  const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
26828
27971
  const {
26829
27972
  created: createdSchemas,
@@ -27051,7 +28194,40 @@ var init_snapshotsDiffer = __esm({
27051
28194
  return [tableKey2, tableValue];
27052
28195
  }
27053
28196
  );
27054
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
28197
+ const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
28198
+ const {
28199
+ created: createdViews,
28200
+ deleted: deletedViews,
28201
+ renamed: renamedViews,
28202
+ moved: movedViews
28203
+ } = await viewsResolver2({
28204
+ created: viewsDiff.added,
28205
+ deleted: viewsDiff.deleted
28206
+ });
28207
+ const renamesViewDic = {};
28208
+ renamedViews.forEach((it) => {
28209
+ renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
28210
+ });
28211
+ const movedViewDic = {};
28212
+ movedViews.forEach((it) => {
28213
+ movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
28214
+ });
28215
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
28216
+ viewsPatchedSnap1.views = mapEntries(
28217
+ viewsPatchedSnap1.views,
28218
+ (viewKey, viewValue) => {
28219
+ const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
28220
+ const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
28221
+ if (rename) {
28222
+ viewValue.name = rename.to;
28223
+ viewKey = `${viewValue.schema}.${viewValue.name}`;
28224
+ }
28225
+ if (moved)
28226
+ viewKey = `${moved.to}.${viewValue.name}`;
28227
+ return [viewKey, viewValue];
28228
+ }
28229
+ );
28230
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
27055
28231
  const typedResult = diffResultScheme.parse(diffResult);
27056
28232
  const jsonStatements = [];
27057
28233
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -27276,6 +28452,9 @@ var init_snapshotsDiffer = __esm({
27276
28452
  const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
27277
28453
  return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
27278
28454
  }).flat() ?? [];
28455
+ const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
28456
+ return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
28457
+ }).flat() ?? [];
27279
28458
  const createSequences = createdSequences.map((it) => {
27280
28459
  return prepareCreateSequenceJson(it);
27281
28460
  }) ?? [];
@@ -27303,6 +28482,137 @@ var init_snapshotsDiffer = __esm({
27303
28482
  const createTables = createdTables.map((it) => {
27304
28483
  return preparePgCreateTableJson(it, curFull);
27305
28484
  });
28485
+ const createViews = [];
28486
+ const dropViews = [];
28487
+ const renameViews = [];
28488
+ const alterViews = [];
28489
+ createViews.push(
28490
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
28491
+ return preparePgCreateViewJson(
28492
+ it.name,
28493
+ it.schema,
28494
+ it.definition,
28495
+ it.materialized,
28496
+ it.withNoData,
28497
+ it.with,
28498
+ it.using,
28499
+ it.tablespace
28500
+ );
28501
+ })
28502
+ );
28503
+ dropViews.push(
28504
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
28505
+ return prepareDropViewJson(it.name, it.schema, it.materialized);
28506
+ })
28507
+ );
28508
+ renameViews.push(
28509
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
28510
+ return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
28511
+ })
28512
+ );
28513
+ alterViews.push(
28514
+ ...movedViews.filter(
28515
+ (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
28516
+ ).map((it) => {
28517
+ return preparePgAlterViewAlterSchemaJson(
28518
+ it.schemaTo,
28519
+ it.schemaFrom,
28520
+ it.name,
28521
+ json2.views[`${it.schemaTo}.${it.name}`].materialized
28522
+ );
28523
+ })
28524
+ );
28525
+ const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting);
28526
+ for (const alteredView of alteredViews) {
28527
+ const viewKey = `${alteredView.schema}.${alteredView.name}`;
28528
+ const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey];
28529
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
28530
+ dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
28531
+ createViews.push(
28532
+ preparePgCreateViewJson(
28533
+ alteredView.name,
28534
+ alteredView.schema,
28535
+ definition,
28536
+ materialized,
28537
+ withNoData,
28538
+ withOption,
28539
+ using,
28540
+ tablespace
28541
+ )
28542
+ );
28543
+ continue;
28544
+ }
28545
+ if (alteredView.addedWithOption) {
28546
+ alterViews.push(
28547
+ preparePgAlterViewAddWithOptionJson(
28548
+ alteredView.name,
28549
+ alteredView.schema,
28550
+ materialized,
28551
+ alteredView.addedWithOption
28552
+ )
28553
+ );
28554
+ }
28555
+ if (alteredView.deletedWithOption) {
28556
+ alterViews.push(
28557
+ preparePgAlterViewDropWithOptionJson(
28558
+ alteredView.name,
28559
+ alteredView.schema,
28560
+ materialized,
28561
+ alteredView.deletedWithOption
28562
+ )
28563
+ );
28564
+ }
28565
+ if (alteredView.addedWith) {
28566
+ alterViews.push(
28567
+ preparePgAlterViewAddWithOptionJson(
28568
+ alteredView.name,
28569
+ alteredView.schema,
28570
+ materialized,
28571
+ alteredView.addedWith
28572
+ )
28573
+ );
28574
+ }
28575
+ if (alteredView.deletedWith) {
28576
+ alterViews.push(
28577
+ preparePgAlterViewDropWithOptionJson(
28578
+ alteredView.name,
28579
+ alteredView.schema,
28580
+ materialized,
28581
+ alteredView.deletedWith
28582
+ )
28583
+ );
28584
+ }
28585
+ if (alteredView.alteredWith) {
28586
+ alterViews.push(
28587
+ preparePgAlterViewAddWithOptionJson(
28588
+ alteredView.name,
28589
+ alteredView.schema,
28590
+ materialized,
28591
+ alteredView.alteredWith
28592
+ )
28593
+ );
28594
+ }
28595
+ if (alteredView.alteredTablespace) {
28596
+ alterViews.push(
28597
+ preparePgAlterViewAlterTablespaceJson(
28598
+ alteredView.name,
28599
+ alteredView.schema,
28600
+ materialized,
28601
+ alteredView.alteredTablespace.__new
28602
+ )
28603
+ );
28604
+ }
28605
+ if (alteredView.alteredUsing) {
28606
+ alterViews.push(
28607
+ preparePgAlterViewAlterUsingJson(
28608
+ alteredView.name,
28609
+ alteredView.schema,
28610
+ materialized,
28611
+ alteredView.alteredUsing.__new
28612
+ )
28613
+ );
28614
+ }
28615
+ }
27306
28616
  jsonStatements.push(...createSchemas);
27307
28617
  jsonStatements.push(...renameSchemas);
27308
28618
  jsonStatements.push(...createEnums);
@@ -27314,6 +28624,9 @@ var init_snapshotsDiffer = __esm({
27314
28624
  jsonStatements.push(...renameSequences);
27315
28625
  jsonStatements.push(...jsonAlterSequences);
27316
28626
  jsonStatements.push(...createTables);
28627
+ jsonStatements.push(...dropViews);
28628
+ jsonStatements.push(...renameViews);
28629
+ jsonStatements.push(...alterViews);
27317
28630
  jsonStatements.push(...jsonDropTables);
27318
28631
  jsonStatements.push(...jsonSetTableSchemas);
27319
28632
  jsonStatements.push(...jsonRenameTables);
@@ -27333,6 +28646,8 @@ var init_snapshotsDiffer = __esm({
27333
28646
  jsonStatements.push(...jsonAlteredCompositePKs);
27334
28647
  jsonStatements.push(...jsonAddedUniqueConstraints);
27335
28648
  jsonStatements.push(...jsonAlteredUniqueConstraints);
28649
+ jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
28650
+ jsonStatements.push(...createViews);
27336
28651
  jsonStatements.push(...dropEnums);
27337
28652
  jsonStatements.push(...dropSequences);
27338
28653
  jsonStatements.push(...dropSchemas);
@@ -27353,7 +28668,17 @@ var init_snapshotsDiffer = __esm({
27353
28668
  }
27354
28669
  return true;
27355
28670
  });
27356
- const sqlStatements = fromJson(filteredJsonStatements, "postgresql");
28671
+ const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
28672
+ if (st.type === "alter_type_add_value") {
28673
+ if (jsonStatements.find(
28674
+ (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.schema === st.schema
28675
+ )) {
28676
+ return false;
28677
+ }
28678
+ }
28679
+ return true;
28680
+ });
28681
+ const sqlStatements = fromJson(filteredEnumsJsonStatements, "postgresql");
27357
28682
  const uniqueSqlStatements = [];
27358
28683
  sqlStatements.forEach((ss) => {
27359
28684
  if (!uniqueSqlStatements.includes(ss)) {
@@ -27369,12 +28694,12 @@ var init_snapshotsDiffer = __esm({
27369
28694
  });
27370
28695
  const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
27371
28696
  return {
27372
- statements: filteredJsonStatements,
28697
+ statements: filteredEnumsJsonStatements,
27373
28698
  sqlStatements: uniqueSqlStatements,
27374
28699
  _meta
27375
28700
  };
27376
28701
  };
27377
- applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
28702
+ applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
27378
28703
  for (const tableName in json1.tables) {
27379
28704
  const table4 = json1.tables[tableName];
27380
28705
  for (const indexName4 in table4.indexes) {
@@ -27471,7 +28796,33 @@ var init_snapshotsDiffer = __esm({
27471
28796
  return [tableKey2, tableValue];
27472
28797
  }
27473
28798
  );
27474
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
28799
+ const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
28800
+ const {
28801
+ created: createdViews,
28802
+ deleted: deletedViews,
28803
+ renamed: renamedViews
28804
+ // renamed or moved
28805
+ } = await viewsResolver2({
28806
+ created: viewsDiff.added,
28807
+ deleted: viewsDiff.deleted
28808
+ });
28809
+ const renamesViewDic = {};
28810
+ renamedViews.forEach((it) => {
28811
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
28812
+ });
28813
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
28814
+ viewsPatchedSnap1.views = mapEntries(
28815
+ viewsPatchedSnap1.views,
28816
+ (viewKey, viewValue) => {
28817
+ const rename = renamesViewDic[viewValue.name];
28818
+ if (rename) {
28819
+ viewValue.name = rename.to;
28820
+ viewKey = rename.to;
28821
+ }
28822
+ return [viewKey, viewValue];
28823
+ }
28824
+ );
28825
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
27475
28826
  const typedResult = diffResultSchemeMysql.parse(diffResult);
27476
28827
  const jsonStatements = [];
27477
28828
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -27653,10 +29004,68 @@ var init_snapshotsDiffer = __esm({
27653
29004
  curFull.internal
27654
29005
  );
27655
29006
  });
29007
+ const createViews = [];
29008
+ const dropViews = [];
29009
+ const renameViews = [];
29010
+ const alterViews = [];
29011
+ createViews.push(
29012
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
29013
+ return prepareMySqlCreateViewJson(
29014
+ it.name,
29015
+ it.definition,
29016
+ it.meta
29017
+ );
29018
+ })
29019
+ );
29020
+ dropViews.push(
29021
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
29022
+ return prepareDropViewJson(it.name);
29023
+ })
29024
+ );
29025
+ renameViews.push(
29026
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
29027
+ return prepareRenameViewJson(it.to.name, it.from.name);
29028
+ })
29029
+ );
29030
+ const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
29031
+ for (const alteredView of alteredViews) {
29032
+ const { definition, meta } = json2.views[alteredView.name];
29033
+ if (alteredView.alteredExisting) {
29034
+ dropViews.push(prepareDropViewJson(alteredView.name));
29035
+ createViews.push(
29036
+ prepareMySqlCreateViewJson(
29037
+ alteredView.name,
29038
+ definition,
29039
+ meta
29040
+ )
29041
+ );
29042
+ continue;
29043
+ }
29044
+ if (alteredView.alteredDefinition && action !== "push") {
29045
+ createViews.push(
29046
+ prepareMySqlCreateViewJson(
29047
+ alteredView.name,
29048
+ definition,
29049
+ meta,
29050
+ true
29051
+ )
29052
+ );
29053
+ continue;
29054
+ }
29055
+ if (alteredView.alteredMeta) {
29056
+ const view4 = curFull["views"][alteredView.name];
29057
+ alterViews.push(
29058
+ prepareMySqlAlterView(view4)
29059
+ );
29060
+ }
29061
+ }
27656
29062
  jsonStatements.push(...jsonMySqlCreateTables);
27657
29063
  jsonStatements.push(...jsonDropTables);
27658
29064
  jsonStatements.push(...jsonRenameTables);
27659
29065
  jsonStatements.push(...jsonRenameColumnsStatements);
29066
+ jsonStatements.push(...dropViews);
29067
+ jsonStatements.push(...renameViews);
29068
+ jsonStatements.push(...alterViews);
27660
29069
  jsonStatements.push(...jsonDeletedUniqueConstraints);
27661
29070
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
27662
29071
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
@@ -27673,6 +29082,7 @@ var init_snapshotsDiffer = __esm({
27673
29082
  jsonStatements.push(...jsonDropColumnsStatemets);
27674
29083
  jsonStatements.push(...jsonAlteredCompositePKs);
27675
29084
  jsonStatements.push(...jsonAddedUniqueConstraints);
29085
+ jsonStatements.push(...createViews);
27676
29086
  jsonStatements.push(...jsonAlteredUniqueConstraints);
27677
29087
  const sqlStatements = fromJson(jsonStatements, "mysql");
27678
29088
  const uniqueSqlStatements = [];
@@ -27691,7 +29101,7 @@ var init_snapshotsDiffer = __esm({
27691
29101
  _meta
27692
29102
  };
27693
29103
  };
27694
- applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
29104
+ applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
27695
29105
  const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
27696
29106
  const {
27697
29107
  created: createdTables,
@@ -27761,7 +29171,32 @@ var init_snapshotsDiffer = __esm({
27761
29171
  return [tableKey2, tableValue];
27762
29172
  }
27763
29173
  );
27764
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
29174
+ const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
29175
+ const {
29176
+ created: createdViews,
29177
+ deleted: deletedViews,
29178
+ renamed: renamedViews
29179
+ // renamed or moved
29180
+ } = await viewsResolver2({
29181
+ created: viewsDiff.added,
29182
+ deleted: viewsDiff.deleted
29183
+ });
29184
+ const renamesViewDic = {};
29185
+ renamedViews.forEach((it) => {
29186
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
29187
+ });
29188
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
29189
+ viewsPatchedSnap1.views = mapEntries(
29190
+ viewsPatchedSnap1.views,
29191
+ (viewKey, viewValue) => {
29192
+ const rename = renamesViewDic[viewValue.name];
29193
+ if (rename) {
29194
+ viewValue.name = rename.to;
29195
+ }
29196
+ return [viewKey, viewValue];
29197
+ }
29198
+ );
29199
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
27765
29200
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
27766
29201
  const tablesMap = {};
27767
29202
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -27940,6 +29375,44 @@ var init_snapshotsDiffer = __esm({
27940
29375
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
27941
29376
  (t2) => t2.type === "delete_reference"
27942
29377
  );
29378
+ const createViews = [];
29379
+ const dropViews = [];
29380
+ createViews.push(
29381
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
29382
+ return prepareSqliteCreateViewJson(
29383
+ it.name,
29384
+ it.definition
29385
+ );
29386
+ })
29387
+ );
29388
+ dropViews.push(
29389
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
29390
+ return prepareDropViewJson(it.name);
29391
+ })
29392
+ );
29393
+ dropViews.push(
29394
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
29395
+ return prepareDropViewJson(it.from.name);
29396
+ })
29397
+ );
29398
+ createViews.push(
29399
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
29400
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
29401
+ })
29402
+ );
29403
+ const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
29404
+ for (const alteredView of alteredViews) {
29405
+ const { definition } = json2.views[alteredView.name];
29406
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
29407
+ dropViews.push(prepareDropViewJson(alteredView.name));
29408
+ createViews.push(
29409
+ prepareSqliteCreateViewJson(
29410
+ alteredView.name,
29411
+ definition
29412
+ )
29413
+ );
29414
+ }
29415
+ }
27943
29416
  const jsonStatements = [];
27944
29417
  jsonStatements.push(...jsonCreateTables);
27945
29418
  jsonStatements.push(...jsonDropTables);
@@ -27957,6 +29430,8 @@ var init_snapshotsDiffer = __esm({
27957
29430
  jsonStatements.push(...jsonDropColumnsStatemets);
27958
29431
  jsonStatements.push(...jsonAlteredCompositePKs);
27959
29432
  jsonStatements.push(...jsonAlteredUniqueConstraints);
29433
+ jsonStatements.push(...dropViews);
29434
+ jsonStatements.push(...createViews);
27960
29435
  const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
27961
29436
  const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
27962
29437
  const uniqueSqlStatements = [];
@@ -27975,7 +29450,7 @@ var init_snapshotsDiffer = __esm({
27975
29450
  _meta
27976
29451
  };
27977
29452
  };
27978
- applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
29453
+ applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
27979
29454
  const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
27980
29455
  const {
27981
29456
  created: createdTables,
@@ -28045,7 +29520,32 @@ var init_snapshotsDiffer = __esm({
28045
29520
  return [tableKey2, tableValue];
28046
29521
  }
28047
29522
  );
28048
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
29523
+ const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
29524
+ const {
29525
+ created: createdViews,
29526
+ deleted: deletedViews,
29527
+ renamed: renamedViews
29528
+ // renamed or moved
29529
+ } = await viewsResolver2({
29530
+ created: viewsDiff.added,
29531
+ deleted: viewsDiff.deleted
29532
+ });
29533
+ const renamesViewDic = {};
29534
+ renamedViews.forEach((it) => {
29535
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
29536
+ });
29537
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
29538
+ viewsPatchedSnap1.views = mapEntries(
29539
+ viewsPatchedSnap1.views,
29540
+ (viewKey, viewValue) => {
29541
+ const rename = renamesViewDic[viewValue.name];
29542
+ if (rename) {
29543
+ viewValue.name = rename.to;
29544
+ }
29545
+ return [viewKey, viewValue];
29546
+ }
29547
+ );
29548
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
28049
29549
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
28050
29550
  const tablesMap = {};
28051
29551
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -28229,6 +29729,44 @@ var init_snapshotsDiffer = __esm({
28229
29729
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
28230
29730
  (t2) => t2.type === "delete_reference"
28231
29731
  );
29732
+ const createViews = [];
29733
+ const dropViews = [];
29734
+ createViews.push(
29735
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
29736
+ return prepareSqliteCreateViewJson(
29737
+ it.name,
29738
+ it.definition
29739
+ );
29740
+ })
29741
+ );
29742
+ dropViews.push(
29743
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
29744
+ return prepareDropViewJson(it.name);
29745
+ })
29746
+ );
29747
+ dropViews.push(
29748
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
29749
+ return prepareDropViewJson(it.from.name);
29750
+ })
29751
+ );
29752
+ createViews.push(
29753
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
29754
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
29755
+ })
29756
+ );
29757
+ const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
29758
+ for (const alteredView of alteredViews) {
29759
+ const { definition } = json2.views[alteredView.name];
29760
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
29761
+ dropViews.push(prepareDropViewJson(alteredView.name));
29762
+ createViews.push(
29763
+ prepareSqliteCreateViewJson(
29764
+ alteredView.name,
29765
+ definition
29766
+ )
29767
+ );
29768
+ }
29769
+ }
28232
29770
  const jsonStatements = [];
28233
29771
  jsonStatements.push(...jsonCreateTables);
28234
29772
  jsonStatements.push(...jsonDropTables);
@@ -28242,6 +29780,8 @@ var init_snapshotsDiffer = __esm({
28242
29780
  jsonStatements.push(...jsonAddColumnsStatemets);
28243
29781
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
28244
29782
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
29783
+ jsonStatements.push(...dropViews);
29784
+ jsonStatements.push(...createViews);
28245
29785
  jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
28246
29786
  jsonStatements.push(...jsonDropColumnsStatemets);
28247
29787
  jsonStatements.push(...jsonAlteredCompositePKs);
@@ -29596,6 +31136,7 @@ __export(migrate_exports, {
29596
31136
  columnsResolver: () => columnsResolver,
29597
31137
  embeddedMigrations: () => embeddedMigrations,
29598
31138
  enumsResolver: () => enumsResolver,
31139
+ mySqlViewsResolver: () => mySqlViewsResolver,
29599
31140
  prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
29600
31141
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
29601
31142
  prepareAndMigratePg: () => prepareAndMigratePg,
@@ -29610,10 +31151,12 @@ __export(migrate_exports, {
29610
31151
  promptSchemasConflict: () => promptSchemasConflict,
29611
31152
  schemasResolver: () => schemasResolver,
29612
31153
  sequencesResolver: () => sequencesResolver,
31154
+ sqliteViewsResolver: () => sqliteViewsResolver,
29613
31155
  tablesResolver: () => tablesResolver,
31156
+ viewsResolver: () => viewsResolver,
29614
31157
  writeResult: () => writeResult
29615
31158
  });
29616
- var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
31159
+ var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
29617
31160
  var init_migrate = __esm({
29618
31161
  "src/cli/commands/migrate.ts"() {
29619
31162
  "use strict";
@@ -29660,6 +31203,60 @@ var init_migrate = __esm({
29660
31203
  throw e2;
29661
31204
  }
29662
31205
  };
31206
+ viewsResolver = async (input) => {
31207
+ try {
31208
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
31209
+ input.created,
31210
+ input.deleted,
31211
+ "view"
31212
+ );
31213
+ return {
31214
+ created,
31215
+ deleted,
31216
+ moved,
31217
+ renamed
31218
+ };
31219
+ } catch (e2) {
31220
+ console.error(e2);
31221
+ throw e2;
31222
+ }
31223
+ };
31224
+ mySqlViewsResolver = async (input) => {
31225
+ try {
31226
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
31227
+ input.created,
31228
+ input.deleted,
31229
+ "view"
31230
+ );
31231
+ return {
31232
+ created,
31233
+ deleted,
31234
+ moved,
31235
+ renamed
31236
+ };
31237
+ } catch (e2) {
31238
+ console.error(e2);
31239
+ throw e2;
31240
+ }
31241
+ };
31242
+ sqliteViewsResolver = async (input) => {
31243
+ try {
31244
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
31245
+ input.created,
31246
+ input.deleted,
31247
+ "view"
31248
+ );
31249
+ return {
31250
+ created,
31251
+ deleted,
31252
+ moved,
31253
+ renamed
31254
+ };
31255
+ } catch (e2) {
31256
+ console.error(e2);
31257
+ throw e2;
31258
+ }
31259
+ };
29663
31260
  sequencesResolver = async (input) => {
29664
31261
  try {
29665
31262
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -29750,6 +31347,7 @@ var init_migrate = __esm({
29750
31347
  sequencesResolver,
29751
31348
  tablesResolver,
29752
31349
  columnsResolver,
31350
+ viewsResolver,
29753
31351
  validatedPrev,
29754
31352
  validatedCur
29755
31353
  );
@@ -29785,6 +31383,7 @@ var init_migrate = __esm({
29785
31383
  sequencesResolver,
29786
31384
  tablesResolver,
29787
31385
  columnsResolver,
31386
+ viewsResolver,
29788
31387
  validatedPrev,
29789
31388
  validatedCur,
29790
31389
  "push"
@@ -29807,6 +31406,7 @@ var init_migrate = __esm({
29807
31406
  squashedCur,
29808
31407
  tablesResolver,
29809
31408
  columnsResolver,
31409
+ mySqlViewsResolver,
29810
31410
  validatedPrev,
29811
31411
  validatedCur,
29812
31412
  "push"
@@ -29851,6 +31451,7 @@ var init_migrate = __esm({
29851
31451
  squashedCur,
29852
31452
  tablesResolver,
29853
31453
  columnsResolver,
31454
+ mySqlViewsResolver,
29854
31455
  validatedPrev,
29855
31456
  validatedCur
29856
31457
  );
@@ -29903,6 +31504,7 @@ var init_migrate = __esm({
29903
31504
  squashedCur,
29904
31505
  tablesResolver,
29905
31506
  columnsResolver,
31507
+ sqliteViewsResolver,
29906
31508
  validatedPrev,
29907
31509
  validatedCur
29908
31510
  );
@@ -29956,6 +31558,7 @@ var init_migrate = __esm({
29956
31558
  squashedCur,
29957
31559
  tablesResolver,
29958
31560
  columnsResolver,
31561
+ sqliteViewsResolver,
29959
31562
  validatedPrev,
29960
31563
  validatedCur
29961
31564
  );
@@ -29985,6 +31588,7 @@ var init_migrate = __esm({
29985
31588
  squashedCur,
29986
31589
  tablesResolver,
29987
31590
  columnsResolver,
31591
+ sqliteViewsResolver,
29988
31592
  validatedPrev,
29989
31593
  validatedCur,
29990
31594
  "push"
@@ -30008,6 +31612,7 @@ var init_migrate = __esm({
30008
31612
  squashedCur,
30009
31613
  tablesResolver,
30010
31614
  columnsResolver,
31615
+ sqliteViewsResolver,
30011
31616
  validatedPrev,
30012
31617
  validatedCur,
30013
31618
  "push"
@@ -34613,20 +36218,20 @@ var require_ponyfill_es2018 = __commonJS({
34613
36218
  ;
34614
36219
  ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
34615
36220
  }
34616
- respondWithNewView(view) {
36221
+ respondWithNewView(view4) {
34617
36222
  if (!IsReadableStreamBYOBRequest(this)) {
34618
36223
  throw byobRequestBrandCheckException("respondWithNewView");
34619
36224
  }
34620
- assertRequiredArgument(view, 1, "respondWithNewView");
34621
- if (!ArrayBuffer.isView(view)) {
36225
+ assertRequiredArgument(view4, 1, "respondWithNewView");
36226
+ if (!ArrayBuffer.isView(view4)) {
34622
36227
  throw new TypeError("You can only respond with array buffer views");
34623
36228
  }
34624
36229
  if (this._associatedReadableByteStreamController === void 0) {
34625
36230
  throw new TypeError("This BYOB request has been invalidated");
34626
36231
  }
34627
- if (IsDetachedBuffer(view.buffer))
36232
+ if (IsDetachedBuffer(view4.buffer))
34628
36233
  ;
34629
- ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
36234
+ ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view4);
34630
36235
  }
34631
36236
  }
34632
36237
  Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
@@ -34727,8 +36332,8 @@ var require_ponyfill_es2018 = __commonJS({
34727
36332
  const entry = this._queue.shift();
34728
36333
  this._queueTotalSize -= entry.byteLength;
34729
36334
  ReadableByteStreamControllerHandleQueueDrain(this);
34730
- const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
34731
- readRequest._chunkSteps(view);
36335
+ const view4 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
36336
+ readRequest._chunkSteps(view4);
34732
36337
  return;
34733
36338
  }
34734
36339
  const autoAllocateChunkSize = this._autoAllocateChunkSize;
@@ -34894,19 +36499,19 @@ var require_ponyfill_es2018 = __commonJS({
34894
36499
  }
34895
36500
  }
34896
36501
  }
34897
- function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
36502
+ function ReadableByteStreamControllerPullInto(controller, view4, readIntoRequest) {
34898
36503
  const stream = controller._controlledReadableByteStream;
34899
36504
  let elementSize = 1;
34900
- if (view.constructor !== DataView) {
34901
- elementSize = view.constructor.BYTES_PER_ELEMENT;
36505
+ if (view4.constructor !== DataView) {
36506
+ elementSize = view4.constructor.BYTES_PER_ELEMENT;
34902
36507
  }
34903
- const ctor = view.constructor;
34904
- const buffer = TransferArrayBuffer(view.buffer);
36508
+ const ctor = view4.constructor;
36509
+ const buffer = TransferArrayBuffer(view4.buffer);
34905
36510
  const pullIntoDescriptor = {
34906
36511
  buffer,
34907
36512
  bufferByteLength: buffer.byteLength,
34908
- byteOffset: view.byteOffset,
34909
- byteLength: view.byteLength,
36513
+ byteOffset: view4.byteOffset,
36514
+ byteLength: view4.byteLength,
34910
36515
  bytesFilled: 0,
34911
36516
  elementSize,
34912
36517
  viewConstructor: ctor,
@@ -35074,9 +36679,9 @@ var require_ponyfill_es2018 = __commonJS({
35074
36679
  function ReadableByteStreamControllerGetBYOBRequest(controller) {
35075
36680
  if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
35076
36681
  const firstDescriptor = controller._pendingPullIntos.peek();
35077
- const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
36682
+ const view4 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
35078
36683
  const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
35079
- SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
36684
+ SetUpReadableStreamBYOBRequest(byobRequest, controller, view4);
35080
36685
  controller._byobRequest = byobRequest;
35081
36686
  }
35082
36687
  return controller._byobRequest;
@@ -35109,29 +36714,29 @@ var require_ponyfill_es2018 = __commonJS({
35109
36714
  firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
35110
36715
  ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
35111
36716
  }
35112
- function ReadableByteStreamControllerRespondWithNewView(controller, view) {
36717
+ function ReadableByteStreamControllerRespondWithNewView(controller, view4) {
35113
36718
  const firstDescriptor = controller._pendingPullIntos.peek();
35114
36719
  const state = controller._controlledReadableByteStream._state;
35115
36720
  if (state === "closed") {
35116
- if (view.byteLength !== 0) {
36721
+ if (view4.byteLength !== 0) {
35117
36722
  throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
35118
36723
  }
35119
36724
  } else {
35120
- if (view.byteLength === 0) {
36725
+ if (view4.byteLength === 0) {
35121
36726
  throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
35122
36727
  }
35123
36728
  }
35124
- if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
36729
+ if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view4.byteOffset) {
35125
36730
  throw new RangeError("The region specified by view does not match byobRequest");
35126
36731
  }
35127
- if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
36732
+ if (firstDescriptor.bufferByteLength !== view4.buffer.byteLength) {
35128
36733
  throw new RangeError("The buffer of view has different capacity than byobRequest");
35129
36734
  }
35130
- if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
36735
+ if (firstDescriptor.bytesFilled + view4.byteLength > firstDescriptor.byteLength) {
35131
36736
  throw new RangeError("The region specified by view is larger than byobRequest");
35132
36737
  }
35133
- const viewByteLength = view.byteLength;
35134
- firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
36738
+ const viewByteLength = view4.byteLength;
36739
+ firstDescriptor.buffer = TransferArrayBuffer(view4.buffer);
35135
36740
  ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
35136
36741
  }
35137
36742
  function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
@@ -35177,9 +36782,9 @@ var require_ponyfill_es2018 = __commonJS({
35177
36782
  }
35178
36783
  SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
35179
36784
  }
35180
- function SetUpReadableStreamBYOBRequest(request, controller, view) {
36785
+ function SetUpReadableStreamBYOBRequest(request, controller, view4) {
35181
36786
  request._associatedReadableByteStreamController = controller;
35182
- request._view = view;
36787
+ request._view = view4;
35183
36788
  }
35184
36789
  function byobRequestBrandCheckException(name) {
35185
36790
  return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
@@ -35255,20 +36860,20 @@ var require_ponyfill_es2018 = __commonJS({
35255
36860
  *
35256
36861
  * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
35257
36862
  */
35258
- read(view) {
36863
+ read(view4) {
35259
36864
  if (!IsReadableStreamBYOBReader(this)) {
35260
36865
  return promiseRejectedWith(byobReaderBrandCheckException("read"));
35261
36866
  }
35262
- if (!ArrayBuffer.isView(view)) {
36867
+ if (!ArrayBuffer.isView(view4)) {
35263
36868
  return promiseRejectedWith(new TypeError("view must be an array buffer view"));
35264
36869
  }
35265
- if (view.byteLength === 0) {
36870
+ if (view4.byteLength === 0) {
35266
36871
  return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
35267
36872
  }
35268
- if (view.buffer.byteLength === 0) {
36873
+ if (view4.buffer.byteLength === 0) {
35269
36874
  return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
35270
36875
  }
35271
- if (IsDetachedBuffer(view.buffer))
36876
+ if (IsDetachedBuffer(view4.buffer))
35272
36877
  ;
35273
36878
  if (this._ownerReadableStream === void 0) {
35274
36879
  return promiseRejectedWith(readerLockException("read from"));
@@ -35284,7 +36889,7 @@ var require_ponyfill_es2018 = __commonJS({
35284
36889
  _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
35285
36890
  _errorSteps: (e2) => rejectPromise(e2)
35286
36891
  };
35287
- ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
36892
+ ReadableStreamBYOBReaderRead(this, view4, readIntoRequest);
35288
36893
  return promise;
35289
36894
  }
35290
36895
  /**
@@ -35330,13 +36935,13 @@ var require_ponyfill_es2018 = __commonJS({
35330
36935
  }
35331
36936
  return x2 instanceof ReadableStreamBYOBReader;
35332
36937
  }
35333
- function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
36938
+ function ReadableStreamBYOBReaderRead(reader, view4, readIntoRequest) {
35334
36939
  const stream = reader._ownerReadableStream;
35335
36940
  stream._disturbed = true;
35336
36941
  if (stream._state === "errored") {
35337
36942
  readIntoRequest._errorSteps(stream._storedError);
35338
36943
  } else {
35339
- ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
36944
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view4, readIntoRequest);
35340
36945
  }
35341
36946
  }
35342
36947
  function byobReaderBrandCheckException(name) {
@@ -36885,7 +38490,7 @@ var require_ponyfill_es2018 = __commonJS({
36885
38490
  };
36886
38491
  ReadableStreamDefaultReaderRead(reader, readRequest);
36887
38492
  }
36888
- function pullWithBYOBReader(view, forBranch2) {
38493
+ function pullWithBYOBReader(view4, forBranch2) {
36889
38494
  if (IsReadableStreamDefaultReader(reader)) {
36890
38495
  ReadableStreamReaderGenericRelease(reader);
36891
38496
  reader = AcquireReadableStreamBYOBReader(stream);
@@ -36951,7 +38556,7 @@ var require_ponyfill_es2018 = __commonJS({
36951
38556
  reading = false;
36952
38557
  }
36953
38558
  };
36954
- ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
38559
+ ReadableStreamBYOBReaderRead(reader, view4, readIntoRequest);
36955
38560
  }
36956
38561
  function pull1Algorithm() {
36957
38562
  if (reading) {
@@ -51810,15 +53415,15 @@ var require_dist_cjs36 = __commonJS({
51810
53415
  throw new Error("Int64 buffers must be exactly 8 bytes");
51811
53416
  }
51812
53417
  }
51813
- static fromNumber(number3) {
51814
- if (number3 > 9223372036854776e3 || number3 < -9223372036854776e3) {
51815
- throw new Error(`${number3} is too large (or, if negative, too small) to represent as an Int64`);
53418
+ static fromNumber(number2) {
53419
+ if (number2 > 9223372036854776e3 || number2 < -9223372036854776e3) {
53420
+ throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`);
51816
53421
  }
51817
53422
  const bytes = new Uint8Array(8);
51818
- for (let i2 = 7, remaining = Math.abs(Math.round(number3)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
53423
+ for (let i2 = 7, remaining = Math.abs(Math.round(number2)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
51819
53424
  bytes[i2] = remaining;
51820
53425
  }
51821
- if (number3 < 0) {
53426
+ if (number2 < 0) {
51822
53427
  negate(bytes);
51823
53428
  }
51824
53429
  return new _Int642(bytes);
@@ -62362,7 +63967,7 @@ __export(studio_exports, {
62362
63967
  prepareSQLiteSchema: () => prepareSQLiteSchema,
62363
63968
  prepareServer: () => prepareServer
62364
63969
  });
62365
- var import_crypto8, import_drizzle_orm8, import_mysql_core4, import_pg_core4, import_sqlite_core3, import_fs10, import_node_https2, preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, extractRelations, init, proxySchema, defaultsSchema, schema4, jsonStringify, prepareServer;
63970
+ var import_crypto8, import_drizzle_orm8, import_mysql_core5, import_pg_core4, import_sqlite_core3, import_fs10, import_node_https2, preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, extractRelations, init, proxySchema, defaultsSchema, schema4, jsonStringify, prepareServer;
62366
63971
  var init_studio2 = __esm({
62367
63972
  "src/serializer/studio.ts"() {
62368
63973
  "use strict";
@@ -62370,7 +63975,7 @@ var init_studio2 = __esm({
62370
63975
  init_esm();
62371
63976
  import_crypto8 = require("crypto");
62372
63977
  import_drizzle_orm8 = require("drizzle-orm");
62373
- import_mysql_core4 = require("drizzle-orm/mysql-core");
63978
+ import_mysql_core5 = require("drizzle-orm/mysql-core");
62374
63979
  import_pg_core4 = require("drizzle-orm/pg-core");
62375
63980
  import_sqlite_core3 = require("drizzle-orm/sqlite-core");
62376
63981
  import_fs10 = __toESM(require("fs"));
@@ -62427,8 +64032,8 @@ var init_studio2 = __esm({
62427
64032
  const i0 = require(`${it}`);
62428
64033
  const i0values = Object.entries(i0);
62429
64034
  i0values.forEach(([k, t2]) => {
62430
- if ((0, import_drizzle_orm8.is)(t2, import_mysql_core4.MySqlTable)) {
62431
- const schema5 = (0, import_mysql_core4.getTableConfig)(t2).schema || "public";
64035
+ if ((0, import_drizzle_orm8.is)(t2, import_mysql_core5.MySqlTable)) {
64036
+ const schema5 = (0, import_mysql_core5.getTableConfig)(t2).schema || "public";
62432
64037
  mysqlSchema3[schema5][k] = t2;
62433
64038
  }
62434
64039
  if ((0, import_drizzle_orm8.is)(t2, import_drizzle_orm8.Relations)) {
@@ -62475,8 +64080,8 @@ var init_studio2 = __esm({
62475
64080
  let tableConfig;
62476
64081
  if ((0, import_drizzle_orm8.is)(table4, import_pg_core4.PgTable)) {
62477
64082
  tableConfig = (0, import_pg_core4.getTableConfig)(table4);
62478
- } else if ((0, import_drizzle_orm8.is)(table4, import_mysql_core4.MySqlTable)) {
62479
- tableConfig = (0, import_mysql_core4.getTableConfig)(table4);
64083
+ } else if ((0, import_drizzle_orm8.is)(table4, import_mysql_core5.MySqlTable)) {
64084
+ tableConfig = (0, import_mysql_core5.getTableConfig)(table4);
62480
64085
  } else {
62481
64086
  tableConfig = (0, import_sqlite_core3.getTableConfig)(table4);
62482
64087
  }
@@ -62606,8 +64211,8 @@ var init_studio2 = __esm({
62606
64211
  let refSchema;
62607
64212
  if ((0, import_drizzle_orm8.is)(refTable, import_pg_core4.PgTable)) {
62608
64213
  refSchema = (0, import_pg_core4.getTableConfig)(refTable).schema;
62609
- } else if ((0, import_drizzle_orm8.is)(refTable, import_mysql_core4.MySqlTable)) {
62610
- refSchema = (0, import_mysql_core4.getTableConfig)(refTable).schema;
64214
+ } else if ((0, import_drizzle_orm8.is)(refTable, import_mysql_core5.MySqlTable)) {
64215
+ refSchema = (0, import_mysql_core5.getTableConfig)(refTable).schema;
62611
64216
  } else if ((0, import_drizzle_orm8.is)(refTable, import_sqlite_core3.SQLiteTable)) {
62612
64217
  refSchema = void 0;
62613
64218
  } else {
@@ -63249,16 +64854,16 @@ var require_map_stream = __commonJS({
63249
64854
  var writeQueue = {};
63250
64855
  stream.writable = true;
63251
64856
  stream.readable = true;
63252
- function queueData(data, number3) {
64857
+ function queueData(data, number2) {
63253
64858
  var nextToWrite = lastWritten + 1;
63254
- if (number3 === nextToWrite) {
64859
+ if (number2 === nextToWrite) {
63255
64860
  if (data !== void 0) {
63256
64861
  stream.emit.apply(stream, ["data", data]);
63257
64862
  }
63258
64863
  lastWritten++;
63259
64864
  nextToWrite++;
63260
64865
  } else {
63261
- writeQueue[number3] = data;
64866
+ writeQueue[number2] = data;
63262
64867
  }
63263
64868
  if (writeQueue.hasOwnProperty(nextToWrite)) {
63264
64869
  var dataToWrite = writeQueue[nextToWrite];
@@ -63273,21 +64878,21 @@ var require_map_stream = __commonJS({
63273
64878
  end();
63274
64879
  }
63275
64880
  }
63276
- function next(err2, data, number3) {
64881
+ function next(err2, data, number2) {
63277
64882
  if (destroyed)
63278
64883
  return;
63279
64884
  inNext = true;
63280
64885
  if (!err2 || self2.opts.failures) {
63281
- queueData(data, number3);
64886
+ queueData(data, number2);
63282
64887
  }
63283
64888
  if (err2) {
63284
64889
  stream.emit.apply(stream, [errorEventName, err2]);
63285
64890
  }
63286
64891
  inNext = false;
63287
64892
  }
63288
- function wrappedMapper(input, number3, callback) {
64893
+ function wrappedMapper(input, number2, callback) {
63289
64894
  return mapper.call(null, input, function(err2, data) {
63290
- callback(err2, data, number3);
64895
+ callback(err2, data, number2);
63291
64896
  });
63292
64897
  }
63293
64898
  stream.write = function(data) {
@@ -77119,7 +78724,7 @@ var init_selector_ui = __esm({
77119
78724
  });
77120
78725
 
77121
78726
  // src/cli/commands/libSqlPushUtils.ts
77122
- var getOldTableName3, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
78727
+ var getOldTableName2, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
77123
78728
  var init_libSqlPushUtils = __esm({
77124
78729
  "src/cli/commands/libSqlPushUtils.ts"() {
77125
78730
  "use strict";
@@ -77127,7 +78732,7 @@ var init_libSqlPushUtils = __esm({
77127
78732
  init_utils();
77128
78733
  init_sqliteSchema();
77129
78734
  init_sqlgenerator();
77130
- getOldTableName3 = (tableName, meta) => {
78735
+ getOldTableName2 = (tableName, meta) => {
77131
78736
  for (const key of Object.keys(meta.tables)) {
77132
78737
  const value = meta.tables[key];
77133
78738
  if (`"${tableName}"` === value) {
@@ -77282,7 +78887,7 @@ var init_libSqlPushUtils = __esm({
77282
78887
  } else if (statement.type === "recreate_table") {
77283
78888
  const tableName = statement.tableName;
77284
78889
  let dataLoss = false;
77285
- const oldTableName = getOldTableName3(tableName, meta);
78890
+ const oldTableName = getOldTableName2(tableName, meta);
77286
78891
  const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
77287
78892
  const currentColumnNames = Object.keys(json2.tables[tableName].columns);
77288
78893
  const { removedColumns, addedColumns } = findAddedAndRemoved(
@@ -77649,6 +79254,7 @@ var init_pgPushUtils = __esm({
77649
79254
  const columnsToRemove = [];
77650
79255
  const schemasToRemove = [];
77651
79256
  const tablesToTruncate = [];
79257
+ const matViewsToRemove = [];
77652
79258
  let renamedSchemas = {};
77653
79259
  let renamedTables = {};
77654
79260
  for (const statement of statements) {
@@ -77658,38 +79264,32 @@ var init_pgPushUtils = __esm({
77658
79264
  renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
77659
79265
  } else if (statement.type === "drop_table") {
77660
79266
  const res = await db.query(
77661
- `select count(*) as count from ${tableNameWithSchemaFrom(
77662
- statement.schema,
77663
- statement.tableName,
77664
- renamedSchemas,
77665
- renamedTables
77666
- )}`
79267
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
77667
79268
  );
77668
79269
  const count = Number(res[0].count);
79270
+ if (count > 0) {
79271
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count} items`);
79272
+ tablesToRemove.push(statement.tableName);
79273
+ shouldAskForApprove = true;
79274
+ }
79275
+ } else if (statement.type === "drop_view" && statement.materialized) {
79276
+ const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
79277
+ const count = Number(res[0].count);
77669
79278
  if (count > 0) {
77670
79279
  infoToPrint.push(
77671
- `\xB7 You're about to delete ${source_default.underline(
77672
- statement.tableName
77673
- )} table with ${count} items`
79280
+ `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count} items`
77674
79281
  );
77675
- tablesToRemove.push(statement.tableName);
79282
+ matViewsToRemove.push(statement.name);
77676
79283
  shouldAskForApprove = true;
77677
79284
  }
77678
79285
  } else if (statement.type === "alter_table_drop_column") {
77679
79286
  const res = await db.query(
77680
- `select count(*) as count from ${tableNameWithSchemaFrom(
77681
- statement.schema,
77682
- statement.tableName,
77683
- renamedSchemas,
77684
- renamedTables
77685
- )}`
79287
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
77686
79288
  );
77687
79289
  const count = Number(res[0].count);
77688
79290
  if (count > 0) {
77689
79291
  infoToPrint.push(
77690
- `\xB7 You're about to delete ${source_default.underline(
77691
- statement.columnName
77692
- )} column in ${statement.tableName} table with ${count} items`
79292
+ `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count} items`
77693
79293
  );
77694
79294
  columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
77695
79295
  shouldAskForApprove = true;
@@ -77700,58 +79300,35 @@ var init_pgPushUtils = __esm({
77700
79300
  );
77701
79301
  const count = Number(res[0].count);
77702
79302
  if (count > 0) {
77703
- infoToPrint.push(
77704
- `\xB7 You're about to delete ${source_default.underline(
77705
- statement.name
77706
- )} schema with ${count} tables`
77707
- );
79303
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count} tables`);
77708
79304
  schemasToRemove.push(statement.name);
77709
79305
  shouldAskForApprove = true;
77710
79306
  }
77711
79307
  } else if (statement.type === "alter_table_alter_column_set_type") {
77712
79308
  const res = await db.query(
77713
- `select count(*) as count from ${tableNameWithSchemaFrom(
77714
- statement.schema,
77715
- statement.tableName,
77716
- renamedSchemas,
77717
- renamedTables
77718
- )}`
79309
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
77719
79310
  );
77720
79311
  const count = Number(res[0].count);
77721
79312
  if (count > 0) {
77722
79313
  infoToPrint.push(
77723
- `\xB7 You're about to change ${source_default.underline(
77724
- statement.columnName
77725
- )} column type from ${source_default.underline(
77726
- statement.oldDataType
77727
- )} to ${source_default.underline(statement.newDataType)} with ${count} items`
79314
+ `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
79315
+ statement.newDataType
79316
+ )} with ${count} items`
77728
79317
  );
77729
79318
  statementsToExecute.push(
77730
- `truncate table ${tableNameWithSchemaFrom(
77731
- statement.schema,
77732
- statement.tableName,
77733
- renamedSchemas,
77734
- renamedTables
77735
- )} cascade;`
79319
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
77736
79320
  );
77737
79321
  tablesToTruncate.push(statement.tableName);
77738
79322
  shouldAskForApprove = true;
77739
79323
  }
77740
79324
  } else if (statement.type === "alter_table_alter_column_drop_pk") {
77741
79325
  const res = await db.query(
77742
- `select count(*) as count from ${tableNameWithSchemaFrom(
77743
- statement.schema,
77744
- statement.tableName,
77745
- renamedSchemas,
77746
- renamedTables
77747
- )}`
79326
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
77748
79327
  );
77749
79328
  const count = Number(res[0].count);
77750
79329
  if (count > 0) {
77751
79330
  infoToPrint.push(
77752
- `\xB7 You're about to change ${source_default.underline(
77753
- statement.tableName
77754
- )} primary key. This statements may fail and you table may left without primary key`
79331
+ `\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`
77755
79332
  );
77756
79333
  tablesToTruncate.push(statement.tableName);
77757
79334
  shouldAskForApprove = true;
@@ -77775,40 +79352,23 @@ var init_pgPushUtils = __esm({
77775
79352
  } else if (statement.type === "alter_table_add_column") {
77776
79353
  if (statement.column.notNull && typeof statement.column.default === "undefined") {
77777
79354
  const res = await db.query(
77778
- `select count(*) as count from ${tableNameWithSchemaFrom(
77779
- statement.schema,
77780
- statement.tableName,
77781
- renamedSchemas,
77782
- renamedTables
77783
- )}`
79355
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
77784
79356
  );
77785
79357
  const count = Number(res[0].count);
77786
79358
  if (count > 0) {
77787
79359
  infoToPrint.push(
77788
- `\xB7 You're about to add not-null ${source_default.underline(
77789
- statement.column.name
77790
- )} column without default value, which contains ${count} items`
79360
+ `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count} items`
77791
79361
  );
77792
79362
  tablesToTruncate.push(statement.tableName);
77793
79363
  statementsToExecute.push(
77794
- `truncate table ${tableNameWithSchemaFrom(
77795
- statement.schema,
77796
- statement.tableName,
77797
- renamedSchemas,
77798
- renamedTables
77799
- )} cascade;`
79364
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
77800
79365
  );
77801
79366
  shouldAskForApprove = true;
77802
79367
  }
77803
79368
  }
77804
79369
  } else if (statement.type === "create_unique_constraint") {
77805
79370
  const res = await db.query(
77806
- `select count(*) as count from ${tableNameWithSchemaFrom(
77807
- statement.schema,
77808
- statement.tableName,
77809
- renamedSchemas,
77810
- renamedTables
77811
- )}`
79371
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
77812
79372
  );
77813
79373
  const count = Number(res[0].count);
77814
79374
  if (count > 0) {
@@ -77822,20 +79382,12 @@ var init_pgPushUtils = __esm({
77822
79382
  `
77823
79383
  );
77824
79384
  const { status, data } = await (0, import_hanji7.render)(
77825
- new Select([
77826
- "No, add the constraint without truncating the table",
77827
- `Yes, truncate the table`
77828
- ])
79385
+ new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
77829
79386
  );
77830
79387
  if ((data == null ? void 0 : data.index) === 1) {
77831
79388
  tablesToTruncate.push(statement.tableName);
77832
79389
  statementsToExecute.push(
77833
- `truncate table ${tableNameWithSchemaFrom(
77834
- statement.schema,
77835
- statement.tableName,
77836
- renamedSchemas,
77837
- renamedTables
77838
- )} cascade;`
79390
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
77839
79391
  );
77840
79392
  shouldAskForApprove = true;
77841
79393
  }
@@ -77845,10 +79397,7 @@ var init_pgPushUtils = __esm({
77845
79397
  if (typeof stmnt !== "undefined") {
77846
79398
  if (statement.type === "drop_table") {
77847
79399
  statementsToExecute.push(
77848
- `DROP TABLE ${concatSchemaAndTableName(
77849
- statement.schema,
77850
- statement.tableName
77851
- )} CASCADE;`
79400
+ `DROP TABLE ${concatSchemaAndTableName(statement.schema, statement.tableName)} CASCADE;`
77852
79401
  );
77853
79402
  } else {
77854
79403
  statementsToExecute.push(...stmnt);
@@ -77859,6 +79408,7 @@ var init_pgPushUtils = __esm({
77859
79408
  statementsToExecute,
77860
79409
  shouldAskForApprove,
77861
79410
  infoToPrint,
79411
+ matViewsToRemove: [...new Set(matViewsToRemove)],
77862
79412
  columnsToRemove: [...new Set(columnsToRemove)],
77863
79413
  schemasToRemove: [...new Set(schemasToRemove)],
77864
79414
  tablesToTruncate: [...new Set(tablesToTruncate)],
@@ -79126,6 +80676,15 @@ var init_introspect_sqlite = __esm({
79126
80676
  },
79127
80677
  { sqlite: [] }
79128
80678
  );
80679
+ Object.values(schema5.views).forEach((it) => {
80680
+ imports.sqlite.push("sqliteView");
80681
+ const columnImports = Object.values(it.columns).map((col) => {
80682
+ return col.type;
80683
+ }).filter((type) => {
80684
+ return sqliteImportsList.has(type);
80685
+ });
80686
+ imports.sqlite.push(...columnImports);
80687
+ });
79129
80688
  const tableStatements = Object.values(schema5.tables).map((table4) => {
79130
80689
  const func = "sqliteTable";
79131
80690
  let statement = "";
@@ -79172,6 +80731,29 @@ var init_introspect_sqlite = __esm({
79172
80731
  statement += ");";
79173
80732
  return statement;
79174
80733
  });
80734
+ const viewsStatements = Object.values(schema5.views).map((view4) => {
80735
+ var _a;
80736
+ const func = "sqliteView";
80737
+ let statement = "";
80738
+ if (imports.sqlite.includes(withCasing(view4.name, casing2))) {
80739
+ statement = `// Table name is in conflict with ${withCasing(
80740
+ view4.name,
80741
+ casing2
80742
+ )} import.
80743
+ // Please change to any other name, that is not in imports list
80744
+ `;
80745
+ }
80746
+ statement += `export const ${withCasing(view4.name, casing2)} = ${func}("${view4.name}", {
80747
+ `;
80748
+ statement += createTableColumns(
80749
+ Object.values(view4.columns),
80750
+ [],
80751
+ casing2
80752
+ );
80753
+ statement += "})";
80754
+ statement += `.as(sql\`${(_a = view4.definition) == null ? void 0 : _a.replaceAll("`", "\\`")}\`);`;
80755
+ return statement;
80756
+ });
79175
80757
  const uniqueSqliteImports = [
79176
80758
  "sqliteTable",
79177
80759
  "AnySQLiteColumn",
@@ -79183,7 +80765,9 @@ var init_introspect_sqlite = __esm({
79183
80765
  import { sql } from "drizzle-orm"
79184
80766
 
79185
80767
  `;
79186
- const decalrations = tableStatements.join("\n\n");
80768
+ let decalrations = tableStatements.join("\n\n");
80769
+ decalrations += "\n\n";
80770
+ decalrations += viewsStatements.join("\n\n");
79187
80771
  const file = importsTs + decalrations;
79188
80772
  const schemaEntry = `
79189
80773
  {
@@ -79583,6 +81167,7 @@ var init_push = __esm({
79583
81167
  statementsToExecute,
79584
81168
  columnsToRemove,
79585
81169
  tablesToRemove,
81170
+ matViewsToRemove,
79586
81171
  tablesToTruncate,
79587
81172
  infoToPrint,
79588
81173
  schemasToRemove
@@ -79620,7 +81205,7 @@ var init_push = __esm({
79620
81205
  const { status, data } = await (0, import_hanji11.render)(
79621
81206
  new Select([
79622
81207
  "No, abort",
79623
- `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
81208
+ `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}${matViewsToRemove.length > 0 ? ` remove ${matViewsToRemove.length} ${matViewsToRemove.length > 1 ? "materialized views" : "materialize view"},` : " "}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
79624
81209
  ])
79625
81210
  );
79626
81211
  if ((data == null ? void 0 : data.index) === 0) {
@@ -80305,6 +81890,26 @@ var init_introspect_mysql = __esm({
80305
81890
  },
80306
81891
  { mysql: [] }
80307
81892
  );
81893
+ Object.values(schema5.views).forEach((it) => {
81894
+ imports.mysql.push("mysqlView");
81895
+ const columnImports = Object.values(it.columns).map((col) => {
81896
+ let patched = importsPatch[col.type] ?? col.type;
81897
+ patched = patched.startsWith("varchar(") ? "varchar" : patched;
81898
+ patched = patched.startsWith("char(") ? "char" : patched;
81899
+ patched = patched.startsWith("binary(") ? "binary" : patched;
81900
+ patched = patched.startsWith("decimal(") ? "decimal" : patched;
81901
+ patched = patched.startsWith("smallint(") ? "smallint" : patched;
81902
+ patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
81903
+ patched = patched.startsWith("datetime(") ? "datetime" : patched;
81904
+ patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
81905
+ patched = patched.startsWith("int(") ? "int" : patched;
81906
+ patched = patched.startsWith("double(") ? "double" : patched;
81907
+ return patched;
81908
+ }).filter((type) => {
81909
+ return mysqlImportsList.has(type);
81910
+ });
81911
+ imports.mysql.push(...columnImports);
81912
+ });
80308
81913
  const tableStatements = Object.values(schema5.tables).map((table4) => {
80309
81914
  const func = "mysqlTable";
80310
81915
  let statement = "";
@@ -80353,6 +81958,34 @@ var init_introspect_mysql = __esm({
80353
81958
  statement += ");";
80354
81959
  return statement;
80355
81960
  });
81961
+ const viewsStatements = Object.values(schema5.views).map((view4) => {
81962
+ const { columns, name, algorithm, definition, sqlSecurity, withCheckOption } = view4;
81963
+ const func = "mysqlView";
81964
+ let statement = "";
81965
+ if (imports.mysql.includes(withCasing4(name))) {
81966
+ statement = `// Table name is in conflict with ${withCasing4(
81967
+ view4.name
81968
+ )} import.
81969
+ // Please change to any other name, that is not in imports list
81970
+ `;
81971
+ }
81972
+ statement += `export const ${withCasing4(name)} = ${func}("${name}", {
81973
+ `;
81974
+ statement += createTableColumns2(
81975
+ Object.values(columns),
81976
+ [],
81977
+ withCasing4,
81978
+ casing2,
81979
+ name,
81980
+ schema5
81981
+ );
81982
+ statement += "})";
81983
+ statement += algorithm ? `.algorithm("${algorithm}")` : "";
81984
+ statement += sqlSecurity ? `.sqlSecurity("${sqlSecurity}")` : "";
81985
+ statement += withCheckOption ? `.withCheckOption("${withCheckOption}")` : "";
81986
+ statement += `.as(sql\`${definition == null ? void 0 : definition.replaceAll("`", "\\`")}\`);`;
81987
+ return statement;
81988
+ });
80356
81989
  const uniqueMySqlImports = [
80357
81990
  "mysqlTable",
80358
81991
  "mysqlSchema",
@@ -80367,6 +82000,8 @@ import { sql } from "drizzle-orm"
80367
82000
  `;
80368
82001
  let decalrations = "";
80369
82002
  decalrations += tableStatements.join("\n\n");
82003
+ decalrations += "\n";
82004
+ decalrations += viewsStatements.join("\n\n");
80370
82005
  const file = importsTs + decalrations;
80371
82006
  const schemaEntry = `
80372
82007
  {
@@ -80914,13 +82549,10 @@ var init_introspect_pg = __esm({
80914
82549
  return [it[0], withCasing2(it[1], casing2)];
80915
82550
  })
80916
82551
  );
80917
- const enumTypes = Object.values(schema5.enums).reduce(
80918
- (acc, cur) => {
80919
- acc.add(`${cur.schema}.${cur.name}`);
80920
- return acc;
80921
- },
80922
- /* @__PURE__ */ new Set()
80923
- );
82552
+ const enumTypes = Object.values(schema5.enums).reduce((acc, cur) => {
82553
+ acc.add(`${cur.schema}.${cur.name}`);
82554
+ return acc;
82555
+ }, /* @__PURE__ */ new Set());
80924
82556
  const imports = Object.values(schema5.tables).reduce(
80925
82557
  (res, it) => {
80926
82558
  const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
@@ -80928,12 +82560,8 @@ var init_introspect_pg = __esm({
80928
82560
  if (Object.values(it.foreignKeys).some((it2) => isCyclic3(it2) && !isSelf3(it2))) {
80929
82561
  res.pg.push("type AnyPgColumn");
80930
82562
  }
80931
- const pkImports = Object.values(it.compositePrimaryKeys).map(
80932
- (it2) => "primaryKey"
80933
- );
80934
- const uniqueImports = Object.values(it.uniqueConstraints).map(
80935
- (it2) => "unique"
80936
- );
82563
+ const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
82564
+ const uniqueImports = Object.values(it.uniqueConstraints).map((it2) => "unique");
80937
82565
  if (it.schema && it.schema !== "public" && it.schema !== "") {
80938
82566
  res.pg.push("pgSchema");
80939
82567
  }
@@ -80960,6 +82588,30 @@ var init_introspect_pg = __esm({
80960
82588
  },
80961
82589
  { pg: [] }
80962
82590
  );
82591
+ Object.values(schema5.views).forEach((it) => {
82592
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
82593
+ imports.pg.push("pgSchema");
82594
+ } else if (it.schema === "public") {
82595
+ it.materialized ? imports.pg.push("pgMaterializedView") : imports.pg.push("pgView");
82596
+ }
82597
+ Object.values(it.columns).forEach(() => {
82598
+ const columnImports = Object.values(it.columns).map((col) => {
82599
+ let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
82600
+ patched = patched === "double precision" ? "doublePrecision" : patched;
82601
+ patched = patched.startsWith("varchar(") ? "varchar" : patched;
82602
+ patched = patched.startsWith("char(") ? "char" : patched;
82603
+ patched = patched.startsWith("numeric(") ? "numeric" : patched;
82604
+ patched = patched.startsWith("time(") ? "time" : patched;
82605
+ patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
82606
+ patched = patched.startsWith("vector(") ? "vector" : patched;
82607
+ patched = patched.startsWith("geometry(") ? "geometry" : patched;
82608
+ return patched;
82609
+ }).filter((type) => {
82610
+ return pgImportsList.has(type);
82611
+ });
82612
+ imports.pg.push(...columnImports);
82613
+ });
82614
+ });
80963
82615
  Object.values(schema5.sequences).forEach((it) => {
80964
82616
  if (it.schema && it.schema !== "public" && it.schema !== "") {
80965
82617
  imports.pg.push("pgSchema");
@@ -81034,30 +82686,40 @@ var init_introspect_pg = __esm({
81034
82686
  statement += ",\n";
81035
82687
  statement += "(table) => {\n";
81036
82688
  statement += " return {\n";
81037
- statement += createTableIndexes3(
81038
- table4.name,
81039
- Object.values(table4.indexes),
81040
- casing2
81041
- );
82689
+ statement += createTableIndexes3(table4.name, Object.values(table4.indexes), casing2);
81042
82690
  statement += createTableFKs3(Object.values(table4.foreignKeys), schemas, casing2);
81043
- statement += createTablePKs3(
81044
- Object.values(table4.compositePrimaryKeys),
81045
- casing2
81046
- );
81047
- statement += createTableUniques3(
81048
- Object.values(table4.uniqueConstraints),
81049
- casing2
81050
- );
82691
+ statement += createTablePKs3(Object.values(table4.compositePrimaryKeys), casing2);
82692
+ statement += createTableUniques3(Object.values(table4.uniqueConstraints), casing2);
81051
82693
  statement += " }\n";
81052
82694
  statement += "}";
81053
82695
  }
81054
82696
  statement += ");";
81055
82697
  return statement;
81056
82698
  });
82699
+ const viewsStatements = Object.values(schema5.views).map((it) => {
82700
+ const viewSchema = schemas[it.schema];
82701
+ const paramName = paramNameFor(it.name, viewSchema);
82702
+ const func = viewSchema ? it.materialized ? `${viewSchema}.materializedView` : `${viewSchema}.view` : it.materialized ? "pgMaterializedView" : "pgView";
82703
+ const withOption = it.with ?? "";
82704
+ const as = `sql\`${it.definition}\``;
82705
+ const tablespace = it.tablespace ?? "";
82706
+ const columns = createTableColumns3(
82707
+ "",
82708
+ Object.values(it.columns),
82709
+ [],
82710
+ enumTypes,
82711
+ schemas,
82712
+ casing2,
82713
+ schema5.internal
82714
+ );
82715
+ let statement = `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", {${columns}})`;
82716
+ statement += tablespace ? `.tablespace("${tablespace}")` : "";
82717
+ statement += withOption ? `.with(${JSON.stringify(withOption)})` : "";
82718
+ statement += `.as(${as});`;
82719
+ return statement;
82720
+ }).join("\n\n");
81057
82721
  const uniquePgImports = ["pgTable", ...new Set(imports.pg)];
81058
- const importsTs = `import { ${uniquePgImports.join(
81059
- ", "
81060
- )} } from "drizzle-orm/pg-core"
82722
+ const importsTs = `import { ${uniquePgImports.join(", ")} } from "drizzle-orm/pg-core"
81061
82723
  import { sql } from "drizzle-orm"
81062
82724
 
81063
82725
  `;
@@ -81066,6 +82728,8 @@ var init_introspect_pg = __esm({
81066
82728
  decalrations += sequencesStatements;
81067
82729
  decalrations += "\n";
81068
82730
  decalrations += tableStatements.join("\n\n");
82731
+ decalrations += "\n";
82732
+ decalrations += viewsStatements;
81069
82733
  const file = importsTs + decalrations;
81070
82734
  const schemaEntry = `
81071
82735
  {
@@ -81190,10 +82854,7 @@ var init_introspect_pg = __esm({
81190
82854
  const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
81191
82855
  const lowered = type.toLowerCase().replace("[]", "");
81192
82856
  if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
81193
- let out = `${withCasing2(name, casing2)}: ${withCasing2(
81194
- paramNameFor(type.replace("[]", ""), typeSchema),
81195
- casing2
81196
- )}(${dbColumnName3({ name, casing: casing2 })})`;
82857
+ let out = `${withCasing2(name, casing2)}: ${withCasing2(paramNameFor(type.replace("[]", ""), typeSchema), casing2)}(${dbColumnName3({ name, casing: casing2 })})`;
81197
82858
  return out;
81198
82859
  }
81199
82860
  if (lowered.startsWith("serial")) {
@@ -81203,10 +82864,7 @@ var init_introspect_pg = __esm({
81203
82864
  return `${withCasing2(name, casing2)}: smallserial(${dbColumnName3({ name, casing: casing2 })})`;
81204
82865
  }
81205
82866
  if (lowered.startsWith("bigserial")) {
81206
- return `${withCasing2(
81207
- name,
81208
- casing2
81209
- )}: bigserial(${dbColumnName3({ name, casing: casing2, withMode: true })}{ mode: "bigint" })`;
82867
+ return `${withCasing2(name, casing2)}: bigserial(${dbColumnName3({ name, casing: casing2, withMode: true })}{ mode: "bigint" })`;
81210
82868
  }
81211
82869
  if (lowered.startsWith("integer")) {
81212
82870
  let out = `${withCasing2(name, casing2)}: integer(${dbColumnName3({ name, casing: casing2 })})`;
@@ -81249,9 +82907,7 @@ var init_introspect_pg = __esm({
81249
82907
  }
81250
82908
  if (lowered.startsWith("timestamp")) {
81251
82909
  const withTimezone = lowered.includes("with time zone");
81252
- let precision = lowered.startsWith("timestamp(") ? Number(
81253
- lowered.split(" ")[0].substring("timestamp(".length, lowered.split(" ")[0].length - 1)
81254
- ) : null;
82910
+ let precision = lowered.startsWith("timestamp(") ? Number(lowered.split(" ")[0].substring("timestamp(".length, lowered.split(" ")[0].length - 1)) : null;
81255
82911
  precision = precision ? precision : null;
81256
82912
  const params = timeConfig2({
81257
82913
  precision,
@@ -81263,9 +82919,7 @@ var init_introspect_pg = __esm({
81263
82919
  }
81264
82920
  if (lowered.startsWith("time")) {
81265
82921
  const withTimezone = lowered.includes("with time zone");
81266
- let precision = lowered.startsWith("time(") ? Number(
81267
- lowered.split(" ")[0].substring("time(".length, lowered.split(" ")[0].length - 1)
81268
- ) : null;
82922
+ let precision = lowered.startsWith("time(") ? Number(lowered.split(" ")[0].substring("time(".length, lowered.split(" ")[0].length - 1)) : null;
81269
82923
  precision = precision ? precision : null;
81270
82924
  const params = timeConfig2({ precision, withTimezone });
81271
82925
  let out = params ? `${withCasing2(name, casing2)}: time(${dbColumnName3({ name, casing: casing2, withMode: true })}${params})` : `${withCasing2(name, casing2)}: time(${dbColumnName3({ name, casing: casing2 })})`;
@@ -81311,13 +82965,7 @@ var init_introspect_pg = __esm({
81311
82965
  if (lowered.startsWith("varchar")) {
81312
82966
  let out;
81313
82967
  if (lowered.length !== 7) {
81314
- out = `${withCasing2(
81315
- name,
81316
- casing2
81317
- )}: varchar(${dbColumnName3({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(
81318
- 8,
81319
- lowered.length - 1
81320
- )} })`;
82968
+ out = `${withCasing2(name, casing2)}: varchar(${dbColumnName3({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(8, lowered.length - 1)} })`;
81321
82969
  } else {
81322
82970
  out = `${withCasing2(name, casing2)}: varchar(${dbColumnName3({ name, casing: casing2 })})`;
81323
82971
  }
@@ -81358,13 +83006,7 @@ var init_introspect_pg = __esm({
81358
83006
  if (lowered.startsWith("vector")) {
81359
83007
  let out;
81360
83008
  if (lowered.length !== 6) {
81361
- out = `${withCasing2(
81362
- name,
81363
- casing2
81364
- )}: vector(${dbColumnName3({ name, casing: casing2, withMode: true })}{ dimensions: ${lowered.substring(
81365
- 7,
81366
- lowered.length - 1
81367
- )} })`;
83009
+ out = `${withCasing2(name, casing2)}: vector(${dbColumnName3({ name, casing: casing2, withMode: true })}{ dimensions: ${lowered.substring(7, lowered.length - 1)} })`;
81368
83010
  } else {
81369
83011
  out = `${withCasing2(name, casing2)}: vector(${dbColumnName3({ name, casing: casing2 })})`;
81370
83012
  }
@@ -81373,13 +83015,7 @@ var init_introspect_pg = __esm({
81373
83015
  if (lowered.startsWith("char")) {
81374
83016
  let out;
81375
83017
  if (lowered.length !== 4) {
81376
- out = `${withCasing2(
81377
- name,
81378
- casing2
81379
- )}: char(${dbColumnName3({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(
81380
- 5,
81381
- lowered.length - 1
81382
- )} })`;
83018
+ out = `${withCasing2(name, casing2)}: char(${dbColumnName3({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(5, lowered.length - 1)} })`;
81383
83019
  } else {
81384
83020
  out = `${withCasing2(name, casing2)}: char(${dbColumnName3({ name, casing: casing2 })})`;
81385
83021
  }
@@ -81425,19 +83061,9 @@ var init_introspect_pg = __esm({
81425
83061
  statement += " ";
81426
83062
  statement += columnStatement;
81427
83063
  if ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[it.name]) == null ? void 0 : _b.isArray) {
81428
- statement += dimensionsInArray(
81429
- (_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions
81430
- );
83064
+ statement += dimensionsInArray((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions);
81431
83065
  }
81432
- statement += mapDefault(
81433
- tableName,
81434
- it.type,
81435
- it.name,
81436
- enumTypes,
81437
- it.typeSchema ?? "public",
81438
- it.default,
81439
- internals
81440
- );
83066
+ statement += mapDefault(tableName, it.type, it.name, enumTypes, it.typeSchema ?? "public", it.default, internals);
81441
83067
  statement += it.primaryKey ? ".primaryKey()" : "";
81442
83068
  statement += it.notNull && !it.identity ? ".notNull()" : "";
81443
83069
  statement += it.identity ? generateIdentityParams(it.identity) : "";
@@ -81624,6 +83250,7 @@ var init_introspect = __esm({
81624
83250
  sequencesResolver,
81625
83251
  tablesResolver,
81626
83252
  columnsResolver,
83253
+ viewsResolver,
81627
83254
  dryPg,
81628
83255
  schema5
81629
83256
  );
@@ -81706,6 +83333,7 @@ var init_introspect = __esm({
81706
83333
  squashMysqlScheme(schema5),
81707
83334
  tablesResolver,
81708
83335
  columnsResolver,
83336
+ mySqlViewsResolver,
81709
83337
  dryMySql,
81710
83338
  schema5
81711
83339
  );
@@ -81787,6 +83415,7 @@ var init_introspect = __esm({
81787
83415
  squashSqliteScheme(schema5),
81788
83416
  tablesResolver,
81789
83417
  columnsResolver,
83418
+ sqliteViewsResolver,
81790
83419
  drySQLite,
81791
83420
  schema5
81792
83421
  );
@@ -81863,11 +83492,12 @@ var init_introspect = __esm({
81863
83492
  console.log();
81864
83493
  const { snapshots, journal } = prepareOutFolder(out, "sqlite");
81865
83494
  if (snapshots.length === 0) {
81866
- const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
83495
+ const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
81867
83496
  squashSqliteScheme(drySQLite),
81868
83497
  squashSqliteScheme(schema5),
81869
83498
  tablesResolver,
81870
83499
  columnsResolver,
83500
+ sqliteViewsResolver,
81871
83501
  drySQLite,
81872
83502
  schema5
81873
83503
  );
@@ -85354,7 +86984,7 @@ init_utils2();
85354
86984
  var version2 = async () => {
85355
86985
  const { npmVersion } = await ormCoreVersions();
85356
86986
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
85357
- const envVersion = "0.25.0-746aeed";
86987
+ const envVersion = "0.25.0-8c3e1b5";
85358
86988
  const kitVersion = envVersion ? `v${envVersion}` : "--";
85359
86989
  const versions = `drizzle-kit: ${kitVersion}
85360
86990
  ${ormVersion}`;