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/api.js CHANGED
@@ -562,7 +562,7 @@ function is(value, type) {
562
562
  `Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
563
563
  );
564
564
  }
565
- let cls = value.constructor;
565
+ let cls = Object.getPrototypeOf(value).constructor;
566
566
  if (cls) {
567
567
  while (cls) {
568
568
  if (entityKind in cls && cls[entityKind] === type[entityKind]) {
@@ -3410,8 +3410,8 @@ var require_hanji = __commonJS({
3410
3410
  };
3411
3411
  exports2.deferred = deferred;
3412
3412
  var Terminal = class {
3413
- constructor(view, stdin, stdout, closable) {
3414
- this.view = view;
3413
+ constructor(view4, stdin, stdout, closable) {
3414
+ this.view = view4;
3415
3415
  this.stdin = stdin;
3416
3416
  this.stdout = stdout;
3417
3417
  this.closable = closable;
@@ -3449,7 +3449,7 @@ var require_hanji = __commonJS({
3449
3449
  this.resolve({ status: "submitted", data: this.view.result() });
3450
3450
  return;
3451
3451
  }
3452
- view.input(str, key);
3452
+ view4.input(str, key);
3453
3453
  };
3454
3454
  this.stdin.on("keypress", keypress);
3455
3455
  this.view.attach(this);
@@ -3511,8 +3511,8 @@ var require_hanji = __commonJS({
3511
3511
  };
3512
3512
  exports2.TaskView = TaskView2;
3513
3513
  var TaskTerminal = class {
3514
- constructor(view, stdout) {
3515
- this.view = view;
3514
+ constructor(view4, stdout) {
3515
+ this.view = view4;
3516
3516
  this.stdout = stdout;
3517
3517
  this.text = "";
3518
3518
  this.view.attach(this);
@@ -3531,22 +3531,22 @@ var require_hanji = __commonJS({
3531
3531
  }
3532
3532
  };
3533
3533
  exports2.TaskTerminal = TaskTerminal;
3534
- function render6(view) {
3534
+ function render6(view4) {
3535
3535
  const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
3536
- if (view instanceof Prompt3) {
3537
- const terminal = new Terminal(view, stdin, stdout, closable);
3536
+ if (view4 instanceof Prompt3) {
3537
+ const terminal = new Terminal(view4, stdin, stdout, closable);
3538
3538
  terminal.requestLayout();
3539
3539
  return terminal.result();
3540
3540
  }
3541
- stdout.write(`${view}
3541
+ stdout.write(`${view4}
3542
3542
  `);
3543
3543
  closable.close();
3544
3544
  return;
3545
3545
  }
3546
3546
  exports2.render = render6;
3547
- function renderWithTask4(view, task) {
3547
+ function renderWithTask4(view4, task) {
3548
3548
  return __awaiter(this, void 0, void 0, function* () {
3549
- const terminal = new TaskTerminal(view, process.stdout);
3549
+ const terminal = new TaskTerminal(view4, process.stdout);
3550
3550
  terminal.requestLayout();
3551
3551
  const result = yield task;
3552
3552
  terminal.clear();
@@ -5873,8 +5873,8 @@ var init_lib = __esm({
5873
5873
  unknownKeys: "strict",
5874
5874
  ...message !== void 0 ? {
5875
5875
  errorMap: (issue, ctx) => {
5876
- var _a324, _b233, _c12, _d5;
5877
- const defaultError = (_c12 = (_b233 = (_a324 = this._def).errorMap) === null || _b233 === void 0 ? void 0 : _b233.call(_a324, issue, ctx).message) !== null && _c12 !== void 0 ? _c12 : ctx.defaultError;
5876
+ var _a324, _b233, _c11, _d5;
5877
+ const defaultError = (_c11 = (_b233 = (_a324 = this._def).errorMap) === null || _b233 === void 0 ? void 0 : _b233.call(_a324, issue, ctx).message) !== null && _c11 !== void 0 ? _c11 : ctx.defaultError;
5878
5878
  if (issue.code === "unrecognized_keys")
5879
5879
  return {
5880
5880
  message: (_d5 = errorUtil.errToObj(message).message) !== null && _d5 !== void 0 ? _d5 : defaultError
@@ -7376,7 +7376,7 @@ var init_lib = __esm({
7376
7376
  });
7377
7377
 
7378
7378
  // src/serializer/mysqlSchema.ts
7379
- var index, fk, column, tableV3, compositePK, uniqueConstraint, tableV4, table, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
7379
+ var index, fk, column, tableV3, compositePK, uniqueConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
7380
7380
  var init_mysqlSchema = __esm({
7381
7381
  "src/serializer/mysqlSchema.ts"() {
7382
7382
  "use strict";
@@ -7441,6 +7441,17 @@ var init_mysqlSchema = __esm({
7441
7441
  compositePrimaryKeys: recordType(stringType(), compositePK),
7442
7442
  uniqueConstraints: recordType(stringType(), uniqueConstraint).default({})
7443
7443
  }).strict();
7444
+ viewMeta = objectType({
7445
+ algorithm: enumType(["undefined", "merge", "temptable"]),
7446
+ sqlSecurity: enumType(["definer", "invoker"]),
7447
+ withCheckOption: enumType(["local", "cascaded"]).optional()
7448
+ }).strict();
7449
+ view = objectType({
7450
+ name: stringType(),
7451
+ columns: recordType(stringType(), column),
7452
+ definition: stringType().optional(),
7453
+ isExisting: booleanType()
7454
+ }).strict().merge(viewMeta);
7444
7455
  kitInternals = objectType({
7445
7456
  tables: recordType(
7446
7457
  stringType(),
@@ -7493,6 +7504,7 @@ var init_mysqlSchema = __esm({
7493
7504
  version: literalType("5"),
7494
7505
  dialect,
7495
7506
  tables: recordType(stringType(), table),
7507
+ views: recordType(stringType(), view),
7496
7508
  _meta: objectType({
7497
7509
  tables: recordType(stringType(), stringType()),
7498
7510
  columns: recordType(stringType(), stringType())
@@ -7518,10 +7530,16 @@ var init_mysqlSchema = __esm({
7518
7530
  compositePrimaryKeys: recordType(stringType(), stringType()),
7519
7531
  uniqueConstraints: recordType(stringType(), stringType()).default({})
7520
7532
  }).strict();
7533
+ viewSquashed = view.omit({
7534
+ algorithm: true,
7535
+ sqlSecurity: true,
7536
+ withCheckOption: true
7537
+ }).extend({ meta: stringType() });
7521
7538
  schemaSquashed = objectType({
7522
7539
  version: literalType("5"),
7523
7540
  dialect,
7524
- tables: recordType(stringType(), tableSquashed)
7541
+ tables: recordType(stringType(), tableSquashed),
7542
+ views: recordType(stringType(), viewSquashed)
7525
7543
  }).strict();
7526
7544
  schemaSquashedV4 = objectType({
7527
7545
  version: literalType("4"),
@@ -7583,6 +7601,18 @@ var init_mysqlSchema = __esm({
7583
7601
  onDelete
7584
7602
  });
7585
7603
  return result;
7604
+ },
7605
+ squashView: (view4) => {
7606
+ return `${view4.algorithm};${view4.sqlSecurity};${view4.withCheckOption}`;
7607
+ },
7608
+ unsquashView: (meta) => {
7609
+ const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
7610
+ const toReturn = {
7611
+ algorithm,
7612
+ sqlSecurity,
7613
+ withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
7614
+ };
7615
+ return viewMeta.parse(toReturn);
7586
7616
  }
7587
7617
  };
7588
7618
  squashMysqlScheme = (json3) => {
@@ -7616,10 +7646,23 @@ var init_mysqlSchema = __esm({
7616
7646
  ];
7617
7647
  })
7618
7648
  );
7649
+ const mappedViews = Object.fromEntries(
7650
+ Object.entries(json3.views).map(([key, value]) => {
7651
+ const meta = MySqlSquasher.squashView(value);
7652
+ return [key, {
7653
+ name: value.name,
7654
+ isExisting: value.isExisting,
7655
+ columns: value.columns,
7656
+ definition: value.definition,
7657
+ meta
7658
+ }];
7659
+ })
7660
+ );
7619
7661
  return {
7620
7662
  version: "5",
7621
7663
  dialect: json3.dialect,
7622
- tables: mappedTables
7664
+ tables: mappedTables,
7665
+ views: mappedViews
7623
7666
  };
7624
7667
  };
7625
7668
  mysqlSchema = schema;
@@ -7633,6 +7676,7 @@ var init_mysqlSchema = __esm({
7633
7676
  prevId: "",
7634
7677
  tables: {},
7635
7678
  schemas: {},
7679
+ views: {},
7636
7680
  _meta: {
7637
7681
  schemas: {},
7638
7682
  tables: {},
@@ -7661,7 +7705,7 @@ var init_vector = __esm({
7661
7705
  });
7662
7706
 
7663
7707
  // src/serializer/pgSchema.ts
7664
- var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
7708
+ 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;
7665
7709
  var init_pgSchema = __esm({
7666
7710
  "src/serializer/pgSchema.ts"() {
7667
7711
  "use strict";
@@ -7856,6 +7900,44 @@ var init_pgSchema = __esm({
7856
7900
  columns: stringType().array(),
7857
7901
  nullsNotDistinct: booleanType()
7858
7902
  }).strict();
7903
+ viewWithOption = objectType({
7904
+ checkOption: enumType(["local", "cascaded"]).optional(),
7905
+ securityBarrier: booleanType().optional(),
7906
+ securityInvoker: booleanType().optional()
7907
+ }).strict();
7908
+ matViewWithOption = objectType({
7909
+ fillfactor: numberType().optional(),
7910
+ toastTupleTarget: numberType().optional(),
7911
+ parallelWorkers: numberType().optional(),
7912
+ autovacuumEnabled: booleanType().optional(),
7913
+ vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
7914
+ vacuumTruncate: booleanType().optional(),
7915
+ autovacuumVacuumThreshold: numberType().optional(),
7916
+ autovacuumVacuumScaleFactor: numberType().optional(),
7917
+ autovacuumVacuumCostDelay: numberType().optional(),
7918
+ autovacuumVacuumCostLimit: numberType().optional(),
7919
+ autovacuumFreezeMinAge: numberType().optional(),
7920
+ autovacuumFreezeMaxAge: numberType().optional(),
7921
+ autovacuumFreezeTableAge: numberType().optional(),
7922
+ autovacuumMultixactFreezeMinAge: numberType().optional(),
7923
+ autovacuumMultixactFreezeMaxAge: numberType().optional(),
7924
+ autovacuumMultixactFreezeTableAge: numberType().optional(),
7925
+ logAutovacuumMinDuration: numberType().optional(),
7926
+ userCatalogTable: booleanType().optional()
7927
+ }).strict();
7928
+ mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
7929
+ view2 = objectType({
7930
+ name: stringType(),
7931
+ schema: stringType(),
7932
+ columns: recordType(stringType(), column2),
7933
+ definition: stringType().optional(),
7934
+ materialized: booleanType(),
7935
+ with: mergedViewWithOption.optional(),
7936
+ isExisting: booleanType(),
7937
+ withNoData: booleanType().optional(),
7938
+ using: stringType().optional(),
7939
+ tablespace: stringType().optional()
7940
+ }).strict();
7859
7941
  tableV42 = objectType({
7860
7942
  name: stringType(),
7861
7943
  schema: stringType(),
@@ -7990,6 +8072,7 @@ var init_pgSchema = __esm({
7990
8072
  tables: recordType(stringType(), table2),
7991
8073
  enums: recordType(stringType(), enumSchema),
7992
8074
  schemas: recordType(stringType(), stringType()),
8075
+ views: recordType(stringType(), view2).default({}),
7993
8076
  sequences: recordType(stringType(), sequenceSchema).default({}),
7994
8077
  _meta: objectType({
7995
8078
  schemas: recordType(stringType(), stringType()),
@@ -8034,6 +8117,7 @@ var init_pgSchema = __esm({
8034
8117
  tables: recordType(stringType(), tableSquashed2),
8035
8118
  enums: recordType(stringType(), enumSchema),
8036
8119
  schemas: recordType(stringType(), stringType()),
8120
+ views: recordType(stringType(), view2),
8037
8121
  sequences: recordType(stringType(), sequenceSquashed)
8038
8122
  }).strict();
8039
8123
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
@@ -8251,6 +8335,7 @@ var init_pgSchema = __esm({
8251
8335
  tables: mappedTables,
8252
8336
  enums: json3.enums,
8253
8337
  schemas: json3.schemas,
8338
+ views: json3.views,
8254
8339
  sequences: mappedSequences
8255
8340
  };
8256
8341
  };
@@ -8273,7 +8358,7 @@ var init_pgSchema = __esm({
8273
8358
  });
8274
8359
 
8275
8360
  // src/serializer/sqliteSchema.ts
8276
- var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, table3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema2, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
8361
+ var index3, fk3, compositePK3, column3, tableV33, uniqueConstraint3, table3, view3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals3, latestVersion, schemaInternal2, schemaV32, schemaV42, schemaV52, schema2, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
8277
8362
  var init_sqliteSchema = __esm({
8278
8363
  "src/serializer/sqliteSchema.ts"() {
8279
8364
  "use strict";
@@ -8328,6 +8413,12 @@ var init_sqliteSchema = __esm({
8328
8413
  compositePrimaryKeys: recordType(stringType(), compositePK3),
8329
8414
  uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
8330
8415
  }).strict();
8416
+ view3 = objectType({
8417
+ name: stringType(),
8418
+ columns: recordType(stringType(), column3),
8419
+ definition: stringType().optional(),
8420
+ isExisting: booleanType()
8421
+ }).strict();
8331
8422
  dialect2 = enumType(["sqlite"]);
8332
8423
  schemaHash3 = objectType({
8333
8424
  id: stringType(),
@@ -8343,6 +8434,7 @@ var init_sqliteSchema = __esm({
8343
8434
  version: literalType("4"),
8344
8435
  dialect: dialect2,
8345
8436
  tables: recordType(stringType(), table3),
8437
+ views: recordType(stringType(), view3),
8346
8438
  enums: objectType({})
8347
8439
  }).strict();
8348
8440
  schemaInternalV52 = objectType({
@@ -8371,6 +8463,7 @@ var init_sqliteSchema = __esm({
8371
8463
  version: latestVersion,
8372
8464
  dialect: dialect2,
8373
8465
  tables: recordType(stringType(), table3),
8466
+ views: recordType(stringType(), view3),
8374
8467
  enums: objectType({}),
8375
8468
  _meta: objectType({
8376
8469
  tables: recordType(stringType(), stringType()),
@@ -8394,6 +8487,7 @@ var init_sqliteSchema = __esm({
8394
8487
  version: latestVersion,
8395
8488
  dialect: dialect2,
8396
8489
  tables: recordType(stringType(), tableSquashed3),
8490
+ views: recordType(stringType(), view3),
8397
8491
  enums: anyType()
8398
8492
  }).strict();
8399
8493
  SQLiteSquasher = {
@@ -8513,6 +8607,7 @@ var init_sqliteSchema = __esm({
8513
8607
  version: "6",
8514
8608
  dialect: json3.dialect,
8515
8609
  tables: mappedTables,
8610
+ views: json3.views,
8516
8611
  enums: json3.enums
8517
8612
  };
8518
8613
  };
@@ -8522,6 +8617,7 @@ var init_sqliteSchema = __esm({
8522
8617
  id: originUUID,
8523
8618
  prevId: "",
8524
8619
  tables: {},
8620
+ views: {},
8525
8621
  enums: {},
8526
8622
  _meta: {
8527
8623
  tables: {},
@@ -11217,6 +11313,7 @@ function applyJsonDiff(json1, json22) {
11217
11313
  difference.tables = difference.tables || {};
11218
11314
  difference.enums = difference.enums || {};
11219
11315
  difference.sequences = difference.sequences || {};
11316
+ difference.views = difference.views || {};
11220
11317
  const schemaKeys = Object.keys(difference.schemas);
11221
11318
  for (let key of schemaKeys) {
11222
11319
  if (key.endsWith("__added") || key.endsWith("__deleted")) {
@@ -11272,6 +11369,70 @@ function applyJsonDiff(json1, json22) {
11272
11369
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
11273
11370
  return json22.sequences[it[0]];
11274
11371
  });
11372
+ const viewsEntries = Object.entries(difference.views);
11373
+ const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
11374
+ ([nameWithSchema, view4]) => {
11375
+ const deletedWithOption = view4.with__deleted;
11376
+ const addedWithOption = view4.with__added;
11377
+ const deletedWith = Object.fromEntries(
11378
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
11379
+ return [key.replace("__deleted", ""), value];
11380
+ })
11381
+ );
11382
+ const addedWith = Object.fromEntries(
11383
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
11384
+ return [key.replace("__added", ""), value];
11385
+ })
11386
+ );
11387
+ const alterWith = Object.fromEntries(
11388
+ Object.entries(view4.with || {}).filter(
11389
+ (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
11390
+ ).map(
11391
+ (it) => {
11392
+ return [it[0], it[1].__new];
11393
+ }
11394
+ )
11395
+ );
11396
+ const alteredSchema = view4.schema;
11397
+ const alteredDefinition = view4.definition;
11398
+ const alteredExisting = view4.isExisting;
11399
+ const addedTablespace = view4.tablespace__added;
11400
+ const droppedTablespace = view4.tablespace__deleted;
11401
+ const alterTablespaceTo = view4.tablespace;
11402
+ let alteredTablespace;
11403
+ if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
11404
+ if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
11405
+ if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
11406
+ const addedUsing = view4.using__added;
11407
+ const droppedUsing = view4.using__deleted;
11408
+ const alterUsingTo = view4.using;
11409
+ let alteredUsing;
11410
+ if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
11411
+ if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
11412
+ if (alterUsingTo) alteredUsing = alterUsingTo;
11413
+ const alteredMeta = view4.meta;
11414
+ return Object.fromEntries(
11415
+ Object.entries({
11416
+ name: json22.views[nameWithSchema].name,
11417
+ schema: json22.views[nameWithSchema].schema,
11418
+ // pg
11419
+ deletedWithOption,
11420
+ addedWithOption,
11421
+ deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
11422
+ addedWith: Object.keys(addedWith).length ? addedWith : void 0,
11423
+ alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
11424
+ alteredSchema,
11425
+ alteredTablespace,
11426
+ alteredUsing,
11427
+ // mysql
11428
+ alteredMeta,
11429
+ // common
11430
+ alteredDefinition,
11431
+ alteredExisting
11432
+ }).filter(([_2, value]) => value !== void 0)
11433
+ );
11434
+ }
11435
+ );
11275
11436
  const alteredTablesWithColumns = Object.values(difference.tables).map(
11276
11437
  (table4) => {
11277
11438
  return findAlternationsInTable(table4);
@@ -11280,7 +11441,8 @@ function applyJsonDiff(json1, json22) {
11280
11441
  return {
11281
11442
  alteredTablesWithColumns,
11282
11443
  alteredEnums,
11283
- alteredSequences
11444
+ alteredSequences,
11445
+ alteredViews
11284
11446
  };
11285
11447
  }
11286
11448
  var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
@@ -11675,7 +11837,7 @@ function fromJson(statements, dialect4, action, json22) {
11675
11837
  }).filter((it) => it !== "");
11676
11838
  return result;
11677
11839
  }
11678
- 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;
11840
+ 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;
11679
11841
  var init_sqlgenerator = __esm({
11680
11842
  "src/sqlgenerator.ts"() {
11681
11843
  "use strict";
@@ -11888,6 +12050,187 @@ var init_sqlgenerator = __esm({
11888
12050
  return statement;
11889
12051
  }
11890
12052
  };
12053
+ PgCreateViewConvertor = class extends Convertor {
12054
+ can(statement, dialect4) {
12055
+ return statement.type === "create_view" && dialect4 === "postgresql";
12056
+ }
12057
+ convert(st) {
12058
+ const { definition, name: viewName, schema: schema4, with: withOption, materialized, withNoData, tablespace, using } = st;
12059
+ const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
12060
+ let statement = materialized ? `CREATE MATERIALIZED VIEW ${name2}` : `CREATE VIEW ${name2}`;
12061
+ if (using) statement += ` USING "${using}"`;
12062
+ const options = [];
12063
+ if (withOption) {
12064
+ statement += ` WITH (`;
12065
+ Object.entries(withOption).forEach(([key, value]) => {
12066
+ if (typeof value === "undefined") return;
12067
+ options.push(`${key.snake_case()} = ${value}`);
12068
+ });
12069
+ statement += options.join(", ");
12070
+ statement += `)`;
12071
+ }
12072
+ if (tablespace) statement += ` TABLESPACE ${tablespace}`;
12073
+ statement += ` AS (${definition})`;
12074
+ if (withNoData) statement += ` WITH NO DATA`;
12075
+ statement += `;`;
12076
+ return statement;
12077
+ }
12078
+ };
12079
+ MySqlCreateViewConvertor = class extends Convertor {
12080
+ can(statement, dialect4) {
12081
+ return statement.type === "mysql_create_view" && dialect4 === "mysql";
12082
+ }
12083
+ convert(st) {
12084
+ const { definition, name: name2, algorithm, sqlSecurity, withCheckOption, replace } = st;
12085
+ let statement = `CREATE `;
12086
+ statement += replace ? `OR REPLACE ` : "";
12087
+ statement += algorithm ? `ALGORITHM = ${algorithm}
12088
+ ` : "";
12089
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
12090
+ ` : "";
12091
+ statement += `VIEW \`${name2}\` AS (${definition})`;
12092
+ statement += withCheckOption ? `
12093
+ WITH ${withCheckOption} CHECK OPTION` : "";
12094
+ statement += ";";
12095
+ return statement;
12096
+ }
12097
+ };
12098
+ SqliteCreateViewConvertor = class extends Convertor {
12099
+ can(statement, dialect4) {
12100
+ return statement.type === "sqlite_create_view" && (dialect4 === "sqlite" || dialect4 === "turso");
12101
+ }
12102
+ convert(st) {
12103
+ const { definition, name: name2 } = st;
12104
+ return `CREATE VIEW \`${name2}\` AS ${definition};`;
12105
+ }
12106
+ };
12107
+ PgDropViewConvertor = class extends Convertor {
12108
+ can(statement, dialect4) {
12109
+ return statement.type === "drop_view" && dialect4 === "postgresql";
12110
+ }
12111
+ convert(st) {
12112
+ const { name: viewName, schema: schema4, materialized } = st;
12113
+ const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
12114
+ return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name2};`;
12115
+ }
12116
+ };
12117
+ MySqlDropViewConvertor = class extends Convertor {
12118
+ can(statement, dialect4) {
12119
+ return statement.type === "drop_view" && dialect4 === "mysql";
12120
+ }
12121
+ convert(st) {
12122
+ const { name: name2 } = st;
12123
+ return `DROP VIEW \`${name2}\`;`;
12124
+ }
12125
+ };
12126
+ SqliteDropViewConvertor = class extends Convertor {
12127
+ can(statement, dialect4) {
12128
+ return statement.type === "drop_view" && (dialect4 === "sqlite" || dialect4 === "turso");
12129
+ }
12130
+ convert(st) {
12131
+ const { name: name2 } = st;
12132
+ return `DROP VIEW \`${name2}\`;`;
12133
+ }
12134
+ };
12135
+ MySqlAlterViewConvertor = class extends Convertor {
12136
+ can(statement, dialect4) {
12137
+ return statement.type === "alter_mysql_view" && dialect4 === "mysql";
12138
+ }
12139
+ convert(st) {
12140
+ const { name: name2, algorithm, definition, sqlSecurity, withCheckOption } = st;
12141
+ let statement = `ALTER `;
12142
+ statement += algorithm ? `ALGORITHM = ${algorithm}
12143
+ ` : "";
12144
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
12145
+ ` : "";
12146
+ statement += `VIEW \`${name2}\` AS ${definition}`;
12147
+ statement += withCheckOption ? `
12148
+ WITH ${withCheckOption} CHECK OPTION` : "";
12149
+ statement += ";";
12150
+ return statement;
12151
+ }
12152
+ };
12153
+ PgRenameViewConvertor = class extends Convertor {
12154
+ can(statement, dialect4) {
12155
+ return statement.type === "rename_view" && dialect4 === "postgresql";
12156
+ }
12157
+ convert(st) {
12158
+ const { nameFrom: from, nameTo: to, schema: schema4, materialized } = st;
12159
+ const nameFrom = `"${schema4}"."${from}"`;
12160
+ return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
12161
+ }
12162
+ };
12163
+ MySqlRenameViewConvertor = class extends Convertor {
12164
+ can(statement, dialect4) {
12165
+ return statement.type === "rename_view" && dialect4 === "mysql";
12166
+ }
12167
+ convert(st) {
12168
+ const { nameFrom: from, nameTo: to } = st;
12169
+ return `RENAME TABLE \`${from}\` RENAME TO \`${to}\`;`;
12170
+ }
12171
+ };
12172
+ PgAlterViewSchemaConvertor = class extends Convertor {
12173
+ can(statement, dialect4) {
12174
+ return statement.type === "alter_view_alter_schema" && dialect4 === "postgresql";
12175
+ }
12176
+ convert(st) {
12177
+ const { fromSchema, toSchema, name: name2, materialized } = st;
12178
+ const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name2}" SET SCHEMA "${toSchema}";`;
12179
+ return statement;
12180
+ }
12181
+ };
12182
+ PgAlterViewAddWithOptionConvertor = class extends Convertor {
12183
+ can(statement, dialect4) {
12184
+ return statement.type === "alter_view_add_with_option" && dialect4 === "postgresql";
12185
+ }
12186
+ convert(st) {
12187
+ const { schema: schema4, with: withOption, name: name2, materialized } = st;
12188
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${name2}" SET (`;
12189
+ const options = [];
12190
+ Object.entries(withOption).forEach(([key, value]) => {
12191
+ options.push(`${key.snake_case()} = ${value}`);
12192
+ });
12193
+ statement += options.join(", ");
12194
+ statement += `);`;
12195
+ return statement;
12196
+ }
12197
+ };
12198
+ PgAlterViewDropWithOptionConvertor = class extends Convertor {
12199
+ can(statement, dialect4) {
12200
+ return statement.type === "alter_view_drop_with_option" && dialect4 === "postgresql";
12201
+ }
12202
+ convert(st) {
12203
+ const { schema: schema4, name: name2, materialized, with: withOptions } = st;
12204
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${name2}" RESET (`;
12205
+ const options = [];
12206
+ Object.entries(withOptions).forEach(([key, value]) => {
12207
+ options.push(`${key.snake_case()}`);
12208
+ });
12209
+ statement += options.join(", ");
12210
+ statement += ");";
12211
+ return statement;
12212
+ }
12213
+ };
12214
+ PgAlterViewAlterTablespaceConvertor = class extends Convertor {
12215
+ can(statement, dialect4) {
12216
+ return statement.type === "alter_view_alter_tablespace" && dialect4 === "postgresql";
12217
+ }
12218
+ convert(st) {
12219
+ const { schema: schema4, name: name2, toTablespace } = st;
12220
+ const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET TABLESPACE ${toTablespace};`;
12221
+ return statement;
12222
+ }
12223
+ };
12224
+ PgAlterViewAlterUsingConvertor = class extends Convertor {
12225
+ can(statement, dialect4) {
12226
+ return statement.type === "alter_view_alter_using" && dialect4 === "postgresql";
12227
+ }
12228
+ convert(st) {
12229
+ const { schema: schema4, name: name2, toUsing } = st;
12230
+ const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET ACCESS METHOD "${toUsing}";`;
12231
+ return statement;
12232
+ }
12233
+ };
11891
12234
  PgAlterTableAlterColumnSetGenerated = class extends Convertor {
11892
12235
  can(statement, dialect4) {
11893
12236
  return statement.type === "alter_table_alter_column_set_identity" && dialect4 === "postgresql";
@@ -12056,20 +12399,22 @@ var init_sqlgenerator = __esm({
12056
12399
  }
12057
12400
  convert(st) {
12058
12401
  const { name: name2, values, schema: schema4 } = st;
12059
- const tableNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12402
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12060
12403
  let valuesStatement = "(";
12061
12404
  valuesStatement += values.map((it) => `'${it}'`).join(", ");
12062
12405
  valuesStatement += ")";
12063
- let statement = "DO $$ BEGIN";
12064
- statement += "\n";
12065
- statement += ` CREATE TYPE ${tableNameWithSchema} AS ENUM${valuesStatement};`;
12066
- statement += "\n";
12067
- statement += "EXCEPTION";
12068
- statement += "\n";
12069
- statement += " WHEN duplicate_object THEN null;";
12070
- statement += "\n";
12071
- statement += "END $$;";
12072
- statement += "\n";
12406
+ let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
12407
+ return statement;
12408
+ }
12409
+ };
12410
+ DropTypeEnumConvertor = class extends Convertor {
12411
+ can(statement) {
12412
+ return statement.type === "drop_type_enum";
12413
+ }
12414
+ convert(st) {
12415
+ const { name: name2, schema: schema4 } = st;
12416
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12417
+ let statement = `DROP TYPE ${enumNameWithSchema};`;
12073
12418
  return statement;
12074
12419
  }
12075
12420
  };
@@ -12078,9 +12423,56 @@ var init_sqlgenerator = __esm({
12078
12423
  return statement.type === "alter_type_add_value";
12079
12424
  }
12080
12425
  convert(st) {
12081
- const { name: name2, schema: schema4, value } = st;
12082
- const schemaPrefix = schema4 && schema4 !== "public" ? `"${schema4}".` : "";
12083
- return `ALTER TYPE ${schemaPrefix}"${name2}" ADD VALUE '${value}';`;
12426
+ const { name: name2, schema: schema4, value, before } = st;
12427
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12428
+ return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
12429
+ }
12430
+ };
12431
+ AlterTypeSetSchemaConvertor = class extends Convertor {
12432
+ can(statement) {
12433
+ return statement.type === "move_type_enum";
12434
+ }
12435
+ convert(st) {
12436
+ const { name: name2, schemaFrom, schemaTo } = st;
12437
+ const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name2}"` : `"${name2}"`;
12438
+ return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
12439
+ }
12440
+ };
12441
+ AlterRenameTypeConvertor = class extends Convertor {
12442
+ can(statement) {
12443
+ return statement.type === "rename_type_enum";
12444
+ }
12445
+ convert(st) {
12446
+ const { nameTo, nameFrom, schema: schema4 } = st;
12447
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${nameFrom}"` : `"${nameFrom}"`;
12448
+ return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
12449
+ }
12450
+ };
12451
+ AlterTypeDropValueConvertor = class extends Convertor {
12452
+ can(statement) {
12453
+ return statement.type === "alter_type_drop_value";
12454
+ }
12455
+ convert(st) {
12456
+ const { columnsWithEnum, name: name2, newValues, schema: schema4 } = st;
12457
+ const statements = [];
12458
+ for (const withEnum of columnsWithEnum) {
12459
+ statements.push(
12460
+ `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
12461
+ );
12462
+ }
12463
+ statements.push(new DropTypeEnumConvertor().convert({ name: name2, schema: schema4, type: "drop_type_enum" }));
12464
+ statements.push(new CreateTypeEnumConvertor().convert({
12465
+ name: name2,
12466
+ schema: schema4,
12467
+ values: newValues,
12468
+ type: "create_type_enum"
12469
+ }));
12470
+ for (const withEnum of columnsWithEnum) {
12471
+ statements.push(
12472
+ `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE "${schema4}"."${name2}" USING "${withEnum.column}"::"${schema4}"."${name2}";`
12473
+ );
12474
+ }
12475
+ return statements;
12084
12476
  }
12085
12477
  };
12086
12478
  PgDropTableConvertor = class extends Convertor {
@@ -13223,7 +13615,26 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13223
13615
  convertors.push(new SQLiteCreateTableConvertor());
13224
13616
  convertors.push(new SQLiteRecreateTableConvertor());
13225
13617
  convertors.push(new LibSQLRecreateTableConvertor());
13618
+ convertors.push(new PgCreateViewConvertor());
13619
+ convertors.push(new PgDropViewConvertor());
13620
+ convertors.push(new PgRenameViewConvertor());
13621
+ convertors.push(new PgAlterViewSchemaConvertor());
13622
+ convertors.push(new PgAlterViewAddWithOptionConvertor());
13623
+ convertors.push(new PgAlterViewDropWithOptionConvertor());
13624
+ convertors.push(new PgAlterViewAlterTablespaceConvertor());
13625
+ convertors.push(new PgAlterViewAlterUsingConvertor());
13626
+ convertors.push(new MySqlCreateViewConvertor());
13627
+ convertors.push(new MySqlDropViewConvertor());
13628
+ convertors.push(new MySqlRenameViewConvertor());
13629
+ convertors.push(new MySqlAlterViewConvertor());
13630
+ convertors.push(new SqliteCreateViewConvertor());
13631
+ convertors.push(new SqliteDropViewConvertor());
13226
13632
  convertors.push(new CreateTypeEnumConvertor());
13633
+ convertors.push(new DropTypeEnumConvertor());
13634
+ convertors.push(new AlterTypeAddValueConvertor());
13635
+ convertors.push(new AlterTypeSetSchemaConvertor());
13636
+ convertors.push(new AlterRenameTypeConvertor());
13637
+ convertors.push(new AlterTypeDropValueConvertor());
13227
13638
  convertors.push(new CreatePgSequenceConvertor());
13228
13639
  convertors.push(new DropPgSequenceConvertor());
13229
13640
  convertors.push(new RenamePgSequenceConvertor());
@@ -13255,7 +13666,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13255
13666
  convertors.push(new PgDropIndexConvertor());
13256
13667
  convertors.push(new SqliteDropIndexConvertor());
13257
13668
  convertors.push(new MySqlDropIndexConvertor());
13258
- convertors.push(new AlterTypeAddValueConvertor());
13259
13669
  convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
13260
13670
  convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
13261
13671
  convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
@@ -13556,7 +13966,7 @@ var init_sqlitePushUtils = __esm({
13556
13966
  });
13557
13967
 
13558
13968
  // src/jsonStatements.ts
13559
- 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;
13969
+ 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;
13560
13970
  var init_jsonStatements = __esm({
13561
13971
  "src/jsonStatements.ts"() {
13562
13972
  "use strict";
@@ -13646,6 +14056,27 @@ var init_jsonStatements = __esm({
13646
14056
  };
13647
14057
  });
13648
14058
  };
14059
+ prepareDropEnumValues = (name2, schema4, removedValues, json22) => {
14060
+ if (!removedValues.length) return [];
14061
+ const affectedColumns = [];
14062
+ for (const tableKey2 in json22.tables) {
14063
+ const table4 = json22.tables[tableKey2];
14064
+ for (const columnKey in table4.columns) {
14065
+ const column4 = table4.columns[columnKey];
14066
+ if (column4.type === name2 && column4.typeSchema === schema4) {
14067
+ affectedColumns.push({ schema: table4.schema || "public", table: table4.name, column: column4.name });
14068
+ }
14069
+ }
14070
+ }
14071
+ return [{
14072
+ type: "alter_type_drop_value",
14073
+ name: name2,
14074
+ schema: schema4,
14075
+ deletedValues: removedValues,
14076
+ newValues: json22.enums[`${schema4}.${name2}`].values,
14077
+ columnsWithEnum: affectedColumns
14078
+ }];
14079
+ };
13649
14080
  prepareDropEnumJson = (name2, schema4) => {
13650
14081
  return {
13651
14082
  type: "drop_type_enum",
@@ -14889,6 +15320,103 @@ var init_jsonStatements = __esm({
14889
15320
  };
14890
15321
  });
14891
15322
  };
15323
+ preparePgCreateViewJson = (name2, schema4, definition, materialized, withNoData = false, withOption, using, tablespace) => {
15324
+ return {
15325
+ type: "create_view",
15326
+ name: name2,
15327
+ schema: schema4,
15328
+ definition,
15329
+ with: withOption,
15330
+ materialized,
15331
+ withNoData,
15332
+ using,
15333
+ tablespace
15334
+ };
15335
+ };
15336
+ prepareMySqlCreateViewJson = (name2, definition, meta, replace = false) => {
15337
+ const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
15338
+ return {
15339
+ type: "mysql_create_view",
15340
+ name: name2,
15341
+ definition,
15342
+ algorithm,
15343
+ sqlSecurity,
15344
+ withCheckOption,
15345
+ replace
15346
+ };
15347
+ };
15348
+ prepareSqliteCreateViewJson = (name2, definition) => {
15349
+ return {
15350
+ type: "sqlite_create_view",
15351
+ name: name2,
15352
+ definition
15353
+ };
15354
+ };
15355
+ prepareDropViewJson = (name2, schema4, materialized) => {
15356
+ const resObject = { name: name2, type: "drop_view" };
15357
+ if (schema4) resObject["schema"] = schema4;
15358
+ if (materialized) resObject["materialized"] = materialized;
15359
+ return resObject;
15360
+ };
15361
+ prepareRenameViewJson = (to, from, schema4, materialized) => {
15362
+ const resObject = {
15363
+ type: "rename_view",
15364
+ nameTo: to,
15365
+ nameFrom: from
15366
+ };
15367
+ if (schema4) resObject["schema"] = schema4;
15368
+ if (materialized) resObject["materialized"] = materialized;
15369
+ return resObject;
15370
+ };
15371
+ preparePgAlterViewAlterSchemaJson = (to, from, name2, materialized) => {
15372
+ const returnObject = {
15373
+ type: "alter_view_alter_schema",
15374
+ fromSchema: from,
15375
+ toSchema: to,
15376
+ name: name2
15377
+ };
15378
+ if (materialized) returnObject["materialized"] = materialized;
15379
+ return returnObject;
15380
+ };
15381
+ preparePgAlterViewAddWithOptionJson = (name2, schema4, materialized, withOption) => {
15382
+ return {
15383
+ type: "alter_view_add_with_option",
15384
+ name: name2,
15385
+ schema: schema4,
15386
+ materialized,
15387
+ with: withOption
15388
+ };
15389
+ };
15390
+ preparePgAlterViewDropWithOptionJson = (name2, schema4, materialized, withOption) => {
15391
+ return {
15392
+ type: "alter_view_drop_with_option",
15393
+ name: name2,
15394
+ schema: schema4,
15395
+ materialized,
15396
+ with: withOption
15397
+ };
15398
+ };
15399
+ preparePgAlterViewAlterTablespaceJson = (name2, schema4, materialized, to) => {
15400
+ return {
15401
+ type: "alter_view_alter_tablespace",
15402
+ name: name2,
15403
+ schema: schema4,
15404
+ materialized,
15405
+ toTablespace: to
15406
+ };
15407
+ };
15408
+ preparePgAlterViewAlterUsingJson = (name2, schema4, materialized, to) => {
15409
+ return {
15410
+ type: "alter_view_alter_using",
15411
+ name: name2,
15412
+ schema: schema4,
15413
+ materialized,
15414
+ toUsing: to
15415
+ };
15416
+ };
15417
+ prepareMySqlAlterView = (view4) => {
15418
+ return { type: "alter_mysql_view", ...view4 };
15419
+ };
14892
15420
  }
14893
15421
  });
14894
15422
 
@@ -15176,6 +15704,7 @@ var init_statementCombiner = __esm({
15176
15704
  // src/snapshotsDiffer.ts
15177
15705
  var snapshotsDiffer_exports = {};
15178
15706
  __export(snapshotsDiffer_exports, {
15707
+ alteredPgViewSchema: () => alteredPgViewSchema,
15179
15708
  alteredTableScheme: () => alteredTableScheme,
15180
15709
  applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff,
15181
15710
  applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff,
@@ -15187,7 +15716,7 @@ __export(snapshotsDiffer_exports, {
15187
15716
  makePatched: () => makePatched,
15188
15717
  makeSelfOrPatched: () => makeSelfOrPatched
15189
15718
  });
15190
- var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
15719
+ var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
15191
15720
  var init_snapshotsDiffer = __esm({
15192
15721
  "src/snapshotsDiffer.ts"() {
15193
15722
  "use strict";
@@ -15356,18 +15885,62 @@ var init_snapshotsDiffer = __esm({
15356
15885
  })
15357
15886
  )
15358
15887
  }).strict();
15888
+ alteredViewCommon = objectType({
15889
+ name: stringType(),
15890
+ alteredDefinition: objectType({
15891
+ __old: stringType(),
15892
+ __new: stringType()
15893
+ }).strict().optional(),
15894
+ alteredExisting: objectType({
15895
+ __old: booleanType(),
15896
+ __new: booleanType()
15897
+ }).strict().optional()
15898
+ });
15899
+ alteredPgViewSchema = alteredViewCommon.merge(
15900
+ objectType({
15901
+ schema: stringType(),
15902
+ deletedWithOption: mergedViewWithOption.optional(),
15903
+ addedWithOption: mergedViewWithOption.optional(),
15904
+ addedWith: mergedViewWithOption.optional(),
15905
+ deletedWith: mergedViewWithOption.optional(),
15906
+ alteredWith: mergedViewWithOption.optional(),
15907
+ alteredSchema: objectType({
15908
+ __old: stringType(),
15909
+ __new: stringType()
15910
+ }).strict().optional(),
15911
+ alteredTablespace: objectType({
15912
+ __old: stringType(),
15913
+ __new: stringType()
15914
+ }).strict().optional(),
15915
+ alteredUsing: objectType({
15916
+ __old: stringType(),
15917
+ __new: stringType()
15918
+ }).strict().optional()
15919
+ }).strict()
15920
+ );
15921
+ alteredMySqlViewSchema = alteredViewCommon.merge(
15922
+ objectType({
15923
+ alteredMeta: objectType({
15924
+ __old: stringType(),
15925
+ __new: stringType()
15926
+ }).strict().optional()
15927
+ }).strict()
15928
+ );
15359
15929
  diffResultScheme = objectType({
15360
15930
  alteredTablesWithColumns: alteredTableScheme.array(),
15361
15931
  alteredEnums: changedEnumSchema.array(),
15362
- alteredSequences: sequenceSquashed.array()
15932
+ alteredSequences: sequenceSquashed.array(),
15933
+ alteredViews: alteredPgViewSchema.array()
15363
15934
  }).strict();
15364
15935
  diffResultSchemeMysql = objectType({
15365
15936
  alteredTablesWithColumns: alteredTableScheme.array(),
15366
- alteredEnums: neverType().array()
15937
+ alteredEnums: neverType().array(),
15938
+ alteredViews: alteredMySqlViewSchema.array()
15367
15939
  });
15368
15940
  diffResultSchemeSQLite = objectType({
15369
15941
  alteredTablesWithColumns: alteredTableScheme.array(),
15370
- alteredEnums: neverType().array()
15942
+ alteredEnums: neverType().array(),
15943
+ alteredViews: alteredViewCommon.array()
15371
15944
  });
15372
15945
  schemaChangeFor = (table4, renamedSchemas) => {
15373
15946
  for (let ren of renamedSchemas) {
@@ -15414,7 +15987,7 @@ var init_snapshotsDiffer = __esm({
15414
15987
  }
15415
15988
  return column4;
15416
15989
  };
15417
- applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
15990
+ applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
15418
15991
  const schemasDiff = diffSchemasOrTables(json1.schemas, json22.schemas);
15419
15992
  const {
15420
15993
  created: createdSchemas,
@@ -15642,7 +16215,39 @@ var init_snapshotsDiffer = __esm({
15642
16215
  return [tableKey2, tableValue];
15643
16216
  }
15644
16217
  );
15645
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
16218
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
16219
+ const {
16220
+ created: createdViews,
16221
+ deleted: deletedViews,
16222
+ renamed: renamedViews,
16223
+ moved: movedViews
16224
+ } = await viewsResolver2({
16225
+ created: viewsDiff.added,
16226
+ deleted: viewsDiff.deleted
16227
+ });
16228
+ const renamesViewDic = {};
16229
+ renamedViews.forEach((it) => {
16230
+ renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
16231
+ });
16232
+ const movedViewDic = {};
16233
+ movedViews.forEach((it) => {
16234
+ movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
16235
+ });
16236
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
16237
+ viewsPatchedSnap1.views = mapEntries(
16238
+ viewsPatchedSnap1.views,
16239
+ (viewKey, viewValue) => {
16240
+ const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
16241
+ const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
16242
+ if (rename) {
16243
+ viewValue.name = rename.to;
16244
+ viewKey = `${viewValue.schema}.${viewValue.name}`;
16245
+ }
16246
+ if (moved) viewKey = `${moved.to}.${viewValue.name}`;
16247
+ return [viewKey, viewValue];
16248
+ }
16249
+ );
16250
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
15646
16251
  const typedResult = diffResultScheme.parse(diffResult);
15647
16252
  const jsonStatements = [];
15648
16253
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -15867,6 +16472,9 @@ var init_snapshotsDiffer = __esm({
15867
16472
  const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
15868
16473
  return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
15869
16474
  }).flat() ?? [];
16475
+ const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
16476
+ return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
16477
+ }).flat() ?? [];
15870
16478
  const createSequences = createdSequences.map((it) => {
15871
16479
  return prepareCreateSequenceJson(it);
15872
16480
  }) ?? [];
@@ -15894,6 +16502,137 @@ var init_snapshotsDiffer = __esm({
15894
16502
  const createTables = createdTables.map((it) => {
15895
16503
  return preparePgCreateTableJson(it, curFull);
15896
16504
  });
16505
+ const createViews = [];
16506
+ const dropViews = [];
16507
+ const renameViews = [];
16508
+ const alterViews = [];
16509
+ createViews.push(
16510
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
16511
+ return preparePgCreateViewJson(
16512
+ it.name,
16513
+ it.schema,
16514
+ it.definition,
16515
+ it.materialized,
16516
+ it.withNoData,
16517
+ it.with,
16518
+ it.using,
16519
+ it.tablespace
16520
+ );
16521
+ })
16522
+ );
16523
+ dropViews.push(
16524
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
16525
+ return prepareDropViewJson(it.name, it.schema, it.materialized);
16526
+ })
16527
+ );
16528
+ renameViews.push(
16529
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
16530
+ return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
16531
+ })
16532
+ );
16533
+ alterViews.push(
16534
+ ...movedViews.filter(
16535
+ (it) => !json22.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
16536
+ ).map((it) => {
16537
+ return preparePgAlterViewAlterSchemaJson(
16538
+ it.schemaTo,
16539
+ it.schemaFrom,
16540
+ it.name,
16541
+ json22.views[`${it.schemaTo}.${it.name}`].materialized
16542
+ );
16543
+ })
16544
+ );
16545
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[`${it.schema}.${it.name}`].isExisting);
16546
+ for (const alteredView of alteredViews) {
16547
+ const viewKey = `${alteredView.schema}.${alteredView.name}`;
16548
+ const { materialized, with: withOption, definition, withNoData, using, tablespace } = json22.views[viewKey];
16549
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
16550
+ dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
16551
+ createViews.push(
16552
+ preparePgCreateViewJson(
16553
+ alteredView.name,
16554
+ alteredView.schema,
16555
+ definition,
16556
+ materialized,
16557
+ withNoData,
16558
+ withOption,
16559
+ using,
16560
+ tablespace
16561
+ )
16562
+ );
16563
+ continue;
16564
+ }
16565
+ if (alteredView.addedWithOption) {
16566
+ alterViews.push(
16567
+ preparePgAlterViewAddWithOptionJson(
16568
+ alteredView.name,
16569
+ alteredView.schema,
16570
+ materialized,
16571
+ alteredView.addedWithOption
16572
+ )
16573
+ );
16574
+ }
16575
+ if (alteredView.deletedWithOption) {
16576
+ alterViews.push(
16577
+ preparePgAlterViewDropWithOptionJson(
16578
+ alteredView.name,
16579
+ alteredView.schema,
16580
+ materialized,
16581
+ alteredView.deletedWithOption
16582
+ )
16583
+ );
16584
+ }
16585
+ if (alteredView.addedWith) {
16586
+ alterViews.push(
16587
+ preparePgAlterViewAddWithOptionJson(
16588
+ alteredView.name,
16589
+ alteredView.schema,
16590
+ materialized,
16591
+ alteredView.addedWith
16592
+ )
16593
+ );
16594
+ }
16595
+ if (alteredView.deletedWith) {
16596
+ alterViews.push(
16597
+ preparePgAlterViewDropWithOptionJson(
16598
+ alteredView.name,
16599
+ alteredView.schema,
16600
+ materialized,
16601
+ alteredView.deletedWith
16602
+ )
16603
+ );
16604
+ }
16605
+ if (alteredView.alteredWith) {
16606
+ alterViews.push(
16607
+ preparePgAlterViewAddWithOptionJson(
16608
+ alteredView.name,
16609
+ alteredView.schema,
16610
+ materialized,
16611
+ alteredView.alteredWith
16612
+ )
16613
+ );
16614
+ }
16615
+ if (alteredView.alteredTablespace) {
16616
+ alterViews.push(
16617
+ preparePgAlterViewAlterTablespaceJson(
16618
+ alteredView.name,
16619
+ alteredView.schema,
16620
+ materialized,
16621
+ alteredView.alteredTablespace.__new
16622
+ )
16623
+ );
16624
+ }
16625
+ if (alteredView.alteredUsing) {
16626
+ alterViews.push(
16627
+ preparePgAlterViewAlterUsingJson(
16628
+ alteredView.name,
16629
+ alteredView.schema,
16630
+ materialized,
16631
+ alteredView.alteredUsing.__new
16632
+ )
16633
+ );
16634
+ }
16635
+ }
15897
16636
  jsonStatements.push(...createSchemas);
15898
16637
  jsonStatements.push(...renameSchemas);
15899
16638
  jsonStatements.push(...createEnums);
@@ -15905,6 +16644,9 @@ var init_snapshotsDiffer = __esm({
15905
16644
  jsonStatements.push(...renameSequences);
15906
16645
  jsonStatements.push(...jsonAlterSequences);
15907
16646
  jsonStatements.push(...createTables);
16647
+ jsonStatements.push(...dropViews);
16648
+ jsonStatements.push(...renameViews);
16649
+ jsonStatements.push(...alterViews);
15908
16650
  jsonStatements.push(...jsonDropTables);
15909
16651
  jsonStatements.push(...jsonSetTableSchemas);
15910
16652
  jsonStatements.push(...jsonRenameTables);
@@ -15924,6 +16666,8 @@ var init_snapshotsDiffer = __esm({
15924
16666
  jsonStatements.push(...jsonAlteredCompositePKs);
15925
16667
  jsonStatements.push(...jsonAddedUniqueConstraints);
15926
16668
  jsonStatements.push(...jsonAlteredUniqueConstraints);
16669
+ jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
16670
+ jsonStatements.push(...createViews);
15927
16671
  jsonStatements.push(...dropEnums);
15928
16672
  jsonStatements.push(...dropSequences);
15929
16673
  jsonStatements.push(...dropSchemas);
@@ -15944,7 +16688,17 @@ var init_snapshotsDiffer = __esm({
15944
16688
  }
15945
16689
  return true;
15946
16690
  });
15947
- const sqlStatements = fromJson(filteredJsonStatements, "postgresql");
16691
+ const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
16692
+ if (st.type === "alter_type_add_value") {
16693
+ if (jsonStatements.find(
16694
+ (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.schema === st.schema
16695
+ )) {
16696
+ return false;
16697
+ }
16698
+ }
16699
+ return true;
16700
+ });
16701
+ const sqlStatements = fromJson(filteredEnumsJsonStatements, "postgresql");
15948
16702
  const uniqueSqlStatements = [];
15949
16703
  sqlStatements.forEach((ss) => {
15950
16704
  if (!uniqueSqlStatements.includes(ss)) {
@@ -15960,12 +16714,12 @@ var init_snapshotsDiffer = __esm({
15960
16714
  });
15961
16715
  const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
15962
16716
  return {
15963
- statements: filteredJsonStatements,
16717
+ statements: filteredEnumsJsonStatements,
15964
16718
  sqlStatements: uniqueSqlStatements,
15965
16719
  _meta
15966
16720
  };
15967
16721
  };
15968
- applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
16722
+ applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
15969
16723
  for (const tableName in json1.tables) {
15970
16724
  const table4 = json1.tables[tableName];
15971
16725
  for (const indexName2 in table4.indexes) {
@@ -16062,7 +16816,33 @@ var init_snapshotsDiffer = __esm({
16062
16816
  return [tableKey2, tableValue];
16063
16817
  }
16064
16818
  );
16065
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
16819
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
16820
+ const {
16821
+ created: createdViews,
16822
+ deleted: deletedViews,
16823
+ renamed: renamedViews
16824
+ // renamed or moved
16825
+ } = await viewsResolver2({
16826
+ created: viewsDiff.added,
16827
+ deleted: viewsDiff.deleted
16828
+ });
16829
+ const renamesViewDic = {};
16830
+ renamedViews.forEach((it) => {
16831
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
16832
+ });
16833
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
16834
+ viewsPatchedSnap1.views = mapEntries(
16835
+ viewsPatchedSnap1.views,
16836
+ (viewKey, viewValue) => {
16837
+ const rename = renamesViewDic[viewValue.name];
16838
+ if (rename) {
16839
+ viewValue.name = rename.to;
16840
+ viewKey = rename.to;
16841
+ }
16842
+ return [viewKey, viewValue];
16843
+ }
16844
+ );
16845
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16066
16846
  const typedResult = diffResultSchemeMysql.parse(diffResult);
16067
16847
  const jsonStatements = [];
16068
16848
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -16244,10 +17024,68 @@ var init_snapshotsDiffer = __esm({
16244
17024
  curFull.internal
16245
17025
  );
16246
17026
  });
17027
+ const createViews = [];
17028
+ const dropViews = [];
17029
+ const renameViews = [];
17030
+ const alterViews = [];
17031
+ createViews.push(
17032
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17033
+ return prepareMySqlCreateViewJson(
17034
+ it.name,
17035
+ it.definition,
17036
+ it.meta
17037
+ );
17038
+ })
17039
+ );
17040
+ dropViews.push(
17041
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17042
+ return prepareDropViewJson(it.name);
17043
+ })
17044
+ );
17045
+ renameViews.push(
17046
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
17047
+ return prepareRenameViewJson(it.to.name, it.from.name);
17048
+ })
17049
+ );
17050
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17051
+ for (const alteredView of alteredViews) {
17052
+ const { definition, meta } = json22.views[alteredView.name];
17053
+ if (alteredView.alteredExisting) {
17054
+ dropViews.push(prepareDropViewJson(alteredView.name));
17055
+ createViews.push(
17056
+ prepareMySqlCreateViewJson(
17057
+ alteredView.name,
17058
+ definition,
17059
+ meta
17060
+ )
17061
+ );
17062
+ continue;
17063
+ }
17064
+ if (alteredView.alteredDefinition && action !== "push") {
17065
+ createViews.push(
17066
+ prepareMySqlCreateViewJson(
17067
+ alteredView.name,
17068
+ definition,
17069
+ meta,
17070
+ true
17071
+ )
17072
+ );
17073
+ continue;
17074
+ }
17075
+ if (alteredView.alteredMeta) {
17076
+ const view4 = curFull["views"][alteredView.name];
17077
+ alterViews.push(
17078
+ prepareMySqlAlterView(view4)
17079
+ );
17080
+ }
17081
+ }
16247
17082
  jsonStatements.push(...jsonMySqlCreateTables);
16248
17083
  jsonStatements.push(...jsonDropTables);
16249
17084
  jsonStatements.push(...jsonRenameTables);
16250
17085
  jsonStatements.push(...jsonRenameColumnsStatements);
17086
+ jsonStatements.push(...dropViews);
17087
+ jsonStatements.push(...renameViews);
17088
+ jsonStatements.push(...alterViews);
16251
17089
  jsonStatements.push(...jsonDeletedUniqueConstraints);
16252
17090
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
16253
17091
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
@@ -16264,6 +17102,7 @@ var init_snapshotsDiffer = __esm({
16264
17102
  jsonStatements.push(...jsonDropColumnsStatemets);
16265
17103
  jsonStatements.push(...jsonAlteredCompositePKs);
16266
17104
  jsonStatements.push(...jsonAddedUniqueConstraints);
17105
+ jsonStatements.push(...createViews);
16267
17106
  jsonStatements.push(...jsonAlteredUniqueConstraints);
16268
17107
  const sqlStatements = fromJson(jsonStatements, "mysql");
16269
17108
  const uniqueSqlStatements = [];
@@ -16282,7 +17121,7 @@ var init_snapshotsDiffer = __esm({
16282
17121
  _meta
16283
17122
  };
16284
17123
  };
16285
- applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
17124
+ applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16286
17125
  const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
16287
17126
  const {
16288
17127
  created: createdTables,
@@ -16352,7 +17191,32 @@ var init_snapshotsDiffer = __esm({
16352
17191
  return [tableKey2, tableValue];
16353
17192
  }
16354
17193
  );
16355
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17194
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17195
+ const {
17196
+ created: createdViews,
17197
+ deleted: deletedViews,
17198
+ renamed: renamedViews
17199
+ // renamed or moved
17200
+ } = await viewsResolver2({
17201
+ created: viewsDiff.added,
17202
+ deleted: viewsDiff.deleted
17203
+ });
17204
+ const renamesViewDic = {};
17205
+ renamedViews.forEach((it) => {
17206
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17207
+ });
17208
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17209
+ viewsPatchedSnap1.views = mapEntries(
17210
+ viewsPatchedSnap1.views,
17211
+ (viewKey, viewValue) => {
17212
+ const rename = renamesViewDic[viewValue.name];
17213
+ if (rename) {
17214
+ viewValue.name = rename.to;
17215
+ }
17216
+ return [viewKey, viewValue];
17217
+ }
17218
+ );
17219
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16356
17220
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
16357
17221
  const tablesMap = {};
16358
17222
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -16531,6 +17395,44 @@ var init_snapshotsDiffer = __esm({
16531
17395
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
16532
17396
  (t) => t.type === "delete_reference"
16533
17397
  );
17398
+ const createViews = [];
17399
+ const dropViews = [];
17400
+ createViews.push(
17401
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17402
+ return prepareSqliteCreateViewJson(
17403
+ it.name,
17404
+ it.definition
17405
+ );
17406
+ })
17407
+ );
17408
+ dropViews.push(
17409
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17410
+ return prepareDropViewJson(it.name);
17411
+ })
17412
+ );
17413
+ dropViews.push(
17414
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17415
+ return prepareDropViewJson(it.from.name);
17416
+ })
17417
+ );
17418
+ createViews.push(
17419
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17420
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
17421
+ })
17422
+ );
17423
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17424
+ for (const alteredView of alteredViews) {
17425
+ const { definition } = json22.views[alteredView.name];
17426
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
17427
+ dropViews.push(prepareDropViewJson(alteredView.name));
17428
+ createViews.push(
17429
+ prepareSqliteCreateViewJson(
17430
+ alteredView.name,
17431
+ definition
17432
+ )
17433
+ );
17434
+ }
17435
+ }
16534
17436
  const jsonStatements = [];
16535
17437
  jsonStatements.push(...jsonCreateTables);
16536
17438
  jsonStatements.push(...jsonDropTables);
@@ -16548,6 +17450,8 @@ var init_snapshotsDiffer = __esm({
16548
17450
  jsonStatements.push(...jsonDropColumnsStatemets);
16549
17451
  jsonStatements.push(...jsonAlteredCompositePKs);
16550
17452
  jsonStatements.push(...jsonAlteredUniqueConstraints);
17453
+ jsonStatements.push(...dropViews);
17454
+ jsonStatements.push(...createViews);
16551
17455
  const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json22, action);
16552
17456
  const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
16553
17457
  const uniqueSqlStatements = [];
@@ -16566,7 +17470,7 @@ var init_snapshotsDiffer = __esm({
16566
17470
  _meta
16567
17471
  };
16568
17472
  };
16569
- applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
17473
+ applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16570
17474
  const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
16571
17475
  const {
16572
17476
  created: createdTables,
@@ -16636,7 +17540,32 @@ var init_snapshotsDiffer = __esm({
16636
17540
  return [tableKey2, tableValue];
16637
17541
  }
16638
17542
  );
16639
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17543
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17544
+ const {
17545
+ created: createdViews,
17546
+ deleted: deletedViews,
17547
+ renamed: renamedViews
17548
+ // renamed or moved
17549
+ } = await viewsResolver2({
17550
+ created: viewsDiff.added,
17551
+ deleted: viewsDiff.deleted
17552
+ });
17553
+ const renamesViewDic = {};
17554
+ renamedViews.forEach((it) => {
17555
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17556
+ });
17557
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17558
+ viewsPatchedSnap1.views = mapEntries(
17559
+ viewsPatchedSnap1.views,
17560
+ (viewKey, viewValue) => {
17561
+ const rename = renamesViewDic[viewValue.name];
17562
+ if (rename) {
17563
+ viewValue.name = rename.to;
17564
+ }
17565
+ return [viewKey, viewValue];
17566
+ }
17567
+ );
17568
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16640
17569
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
16641
17570
  const tablesMap = {};
16642
17571
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -16820,6 +17749,44 @@ var init_snapshotsDiffer = __esm({
16820
17749
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
16821
17750
  (t) => t.type === "delete_reference"
16822
17751
  );
17752
+ const createViews = [];
17753
+ const dropViews = [];
17754
+ createViews.push(
17755
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17756
+ return prepareSqliteCreateViewJson(
17757
+ it.name,
17758
+ it.definition
17759
+ );
17760
+ })
17761
+ );
17762
+ dropViews.push(
17763
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17764
+ return prepareDropViewJson(it.name);
17765
+ })
17766
+ );
17767
+ dropViews.push(
17768
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17769
+ return prepareDropViewJson(it.from.name);
17770
+ })
17771
+ );
17772
+ createViews.push(
17773
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17774
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
17775
+ })
17776
+ );
17777
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17778
+ for (const alteredView of alteredViews) {
17779
+ const { definition } = json22.views[alteredView.name];
17780
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
17781
+ dropViews.push(prepareDropViewJson(alteredView.name));
17782
+ createViews.push(
17783
+ prepareSqliteCreateViewJson(
17784
+ alteredView.name,
17785
+ definition
17786
+ )
17787
+ );
17788
+ }
17789
+ }
16823
17790
  const jsonStatements = [];
16824
17791
  jsonStatements.push(...jsonCreateTables);
16825
17792
  jsonStatements.push(...jsonDropTables);
@@ -16833,6 +17800,8 @@ var init_snapshotsDiffer = __esm({
16833
17800
  jsonStatements.push(...jsonAddColumnsStatemets);
16834
17801
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
16835
17802
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
17803
+ jsonStatements.push(...dropViews);
17804
+ jsonStatements.push(...createViews);
16836
17805
  jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
16837
17806
  jsonStatements.push(...jsonDropColumnsStatemets);
16838
17807
  jsonStatements.push(...jsonAlteredCompositePKs);
@@ -16995,7 +17964,7 @@ var init_outputs = __esm({
16995
17964
  });
16996
17965
 
16997
17966
  // src/cli/commands/migrate.ts
16998
- var import_hanji2, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
17967
+ var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
16999
17968
  var init_migrate = __esm({
17000
17969
  "src/cli/commands/migrate.ts"() {
17001
17970
  "use strict";
@@ -17040,6 +18009,60 @@ var init_migrate = __esm({
17040
18009
  throw e;
17041
18010
  }
17042
18011
  };
18012
+ viewsResolver = async (input) => {
18013
+ try {
18014
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18015
+ input.created,
18016
+ input.deleted,
18017
+ "view"
18018
+ );
18019
+ return {
18020
+ created,
18021
+ deleted,
18022
+ moved,
18023
+ renamed
18024
+ };
18025
+ } catch (e) {
18026
+ console.error(e);
18027
+ throw e;
18028
+ }
18029
+ };
18030
+ mySqlViewsResolver = async (input) => {
18031
+ try {
18032
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18033
+ input.created,
18034
+ input.deleted,
18035
+ "view"
18036
+ );
18037
+ return {
18038
+ created,
18039
+ deleted,
18040
+ moved,
18041
+ renamed
18042
+ };
18043
+ } catch (e) {
18044
+ console.error(e);
18045
+ throw e;
18046
+ }
18047
+ };
18048
+ sqliteViewsResolver = async (input) => {
18049
+ try {
18050
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18051
+ input.created,
18052
+ input.deleted,
18053
+ "view"
18054
+ );
18055
+ return {
18056
+ created,
18057
+ deleted,
18058
+ moved,
18059
+ renamed
18060
+ };
18061
+ } catch (e) {
18062
+ console.error(e);
18063
+ throw e;
18064
+ }
18065
+ };
17043
18066
  sequencesResolver = async (input) => {
17044
18067
  try {
17045
18068
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -19004,7 +20027,7 @@ var version;
19004
20027
  var init_version = __esm({
19005
20028
  "../drizzle-orm/dist/version.js"() {
19006
20029
  "use strict";
19007
- version = "0.34.0";
20030
+ version = "0.34.1";
19008
20031
  }
19009
20032
  });
19010
20033
 
@@ -19115,7 +20138,7 @@ function fillPlaceholders(params, values) {
19115
20138
  return p;
19116
20139
  });
19117
20140
  }
19118
- var _a20, FakePrimitiveParam, _a21, StringChunk, _a22, _SQL, SQL, _a23, Name, noopDecoder, noopEncoder, noopMapper, _a24, Param, _a25, Placeholder, _a26, _b10, View;
20141
+ var _a20, FakePrimitiveParam, _a21, StringChunk, _a22, _SQL, SQL, _a23, Name, noopDecoder, noopEncoder, noopMapper, _a24, Param, _a25, Placeholder, _a26, _b10, View3;
19119
20142
  var init_sql = __esm({
19120
20143
  "../drizzle-orm/dist/sql/sql.js"() {
19121
20144
  "use strict";
@@ -19218,7 +20241,7 @@ var init_sql = __esm({
19218
20241
  }
19219
20242
  return { sql: escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), params: [] };
19220
20243
  }
19221
- if (is(chunk, View)) {
20244
+ if (is(chunk, View3)) {
19222
20245
  const schemaName = chunk[ViewBaseConfig].schema;
19223
20246
  const viewName = chunk[ViewBaseConfig].name;
19224
20247
  return {
@@ -19437,7 +20460,7 @@ var init_sql = __esm({
19437
20460
  };
19438
20461
  __publicField(Placeholder, _a25, "Placeholder");
19439
20462
  _b10 = entityKind, _a26 = ViewBaseConfig;
19440
- View = class {
20463
+ View3 = class {
19441
20464
  constructor({ name: name2, schema: schema4, selectedFields, query }) {
19442
20465
  /** @internal */
19443
20466
  __publicField(this, _a26);
@@ -19455,7 +20478,7 @@ var init_sql = __esm({
19455
20478
  return new SQL([this]);
19456
20479
  }
19457
20480
  };
19458
- __publicField(View, _b10, "View");
20481
+ __publicField(View3, _b10, "View");
19459
20482
  Column2.prototype.getSQL = function() {
19460
20483
  return new SQL([this]);
19461
20484
  };
@@ -19606,7 +20629,7 @@ var init_errors = __esm({
19606
20629
 
19607
20630
  // ../drizzle-orm/dist/sql/expressions/conditions.js
19608
20631
  function bindIfParam(value, column4) {
19609
- if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table) && !is(value, View)) {
20632
+ if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table) && !is(value, View3)) {
19610
20633
  return new Param(value, column4);
19611
20634
  }
19612
20635
  return value;
@@ -19977,7 +21000,7 @@ function getTableColumns(table4) {
19977
21000
  return table4[Table.Symbol.Columns];
19978
21001
  }
19979
21002
  function getTableLikeName(table4) {
19980
- return is(table4, Subquery) ? table4._.alias : is(table4, View) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : table4[Table.Symbol.IsAlias] ? table4[Table.Symbol.Name] : table4[Table.Symbol.BaseName];
21003
+ return is(table4, Subquery) ? table4._.alias : is(table4, View3) ? table4[ViewBaseConfig].name : is(table4, SQL) ? void 0 : table4[Table.Symbol.IsAlias] ? table4[Table.Symbol.Name] : table4[Table.Symbol.BaseName];
19981
21004
  }
19982
21005
  function getColumnNameAndConfig(a, b) {
19983
21006
  return {
@@ -20895,23 +21918,23 @@ function hexToBytes(hex) {
20895
21918
  }
20896
21919
  function bytesToFloat64(bytes, offset) {
20897
21920
  const buffer = new ArrayBuffer(8);
20898
- const view = new DataView(buffer);
21921
+ const view4 = new DataView(buffer);
20899
21922
  for (let i = 0; i < 8; i++) {
20900
- view.setUint8(i, bytes[offset + i]);
21923
+ view4.setUint8(i, bytes[offset + i]);
20901
21924
  }
20902
- return view.getFloat64(0, true);
21925
+ return view4.getFloat64(0, true);
20903
21926
  }
20904
21927
  function parseEWKB(hex) {
20905
21928
  const bytes = hexToBytes(hex);
20906
21929
  let offset = 0;
20907
21930
  const byteOrder = bytes[offset];
20908
21931
  offset += 1;
20909
- const view = new DataView(bytes.buffer);
20910
- const geomType = view.getUint32(offset, byteOrder === 1);
21932
+ const view4 = new DataView(bytes.buffer);
21933
+ const geomType = view4.getUint32(offset, byteOrder === 1);
20911
21934
  offset += 4;
20912
21935
  let _srid;
20913
21936
  if (geomType & 536870912) {
20914
- _srid = view.getUint32(offset, byteOrder === 1);
21937
+ _srid = view4.getUint32(offset, byteOrder === 1);
20915
21938
  offset += 4;
20916
21939
  }
20917
21940
  if ((geomType & 65535) === 1) {
@@ -22134,7 +23157,7 @@ __export(dist_exports, {
22134
23157
  Table: () => Table,
22135
23158
  TableAliasProxyHandler: () => TableAliasProxyHandler,
22136
23159
  TransactionRollbackError: () => TransactionRollbackError,
22137
- View: () => View,
23160
+ View: () => View3,
22138
23161
  ViewBaseConfig: () => ViewBaseConfig,
22139
23162
  WithSubquery: () => WithSubquery,
22140
23163
  aliasedRelation: () => aliasedRelation,
@@ -22568,7 +23591,7 @@ var init_view_base = __esm({
22568
23591
  "use strict";
22569
23592
  init_entity();
22570
23593
  init_sql();
22571
- PgViewBase = class extends (_b99 = View, _a128 = entityKind, _b99) {
23594
+ PgViewBase = class extends (_b99 = View3, _a128 = entityKind, _b99) {
22572
23595
  };
22573
23596
  __publicField(PgViewBase, _a128, "PgViewBase");
22574
23597
  }
@@ -22791,7 +23814,7 @@ var init_dialect = __esm({
22791
23814
  joinsArray.push(
22792
23815
  sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
22793
23816
  );
22794
- } else if (is(table22, View)) {
23817
+ } else if (is(table22, View3)) {
22795
23818
  const viewName = table22[ViewBaseConfig].name;
22796
23819
  const viewSchema = table22[ViewBaseConfig].schema;
22797
23820
  const origViewName = table22[ViewBaseConfig].originalName;
@@ -22928,10 +23951,10 @@ var init_dialect = __esm({
22928
23951
  const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
22929
23952
  return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
22930
23953
  }
22931
- buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
23954
+ buildRefreshMaterializedViewQuery({ view: view4, concurrently, withNoData }) {
22932
23955
  const concurrentlySql = concurrently ? sql` concurrently` : void 0;
22933
23956
  const withNoDataSql = withNoData ? sql` with no data` : void 0;
22934
- return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
23957
+ return sql`refresh materialized view${concurrentlySql} ${view4}${withNoDataSql}`;
22935
23958
  }
22936
23959
  prepareTyping(encoder) {
22937
23960
  if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
@@ -23705,7 +24728,7 @@ var init_selection_proxy = __esm({
23705
24728
  if (typeof prop === "symbol") {
23706
24729
  return subquery[prop];
23707
24730
  }
23708
- const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
24731
+ const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View3) ? subquery[ViewBaseConfig].selectedFields : subquery;
23709
24732
  const value = columns[prop];
23710
24733
  if (is(value, SQL.Aliased)) {
23711
24734
  if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
@@ -24187,7 +25210,7 @@ var init_select2 = __esm({
24187
25210
  };
24188
25211
  }
24189
25212
  if (typeof tableName === "string" && !is(table4, SQL)) {
24190
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
25213
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
24191
25214
  this.config.fields[tableName] = selection;
24192
25215
  }
24193
25216
  }
@@ -24606,7 +25629,7 @@ var init_refresh_materialized_view = __esm({
24606
25629
  init_query_promise();
24607
25630
  init_tracing();
24608
25631
  PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
24609
- constructor(view, session, dialect4) {
25632
+ constructor(view4, session, dialect4) {
24610
25633
  super();
24611
25634
  __publicField(this, "config");
24612
25635
  __publicField(this, "execute", (placeholderValues) => {
@@ -24616,7 +25639,7 @@ var init_refresh_materialized_view = __esm({
24616
25639
  });
24617
25640
  this.session = session;
24618
25641
  this.dialect = dialect4;
24619
- this.config = { view };
25642
+ this.config = { view: view4 };
24620
25643
  }
24621
25644
  concurrently() {
24622
25645
  if (this.config.withNoData !== void 0) {
@@ -25247,8 +26270,8 @@ var init_db = __esm({
25247
26270
  delete(table4) {
25248
26271
  return new PgDeleteBase(table4, this.session, this.dialect);
25249
26272
  }
25250
- refreshMaterializedView(view) {
25251
- return new PgRefreshMaterializedView(view, this.session, this.dialect);
26273
+ refreshMaterializedView(view4) {
26274
+ return new PgRefreshMaterializedView(view4, this.session, this.dialect);
25252
26275
  }
25253
26276
  execute(query) {
25254
26277
  const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
@@ -25438,7 +26461,13 @@ function pgMaterializedViewWithSchema(name2, selection, schema4) {
25438
26461
  }
25439
26462
  return new MaterializedViewBuilder(name2, schema4);
25440
26463
  }
25441
- var _a148, DefaultViewBuilderCore, _a149, _b107, ViewBuilder, _a150, _b108, ManualViewBuilder, _a151, MaterializedViewBuilderCore, _a152, _b109, MaterializedViewBuilder, _a153, _b110, ManualMaterializedViewBuilder, _a154, _b111, _c4, PgView, PgMaterializedViewConfig, _a155, _b112, _c5, PgMaterializedView;
26464
+ function isPgView(obj) {
26465
+ return is(obj, PgView2);
26466
+ }
26467
+ function isPgMaterializedView(obj) {
26468
+ return is(obj, PgMaterializedView);
26469
+ }
26470
+ var _a148, DefaultViewBuilderCore, _a149, _b107, ViewBuilder, _a150, _b108, ManualViewBuilder, _a151, MaterializedViewBuilderCore, _a152, _b109, MaterializedViewBuilder, _a153, _b110, ManualMaterializedViewBuilder, _a154, _b111, _c4, PgView2, PgMaterializedViewConfig, _a155, _b112, _c5, PgMaterializedView;
25442
26471
  var init_view = __esm({
25443
26472
  "../drizzle-orm/dist/pg-core/view.js"() {
25444
26473
  "use strict";
@@ -25475,7 +26504,7 @@ var init_view = __esm({
25475
26504
  });
25476
26505
  const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
25477
26506
  return new Proxy(
25478
- new PgView({
26507
+ new PgView2({
25479
26508
  pgConfig: this.config,
25480
26509
  config: {
25481
26510
  name: this.name,
@@ -25497,7 +26526,7 @@ var init_view = __esm({
25497
26526
  }
25498
26527
  existing() {
25499
26528
  return new Proxy(
25500
- new PgView({
26529
+ new PgView2({
25501
26530
  pgConfig: void 0,
25502
26531
  config: {
25503
26532
  name: this.name,
@@ -25516,7 +26545,7 @@ var init_view = __esm({
25516
26545
  }
25517
26546
  as(query) {
25518
26547
  return new Proxy(
25519
- new PgView({
26548
+ new PgView2({
25520
26549
  pgConfig: this.config,
25521
26550
  config: {
25522
26551
  name: this.name,
@@ -25601,7 +26630,12 @@ var init_view = __esm({
25601
26630
  existing() {
25602
26631
  return new Proxy(
25603
26632
  new PgMaterializedView({
25604
- pgConfig: void 0,
26633
+ pgConfig: {
26634
+ tablespace: this.config.tablespace,
26635
+ using: this.config.using,
26636
+ with: this.config.with,
26637
+ withNoData: this.config.withNoData
26638
+ },
25605
26639
  config: {
25606
26640
  name: this.name,
25607
26641
  schema: this.schema,
@@ -25620,7 +26654,12 @@ var init_view = __esm({
25620
26654
  as(query) {
25621
26655
  return new Proxy(
25622
26656
  new PgMaterializedView({
25623
- pgConfig: void 0,
26657
+ pgConfig: {
26658
+ tablespace: this.config.tablespace,
26659
+ using: this.config.using,
26660
+ with: this.config.with,
26661
+ withNoData: this.config.withNoData
26662
+ },
25624
26663
  config: {
25625
26664
  name: this.name,
25626
26665
  schema: this.schema,
@@ -25638,7 +26677,7 @@ var init_view = __esm({
25638
26677
  }
25639
26678
  };
25640
26679
  __publicField(ManualMaterializedViewBuilder, _a153, "PgManualMaterializedViewBuilder");
25641
- PgView = class extends (_c4 = PgViewBase, _b111 = entityKind, _a154 = PgViewConfig, _c4) {
26680
+ PgView2 = class extends (_c4 = PgViewBase, _b111 = entityKind, _a154 = PgViewConfig, _c4) {
25642
26681
  constructor({ pgConfig, config }) {
25643
26682
  super(config);
25644
26683
  __publicField(this, _a154);
@@ -25649,7 +26688,7 @@ var init_view = __esm({
25649
26688
  }
25650
26689
  }
25651
26690
  };
25652
- __publicField(PgView, _b111, "PgView");
26691
+ __publicField(PgView2, _b111, "PgView");
25653
26692
  PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
25654
26693
  PgMaterializedView = class extends (_c5 = PgViewBase, _b112 = entityKind, _a155 = PgMaterializedViewConfig, _c5) {
25655
26694
  constructor({ pgConfig, config }) {
@@ -25844,17 +26883,32 @@ function getTableConfig(table4) {
25844
26883
  schema: schema4
25845
26884
  };
25846
26885
  }
26886
+ function getViewConfig(view4) {
26887
+ return {
26888
+ ...view4[ViewBaseConfig],
26889
+ ...view4[PgViewConfig]
26890
+ };
26891
+ }
26892
+ function getMaterializedViewConfig(view4) {
26893
+ return {
26894
+ ...view4[ViewBaseConfig],
26895
+ ...view4[PgMaterializedViewConfig]
26896
+ };
26897
+ }
25847
26898
  var init_utils4 = __esm({
25848
26899
  "../drizzle-orm/dist/pg-core/utils.js"() {
25849
26900
  "use strict";
25850
26901
  init_entity();
25851
26902
  init_table2();
25852
26903
  init_table();
26904
+ init_view_common();
25853
26905
  init_checks();
25854
26906
  init_foreign_keys();
25855
26907
  init_indexes();
25856
26908
  init_primary_keys();
25857
26909
  init_unique_constraint();
26910
+ init_view_common2();
26911
+ init_view();
25858
26912
  }
25859
26913
  });
25860
26914
 
@@ -25929,7 +26983,7 @@ function buildArrayString(array, sqlType) {
25929
26983
  }).join(",");
25930
26984
  return `{${values}}`;
25931
26985
  }
25932
- var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn;
26986
+ var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery;
25933
26987
  var init_pgSerializer = __esm({
25934
26988
  "src/serializer/pgSerializer.ts"() {
25935
26989
  "use strict";
@@ -25944,22 +26998,14 @@ var init_pgSerializer = __esm({
25944
26998
  indexName = (tableName, columns) => {
25945
26999
  return `${tableName}_${columns.join("_")}_index`;
25946
27000
  };
25947
- generatePgSnapshot = (tables, enums, schemas, sequences, casing2, schemaFilter) => {
27001
+ generatePgSnapshot = (tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter) => {
25948
27002
  const dialect4 = new PgDialect({ casing: casing2 });
25949
27003
  const result = {};
27004
+ const resultViews = {};
25950
27005
  const sequencesToReturn = {};
25951
27006
  const indexesInSchema = {};
25952
27007
  for (const table4 of tables) {
25953
- const {
25954
- name: tableName,
25955
- columns,
25956
- indexes,
25957
- foreignKeys,
25958
- checks,
25959
- schema: schema4,
25960
- primaryKeys,
25961
- uniqueConstraints
25962
- } = getTableConfig(table4);
27008
+ const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema4, primaryKeys, uniqueConstraints } = getTableConfig(table4);
25963
27009
  if (schemaFilter && !schemaFilter.includes(schema4 ?? "public")) {
25964
27010
  continue;
25965
27011
  }
@@ -26015,7 +27061,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26015
27061
  column4.uniqueName
26016
27062
  )} on the ${source_default.underline.blue(
26017
27063
  name2
26018
- )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
27064
+ )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
26019
27065
  existingUnique.columns.join(",")
26020
27066
  )} columns
26021
27067
  `)}`
@@ -26036,9 +27082,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26036
27082
  columnToSet.default = `'${column4.default}'`;
26037
27083
  } else {
26038
27084
  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
26039
- columnToSet.default = `'${JSON.stringify(
26040
- column4.default
26041
- )}'::${sqlTypeLowered}`;
27085
+ columnToSet.default = `'${JSON.stringify(column4.default)}'::${sqlTypeLowered}`;
26042
27086
  } else if (column4.default instanceof Date) {
26043
27087
  if (sqlTypeLowered === "date") {
26044
27088
  columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
@@ -26048,10 +27092,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26048
27092
  columnToSet.default = `'${column4.default.toISOString()}'`;
26049
27093
  }
26050
27094
  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column4.default)) {
26051
- columnToSet.default = `'${buildArrayString(
26052
- column4.default,
26053
- sqlTypeLowered
26054
- )}'`;
27095
+ columnToSet.default = `'${buildArrayString(column4.default, sqlTypeLowered)}'`;
26055
27096
  } else {
26056
27097
  columnToSet.default = column4.default;
26057
27098
  }
@@ -26081,17 +27122,13 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26081
27122
  if (typeof existingUnique !== "undefined") {
26082
27123
  console.log(
26083
27124
  `
26084
- ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
26085
- tableName
26086
- )} table.
26087
- The unique constraint ${source_default.underline.blue(
26088
- name2
26089
- )} on the ${source_default.underline.blue(
26090
- columnNames.join(",")
26091
- )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
26092
- existingUnique.columns.join(",")
26093
- )} columns
26094
- `)}`
27125
+ ${withStyle.errorWarning(
27126
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table.
27127
+ The unique constraint ${source_default.underline.blue(name2)} on the ${source_default.underline.blue(
27128
+ columnNames.join(",")
27129
+ )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
27130
+ `
27131
+ )}`
26095
27132
  );
26096
27133
  process.exit(1);
26097
27134
  }
@@ -26144,9 +27181,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26144
27181
  console.log(
26145
27182
  `
26146
27183
  ${withStyle.errorWarning(
26147
- `Please specify an index name in ${getTableName(
26148
- value.config.table
26149
- )} 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.`
27184
+ `Please specify an index name in ${getTableName(value.config.table)} table that has "${dialect4.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
26150
27185
  )}`
26151
27186
  );
26152
27187
  process.exit(1);
@@ -26164,9 +27199,7 @@ ${withStyle.errorWarning(
26164
27199
  tableName
26165
27200
  )} table with the ${source_default.blueBright(
26166
27201
  "vector"
26167
- )} 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(
26168
- ", "
26169
- )}].
27202
+ )} 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(", ")}].
26170
27203
 
26171
27204
  You can specify it using current syntax: ${source_default.underline(
26172
27205
  `index("${value.config.name}").using("${value.config.method}", table.${name3}.op("${vectorOps[0]}"))`
@@ -26207,9 +27240,7 @@ You can check the "pg_vector" docs for more info: https://github.com/pgvector/pg
26207
27240
  console.log(
26208
27241
  `
26209
27242
  ${withStyle.errorWarning(
26210
- `We've found duplicated index name across ${source_default.underline.blue(
26211
- schema4 ?? "public"
26212
- )} schema. Please rename your index in either the ${source_default.underline.blue(
27243
+ `We've found duplicated index name across ${source_default.underline.blue(schema4 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
26213
27244
  tableName
26214
27245
  )} table or the table with the duplicated index name`
26215
27246
  )}`
@@ -26262,6 +27293,136 @@ ${withStyle.errorWarning(
26262
27293
  } else {
26263
27294
  }
26264
27295
  }
27296
+ const combinedViews = [...views, ...matViews];
27297
+ for (const view4 of combinedViews) {
27298
+ let viewName;
27299
+ let schema4;
27300
+ let query;
27301
+ let selectedFields;
27302
+ let isExisting;
27303
+ let withOption;
27304
+ let tablespace;
27305
+ let using;
27306
+ let withNoData;
27307
+ let materialized = false;
27308
+ if (is(view4, PgView2)) {
27309
+ ({ name: viewName, schema: schema4, query, selectedFields, isExisting, with: withOption } = getViewConfig(view4));
27310
+ } else {
27311
+ ({ name: viewName, schema: schema4, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = getMaterializedViewConfig(view4));
27312
+ materialized = true;
27313
+ }
27314
+ const viewSchema = schema4 ?? "public";
27315
+ const viewKey = `${viewSchema}.${viewName}`;
27316
+ const columnsObject = {};
27317
+ const uniqueConstraintObject = {};
27318
+ const existingView = resultViews[viewKey];
27319
+ if (typeof existingView !== "undefined") {
27320
+ console.log(
27321
+ `
27322
+ ${withStyle.errorWarning(
27323
+ `We've found duplicated view name across ${source_default.underline.blue(schema4 ?? "public")} schema. Please rename your view`
27324
+ )}`
27325
+ );
27326
+ process.exit(1);
27327
+ }
27328
+ for (const key in selectedFields) {
27329
+ if (is(selectedFields[key], PgColumn)) {
27330
+ const column4 = selectedFields[key];
27331
+ const notNull = column4.notNull;
27332
+ const primaryKey = column4.primary;
27333
+ const sqlTypeLowered = column4.getSQLType().toLowerCase();
27334
+ const typeSchema = is(column4, PgEnumColumn) ? column4.enum.schema || "public" : void 0;
27335
+ const generated = column4.generated;
27336
+ const identity = column4.generatedIdentity;
27337
+ const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
27338
+ const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column4.columnType) : "1");
27339
+ const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column4.getSQLType()));
27340
+ const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
27341
+ const cache = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
27342
+ const columnToSet = {
27343
+ name: column4.name,
27344
+ type: column4.getSQLType(),
27345
+ typeSchema,
27346
+ primaryKey,
27347
+ notNull,
27348
+ generated: generated ? {
27349
+ as: is(generated.as, SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
27350
+ type: "stored"
27351
+ } : void 0,
27352
+ identity: identity ? {
27353
+ type: identity.type,
27354
+ name: identity.sequenceName ?? `${viewName}_${column4.name}_seq`,
27355
+ schema: schema4 ?? "public",
27356
+ increment,
27357
+ startWith,
27358
+ minValue,
27359
+ maxValue,
27360
+ cache,
27361
+ cycle: identity?.sequenceOptions?.cycle ?? false
27362
+ } : void 0
27363
+ };
27364
+ if (column4.isUnique) {
27365
+ const existingUnique = uniqueConstraintObject[column4.uniqueName];
27366
+ if (typeof existingUnique !== "undefined") {
27367
+ console.log(
27368
+ `
27369
+ ${withStyle.errorWarning(
27370
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table.
27371
+ The unique constraint ${source_default.underline.blue(column4.uniqueName)} on the ${source_default.underline.blue(
27372
+ column4.name
27373
+ )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
27374
+ `
27375
+ )}`
27376
+ );
27377
+ process.exit(1);
27378
+ }
27379
+ uniqueConstraintObject[column4.uniqueName] = {
27380
+ name: column4.uniqueName,
27381
+ nullsNotDistinct: column4.uniqueType === "not distinct",
27382
+ columns: [columnToSet.name]
27383
+ };
27384
+ }
27385
+ if (column4.default !== void 0) {
27386
+ if (is(column4.default, SQL)) {
27387
+ columnToSet.default = sqlToStr(column4.default, casing2);
27388
+ } else {
27389
+ if (typeof column4.default === "string") {
27390
+ columnToSet.default = `'${column4.default}'`;
27391
+ } else {
27392
+ if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
27393
+ columnToSet.default = `'${JSON.stringify(column4.default)}'::${sqlTypeLowered}`;
27394
+ } else if (column4.default instanceof Date) {
27395
+ if (sqlTypeLowered === "date") {
27396
+ columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
27397
+ } else if (sqlTypeLowered === "timestamp") {
27398
+ columnToSet.default = `'${column4.default.toISOString().replace("T", " ").slice(0, 23)}'`;
27399
+ } else {
27400
+ columnToSet.default = `'${column4.default.toISOString()}'`;
27401
+ }
27402
+ } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column4.default)) {
27403
+ columnToSet.default = `'${buildArrayString(column4.default, sqlTypeLowered)}'`;
27404
+ } else {
27405
+ columnToSet.default = column4.default;
27406
+ }
27407
+ }
27408
+ }
27409
+ }
27410
+ columnsObject[column4.name] = columnToSet;
27411
+ }
27412
+ }
27413
+ resultViews[viewKey] = {
27414
+ columns: columnsObject,
27415
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
27416
+ name: viewName,
27417
+ schema: viewSchema,
27418
+ isExisting,
27419
+ with: withOption,
27420
+ withNoData,
27421
+ materialized,
27422
+ tablespace,
27423
+ using
27424
+ };
27425
+ }
26265
27426
  const enumsToReturn = enums.reduce((map, obj) => {
26266
27427
  const enumSchema3 = obj.schema || "public";
26267
27428
  const key = `${enumSchema3}.${obj.enumName}`;
@@ -26288,6 +27449,7 @@ ${withStyle.errorWarning(
26288
27449
  enums: enumsToReturn,
26289
27450
  schemas: schemasObject,
26290
27451
  sequences: sequencesToReturn,
27452
+ views: resultViews,
26291
27453
  _meta: {
26292
27454
  schemas: {},
26293
27455
  tables: {},
@@ -26304,10 +27466,25 @@ ${withStyle.errorWarning(
26304
27466
  };
26305
27467
  fromDatabase = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
26306
27468
  const result = {};
27469
+ const views = {};
26307
27470
  const internals = { tables: {} };
26308
- const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
27471
+ const where = schemaFilters.map((t) => `n.nspname = '${t}'`).join(" or ");
26309
27472
  const allTables = await db.query(
26310
- `SELECT table_schema, table_name FROM information_schema.tables${where === "" ? "" : ` WHERE ${where}`};`
27473
+ `SELECT
27474
+ n.nspname AS table_schema,
27475
+ c.relname AS table_name,
27476
+ CASE
27477
+ WHEN c.relkind = 'r' THEN 'table'
27478
+ WHEN c.relkind = 'v' THEN 'view'
27479
+ WHEN c.relkind = 'm' THEN 'materialized_view'
27480
+ END AS type
27481
+ FROM
27482
+ pg_catalog.pg_class c
27483
+ JOIN
27484
+ pg_catalog.pg_namespace n ON n.oid = c.relnamespace
27485
+ WHERE
27486
+ c.relkind IN ('r', 'v', 'm')
27487
+ ${where === "" ? "" : ` AND ${where}`};`
26311
27488
  );
26312
27489
  const schemas = new Set(allTables.map((it) => it.table_schema));
26313
27490
  schemas.delete("public");
@@ -26327,6 +27504,7 @@ ${withStyle.errorWarning(
26327
27504
  let indexesCount = 0;
26328
27505
  let foreignKeysCount = 0;
26329
27506
  let tableCount = 0;
27507
+ let viewsCount = 0;
26330
27508
  const sequencesToReturn = {};
26331
27509
  const seqWhere = schemaFilters.map((t) => `schemaname = '${t}'`).join(" or ");
26332
27510
  const allSequences = await db.query(
@@ -26385,7 +27563,7 @@ ${withStyle.errorWarning(
26385
27563
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
26386
27564
  }
26387
27565
  const sequencesInColumns = [];
26388
- const all = allTables.map((row) => {
27566
+ const all = allTables.filter((it) => it.type === "table").map((row) => {
26389
27567
  return new Promise(async (res, rej) => {
26390
27568
  const tableName = row.table_name;
26391
27569
  if (!tablesFilter(tableName)) return res("");
@@ -26397,42 +27575,7 @@ ${withStyle.errorWarning(
26397
27575
  const foreignKeysToReturn = {};
26398
27576
  const primaryKeys = {};
26399
27577
  const uniqueConstrains = {};
26400
- const tableResponse = await db.query(
26401
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
26402
- , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
26403
- AND EXISTS (
26404
- SELECT FROM pg_attrdef ad
26405
- WHERE ad.adrelid = a.attrelid
26406
- AND ad.adnum = a.attnum
26407
- AND pg_get_expr(ad.adbin, ad.adrelid)
26408
- = 'nextval('''
26409
- || (pg_get_serial_sequence (a.attrelid::regclass::text
26410
- , a.attname))::regclass
26411
- || '''::regclass)'
26412
- )
26413
- THEN CASE a.atttypid
26414
- WHEN 'int'::regtype THEN 'serial'
26415
- WHEN 'int8'::regtype THEN 'bigserial'
26416
- WHEN 'int2'::regtype THEN 'smallserial'
26417
- END
26418
- ELSE format_type(a.atttypid, a.atttypmod)
26419
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
26420
- pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
26421
- INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
26422
- INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
26423
- INFORMATION_SCHEMA.COLUMNS.is_generated, generation_expression,
26424
- INFORMATION_SCHEMA.COLUMNS.is_identity,INFORMATION_SCHEMA.COLUMNS.identity_generation,
26425
- INFORMATION_SCHEMA.COLUMNS.identity_start, INFORMATION_SCHEMA.COLUMNS.identity_increment,
26426
- INFORMATION_SCHEMA.COLUMNS.identity_maximum, INFORMATION_SCHEMA.COLUMNS.identity_minimum,
26427
- INFORMATION_SCHEMA.COLUMNS.identity_cycle
26428
- FROM pg_attribute a
26429
- JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
26430
- JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
26431
- WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
26432
- AND a.attnum > 0
26433
- AND NOT a.attisdropped
26434
- ORDER BY a.attnum;`
26435
- );
27578
+ const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
26436
27579
  const tableConstraints = await db.query(
26437
27580
  `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
26438
27581
  FROM information_schema.table_constraints tc
@@ -26514,13 +27657,9 @@ ${withStyle.errorWarning(
26514
27657
  foreignKeysToReturn[foreignKeyName].columnsFrom = [
26515
27658
  ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
26516
27659
  ];
26517
- foreignKeysToReturn[foreignKeyName].columnsTo = [
26518
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
26519
- ];
27660
+ foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
26520
27661
  }
26521
- const uniqueConstrainsRows = tableConstraints.filter(
26522
- (mapRow) => mapRow.constraint_type === "UNIQUE"
26523
- );
27662
+ const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
26524
27663
  for (const unqs of uniqueConstrainsRows) {
26525
27664
  const columnName = unqs.column_name;
26526
27665
  const constraintName = unqs.constraint_name;
@@ -26535,7 +27674,7 @@ ${withStyle.errorWarning(
26535
27674
  }
26536
27675
  }
26537
27676
  for (const columnResponse of tableResponse) {
26538
- const columnName = columnResponse.attname;
27677
+ const columnName = columnResponse.column_name;
26539
27678
  const columnAdditionalDT = columnResponse.additional_dt;
26540
27679
  const columnDimensions = columnResponse.array_dimensions;
26541
27680
  const enumType2 = columnResponse.enum_name;
@@ -26555,9 +27694,7 @@ ${withStyle.errorWarning(
26555
27694
  const primaryKey = tableConstraints.filter(
26556
27695
  (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
26557
27696
  );
26558
- const cprimaryKey = tableConstraints.filter(
26559
- (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
26560
- );
27697
+ const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
26561
27698
  if (cprimaryKey.length > 1) {
26562
27699
  const tableCompositePkName = await db.query(
26563
27700
  `SELECT conname AS primary_key
@@ -26580,10 +27717,7 @@ ${withStyle.errorWarning(
26580
27717
  [columnName]: {
26581
27718
  isArray: true,
26582
27719
  dimensions: columnDimensions,
26583
- rawType: columnTypeMapped.substring(
26584
- 0,
26585
- columnTypeMapped.length - 2
26586
- )
27720
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
26587
27721
  }
26588
27722
  }
26589
27723
  };
@@ -26592,19 +27726,12 @@ ${withStyle.errorWarning(
26592
27726
  internals.tables[tableName].columns[columnName] = {
26593
27727
  isArray: true,
26594
27728
  dimensions: columnDimensions,
26595
- rawType: columnTypeMapped.substring(
26596
- 0,
26597
- columnTypeMapped.length - 2
26598
- )
27729
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
26599
27730
  };
26600
27731
  }
26601
27732
  }
26602
27733
  }
26603
- const defaultValue = defaultForColumn(
26604
- columnResponse,
26605
- internals,
26606
- tableName
26607
- );
27734
+ const defaultValue = defaultForColumn(columnResponse, internals, tableName);
26608
27735
  if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
26609
27736
  if (typeof internals.tables[tableName] === "undefined") {
26610
27737
  internals.tables[tableName] = {
@@ -26717,7 +27844,9 @@ ${withStyle.errorWarning(
26717
27844
  WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
26718
27845
  group by index_name, table_name,schemaname, generated_by_constraint;`
26719
27846
  );
26720
- const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
27847
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
27848
+ (it) => it.index_name
27849
+ );
26721
27850
  for (const dbIndex of dbIndexes) {
26722
27851
  const indexName2 = dbIndex.indexname;
26723
27852
  const indexColumnName = dbIndex.column_name;
@@ -26791,10 +27920,180 @@ ${withStyle.errorWarning(
26791
27920
  }
26792
27921
  for await (const _2 of all) {
26793
27922
  }
27923
+ const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
27924
+ return new Promise(async (res, rej) => {
27925
+ const viewName = row.table_name;
27926
+ if (!tablesFilter(viewName)) return res("");
27927
+ tableCount += 1;
27928
+ const viewSchema = row.table_schema;
27929
+ try {
27930
+ const columnToReturn = {};
27931
+ const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
27932
+ for (const viewResponse of viewResponses) {
27933
+ const columnName = viewResponse.column_name;
27934
+ const columnAdditionalDT = viewResponse.additional_dt;
27935
+ const columnDimensions = viewResponse.array_dimensions;
27936
+ const enumType2 = viewResponse.enum_name;
27937
+ let columnType = viewResponse.data_type;
27938
+ const typeSchema = viewResponse.type_schema;
27939
+ const isGenerated = viewResponse.is_generated === "ALWAYS";
27940
+ const generationExpression = viewResponse.generation_expression;
27941
+ const isIdentity = viewResponse.is_identity === "YES";
27942
+ const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
27943
+ const identityStart = viewResponse.identity_start;
27944
+ const identityIncrement = viewResponse.identity_increment;
27945
+ const identityMaximum = viewResponse.identity_maximum;
27946
+ const identityMinimum = viewResponse.identity_minimum;
27947
+ const identityCycle = viewResponse.identity_cycle === "YES";
27948
+ const identityName = viewResponse.seq_name;
27949
+ const defaultValueRes = viewResponse.column_default;
27950
+ const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
27951
+ let columnTypeMapped = columnType;
27952
+ if (columnAdditionalDT === "ARRAY") {
27953
+ if (typeof internals.tables[viewName] === "undefined") {
27954
+ internals.tables[viewName] = {
27955
+ columns: {
27956
+ [columnName]: {
27957
+ isArray: true,
27958
+ dimensions: columnDimensions,
27959
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
27960
+ }
27961
+ }
27962
+ };
27963
+ } else {
27964
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
27965
+ internals.tables[viewName].columns[columnName] = {
27966
+ isArray: true,
27967
+ dimensions: columnDimensions,
27968
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
27969
+ };
27970
+ }
27971
+ }
27972
+ }
27973
+ const defaultValue = defaultForColumn(viewResponse, internals, viewName);
27974
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
27975
+ if (typeof internals.tables[viewName] === "undefined") {
27976
+ internals.tables[viewName] = {
27977
+ columns: {
27978
+ [columnName]: {
27979
+ isDefaultAnExpression: true
27980
+ }
27981
+ }
27982
+ };
27983
+ } else {
27984
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
27985
+ internals.tables[viewName].columns[columnName] = {
27986
+ isDefaultAnExpression: true
27987
+ };
27988
+ } else {
27989
+ internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
27990
+ }
27991
+ }
27992
+ }
27993
+ const isSerial = columnType === "serial";
27994
+ if (columnTypeMapped.startsWith("numeric(")) {
27995
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
27996
+ }
27997
+ if (columnAdditionalDT === "ARRAY") {
27998
+ for (let i = 1; i < Number(columnDimensions); i++) {
27999
+ columnTypeMapped += "[]";
28000
+ }
28001
+ }
28002
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
28003
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
28004
+ columnToReturn[columnName] = {
28005
+ name: columnName,
28006
+ type: (
28007
+ // filter vectors, but in future we should filter any extension that was installed by user
28008
+ columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
28009
+ ),
28010
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
28011
+ primaryKey,
28012
+ notNull: viewResponse.is_nullable === "NO",
28013
+ generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
28014
+ identity: isIdentity ? {
28015
+ type: identityGeneration,
28016
+ name: identityName,
28017
+ increment: stringFromDatabaseIdentityProperty(identityIncrement),
28018
+ minValue: stringFromDatabaseIdentityProperty(identityMinimum),
28019
+ maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
28020
+ startWith: stringFromDatabaseIdentityProperty(identityStart),
28021
+ cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${viewSchema}.${identityName}`]?.cache ? sequencesToReturn[`${viewSchema}.${identityName}`]?.cache : void 0,
28022
+ cycle: identityCycle,
28023
+ schema: viewSchema
28024
+ } : void 0
28025
+ };
28026
+ if (identityName) {
28027
+ delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
28028
+ delete sequencesToReturn[identityName];
28029
+ }
28030
+ if (!isSerial && typeof defaultValue !== "undefined") {
28031
+ columnToReturn[columnName].default = defaultValue;
28032
+ }
28033
+ }
28034
+ const [viewInfo] = await db.query(`
28035
+ SELECT
28036
+ c.relname AS view_name,
28037
+ n.nspname AS schema_name,
28038
+ pg_get_viewdef(c.oid, true) AS definition,
28039
+ ts.spcname AS tablespace_name,
28040
+ c.reloptions AS options,
28041
+ pg_tablespace_location(ts.oid) AS location
28042
+ FROM
28043
+ pg_class c
28044
+ JOIN
28045
+ pg_namespace n ON c.relnamespace = n.oid
28046
+ LEFT JOIN
28047
+ pg_tablespace ts ON c.reltablespace = ts.oid
28048
+ WHERE
28049
+ (c.relkind = 'm' OR c.relkind = 'v')
28050
+ AND n.nspname = '${viewSchema}'
28051
+ AND c.relname = '${viewName}';`);
28052
+ const resultWith = {};
28053
+ if (viewInfo.options) {
28054
+ viewInfo.options.forEach((pair) => {
28055
+ const splitted = pair.split("=");
28056
+ const key = splitted[0];
28057
+ const value = splitted[1];
28058
+ if (value === "true") {
28059
+ resultWith[key] = true;
28060
+ } else if (value === "false") {
28061
+ resultWith[key] = false;
28062
+ } else if (!isNaN(Number(value))) {
28063
+ resultWith[key] = Number(value);
28064
+ } else {
28065
+ resultWith[key] = value;
28066
+ }
28067
+ });
28068
+ }
28069
+ const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
28070
+ const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
28071
+ const materialized = row.type === "materialized_view";
28072
+ views[`${viewSchema}.${viewName}`] = {
28073
+ name: viewName,
28074
+ schema: viewSchema,
28075
+ columns: columnToReturn,
28076
+ isExisting: false,
28077
+ definition,
28078
+ materialized,
28079
+ with: withOption,
28080
+ tablespace: viewInfo.tablespace_name ?? void 0
28081
+ };
28082
+ } catch (e) {
28083
+ rej(e);
28084
+ return;
28085
+ }
28086
+ res("");
28087
+ });
28088
+ });
28089
+ viewsCount = allViews.length;
28090
+ for await (const _2 of allViews) {
28091
+ }
26794
28092
  if (progressCallback) {
26795
28093
  progressCallback("columns", columnsCount, "done");
26796
28094
  progressCallback("indexes", indexesCount, "done");
26797
28095
  progressCallback("fks", foreignKeysCount, "done");
28096
+ progressCallback("views", viewsCount, "done");
26798
28097
  }
26799
28098
  const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
26800
28099
  return {
@@ -26804,6 +28103,7 @@ ${withStyle.errorWarning(
26804
28103
  enums: enumsToReturn,
26805
28104
  schemas: schemasObject,
26806
28105
  sequences: sequencesToReturn,
28106
+ views,
26807
28107
  _meta: {
26808
28108
  schemas: {},
26809
28109
  tables: {},
@@ -26813,7 +28113,7 @@ ${withStyle.errorWarning(
26813
28113
  };
26814
28114
  };
26815
28115
  defaultForColumn = (column4, internals, tableName) => {
26816
- const columnName = column4.attname;
28116
+ const columnName = column4.column_name;
26817
28117
  const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false;
26818
28118
  if (column4.column_default === null) {
26819
28119
  return void 0;
@@ -26866,6 +28166,8 @@ ${withStyle.errorWarning(
26866
28166
  }
26867
28167
  return columnDefaultAsString;
26868
28168
  }
28169
+ } else if (column4.data_type.includes("numeric")) {
28170
+ return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
26869
28171
  } else if (column4.data_type === "json" || column4.data_type === "jsonb") {
26870
28172
  const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
26871
28173
  return `'${jsonWithoutSpaces}'::${column4.data_type}`;
@@ -26879,6 +28181,75 @@ ${withStyle.errorWarning(
26879
28181
  return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
26880
28182
  }
26881
28183
  };
28184
+ getColumnsInfoQuery = ({ schema: schema4, table: table4, db }) => {
28185
+ return db.query(
28186
+ `SELECT
28187
+ a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
28188
+ a.attname AS column_name, -- Column name
28189
+ CASE
28190
+ WHEN NOT a.attisdropped THEN
28191
+ CASE
28192
+ WHEN a.attnotnull THEN 'NO'
28193
+ ELSE 'YES'
28194
+ END
28195
+ ELSE NULL
28196
+ END AS is_nullable, -- NULL or NOT NULL constraint
28197
+ a.attndims AS array_dimensions, -- Array dimensions
28198
+ CASE
28199
+ WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
28200
+ AND EXISTS (
28201
+ SELECT FROM pg_attrdef ad
28202
+ WHERE ad.adrelid = a.attrelid
28203
+ AND ad.adnum = a.attnum
28204
+ AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
28205
+ || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
28206
+ )
28207
+ THEN CASE a.atttypid
28208
+ WHEN 'int'::regtype THEN 'serial'
28209
+ WHEN 'int8'::regtype THEN 'bigserial'
28210
+ WHEN 'int2'::regtype THEN 'smallserial'
28211
+ END
28212
+ ELSE format_type(a.atttypid, a.atttypmod)
28213
+ END AS data_type, -- Column data type
28214
+ -- ns.nspname AS type_schema, -- Schema name
28215
+ pg_get_serial_sequence('"${schema4}"."${table4}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any)
28216
+ c.column_default, -- Column default value
28217
+ c.data_type AS additional_dt, -- Data type from information_schema
28218
+ c.udt_name AS enum_name, -- Enum type (if applicable)
28219
+ c.is_generated, -- Is it a generated column?
28220
+ c.generation_expression, -- Generation expression (if generated)
28221
+ c.is_identity, -- Is it an identity column?
28222
+ c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT)
28223
+ c.identity_start, -- Start value of identity column
28224
+ c.identity_increment, -- Increment for identity column
28225
+ c.identity_maximum, -- Maximum value for identity column
28226
+ c.identity_minimum, -- Minimum value for identity column
28227
+ c.identity_cycle, -- Does the identity column cycle?
28228
+ enum_ns.nspname AS type_schema -- Schema of the enum type
28229
+ FROM
28230
+ pg_attribute a
28231
+ JOIN
28232
+ pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
28233
+ JOIN
28234
+ pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
28235
+ LEFT JOIN
28236
+ information_schema.columns c ON c.column_name = a.attname
28237
+ AND c.table_schema = ns.nspname
28238
+ AND c.table_name = cls.relname -- Match schema and table/view name
28239
+ LEFT JOIN
28240
+ pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
28241
+ LEFT JOIN
28242
+ pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
28243
+ WHERE
28244
+ a.attnum > 0 -- Valid column numbers only
28245
+ AND NOT a.attisdropped -- Skip dropped columns
28246
+ AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
28247
+ AND ns.nspname = '${schema4}' -- Filter by schema
28248
+ AND cls.relname = '${table4}' -- Filter by table name
28249
+ ORDER BY
28250
+ a.attnum; -- Order by column number`
28251
+ );
28252
+ };
26882
28253
  }
26883
28254
  });
26884
28255
 
@@ -27633,7 +29004,9 @@ var init_delete2 = __esm({
27633
29004
  "use strict";
27634
29005
  init_entity();
27635
29006
  init_query_promise();
29007
+ init_selection_proxy();
27636
29008
  init_table3();
29009
+ init_table();
27637
29010
  init_utils2();
27638
29011
  SQLiteDeleteBase = class extends (_b141 = QueryPromise, _a194 = entityKind, _b141) {
27639
29012
  constructor(table4, session, dialect4, withList) {
@@ -27690,6 +29063,26 @@ var init_delete2 = __esm({
27690
29063
  this.config.where = where;
27691
29064
  return this;
27692
29065
  }
29066
+ orderBy(...columns) {
29067
+ if (typeof columns[0] === "function") {
29068
+ const orderBy = columns[0](
29069
+ new Proxy(
29070
+ this.config.table[Table.Symbol.Columns],
29071
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
29072
+ )
29073
+ );
29074
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
29075
+ this.config.orderBy = orderByArray;
29076
+ } else {
29077
+ const orderByArray = columns;
29078
+ this.config.orderBy = orderByArray;
29079
+ }
29080
+ return this;
29081
+ }
29082
+ limit(limit) {
29083
+ this.config.limit = limit;
29084
+ return this;
29085
+ }
27693
29086
  returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
27694
29087
  this.config.returning = orderSelectedFields(fields);
27695
29088
  return this;
@@ -27900,7 +29293,7 @@ var init_view_base2 = __esm({
27900
29293
  "use strict";
27901
29294
  init_entity();
27902
29295
  init_sql();
27903
- SQLiteViewBase = class extends (_b143 = View, _a197 = entityKind, _b143) {
29296
+ SQLiteViewBase = class extends (_b143 = View3, _a197 = entityKind, _b143) {
27904
29297
  };
27905
29298
  __publicField(SQLiteViewBase, _a197, "SQLiteViewBase");
27906
29299
  }
@@ -27955,11 +29348,13 @@ var init_dialect2 = __esm({
27955
29348
  withSqlChunks.push(sql` `);
27956
29349
  return sql.join(withSqlChunks);
27957
29350
  }
27958
- buildDeleteQuery({ table: table4, where, returning, withList }) {
29351
+ buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
27959
29352
  const withSql = this.buildWithCTE(withList);
27960
29353
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
27961
29354
  const whereSql = where ? sql` where ${where}` : void 0;
27962
- return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
29355
+ const orderBySql = this.buildOrderBy(orderBy);
29356
+ const limitSql = this.buildLimit(limit);
29357
+ return sql`${withSql}delete from ${table4}${whereSql}${returningSql}${orderBySql}${limitSql}`;
27963
29358
  }
27964
29359
  buildUpdateSet(table4, set) {
27965
29360
  const tableColumns = table4[Table.Symbol.Columns];
@@ -27977,12 +29372,14 @@ var init_dialect2 = __esm({
27977
29372
  return [res];
27978
29373
  }));
27979
29374
  }
27980
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
29375
+ buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
27981
29376
  const withSql = this.buildWithCTE(withList);
27982
29377
  const setSql = this.buildUpdateSet(table4, set);
27983
29378
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
27984
29379
  const whereSql = where ? sql` where ${where}` : void 0;
27985
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
29380
+ const orderBySql = this.buildOrderBy(orderBy);
29381
+ const limitSql = this.buildLimit(limit);
29382
+ return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
27986
29383
  }
27987
29384
  /**
27988
29385
  * Builds selection SQL with provided fields/expressions
@@ -28035,6 +29432,21 @@ var init_dialect2 = __esm({
28035
29432
  });
28036
29433
  return sql.join(chunks);
28037
29434
  }
29435
+ buildLimit(limit) {
29436
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
29437
+ }
29438
+ buildOrderBy(orderBy) {
29439
+ const orderByList = [];
29440
+ if (orderBy) {
29441
+ for (const [index4, orderByValue] of orderBy.entries()) {
29442
+ orderByList.push(orderByValue);
29443
+ if (index4 < orderBy.length - 1) {
29444
+ orderByList.push(sql`, `);
29445
+ }
29446
+ }
29447
+ }
29448
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
29449
+ }
28038
29450
  buildSelectQuery({
28039
29451
  withList,
28040
29452
  fields,
@@ -28099,15 +29511,6 @@ var init_dialect2 = __esm({
28099
29511
  const joinsSql = sql.join(joinsArray);
28100
29512
  const whereSql = where ? sql` where ${where}` : void 0;
28101
29513
  const havingSql = having ? sql` having ${having}` : void 0;
28102
- const orderByList = [];
28103
- if (orderBy) {
28104
- for (const [index4, orderByValue] of orderBy.entries()) {
28105
- orderByList.push(orderByValue);
28106
- if (index4 < orderBy.length - 1) {
28107
- orderByList.push(sql`, `);
28108
- }
28109
- }
28110
- }
28111
29514
  const groupByList = [];
28112
29515
  if (groupBy) {
28113
29516
  for (const [index4, groupByValue] of groupBy.entries()) {
@@ -28118,8 +29521,8 @@ var init_dialect2 = __esm({
28118
29521
  }
28119
29522
  }
28120
29523
  const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0;
28121
- const orderBySql = orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
28122
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
29524
+ const orderBySql = this.buildOrderBy(orderBy);
29525
+ const limitSql = this.buildLimit(limit);
28123
29526
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
28124
29527
  const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
28125
29528
  if (setOperators.length > 0) {
@@ -28838,7 +30241,7 @@ var init_select3 = __esm({
28838
30241
  };
28839
30242
  }
28840
30243
  if (typeof tableName === "string" && !is(table4, SQL)) {
28841
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
30244
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
28842
30245
  this.config.fields[tableName] = selection;
28843
30246
  }
28844
30247
  }
@@ -29230,7 +30633,9 @@ var init_update2 = __esm({
29230
30633
  "use strict";
29231
30634
  init_entity();
29232
30635
  init_query_promise();
30636
+ init_selection_proxy();
29233
30637
  init_table3();
30638
+ init_table();
29234
30639
  init_utils2();
29235
30640
  _a205 = entityKind;
29236
30641
  SQLiteUpdateBuilder = class {
@@ -29309,6 +30714,26 @@ var init_update2 = __esm({
29309
30714
  this.config.where = where;
29310
30715
  return this;
29311
30716
  }
30717
+ orderBy(...columns) {
30718
+ if (typeof columns[0] === "function") {
30719
+ const orderBy = columns[0](
30720
+ new Proxy(
30721
+ this.config.table[Table.Symbol.Columns],
30722
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
30723
+ )
30724
+ );
30725
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
30726
+ this.config.orderBy = orderByArray;
30727
+ } else {
30728
+ const orderByArray = columns;
30729
+ this.config.orderBy = orderByArray;
30730
+ }
30731
+ return this;
30732
+ }
30733
+ limit(limit) {
30734
+ this.config.limit = limit;
30735
+ return this;
30736
+ }
29312
30737
  returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
29313
30738
  this.config.returning = orderSelectedFields(fields);
29314
30739
  return this;
@@ -30124,15 +31549,6 @@ var init_subquery3 = __esm({
30124
31549
  }
30125
31550
  });
30126
31551
 
30127
- // ../drizzle-orm/dist/sqlite-core/view-common.js
30128
- var SQLiteViewConfig;
30129
- var init_view_common3 = __esm({
30130
- "../drizzle-orm/dist/sqlite-core/view-common.js"() {
30131
- "use strict";
30132
- SQLiteViewConfig = Symbol.for("drizzle:SQLiteViewConfig");
30133
- }
30134
- });
30135
-
30136
31552
  // ../drizzle-orm/dist/sqlite-core/utils.js
30137
31553
  function getTableConfig2(table4) {
30138
31554
  const columns = Object.values(table4[SQLiteTable.Symbol.Columns]);
@@ -30169,11 +31585,18 @@ function getTableConfig2(table4) {
30169
31585
  name: name2
30170
31586
  };
30171
31587
  }
31588
+ function getViewConfig2(view4) {
31589
+ return {
31590
+ ...view4[ViewBaseConfig]
31591
+ // ...view[SQLiteViewConfig],
31592
+ };
31593
+ }
30172
31594
  var init_utils6 = __esm({
30173
31595
  "../drizzle-orm/dist/sqlite-core/utils.js"() {
30174
31596
  "use strict";
30175
31597
  init_entity();
30176
31598
  init_table();
31599
+ init_view_common();
30177
31600
  init_checks2();
30178
31601
  init_foreign_keys2();
30179
31602
  init_indexes2();
@@ -30184,7 +31607,7 @@ var init_utils6 = __esm({
30184
31607
  });
30185
31608
 
30186
31609
  // ../drizzle-orm/dist/sqlite-core/view.js
30187
- var _a222, ViewBuilderCore, _a223, _b155, ViewBuilder2, _a224, _b156, ManualViewBuilder2, _a225, _b157, _c8, SQLiteView;
31610
+ var _a222, ViewBuilderCore, _a223, _b155, ViewBuilder2, _a224, _b156, ManualViewBuilder2, _a225, _b157, SQLiteView2;
30188
31611
  var init_view2 = __esm({
30189
31612
  "../drizzle-orm/dist/sqlite-core/view.js"() {
30190
31613
  "use strict";
@@ -30194,7 +31617,6 @@ var init_view2 = __esm({
30194
31617
  init_query_builder3();
30195
31618
  init_table3();
30196
31619
  init_view_base2();
30197
- init_view_common3();
30198
31620
  _a222 = entityKind;
30199
31621
  ViewBuilderCore = class {
30200
31622
  constructor(name2) {
@@ -30216,8 +31638,8 @@ var init_view2 = __esm({
30216
31638
  });
30217
31639
  const aliasedSelectedFields = qb.getSelectedFields();
30218
31640
  return new Proxy(
30219
- new SQLiteView({
30220
- sqliteConfig: this.config,
31641
+ new SQLiteView2({
31642
+ // sqliteConfig: this.config,
30221
31643
  config: {
30222
31644
  name: this.name,
30223
31645
  schema: void 0,
@@ -30238,8 +31660,7 @@ var init_view2 = __esm({
30238
31660
  }
30239
31661
  existing() {
30240
31662
  return new Proxy(
30241
- new SQLiteView({
30242
- sqliteConfig: void 0,
31663
+ new SQLiteView2({
30243
31664
  config: {
30244
31665
  name: this.name,
30245
31666
  schema: void 0,
@@ -30257,8 +31678,7 @@ var init_view2 = __esm({
30257
31678
  }
30258
31679
  as(query) {
30259
31680
  return new Proxy(
30260
- new SQLiteView({
30261
- sqliteConfig: this.config,
31681
+ new SQLiteView2({
30262
31682
  config: {
30263
31683
  name: this.name,
30264
31684
  schema: void 0,
@@ -30276,15 +31696,12 @@ var init_view2 = __esm({
30276
31696
  }
30277
31697
  };
30278
31698
  __publicField(ManualViewBuilder2, _a224, "SQLiteManualViewBuilder");
30279
- SQLiteView = class extends (_c8 = SQLiteViewBase, _b157 = entityKind, _a225 = SQLiteViewConfig, _c8) {
30280
- constructor({ sqliteConfig, config }) {
31699
+ SQLiteView2 = class extends (_b157 = SQLiteViewBase, _a225 = entityKind, _b157) {
31700
+ constructor({ config }) {
30281
31701
  super(config);
30282
- /** @internal */
30283
- __publicField(this, _a225);
30284
- this[SQLiteViewConfig] = sqliteConfig;
30285
31702
  }
30286
31703
  };
30287
- __publicField(SQLiteView, _b157, "SQLiteView");
31704
+ __publicField(SQLiteView2, _a225, "SQLiteView");
30288
31705
  }
30289
31706
  });
30290
31707
 
@@ -30382,9 +31799,10 @@ var init_sqliteSerializer = __esm({
30382
31799
  init_outputs();
30383
31800
  init_utils();
30384
31801
  init_serializer();
30385
- generateSqliteSnapshot = (tables, casing2) => {
31802
+ generateSqliteSnapshot = (tables, views, casing2) => {
30386
31803
  const dialect4 = new SQLiteSyncDialect({ casing: casing2 });
30387
31804
  const result = {};
31805
+ const resultViews = {};
30388
31806
  const internal = { indexes: {} };
30389
31807
  for (const table4 of tables) {
30390
31808
  const columnsObject = {};
@@ -30580,10 +31998,60 @@ The unique constraint ${source_default.underline.blue(
30580
31998
  uniqueConstraints: uniqueConstraintObject
30581
31999
  };
30582
32000
  }
32001
+ for (const view4 of views) {
32002
+ const { name: name2, isExisting, selectedFields, query, schema: schema4 } = getViewConfig2(view4);
32003
+ const columnsObject = {};
32004
+ const existingView = resultViews[name2];
32005
+ if (typeof existingView !== "undefined") {
32006
+ console.log(
32007
+ `
32008
+ ${withStyle.errorWarning(
32009
+ `We've found duplicated view name across ${source_default.underline.blue(
32010
+ schema4 ?? "public"
32011
+ )} schema. Please rename your view`
32012
+ )}`
32013
+ );
32014
+ process.exit(1);
32015
+ }
32016
+ for (const key in selectedFields) {
32017
+ if (is(selectedFields[key], SQLiteColumn)) {
32018
+ const column4 = selectedFields[key];
32019
+ const notNull = column4.notNull;
32020
+ const primaryKey = column4.primary;
32021
+ const generated = column4.generated;
32022
+ const columnToSet = {
32023
+ name: column4.name,
32024
+ type: column4.getSQLType(),
32025
+ primaryKey,
32026
+ notNull,
32027
+ autoincrement: is(column4, SQLiteBaseInteger) ? column4.autoIncrement : false,
32028
+ generated: generated ? {
32029
+ as: is(generated.as, SQL) ? `(${dialect4.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect4.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
32030
+ type: generated.mode ?? "virtual"
32031
+ } : void 0
32032
+ };
32033
+ if (column4.default !== void 0) {
32034
+ if (is(column4.default, SQL)) {
32035
+ columnToSet.default = sqlToStr(column4.default, casing2);
32036
+ } else {
32037
+ columnToSet.default = typeof column4.default === "string" ? `'${column4.default}'` : typeof column4.default === "object" || Array.isArray(column4.default) ? `'${JSON.stringify(column4.default)}'` : column4.default;
32038
+ }
32039
+ }
32040
+ columnsObject[column4.name] = columnToSet;
32041
+ }
32042
+ }
32043
+ resultViews[name2] = {
32044
+ columns: columnsObject,
32045
+ name: name2,
32046
+ isExisting,
32047
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql
32048
+ };
32049
+ }
30583
32050
  return {
30584
32051
  version: "6",
30585
32052
  dialect: "sqlite",
30586
32053
  tables: result,
32054
+ views: resultViews,
30587
32055
  enums: {},
30588
32056
  _meta: {
30589
32057
  tables: {},
@@ -30594,11 +32062,12 @@ The unique constraint ${source_default.underline.blue(
30594
32062
  };
30595
32063
  fromDatabase2 = async (db, tablesFilter = (table4) => true, progressCallback) => {
30596
32064
  const result = {};
32065
+ const resultViews = {};
30597
32066
  const columns = await db.query(
30598
32067
  `SELECT
30599
- 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
32068
+ 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
30600
32069
  FROM sqlite_master AS m JOIN pragma_table_xinfo(m.name) AS p
30601
- WHERE m.type = 'table'
32070
+ WHERE (m.type = 'table' OR m.type = 'view')
30602
32071
  and m.tbl_name != 'sqlite_sequence'
30603
32072
  and m.tbl_name != 'sqlite_stat1'
30604
32073
  and m.tbl_name != '_litestream_seq'
@@ -30624,11 +32093,14 @@ The unique constraint ${source_default.underline.blue(
30624
32093
  let tablesCount = /* @__PURE__ */ new Set();
30625
32094
  let indexesCount = 0;
30626
32095
  let foreignKeysCount = 0;
32096
+ let viewsCount = 0;
30627
32097
  const tableToPk = {};
30628
32098
  let tableToGeneratedColumnsInfo = {};
30629
32099
  for (const column4 of columns) {
30630
32100
  if (!tablesFilter(column4.tableName)) continue;
30631
- columnsCount += 1;
32101
+ if (column4.type !== "view") {
32102
+ columnsCount += 1;
32103
+ }
30632
32104
  if (progressCallback) {
30633
32105
  progressCallback("columns", columnsCount, "fetching");
30634
32106
  }
@@ -30795,10 +32267,40 @@ WHERE
30795
32267
  progressCallback("indexes", indexesCount, "done");
30796
32268
  progressCallback("enums", 0, "done");
30797
32269
  }
32270
+ const views = await db.query(
32271
+ `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
32272
+ );
32273
+ viewsCount = views.length;
32274
+ if (progressCallback) {
32275
+ progressCallback("views", viewsCount, "fetching");
32276
+ }
32277
+ for (const view4 of views) {
32278
+ const viewName = view4["view_name"];
32279
+ const sql2 = view4["sql"];
32280
+ const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
32281
+ const match2 = sql2.match(regex);
32282
+ if (!match2) {
32283
+ console.log("Could not process view");
32284
+ process.exit(1);
32285
+ }
32286
+ const viewDefinition = match2[1];
32287
+ const columns2 = result[viewName].columns;
32288
+ delete result[viewName];
32289
+ resultViews[viewName] = {
32290
+ columns: columns2,
32291
+ isExisting: false,
32292
+ name: viewName,
32293
+ definition: viewDefinition
32294
+ };
32295
+ }
32296
+ if (progressCallback) {
32297
+ progressCallback("views", viewsCount, "done");
32298
+ }
30798
32299
  return {
30799
32300
  version: "6",
30800
32301
  dialect: "sqlite",
30801
32302
  tables: result,
32303
+ views: resultViews,
30802
32304
  enums: {},
30803
32305
  _meta: {
30804
32306
  tables: {},
@@ -32187,13 +33689,13 @@ var init_columns3 = __esm({
32187
33689
  });
32188
33690
 
32189
33691
  // ../drizzle-orm/dist/mysql-core/query-builders/count.js
32190
- var _a295, _b220, _c9, _MySqlCountBuilder, MySqlCountBuilder;
33692
+ var _a295, _b220, _c8, _MySqlCountBuilder, MySqlCountBuilder;
32191
33693
  var init_count3 = __esm({
32192
33694
  "../drizzle-orm/dist/mysql-core/query-builders/count.js"() {
32193
33695
  "use strict";
32194
33696
  init_entity();
32195
33697
  init_sql();
32196
- _MySqlCountBuilder = class _MySqlCountBuilder extends (_c9 = SQL, _b220 = entityKind, _a295 = Symbol.toStringTag, _c9) {
33698
+ _MySqlCountBuilder = class _MySqlCountBuilder extends (_c8 = SQL, _b220 = entityKind, _a295 = Symbol.toStringTag, _c8) {
32197
33699
  constructor(params) {
32198
33700
  super(_MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
32199
33701
  __publicField(this, "sql");
@@ -32247,6 +33749,8 @@ var init_delete3 = __esm({
32247
33749
  "use strict";
32248
33750
  init_entity();
32249
33751
  init_query_promise();
33752
+ init_selection_proxy();
33753
+ init_table();
32250
33754
  MySqlDeleteBase = class extends (_b221 = QueryPromise, _a296 = entityKind, _b221) {
32251
33755
  constructor(table4, session, dialect4, withList) {
32252
33756
  super();
@@ -32299,6 +33803,26 @@ var init_delete3 = __esm({
32299
33803
  this.config.where = where;
32300
33804
  return this;
32301
33805
  }
33806
+ orderBy(...columns) {
33807
+ if (typeof columns[0] === "function") {
33808
+ const orderBy = columns[0](
33809
+ new Proxy(
33810
+ this.config.table[Table.Symbol.Columns],
33811
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
33812
+ )
33813
+ );
33814
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
33815
+ this.config.orderBy = orderByArray;
33816
+ } else {
33817
+ const orderByArray = columns;
33818
+ this.config.orderBy = orderByArray;
33819
+ }
33820
+ return this;
33821
+ }
33822
+ limit(limit) {
33823
+ this.config.limit = limit;
33824
+ return this;
33825
+ }
32302
33826
  /** @internal */
32303
33827
  getSQL() {
32304
33828
  return this.dialect.buildDeleteQuery(this.config);
@@ -32526,7 +34050,7 @@ function mysqlTableWithSchema(name2, columns, extraConfig, schema4, baseName = n
32526
34050
  }
32527
34051
  return table4;
32528
34052
  }
32529
- var InlineForeignKeys3, _a299, _b223, _c10, _d4, _e3, MySqlTable, mysqlTable;
34053
+ var InlineForeignKeys3, _a299, _b223, _c9, _d4, _e3, MySqlTable, mysqlTable;
32530
34054
  var init_table4 = __esm({
32531
34055
  "../drizzle-orm/dist/mysql-core/table.js"() {
32532
34056
  "use strict";
@@ -32534,11 +34058,11 @@ var init_table4 = __esm({
32534
34058
  init_table();
32535
34059
  init_all3();
32536
34060
  InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
32537
- MySqlTable = class extends (_e3 = Table, _d4 = entityKind, _c10 = Table.Symbol.Columns, _b223 = InlineForeignKeys3, _a299 = Table.Symbol.ExtraConfigBuilder, _e3) {
34061
+ MySqlTable = class extends (_e3 = Table, _d4 = entityKind, _c9 = Table.Symbol.Columns, _b223 = InlineForeignKeys3, _a299 = Table.Symbol.ExtraConfigBuilder, _e3) {
32538
34062
  constructor() {
32539
34063
  super(...arguments);
32540
34064
  /** @internal */
32541
- __publicField(this, _c10);
34065
+ __publicField(this, _c9);
32542
34066
  /** @internal */
32543
34067
  __publicField(this, _b223, []);
32544
34068
  /** @internal */
@@ -32563,7 +34087,7 @@ var init_view_base3 = __esm({
32563
34087
  "use strict";
32564
34088
  init_entity();
32565
34089
  init_sql();
32566
- MySqlViewBase = class extends (_b224 = View, _a300 = entityKind, _b224) {
34090
+ MySqlViewBase = class extends (_b224 = View3, _a300 = entityKind, _b224) {
32567
34091
  };
32568
34092
  __publicField(MySqlViewBase, _a300, "MySqlViewBase");
32569
34093
  }
@@ -32645,11 +34169,13 @@ var init_dialect3 = __esm({
32645
34169
  withSqlChunks.push(sql` `);
32646
34170
  return sql.join(withSqlChunks);
32647
34171
  }
32648
- buildDeleteQuery({ table: table4, where, returning, withList }) {
34172
+ buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
32649
34173
  const withSql = this.buildWithCTE(withList);
32650
34174
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32651
34175
  const whereSql = where ? sql` where ${where}` : void 0;
32652
- return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
34176
+ const orderBySql = this.buildOrderBy(orderBy);
34177
+ const limitSql = this.buildLimit(limit);
34178
+ return sql`${withSql}delete from ${table4}${whereSql}${orderBySql}${limitSql}${returningSql}`;
32653
34179
  }
32654
34180
  buildUpdateSet(table4, set) {
32655
34181
  const tableColumns = table4[Table.Symbol.Columns];
@@ -32667,12 +34193,14 @@ var init_dialect3 = __esm({
32667
34193
  return [res];
32668
34194
  }));
32669
34195
  }
32670
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
34196
+ buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
32671
34197
  const withSql = this.buildWithCTE(withList);
32672
34198
  const setSql = this.buildUpdateSet(table4, set);
32673
34199
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32674
34200
  const whereSql = where ? sql` where ${where}` : void 0;
32675
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
34201
+ const orderBySql = this.buildOrderBy(orderBy);
34202
+ const limitSql = this.buildLimit(limit);
34203
+ return sql`${withSql}update ${table4} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
32676
34204
  }
32677
34205
  /**
32678
34206
  * Builds selection SQL with provided fields/expressions
@@ -32724,6 +34252,12 @@ var init_dialect3 = __esm({
32724
34252
  });
32725
34253
  return sql.join(chunks);
32726
34254
  }
34255
+ buildLimit(limit) {
34256
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
34257
+ }
34258
+ buildOrderBy(orderBy) {
34259
+ return orderBy && orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0;
34260
+ }
32727
34261
  buildSelectQuery({
32728
34262
  withList,
32729
34263
  fields,
@@ -32777,7 +34311,7 @@ var init_dialect3 = __esm({
32777
34311
  joinsArray.push(
32778
34312
  sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
32779
34313
  );
32780
- } else if (is(table22, View)) {
34314
+ } else if (is(table22, View3)) {
32781
34315
  const viewName = table22[ViewBaseConfig].name;
32782
34316
  const viewSchema = table22[ViewBaseConfig].schema;
32783
34317
  const origViewName = table22[ViewBaseConfig].originalName;
@@ -32798,15 +34332,9 @@ var init_dialect3 = __esm({
32798
34332
  const joinsSql = sql.join(joinsArray);
32799
34333
  const whereSql = where ? sql` where ${where}` : void 0;
32800
34334
  const havingSql = having ? sql` having ${having}` : void 0;
32801
- let orderBySql;
32802
- if (orderBy && orderBy.length > 0) {
32803
- orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
32804
- }
32805
- let groupBySql;
32806
- if (groupBy && groupBy.length > 0) {
32807
- groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
32808
- }
32809
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
34335
+ const orderBySql = this.buildOrderBy(orderBy);
34336
+ const groupBySql = groupBy && groupBy.length > 0 ? sql` group by ${sql.join(groupBy, sql`, `)}` : void 0;
34337
+ const limitSql = this.buildLimit(limit);
32810
34338
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
32811
34339
  let lockingClausesSql;
32812
34340
  if (lockingClause) {
@@ -33793,7 +35321,7 @@ var init_select4 = __esm({
33793
35321
  };
33794
35322
  }
33795
35323
  if (typeof tableName === "string" && !is(table4, SQL)) {
33796
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
35324
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
33797
35325
  this.config.fields[tableName] = selection;
33798
35326
  }
33799
35327
  }
@@ -34189,6 +35717,8 @@ var init_update3 = __esm({
34189
35717
  "use strict";
34190
35718
  init_entity();
34191
35719
  init_query_promise();
35720
+ init_selection_proxy();
35721
+ init_table();
34192
35722
  init_utils2();
34193
35723
  _a306 = entityKind;
34194
35724
  MySqlUpdateBuilder = class {
@@ -34258,6 +35788,26 @@ var init_update3 = __esm({
34258
35788
  this.config.where = where;
34259
35789
  return this;
34260
35790
  }
35791
+ orderBy(...columns) {
35792
+ if (typeof columns[0] === "function") {
35793
+ const orderBy = columns[0](
35794
+ new Proxy(
35795
+ this.config.table[Table.Symbol.Columns],
35796
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
35797
+ )
35798
+ );
35799
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
35800
+ this.config.orderBy = orderByArray;
35801
+ } else {
35802
+ const orderByArray = columns;
35803
+ this.config.orderBy = orderByArray;
35804
+ }
35805
+ return this;
35806
+ }
35807
+ limit(limit) {
35808
+ this.config.limit = limit;
35809
+ return this;
35810
+ }
34261
35811
  /** @internal */
34262
35812
  getSQL() {
34263
35813
  return this.dialect.buildUpdateQuery(this.config);
@@ -34739,7 +36289,7 @@ var init_primary_keys3 = __esm({
34739
36289
 
34740
36290
  // ../drizzle-orm/dist/mysql-core/view-common.js
34741
36291
  var MySqlViewConfig;
34742
- var init_view_common4 = __esm({
36292
+ var init_view_common3 = __esm({
34743
36293
  "../drizzle-orm/dist/mysql-core/view-common.js"() {
34744
36294
  "use strict";
34745
36295
  MySqlViewConfig = Symbol.for("drizzle:MySqlViewConfig");
@@ -34753,7 +36303,7 @@ function mysqlViewWithSchema(name2, selection, schema4) {
34753
36303
  }
34754
36304
  return new ViewBuilder3(name2, schema4);
34755
36305
  }
34756
- var _a316, ViewBuilderCore2, _a317, _b229, ViewBuilder3, _a318, _b230, ManualViewBuilder3, _a319, _b231, _c11, MySqlView;
36306
+ var _a316, ViewBuilderCore2, _a317, _b229, ViewBuilder3, _a318, _b230, ManualViewBuilder3, _a319, _b231, _c10, MySqlView2;
34757
36307
  var init_view3 = __esm({
34758
36308
  "../drizzle-orm/dist/mysql-core/view.js"() {
34759
36309
  "use strict";
@@ -34763,7 +36313,7 @@ var init_view3 = __esm({
34763
36313
  init_query_builder4();
34764
36314
  init_table4();
34765
36315
  init_view_base3();
34766
- init_view_common4();
36316
+ init_view_common3();
34767
36317
  _a316 = entityKind;
34768
36318
  ViewBuilderCore2 = class {
34769
36319
  constructor(name2, schema4) {
@@ -34775,10 +36325,6 @@ var init_view3 = __esm({
34775
36325
  this.config.algorithm = algorithm;
34776
36326
  return this;
34777
36327
  }
34778
- definer(definer) {
34779
- this.config.definer = definer;
34780
- return this;
34781
- }
34782
36328
  sqlSecurity(sqlSecurity) {
34783
36329
  this.config.sqlSecurity = sqlSecurity;
34784
36330
  return this;
@@ -34802,7 +36348,7 @@ var init_view3 = __esm({
34802
36348
  });
34803
36349
  const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
34804
36350
  return new Proxy(
34805
- new MySqlView({
36351
+ new MySqlView2({
34806
36352
  mysqlConfig: this.config,
34807
36353
  config: {
34808
36354
  name: this.name,
@@ -34824,7 +36370,7 @@ var init_view3 = __esm({
34824
36370
  }
34825
36371
  existing() {
34826
36372
  return new Proxy(
34827
- new MySqlView({
36373
+ new MySqlView2({
34828
36374
  mysqlConfig: void 0,
34829
36375
  config: {
34830
36376
  name: this.name,
@@ -34843,7 +36389,7 @@ var init_view3 = __esm({
34843
36389
  }
34844
36390
  as(query) {
34845
36391
  return new Proxy(
34846
- new MySqlView({
36392
+ new MySqlView2({
34847
36393
  mysqlConfig: this.config,
34848
36394
  config: {
34849
36395
  name: this.name,
@@ -34862,14 +36408,14 @@ var init_view3 = __esm({
34862
36408
  }
34863
36409
  };
34864
36410
  __publicField(ManualViewBuilder3, _a318, "MySqlManualViewBuilder");
34865
- MySqlView = class extends (_c11 = MySqlViewBase, _b231 = entityKind, _a319 = MySqlViewConfig, _c11) {
36411
+ MySqlView2 = class extends (_c10 = MySqlViewBase, _b231 = entityKind, _a319 = MySqlViewConfig, _c10) {
34866
36412
  constructor({ mysqlConfig, config }) {
34867
36413
  super(config);
34868
36414
  __publicField(this, _a319);
34869
36415
  this[MySqlViewConfig] = mysqlConfig;
34870
36416
  }
34871
36417
  };
34872
- __publicField(MySqlView, _b231, "MySqlView");
36418
+ __publicField(MySqlView2, _b231, "MySqlView");
34873
36419
  }
34874
36420
  });
34875
36421
 
@@ -35011,17 +36557,25 @@ function getTableConfig3(table4) {
35011
36557
  baseName
35012
36558
  };
35013
36559
  }
36560
+ function getViewConfig3(view4) {
36561
+ return {
36562
+ ...view4[ViewBaseConfig],
36563
+ ...view4[MySqlViewConfig]
36564
+ };
36565
+ }
35014
36566
  var init_utils7 = __esm({
35015
36567
  "../drizzle-orm/dist/mysql-core/utils.js"() {
35016
36568
  "use strict";
35017
36569
  init_entity();
35018
36570
  init_table();
36571
+ init_view_common();
35019
36572
  init_checks3();
35020
36573
  init_foreign_keys3();
35021
36574
  init_indexes3();
35022
36575
  init_primary_keys3();
35023
36576
  init_table4();
35024
36577
  init_unique_constraint3();
36578
+ init_view_common3();
35025
36579
  }
35026
36580
  });
35027
36581
 
@@ -35044,7 +36598,7 @@ var init_mysql_core = __esm({
35044
36598
  init_table4();
35045
36599
  init_unique_constraint3();
35046
36600
  init_utils7();
35047
- init_view_common4();
36601
+ init_view_common3();
35048
36602
  init_view3();
35049
36603
  }
35050
36604
  });
@@ -35076,12 +36630,14 @@ var init_mysqlSerializer = __esm({
35076
36630
  init_dist();
35077
36631
  init_mysql_core();
35078
36632
  init_mysql_core();
36633
+ init_mysql_core();
35079
36634
  init_outputs();
35080
36635
  init_utils();
35081
36636
  init_serializer();
35082
- generateMySqlSnapshot = (tables, casing2) => {
36637
+ generateMySqlSnapshot = (tables, views, casing2) => {
35083
36638
  const dialect4 = new MySqlDialect({ casing: casing2 });
35084
36639
  const result = {};
36640
+ const resultViews = {};
35085
36641
  const internal = { tables: {}, indexes: {} };
35086
36642
  for (const table4 of tables) {
35087
36643
  const {
@@ -35339,10 +36895,95 @@ We have encountered a collision between the index name on columns ${source_defau
35339
36895
  };
35340
36896
  }
35341
36897
  }
36898
+ for (const view4 of views) {
36899
+ const {
36900
+ isExisting,
36901
+ name: name2,
36902
+ query,
36903
+ schema: schema4,
36904
+ selectedFields,
36905
+ algorithm,
36906
+ sqlSecurity,
36907
+ withCheckOption
36908
+ } = getViewConfig3(view4);
36909
+ const columnsObject = {};
36910
+ const existingView = resultViews[name2];
36911
+ if (typeof existingView !== "undefined") {
36912
+ console.log(
36913
+ `
36914
+ ${withStyle.errorWarning(
36915
+ `We've found duplicated view name across ${source_default.underline.blue(
36916
+ schema4 ?? "public"
36917
+ )} schema. Please rename your view`
36918
+ )}`
36919
+ );
36920
+ process.exit(1);
36921
+ }
36922
+ for (const key in selectedFields) {
36923
+ if (is(selectedFields[key], MySqlColumn)) {
36924
+ const column4 = selectedFields[key];
36925
+ const notNull = column4.notNull;
36926
+ const sqlTypeLowered = column4.getSQLType().toLowerCase();
36927
+ const autoIncrement = typeof column4.autoIncrement === "undefined" ? false : column4.autoIncrement;
36928
+ const generated = column4.generated;
36929
+ const columnToSet = {
36930
+ name: column4.name,
36931
+ type: column4.getSQLType(),
36932
+ primaryKey: false,
36933
+ // If field is autoincrement it's notNull by default
36934
+ // notNull: autoIncrement ? true : notNull,
36935
+ notNull,
36936
+ autoincrement: autoIncrement,
36937
+ onUpdate: column4.hasOnUpdateNow,
36938
+ generated: generated ? {
36939
+ as: is(generated.as, SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
36940
+ type: generated.mode ?? "stored"
36941
+ } : void 0
36942
+ };
36943
+ if (column4.default !== void 0) {
36944
+ if (is(column4.default, SQL)) {
36945
+ columnToSet.default = sqlToStr(column4.default, casing2);
36946
+ } else {
36947
+ if (typeof column4.default === "string") {
36948
+ columnToSet.default = `'${column4.default}'`;
36949
+ } else {
36950
+ if (sqlTypeLowered === "json") {
36951
+ columnToSet.default = `'${JSON.stringify(column4.default)}'`;
36952
+ } else if (column4.default instanceof Date) {
36953
+ if (sqlTypeLowered === "date") {
36954
+ columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
36955
+ } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
36956
+ columnToSet.default = `'${column4.default.toISOString().replace("T", " ").slice(0, 23)}'`;
36957
+ }
36958
+ } else {
36959
+ columnToSet.default = column4.default;
36960
+ }
36961
+ }
36962
+ if (["blob", "text", "json"].includes(column4.getSQLType())) {
36963
+ columnToSet.default = `(${columnToSet.default})`;
36964
+ }
36965
+ }
36966
+ }
36967
+ columnsObject[column4.name] = columnToSet;
36968
+ }
36969
+ }
36970
+ resultViews[name2] = {
36971
+ columns: columnsObject,
36972
+ name: name2,
36973
+ isExisting,
36974
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
36975
+ withCheckOption,
36976
+ algorithm: algorithm ?? "undefined",
36977
+ // set default values
36978
+ sqlSecurity: sqlSecurity ?? "definer"
36979
+ // set default values
36980
+ };
36981
+ }
35342
36982
  return {
35343
36983
  version: "5",
35344
36984
  dialect: "mysql",
35345
36985
  tables: result,
36986
+ views: resultViews,
35346
36987
  _meta: {
35347
36988
  tables: {},
35348
36989
  columns: {}
@@ -35362,6 +37003,7 @@ We have encountered a collision between the index name on columns ${source_defau
35362
37003
  let tablesCount = /* @__PURE__ */ new Set();
35363
37004
  let indexesCount = 0;
35364
37005
  let foreignKeysCount = 0;
37006
+ let viewsCount = 0;
35365
37007
  const idxs = await db.query(
35366
37008
  `select * from INFORMATION_SCHEMA.STATISTICS
35367
37009
  WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
@@ -35601,14 +37243,44 @@ We have encountered a collision between the index name on columns ${source_defau
35601
37243
  }
35602
37244
  }
35603
37245
  }
37246
+ const views = await db.query(
37247
+ `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
37248
+ );
37249
+ const resultViews = {};
37250
+ viewsCount = views.length;
37251
+ if (progressCallback) {
37252
+ progressCallback("views", viewsCount, "fetching");
37253
+ }
37254
+ for await (const view4 of views) {
37255
+ const viewName = view4["TABLE_NAME"];
37256
+ const definition = view4["VIEW_DEFINITION"];
37257
+ const withCheckOption = view4["CHECK_OPTION"] === "NONE" ? void 0 : view4["CHECK_OPTION"].toLowerCase();
37258
+ const sqlSecurity = view4["SECURITY_TYPE"].toLowerCase();
37259
+ const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
37260
+ const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
37261
+ const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
37262
+ const columns2 = result[viewName].columns;
37263
+ delete result[viewName];
37264
+ resultViews[viewName] = {
37265
+ columns: columns2,
37266
+ isExisting: false,
37267
+ name: viewName,
37268
+ algorithm,
37269
+ definition,
37270
+ sqlSecurity,
37271
+ withCheckOption
37272
+ };
37273
+ }
35604
37274
  if (progressCallback) {
35605
37275
  progressCallback("indexes", indexesCount, "done");
35606
37276
  progressCallback("enums", 0, "done");
37277
+ progressCallback("views", viewsCount, "done");
35607
37278
  }
35608
37279
  return {
35609
37280
  version: "5",
35610
37281
  dialect: "mysql",
35611
37282
  tables: result,
37283
+ views: resultViews,
35612
37284
  _meta: {
35613
37285
  tables: {},
35614
37286
  columns: {}
@@ -35924,6 +37596,8 @@ var init_pgImports = __esm({
35924
37596
  const enums = [];
35925
37597
  const schemas = [];
35926
37598
  const sequences = [];
37599
+ const views = [];
37600
+ const matViews = [];
35927
37601
  const i0values = Object.values(exports2);
35928
37602
  i0values.forEach((t) => {
35929
37603
  if (isPgEnum(t)) {
@@ -35936,11 +37610,17 @@ var init_pgImports = __esm({
35936
37610
  if (is(t, PgSchema5)) {
35937
37611
  schemas.push(t);
35938
37612
  }
37613
+ if (isPgView(t)) {
37614
+ views.push(t);
37615
+ }
37616
+ if (isPgMaterializedView(t)) {
37617
+ matViews.push(t);
37618
+ }
35939
37619
  if (isPgSequence(t)) {
35940
37620
  sequences.push(t);
35941
37621
  }
35942
37622
  });
35943
- return { tables, enums, schemas, sequences };
37623
+ return { tables, enums, schemas, sequences, views, matViews };
35944
37624
  };
35945
37625
  }
35946
37626
  });
@@ -35960,25 +37640,31 @@ var init_sqliteImports = __esm({
35960
37640
  init_utils8();
35961
37641
  prepareFromExports2 = (exports2) => {
35962
37642
  const tables = [];
37643
+ const views = [];
35963
37644
  const i0values = Object.values(exports2);
35964
37645
  i0values.forEach((t) => {
35965
37646
  if (is(t, SQLiteTable)) {
35966
37647
  tables.push(t);
35967
37648
  }
37649
+ if (is(t, SQLiteView2)) {
37650
+ views.push(t);
37651
+ }
35968
37652
  });
35969
- return { tables };
37653
+ return { tables, views };
35970
37654
  };
35971
37655
  prepareFromSqliteImports = async (imports) => {
35972
37656
  const tables = [];
37657
+ const views = [];
35973
37658
  const { unregister } = await safeRegister();
35974
37659
  for (let i = 0; i < imports.length; i++) {
35975
37660
  const it = imports[i];
35976
37661
  const i0 = require(`${it}`);
35977
37662
  const prepared = prepareFromExports2(i0);
35978
37663
  tables.push(...prepared.tables);
37664
+ views.push(...prepared.views);
35979
37665
  }
35980
37666
  unregister();
35981
- return { tables: Array.from(new Set(tables)) };
37667
+ return { tables: Array.from(new Set(tables)), views };
35982
37668
  };
35983
37669
  }
35984
37670
  });
@@ -35998,25 +37684,31 @@ var init_mysqlImports = __esm({
35998
37684
  init_utils8();
35999
37685
  prepareFromExports3 = (exports2) => {
36000
37686
  const tables = [];
37687
+ const views = [];
36001
37688
  const i0values = Object.values(exports2);
36002
37689
  i0values.forEach((t) => {
36003
37690
  if (is(t, MySqlTable)) {
36004
37691
  tables.push(t);
36005
37692
  }
37693
+ if (is(t, MySqlView2)) {
37694
+ views.push(t);
37695
+ }
36006
37696
  });
36007
- return { tables };
37697
+ return { tables, views };
36008
37698
  };
36009
37699
  prepareFromMySqlImports = async (imports) => {
36010
37700
  const tables = [];
37701
+ const views = [];
36011
37702
  const { unregister } = await safeRegister();
36012
37703
  for (let i = 0; i < imports.length; i++) {
36013
37704
  const it = imports[i];
36014
37705
  const i0 = require(`${it}`);
36015
37706
  const prepared = prepareFromExports3(i0);
36016
37707
  tables.push(...prepared.tables);
37708
+ views.push(...prepared.views);
36017
37709
  }
36018
37710
  unregister();
36019
- return { tables: Array.from(new Set(tables)) };
37711
+ return { tables: Array.from(new Set(tables)), views };
36020
37712
  };
36021
37713
  }
36022
37714
  });
@@ -36405,6 +38097,7 @@ var pgSuggestions = async (db, statements) => {
36405
38097
  const columnsToRemove = [];
36406
38098
  const schemasToRemove = [];
36407
38099
  const tablesToTruncate = [];
38100
+ const matViewsToRemove = [];
36408
38101
  let renamedSchemas = {};
36409
38102
  let renamedTables = {};
36410
38103
  for (const statement of statements) {
@@ -36414,38 +38107,32 @@ var pgSuggestions = async (db, statements) => {
36414
38107
  renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
36415
38108
  } else if (statement.type === "drop_table") {
36416
38109
  const res = await db.query(
36417
- `select count(*) as count from ${tableNameWithSchemaFrom(
36418
- statement.schema,
36419
- statement.tableName,
36420
- renamedSchemas,
36421
- renamedTables
36422
- )}`
38110
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36423
38111
  );
36424
38112
  const count2 = Number(res[0].count);
38113
+ if (count2 > 0) {
38114
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count2} items`);
38115
+ tablesToRemove.push(statement.tableName);
38116
+ shouldAskForApprove = true;
38117
+ }
38118
+ } else if (statement.type === "drop_view" && statement.materialized) {
38119
+ const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
38120
+ const count2 = Number(res[0].count);
36425
38121
  if (count2 > 0) {
36426
38122
  infoToPrint.push(
36427
- `\xB7 You're about to delete ${source_default.underline(
36428
- statement.tableName
36429
- )} table with ${count2} items`
38123
+ `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count2} items`
36430
38124
  );
36431
- tablesToRemove.push(statement.tableName);
38125
+ matViewsToRemove.push(statement.name);
36432
38126
  shouldAskForApprove = true;
36433
38127
  }
36434
38128
  } else if (statement.type === "alter_table_drop_column") {
36435
38129
  const res = await db.query(
36436
- `select count(*) as count from ${tableNameWithSchemaFrom(
36437
- statement.schema,
36438
- statement.tableName,
36439
- renamedSchemas,
36440
- renamedTables
36441
- )}`
38130
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36442
38131
  );
36443
38132
  const count2 = Number(res[0].count);
36444
38133
  if (count2 > 0) {
36445
38134
  infoToPrint.push(
36446
- `\xB7 You're about to delete ${source_default.underline(
36447
- statement.columnName
36448
- )} column in ${statement.tableName} table with ${count2} items`
38135
+ `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count2} items`
36449
38136
  );
36450
38137
  columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
36451
38138
  shouldAskForApprove = true;
@@ -36456,58 +38143,35 @@ var pgSuggestions = async (db, statements) => {
36456
38143
  );
36457
38144
  const count2 = Number(res[0].count);
36458
38145
  if (count2 > 0) {
36459
- infoToPrint.push(
36460
- `\xB7 You're about to delete ${source_default.underline(
36461
- statement.name
36462
- )} schema with ${count2} tables`
36463
- );
38146
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count2} tables`);
36464
38147
  schemasToRemove.push(statement.name);
36465
38148
  shouldAskForApprove = true;
36466
38149
  }
36467
38150
  } else if (statement.type === "alter_table_alter_column_set_type") {
36468
38151
  const res = await db.query(
36469
- `select count(*) as count from ${tableNameWithSchemaFrom(
36470
- statement.schema,
36471
- statement.tableName,
36472
- renamedSchemas,
36473
- renamedTables
36474
- )}`
38152
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36475
38153
  );
36476
38154
  const count2 = Number(res[0].count);
36477
38155
  if (count2 > 0) {
36478
38156
  infoToPrint.push(
36479
- `\xB7 You're about to change ${source_default.underline(
36480
- statement.columnName
36481
- )} column type from ${source_default.underline(
36482
- statement.oldDataType
36483
- )} to ${source_default.underline(statement.newDataType)} with ${count2} items`
38157
+ `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
38158
+ statement.newDataType
38159
+ )} with ${count2} items`
36484
38160
  );
36485
38161
  statementsToExecute.push(
36486
- `truncate table ${tableNameWithSchemaFrom(
36487
- statement.schema,
36488
- statement.tableName,
36489
- renamedSchemas,
36490
- renamedTables
36491
- )} cascade;`
38162
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36492
38163
  );
36493
38164
  tablesToTruncate.push(statement.tableName);
36494
38165
  shouldAskForApprove = true;
36495
38166
  }
36496
38167
  } else if (statement.type === "alter_table_alter_column_drop_pk") {
36497
38168
  const res = await db.query(
36498
- `select count(*) as count from ${tableNameWithSchemaFrom(
36499
- statement.schema,
36500
- statement.tableName,
36501
- renamedSchemas,
36502
- renamedTables
36503
- )}`
38169
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36504
38170
  );
36505
38171
  const count2 = Number(res[0].count);
36506
38172
  if (count2 > 0) {
36507
38173
  infoToPrint.push(
36508
- `\xB7 You're about to change ${source_default.underline(
36509
- statement.tableName
36510
- )} primary key. This statements may fail and you table may left without primary key`
38174
+ `\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`
36511
38175
  );
36512
38176
  tablesToTruncate.push(statement.tableName);
36513
38177
  shouldAskForApprove = true;
@@ -36531,40 +38195,23 @@ var pgSuggestions = async (db, statements) => {
36531
38195
  } else if (statement.type === "alter_table_add_column") {
36532
38196
  if (statement.column.notNull && typeof statement.column.default === "undefined") {
36533
38197
  const res = await db.query(
36534
- `select count(*) as count from ${tableNameWithSchemaFrom(
36535
- statement.schema,
36536
- statement.tableName,
36537
- renamedSchemas,
36538
- renamedTables
36539
- )}`
38198
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36540
38199
  );
36541
38200
  const count2 = Number(res[0].count);
36542
38201
  if (count2 > 0) {
36543
38202
  infoToPrint.push(
36544
- `\xB7 You're about to add not-null ${source_default.underline(
36545
- statement.column.name
36546
- )} column without default value, which contains ${count2} items`
38203
+ `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count2} items`
36547
38204
  );
36548
38205
  tablesToTruncate.push(statement.tableName);
36549
38206
  statementsToExecute.push(
36550
- `truncate table ${tableNameWithSchemaFrom(
36551
- statement.schema,
36552
- statement.tableName,
36553
- renamedSchemas,
36554
- renamedTables
36555
- )} cascade;`
38207
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36556
38208
  );
36557
38209
  shouldAskForApprove = true;
36558
38210
  }
36559
38211
  }
36560
38212
  } else if (statement.type === "create_unique_constraint") {
36561
38213
  const res = await db.query(
36562
- `select count(*) as count from ${tableNameWithSchemaFrom(
36563
- statement.schema,
36564
- statement.tableName,
36565
- renamedSchemas,
36566
- renamedTables
36567
- )}`
38214
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36568
38215
  );
36569
38216
  const count2 = Number(res[0].count);
36570
38217
  if (count2 > 0) {
@@ -36578,20 +38225,12 @@ var pgSuggestions = async (db, statements) => {
36578
38225
  `
36579
38226
  );
36580
38227
  const { status, data } = await (0, import_hanji5.render)(
36581
- new Select([
36582
- "No, add the constraint without truncating the table",
36583
- `Yes, truncate the table`
36584
- ])
38228
+ new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
36585
38229
  );
36586
38230
  if (data?.index === 1) {
36587
38231
  tablesToTruncate.push(statement.tableName);
36588
38232
  statementsToExecute.push(
36589
- `truncate table ${tableNameWithSchemaFrom(
36590
- statement.schema,
36591
- statement.tableName,
36592
- renamedSchemas,
36593
- renamedTables
36594
- )} cascade;`
38233
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36595
38234
  );
36596
38235
  shouldAskForApprove = true;
36597
38236
  }
@@ -36601,10 +38240,7 @@ var pgSuggestions = async (db, statements) => {
36601
38240
  if (typeof stmnt !== "undefined") {
36602
38241
  if (statement.type === "drop_table") {
36603
38242
  statementsToExecute.push(
36604
- `DROP TABLE ${concatSchemaAndTableName(
36605
- statement.schema,
36606
- statement.tableName
36607
- )} CASCADE;`
38243
+ `DROP TABLE ${concatSchemaAndTableName(statement.schema, statement.tableName)} CASCADE;`
36608
38244
  );
36609
38245
  } else {
36610
38246
  statementsToExecute.push(...stmnt);
@@ -36615,6 +38251,7 @@ var pgSuggestions = async (db, statements) => {
36615
38251
  statementsToExecute,
36616
38252
  shouldAskForApprove,
36617
38253
  infoToPrint,
38254
+ matViewsToRemove: [...new Set(matViewsToRemove)],
36618
38255
  columnsToRemove: [...new Set(columnsToRemove)],
36619
38256
  schemasToRemove: [...new Set(schemasToRemove)],
36620
38257
  tablesToTruncate: [...new Set(tablesToTruncate)],
@@ -36794,6 +38431,9 @@ String.prototype.capitalise = function() {
36794
38431
  String.prototype.concatIf = function(it, condition) {
36795
38432
  return condition ? `${this}${it}` : String(this);
36796
38433
  };
38434
+ String.prototype.snake_case = function() {
38435
+ return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
38436
+ };
36797
38437
  Array.prototype.random = function() {
36798
38438
  return this[~~(Math.random() * this.length)];
36799
38439
  };
@@ -36854,6 +38494,8 @@ var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
36854
38494
  prepared.enums,
36855
38495
  prepared.schemas,
36856
38496
  prepared.sequences,
38497
+ prepared.views,
38498
+ prepared.matViews,
36857
38499
  casing2,
36858
38500
  schemaFilters
36859
38501
  );
@@ -36877,6 +38519,7 @@ var generateMigration = async (prev, cur) => {
36877
38519
  sequencesResolver,
36878
38520
  tablesResolver,
36879
38521
  columnsResolver,
38522
+ viewsResolver,
36880
38523
  validatedPrev,
36881
38524
  validatedCur
36882
38525
  );
@@ -36909,6 +38552,7 @@ var pushSchema = async (imports, drizzleInstance, schemaFilters) => {
36909
38552
  sequencesResolver,
36910
38553
  tablesResolver,
36911
38554
  columnsResolver,
38555
+ viewsResolver,
36912
38556
  validatedPrev,
36913
38557
  validatedCur,
36914
38558
  "push"
@@ -36929,7 +38573,7 @@ var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
36929
38573
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
36930
38574
  const prepared = prepareFromExports4(imports);
36931
38575
  const id = (0, import_crypto.randomUUID)();
36932
- const snapshot = generateSqliteSnapshot(prepared.tables, casing2);
38576
+ const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
36933
38577
  return {
36934
38578
  ...snapshot,
36935
38579
  id,
@@ -36947,6 +38591,7 @@ var generateSQLiteMigration = async (prev, cur) => {
36947
38591
  squashedCur,
36948
38592
  tablesResolver,
36949
38593
  columnsResolver,
38594
+ sqliteViewsResolver,
36950
38595
  validatedPrev,
36951
38596
  validatedCur
36952
38597
  );
@@ -36978,6 +38623,7 @@ var pushSQLiteSchema = async (imports, drizzleInstance) => {
36978
38623
  squashedCur,
36979
38624
  tablesResolver,
36980
38625
  columnsResolver,
38626
+ sqliteViewsResolver,
36981
38627
  validatedPrev,
36982
38628
  validatedCur,
36983
38629
  "push"
@@ -37004,7 +38650,7 @@ var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
37004
38650
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
37005
38651
  const prepared = prepareFromExports4(imports);
37006
38652
  const id = (0, import_crypto.randomUUID)();
37007
- const snapshot = generateMySqlSnapshot(prepared.tables, casing2);
38653
+ const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
37008
38654
  return {
37009
38655
  ...snapshot,
37010
38656
  id,
@@ -37022,6 +38668,7 @@ var generateMySQLMigration = async (prev, cur) => {
37022
38668
  squashedCur,
37023
38669
  tablesResolver,
37024
38670
  columnsResolver,
38671
+ mySqlViewsResolver,
37025
38672
  validatedPrev,
37026
38673
  validatedCur
37027
38674
  );
@@ -37049,6 +38696,7 @@ var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
37049
38696
  squashedCur,
37050
38697
  tablesResolver,
37051
38698
  columnsResolver,
38699
+ mySqlViewsResolver,
37052
38700
  validatedPrev,
37053
38701
  validatedCur,
37054
38702
  "push"