drizzle-kit 0.25.0-665fa03 → 0.25.0-6764bd8

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 +2006 -358
  4. package/api.mjs +2006 -358
  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.mjs CHANGED
@@ -567,7 +567,7 @@ function is(value, type) {
567
567
  `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.`
568
568
  );
569
569
  }
570
- let cls = value.constructor;
570
+ let cls = Object.getPrototypeOf(value).constructor;
571
571
  if (cls) {
572
572
  while (cls) {
573
573
  if (entityKind in cls && cls[entityKind] === type[entityKind]) {
@@ -3415,8 +3415,8 @@ var require_hanji = __commonJS({
3415
3415
  };
3416
3416
  exports.deferred = deferred;
3417
3417
  var Terminal = class {
3418
- constructor(view, stdin, stdout, closable) {
3419
- this.view = view;
3418
+ constructor(view4, stdin, stdout, closable) {
3419
+ this.view = view4;
3420
3420
  this.stdin = stdin;
3421
3421
  this.stdout = stdout;
3422
3422
  this.closable = closable;
@@ -3454,7 +3454,7 @@ var require_hanji = __commonJS({
3454
3454
  this.resolve({ status: "submitted", data: this.view.result() });
3455
3455
  return;
3456
3456
  }
3457
- view.input(str, key);
3457
+ view4.input(str, key);
3458
3458
  };
3459
3459
  this.stdin.on("keypress", keypress);
3460
3460
  this.view.attach(this);
@@ -3516,8 +3516,8 @@ var require_hanji = __commonJS({
3516
3516
  };
3517
3517
  exports.TaskView = TaskView2;
3518
3518
  var TaskTerminal = class {
3519
- constructor(view, stdout) {
3520
- this.view = view;
3519
+ constructor(view4, stdout) {
3520
+ this.view = view4;
3521
3521
  this.stdout = stdout;
3522
3522
  this.text = "";
3523
3523
  this.view.attach(this);
@@ -3536,22 +3536,22 @@ var require_hanji = __commonJS({
3536
3536
  }
3537
3537
  };
3538
3538
  exports.TaskTerminal = TaskTerminal;
3539
- function render6(view) {
3539
+ function render6(view4) {
3540
3540
  const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
3541
- if (view instanceof Prompt3) {
3542
- const terminal = new Terminal(view, stdin, stdout, closable);
3541
+ if (view4 instanceof Prompt3) {
3542
+ const terminal = new Terminal(view4, stdin, stdout, closable);
3543
3543
  terminal.requestLayout();
3544
3544
  return terminal.result();
3545
3545
  }
3546
- stdout.write(`${view}
3546
+ stdout.write(`${view4}
3547
3547
  `);
3548
3548
  closable.close();
3549
3549
  return;
3550
3550
  }
3551
3551
  exports.render = render6;
3552
- function renderWithTask4(view, task) {
3552
+ function renderWithTask4(view4, task) {
3553
3553
  return __awaiter(this, void 0, void 0, function* () {
3554
- const terminal = new TaskTerminal(view, process.stdout);
3554
+ const terminal = new TaskTerminal(view4, process.stdout);
3555
3555
  terminal.requestLayout();
3556
3556
  const result = yield task;
3557
3557
  terminal.clear();
@@ -5878,8 +5878,8 @@ var init_lib = __esm({
5878
5878
  unknownKeys: "strict",
5879
5879
  ...message !== void 0 ? {
5880
5880
  errorMap: (issue, ctx) => {
5881
- var _a324, _b233, _c12, _d5;
5882
- 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;
5881
+ var _a324, _b233, _c11, _d5;
5882
+ 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;
5883
5883
  if (issue.code === "unrecognized_keys")
5884
5884
  return {
5885
5885
  message: (_d5 = errorUtil.errToObj(message).message) !== null && _d5 !== void 0 ? _d5 : defaultError
@@ -7381,7 +7381,7 @@ var init_lib = __esm({
7381
7381
  });
7382
7382
 
7383
7383
  // src/serializer/mysqlSchema.ts
7384
- 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;
7384
+ 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;
7385
7385
  var init_mysqlSchema = __esm({
7386
7386
  "src/serializer/mysqlSchema.ts"() {
7387
7387
  "use strict";
@@ -7446,6 +7446,17 @@ var init_mysqlSchema = __esm({
7446
7446
  compositePrimaryKeys: recordType(stringType(), compositePK),
7447
7447
  uniqueConstraints: recordType(stringType(), uniqueConstraint).default({})
7448
7448
  }).strict();
7449
+ viewMeta = objectType({
7450
+ algorithm: enumType(["undefined", "merge", "temptable"]),
7451
+ sqlSecurity: enumType(["definer", "invoker"]),
7452
+ withCheckOption: enumType(["local", "cascaded"]).optional()
7453
+ }).strict();
7454
+ view = objectType({
7455
+ name: stringType(),
7456
+ columns: recordType(stringType(), column),
7457
+ definition: stringType().optional(),
7458
+ isExisting: booleanType()
7459
+ }).strict().merge(viewMeta);
7449
7460
  kitInternals = objectType({
7450
7461
  tables: recordType(
7451
7462
  stringType(),
@@ -7498,6 +7509,7 @@ var init_mysqlSchema = __esm({
7498
7509
  version: literalType("5"),
7499
7510
  dialect,
7500
7511
  tables: recordType(stringType(), table),
7512
+ views: recordType(stringType(), view),
7501
7513
  _meta: objectType({
7502
7514
  tables: recordType(stringType(), stringType()),
7503
7515
  columns: recordType(stringType(), stringType())
@@ -7523,10 +7535,16 @@ var init_mysqlSchema = __esm({
7523
7535
  compositePrimaryKeys: recordType(stringType(), stringType()),
7524
7536
  uniqueConstraints: recordType(stringType(), stringType()).default({})
7525
7537
  }).strict();
7538
+ viewSquashed = view.omit({
7539
+ algorithm: true,
7540
+ sqlSecurity: true,
7541
+ withCheckOption: true
7542
+ }).extend({ meta: stringType() });
7526
7543
  schemaSquashed = objectType({
7527
7544
  version: literalType("5"),
7528
7545
  dialect,
7529
- tables: recordType(stringType(), tableSquashed)
7546
+ tables: recordType(stringType(), tableSquashed),
7547
+ views: recordType(stringType(), viewSquashed)
7530
7548
  }).strict();
7531
7549
  schemaSquashedV4 = objectType({
7532
7550
  version: literalType("4"),
@@ -7588,6 +7606,18 @@ var init_mysqlSchema = __esm({
7588
7606
  onDelete
7589
7607
  });
7590
7608
  return result;
7609
+ },
7610
+ squashView: (view4) => {
7611
+ return `${view4.algorithm};${view4.sqlSecurity};${view4.withCheckOption}`;
7612
+ },
7613
+ unsquashView: (meta) => {
7614
+ const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
7615
+ const toReturn = {
7616
+ algorithm,
7617
+ sqlSecurity,
7618
+ withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
7619
+ };
7620
+ return viewMeta.parse(toReturn);
7591
7621
  }
7592
7622
  };
7593
7623
  squashMysqlScheme = (json3) => {
@@ -7621,10 +7651,23 @@ var init_mysqlSchema = __esm({
7621
7651
  ];
7622
7652
  })
7623
7653
  );
7654
+ const mappedViews = Object.fromEntries(
7655
+ Object.entries(json3.views).map(([key, value]) => {
7656
+ const meta = MySqlSquasher.squashView(value);
7657
+ return [key, {
7658
+ name: value.name,
7659
+ isExisting: value.isExisting,
7660
+ columns: value.columns,
7661
+ definition: value.definition,
7662
+ meta
7663
+ }];
7664
+ })
7665
+ );
7624
7666
  return {
7625
7667
  version: "5",
7626
7668
  dialect: json3.dialect,
7627
- tables: mappedTables
7669
+ tables: mappedTables,
7670
+ views: mappedViews
7628
7671
  };
7629
7672
  };
7630
7673
  mysqlSchema = schema;
@@ -7638,6 +7681,7 @@ var init_mysqlSchema = __esm({
7638
7681
  prevId: "",
7639
7682
  tables: {},
7640
7683
  schemas: {},
7684
+ views: {},
7641
7685
  _meta: {
7642
7686
  schemas: {},
7643
7687
  tables: {},
@@ -7666,7 +7710,7 @@ var init_vector = __esm({
7666
7710
  });
7667
7711
 
7668
7712
  // src/serializer/pgSchema.ts
7669
- 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;
7713
+ 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;
7670
7714
  var init_pgSchema = __esm({
7671
7715
  "src/serializer/pgSchema.ts"() {
7672
7716
  "use strict";
@@ -7861,6 +7905,44 @@ var init_pgSchema = __esm({
7861
7905
  columns: stringType().array(),
7862
7906
  nullsNotDistinct: booleanType()
7863
7907
  }).strict();
7908
+ viewWithOption = objectType({
7909
+ checkOption: enumType(["local", "cascaded"]).optional(),
7910
+ securityBarrier: booleanType().optional(),
7911
+ securityInvoker: booleanType().optional()
7912
+ }).strict();
7913
+ matViewWithOption = objectType({
7914
+ fillfactor: numberType().optional(),
7915
+ toastTupleTarget: numberType().optional(),
7916
+ parallelWorkers: numberType().optional(),
7917
+ autovacuumEnabled: booleanType().optional(),
7918
+ vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
7919
+ vacuumTruncate: booleanType().optional(),
7920
+ autovacuumVacuumThreshold: numberType().optional(),
7921
+ autovacuumVacuumScaleFactor: numberType().optional(),
7922
+ autovacuumVacuumCostDelay: numberType().optional(),
7923
+ autovacuumVacuumCostLimit: numberType().optional(),
7924
+ autovacuumFreezeMinAge: numberType().optional(),
7925
+ autovacuumFreezeMaxAge: numberType().optional(),
7926
+ autovacuumFreezeTableAge: numberType().optional(),
7927
+ autovacuumMultixactFreezeMinAge: numberType().optional(),
7928
+ autovacuumMultixactFreezeMaxAge: numberType().optional(),
7929
+ autovacuumMultixactFreezeTableAge: numberType().optional(),
7930
+ logAutovacuumMinDuration: numberType().optional(),
7931
+ userCatalogTable: booleanType().optional()
7932
+ }).strict();
7933
+ mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
7934
+ view2 = objectType({
7935
+ name: stringType(),
7936
+ schema: stringType(),
7937
+ columns: recordType(stringType(), column2),
7938
+ definition: stringType().optional(),
7939
+ materialized: booleanType(),
7940
+ with: mergedViewWithOption.optional(),
7941
+ isExisting: booleanType(),
7942
+ withNoData: booleanType().optional(),
7943
+ using: stringType().optional(),
7944
+ tablespace: stringType().optional()
7945
+ }).strict();
7864
7946
  tableV42 = objectType({
7865
7947
  name: stringType(),
7866
7948
  schema: stringType(),
@@ -7995,6 +8077,7 @@ var init_pgSchema = __esm({
7995
8077
  tables: recordType(stringType(), table2),
7996
8078
  enums: recordType(stringType(), enumSchema),
7997
8079
  schemas: recordType(stringType(), stringType()),
8080
+ views: recordType(stringType(), view2).default({}),
7998
8081
  sequences: recordType(stringType(), sequenceSchema).default({}),
7999
8082
  _meta: objectType({
8000
8083
  schemas: recordType(stringType(), stringType()),
@@ -8039,6 +8122,7 @@ var init_pgSchema = __esm({
8039
8122
  tables: recordType(stringType(), tableSquashed2),
8040
8123
  enums: recordType(stringType(), enumSchema),
8041
8124
  schemas: recordType(stringType(), stringType()),
8125
+ views: recordType(stringType(), view2),
8042
8126
  sequences: recordType(stringType(), sequenceSquashed)
8043
8127
  }).strict();
8044
8128
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
@@ -8256,6 +8340,7 @@ var init_pgSchema = __esm({
8256
8340
  tables: mappedTables,
8257
8341
  enums: json3.enums,
8258
8342
  schemas: json3.schemas,
8343
+ views: json3.views,
8259
8344
  sequences: mappedSequences
8260
8345
  };
8261
8346
  };
@@ -8278,7 +8363,7 @@ var init_pgSchema = __esm({
8278
8363
  });
8279
8364
 
8280
8365
  // src/serializer/sqliteSchema.ts
8281
- 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;
8366
+ 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;
8282
8367
  var init_sqliteSchema = __esm({
8283
8368
  "src/serializer/sqliteSchema.ts"() {
8284
8369
  "use strict";
@@ -8333,6 +8418,12 @@ var init_sqliteSchema = __esm({
8333
8418
  compositePrimaryKeys: recordType(stringType(), compositePK3),
8334
8419
  uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
8335
8420
  }).strict();
8421
+ view3 = objectType({
8422
+ name: stringType(),
8423
+ columns: recordType(stringType(), column3),
8424
+ definition: stringType().optional(),
8425
+ isExisting: booleanType()
8426
+ }).strict();
8336
8427
  dialect2 = enumType(["sqlite"]);
8337
8428
  schemaHash3 = objectType({
8338
8429
  id: stringType(),
@@ -8348,6 +8439,7 @@ var init_sqliteSchema = __esm({
8348
8439
  version: literalType("4"),
8349
8440
  dialect: dialect2,
8350
8441
  tables: recordType(stringType(), table3),
8442
+ views: recordType(stringType(), view3),
8351
8443
  enums: objectType({})
8352
8444
  }).strict();
8353
8445
  schemaInternalV52 = objectType({
@@ -8376,6 +8468,7 @@ var init_sqliteSchema = __esm({
8376
8468
  version: latestVersion,
8377
8469
  dialect: dialect2,
8378
8470
  tables: recordType(stringType(), table3),
8471
+ views: recordType(stringType(), view3),
8379
8472
  enums: objectType({}),
8380
8473
  _meta: objectType({
8381
8474
  tables: recordType(stringType(), stringType()),
@@ -8399,6 +8492,7 @@ var init_sqliteSchema = __esm({
8399
8492
  version: latestVersion,
8400
8493
  dialect: dialect2,
8401
8494
  tables: recordType(stringType(), tableSquashed3),
8495
+ views: recordType(stringType(), view3),
8402
8496
  enums: anyType()
8403
8497
  }).strict();
8404
8498
  SQLiteSquasher = {
@@ -8518,6 +8612,7 @@ var init_sqliteSchema = __esm({
8518
8612
  version: "6",
8519
8613
  dialect: json3.dialect,
8520
8614
  tables: mappedTables,
8615
+ views: json3.views,
8521
8616
  enums: json3.enums
8522
8617
  };
8523
8618
  };
@@ -8527,6 +8622,7 @@ var init_sqliteSchema = __esm({
8527
8622
  id: originUUID,
8528
8623
  prevId: "",
8529
8624
  tables: {},
8625
+ views: {},
8530
8626
  enums: {},
8531
8627
  _meta: {
8532
8628
  tables: {},
@@ -11222,6 +11318,7 @@ function applyJsonDiff(json1, json22) {
11222
11318
  difference.tables = difference.tables || {};
11223
11319
  difference.enums = difference.enums || {};
11224
11320
  difference.sequences = difference.sequences || {};
11321
+ difference.views = difference.views || {};
11225
11322
  const schemaKeys = Object.keys(difference.schemas);
11226
11323
  for (let key of schemaKeys) {
11227
11324
  if (key.endsWith("__added") || key.endsWith("__deleted")) {
@@ -11277,6 +11374,70 @@ function applyJsonDiff(json1, json22) {
11277
11374
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
11278
11375
  return json22.sequences[it[0]];
11279
11376
  });
11377
+ const viewsEntries = Object.entries(difference.views);
11378
+ const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
11379
+ ([nameWithSchema, view4]) => {
11380
+ const deletedWithOption = view4.with__deleted;
11381
+ const addedWithOption = view4.with__added;
11382
+ const deletedWith = Object.fromEntries(
11383
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
11384
+ return [key.replace("__deleted", ""), value];
11385
+ })
11386
+ );
11387
+ const addedWith = Object.fromEntries(
11388
+ Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
11389
+ return [key.replace("__added", ""), value];
11390
+ })
11391
+ );
11392
+ const alterWith = Object.fromEntries(
11393
+ Object.entries(view4.with || {}).filter(
11394
+ (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
11395
+ ).map(
11396
+ (it) => {
11397
+ return [it[0], it[1].__new];
11398
+ }
11399
+ )
11400
+ );
11401
+ const alteredSchema = view4.schema;
11402
+ const alteredDefinition = view4.definition;
11403
+ const alteredExisting = view4.isExisting;
11404
+ const addedTablespace = view4.tablespace__added;
11405
+ const droppedTablespace = view4.tablespace__deleted;
11406
+ const alterTablespaceTo = view4.tablespace;
11407
+ let alteredTablespace;
11408
+ if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
11409
+ if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
11410
+ if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
11411
+ const addedUsing = view4.using__added;
11412
+ const droppedUsing = view4.using__deleted;
11413
+ const alterUsingTo = view4.using;
11414
+ let alteredUsing;
11415
+ if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
11416
+ if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
11417
+ if (alterUsingTo) alteredUsing = alterUsingTo;
11418
+ const alteredMeta = view4.meta;
11419
+ return Object.fromEntries(
11420
+ Object.entries({
11421
+ name: json22.views[nameWithSchema].name,
11422
+ schema: json22.views[nameWithSchema].schema,
11423
+ // pg
11424
+ deletedWithOption,
11425
+ addedWithOption,
11426
+ deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
11427
+ addedWith: Object.keys(addedWith).length ? addedWith : void 0,
11428
+ alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
11429
+ alteredSchema,
11430
+ alteredTablespace,
11431
+ alteredUsing,
11432
+ // mysql
11433
+ alteredMeta,
11434
+ // common
11435
+ alteredDefinition,
11436
+ alteredExisting
11437
+ }).filter(([_2, value]) => value !== void 0)
11438
+ );
11439
+ }
11440
+ );
11280
11441
  const alteredTablesWithColumns = Object.values(difference.tables).map(
11281
11442
  (table4) => {
11282
11443
  return findAlternationsInTable(table4);
@@ -11285,7 +11446,8 @@ function applyJsonDiff(json1, json22) {
11285
11446
  return {
11286
11447
  alteredTablesWithColumns,
11287
11448
  alteredEnums,
11288
- alteredSequences
11449
+ alteredSequences,
11450
+ alteredViews
11289
11451
  };
11290
11452
  }
11291
11453
  var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
@@ -11680,7 +11842,7 @@ function fromJson(statements, dialect4, action, json22) {
11680
11842
  }).filter((it) => it !== "");
11681
11843
  return result;
11682
11844
  }
11683
- 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;
11845
+ 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;
11684
11846
  var init_sqlgenerator = __esm({
11685
11847
  "src/sqlgenerator.ts"() {
11686
11848
  "use strict";
@@ -11893,6 +12055,187 @@ var init_sqlgenerator = __esm({
11893
12055
  return statement;
11894
12056
  }
11895
12057
  };
12058
+ PgCreateViewConvertor = class extends Convertor {
12059
+ can(statement, dialect4) {
12060
+ return statement.type === "create_view" && dialect4 === "postgresql";
12061
+ }
12062
+ convert(st) {
12063
+ const { definition, name: viewName, schema: schema4, with: withOption, materialized, withNoData, tablespace, using } = st;
12064
+ const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
12065
+ let statement = materialized ? `CREATE MATERIALIZED VIEW ${name2}` : `CREATE VIEW ${name2}`;
12066
+ if (using) statement += ` USING "${using}"`;
12067
+ const options = [];
12068
+ if (withOption) {
12069
+ statement += ` WITH (`;
12070
+ Object.entries(withOption).forEach(([key, value]) => {
12071
+ if (typeof value === "undefined") return;
12072
+ options.push(`${key.snake_case()} = ${value}`);
12073
+ });
12074
+ statement += options.join(", ");
12075
+ statement += `)`;
12076
+ }
12077
+ if (tablespace) statement += ` TABLESPACE ${tablespace}`;
12078
+ statement += ` AS (${definition})`;
12079
+ if (withNoData) statement += ` WITH NO DATA`;
12080
+ statement += `;`;
12081
+ return statement;
12082
+ }
12083
+ };
12084
+ MySqlCreateViewConvertor = class extends Convertor {
12085
+ can(statement, dialect4) {
12086
+ return statement.type === "mysql_create_view" && dialect4 === "mysql";
12087
+ }
12088
+ convert(st) {
12089
+ const { definition, name: name2, algorithm, sqlSecurity, withCheckOption, replace } = st;
12090
+ let statement = `CREATE `;
12091
+ statement += replace ? `OR REPLACE ` : "";
12092
+ statement += algorithm ? `ALGORITHM = ${algorithm}
12093
+ ` : "";
12094
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
12095
+ ` : "";
12096
+ statement += `VIEW \`${name2}\` AS (${definition})`;
12097
+ statement += withCheckOption ? `
12098
+ WITH ${withCheckOption} CHECK OPTION` : "";
12099
+ statement += ";";
12100
+ return statement;
12101
+ }
12102
+ };
12103
+ SqliteCreateViewConvertor = class extends Convertor {
12104
+ can(statement, dialect4) {
12105
+ return statement.type === "sqlite_create_view" && (dialect4 === "sqlite" || dialect4 === "turso");
12106
+ }
12107
+ convert(st) {
12108
+ const { definition, name: name2 } = st;
12109
+ return `CREATE VIEW \`${name2}\` AS ${definition};`;
12110
+ }
12111
+ };
12112
+ PgDropViewConvertor = class extends Convertor {
12113
+ can(statement, dialect4) {
12114
+ return statement.type === "drop_view" && dialect4 === "postgresql";
12115
+ }
12116
+ convert(st) {
12117
+ const { name: viewName, schema: schema4, materialized } = st;
12118
+ const name2 = schema4 ? `"${schema4}"."${viewName}"` : `"${viewName}"`;
12119
+ return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name2};`;
12120
+ }
12121
+ };
12122
+ MySqlDropViewConvertor = class extends Convertor {
12123
+ can(statement, dialect4) {
12124
+ return statement.type === "drop_view" && dialect4 === "mysql";
12125
+ }
12126
+ convert(st) {
12127
+ const { name: name2 } = st;
12128
+ return `DROP VIEW \`${name2}\`;`;
12129
+ }
12130
+ };
12131
+ SqliteDropViewConvertor = class extends Convertor {
12132
+ can(statement, dialect4) {
12133
+ return statement.type === "drop_view" && (dialect4 === "sqlite" || dialect4 === "turso");
12134
+ }
12135
+ convert(st) {
12136
+ const { name: name2 } = st;
12137
+ return `DROP VIEW \`${name2}\`;`;
12138
+ }
12139
+ };
12140
+ MySqlAlterViewConvertor = class extends Convertor {
12141
+ can(statement, dialect4) {
12142
+ return statement.type === "alter_mysql_view" && dialect4 === "mysql";
12143
+ }
12144
+ convert(st) {
12145
+ const { name: name2, algorithm, definition, sqlSecurity, withCheckOption } = st;
12146
+ let statement = `ALTER `;
12147
+ statement += algorithm ? `ALGORITHM = ${algorithm}
12148
+ ` : "";
12149
+ statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
12150
+ ` : "";
12151
+ statement += `VIEW \`${name2}\` AS ${definition}`;
12152
+ statement += withCheckOption ? `
12153
+ WITH ${withCheckOption} CHECK OPTION` : "";
12154
+ statement += ";";
12155
+ return statement;
12156
+ }
12157
+ };
12158
+ PgRenameViewConvertor = class extends Convertor {
12159
+ can(statement, dialect4) {
12160
+ return statement.type === "rename_view" && dialect4 === "postgresql";
12161
+ }
12162
+ convert(st) {
12163
+ const { nameFrom: from, nameTo: to, schema: schema4, materialized } = st;
12164
+ const nameFrom = `"${schema4}"."${from}"`;
12165
+ return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
12166
+ }
12167
+ };
12168
+ MySqlRenameViewConvertor = class extends Convertor {
12169
+ can(statement, dialect4) {
12170
+ return statement.type === "rename_view" && dialect4 === "mysql";
12171
+ }
12172
+ convert(st) {
12173
+ const { nameFrom: from, nameTo: to } = st;
12174
+ return `RENAME TABLE \`${from}\` RENAME TO \`${to}\`;`;
12175
+ }
12176
+ };
12177
+ PgAlterViewSchemaConvertor = class extends Convertor {
12178
+ can(statement, dialect4) {
12179
+ return statement.type === "alter_view_alter_schema" && dialect4 === "postgresql";
12180
+ }
12181
+ convert(st) {
12182
+ const { fromSchema, toSchema, name: name2, materialized } = st;
12183
+ const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name2}" SET SCHEMA "${toSchema}";`;
12184
+ return statement;
12185
+ }
12186
+ };
12187
+ PgAlterViewAddWithOptionConvertor = class extends Convertor {
12188
+ can(statement, dialect4) {
12189
+ return statement.type === "alter_view_add_with_option" && dialect4 === "postgresql";
12190
+ }
12191
+ convert(st) {
12192
+ const { schema: schema4, with: withOption, name: name2, materialized } = st;
12193
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${name2}" SET (`;
12194
+ const options = [];
12195
+ Object.entries(withOption).forEach(([key, value]) => {
12196
+ options.push(`${key.snake_case()} = ${value}`);
12197
+ });
12198
+ statement += options.join(", ");
12199
+ statement += `);`;
12200
+ return statement;
12201
+ }
12202
+ };
12203
+ PgAlterViewDropWithOptionConvertor = class extends Convertor {
12204
+ can(statement, dialect4) {
12205
+ return statement.type === "alter_view_drop_with_option" && dialect4 === "postgresql";
12206
+ }
12207
+ convert(st) {
12208
+ const { schema: schema4, name: name2, materialized, with: withOptions } = st;
12209
+ let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema4}"."${name2}" RESET (`;
12210
+ const options = [];
12211
+ Object.entries(withOptions).forEach(([key, value]) => {
12212
+ options.push(`${key.snake_case()}`);
12213
+ });
12214
+ statement += options.join(", ");
12215
+ statement += ");";
12216
+ return statement;
12217
+ }
12218
+ };
12219
+ PgAlterViewAlterTablespaceConvertor = class extends Convertor {
12220
+ can(statement, dialect4) {
12221
+ return statement.type === "alter_view_alter_tablespace" && dialect4 === "postgresql";
12222
+ }
12223
+ convert(st) {
12224
+ const { schema: schema4, name: name2, toTablespace } = st;
12225
+ const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET TABLESPACE ${toTablespace};`;
12226
+ return statement;
12227
+ }
12228
+ };
12229
+ PgAlterViewAlterUsingConvertor = class extends Convertor {
12230
+ can(statement, dialect4) {
12231
+ return statement.type === "alter_view_alter_using" && dialect4 === "postgresql";
12232
+ }
12233
+ convert(st) {
12234
+ const { schema: schema4, name: name2, toUsing } = st;
12235
+ const statement = `ALTER MATERIALIZED VIEW "${schema4}"."${name2}" SET ACCESS METHOD "${toUsing}";`;
12236
+ return statement;
12237
+ }
12238
+ };
11896
12239
  PgAlterTableAlterColumnSetGenerated = class extends Convertor {
11897
12240
  can(statement, dialect4) {
11898
12241
  return statement.type === "alter_table_alter_column_set_identity" && dialect4 === "postgresql";
@@ -12061,20 +12404,22 @@ var init_sqlgenerator = __esm({
12061
12404
  }
12062
12405
  convert(st) {
12063
12406
  const { name: name2, values, schema: schema4 } = st;
12064
- const tableNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12407
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12065
12408
  let valuesStatement = "(";
12066
12409
  valuesStatement += values.map((it) => `'${it}'`).join(", ");
12067
12410
  valuesStatement += ")";
12068
- let statement = "DO $$ BEGIN";
12069
- statement += "\n";
12070
- statement += ` CREATE TYPE ${tableNameWithSchema} AS ENUM${valuesStatement};`;
12071
- statement += "\n";
12072
- statement += "EXCEPTION";
12073
- statement += "\n";
12074
- statement += " WHEN duplicate_object THEN null;";
12075
- statement += "\n";
12076
- statement += "END $$;";
12077
- statement += "\n";
12411
+ let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
12412
+ return statement;
12413
+ }
12414
+ };
12415
+ DropTypeEnumConvertor = class extends Convertor {
12416
+ can(statement) {
12417
+ return statement.type === "drop_type_enum";
12418
+ }
12419
+ convert(st) {
12420
+ const { name: name2, schema: schema4 } = st;
12421
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12422
+ let statement = `DROP TYPE ${enumNameWithSchema};`;
12078
12423
  return statement;
12079
12424
  }
12080
12425
  };
@@ -12083,9 +12428,56 @@ var init_sqlgenerator = __esm({
12083
12428
  return statement.type === "alter_type_add_value";
12084
12429
  }
12085
12430
  convert(st) {
12086
- const { name: name2, schema: schema4, value } = st;
12087
- const schemaPrefix = schema4 && schema4 !== "public" ? `"${schema4}".` : "";
12088
- return `ALTER TYPE ${schemaPrefix}"${name2}" ADD VALUE '${value}';`;
12431
+ const { name: name2, schema: schema4, value, before } = st;
12432
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${name2}"` : `"${name2}"`;
12433
+ return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
12434
+ }
12435
+ };
12436
+ AlterTypeSetSchemaConvertor = class extends Convertor {
12437
+ can(statement) {
12438
+ return statement.type === "move_type_enum";
12439
+ }
12440
+ convert(st) {
12441
+ const { name: name2, schemaFrom, schemaTo } = st;
12442
+ const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name2}"` : `"${name2}"`;
12443
+ return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
12444
+ }
12445
+ };
12446
+ AlterRenameTypeConvertor = class extends Convertor {
12447
+ can(statement) {
12448
+ return statement.type === "rename_type_enum";
12449
+ }
12450
+ convert(st) {
12451
+ const { nameTo, nameFrom, schema: schema4 } = st;
12452
+ const enumNameWithSchema = schema4 ? `"${schema4}"."${nameFrom}"` : `"${nameFrom}"`;
12453
+ return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
12454
+ }
12455
+ };
12456
+ AlterTypeDropValueConvertor = class extends Convertor {
12457
+ can(statement) {
12458
+ return statement.type === "alter_type_drop_value";
12459
+ }
12460
+ convert(st) {
12461
+ const { columnsWithEnum, name: name2, newValues, schema: schema4 } = st;
12462
+ const statements = [];
12463
+ for (const withEnum of columnsWithEnum) {
12464
+ statements.push(
12465
+ `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
12466
+ );
12467
+ }
12468
+ statements.push(new DropTypeEnumConvertor().convert({ name: name2, schema: schema4, type: "drop_type_enum" }));
12469
+ statements.push(new CreateTypeEnumConvertor().convert({
12470
+ name: name2,
12471
+ schema: schema4,
12472
+ values: newValues,
12473
+ type: "create_type_enum"
12474
+ }));
12475
+ for (const withEnum of columnsWithEnum) {
12476
+ statements.push(
12477
+ `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE "${schema4}"."${name2}" USING "${withEnum.column}"::"${schema4}"."${name2}";`
12478
+ );
12479
+ }
12480
+ return statements;
12089
12481
  }
12090
12482
  };
12091
12483
  PgDropTableConvertor = class extends Convertor {
@@ -13228,7 +13620,26 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13228
13620
  convertors.push(new SQLiteCreateTableConvertor());
13229
13621
  convertors.push(new SQLiteRecreateTableConvertor());
13230
13622
  convertors.push(new LibSQLRecreateTableConvertor());
13623
+ convertors.push(new PgCreateViewConvertor());
13624
+ convertors.push(new PgDropViewConvertor());
13625
+ convertors.push(new PgRenameViewConvertor());
13626
+ convertors.push(new PgAlterViewSchemaConvertor());
13627
+ convertors.push(new PgAlterViewAddWithOptionConvertor());
13628
+ convertors.push(new PgAlterViewDropWithOptionConvertor());
13629
+ convertors.push(new PgAlterViewAlterTablespaceConvertor());
13630
+ convertors.push(new PgAlterViewAlterUsingConvertor());
13631
+ convertors.push(new MySqlCreateViewConvertor());
13632
+ convertors.push(new MySqlDropViewConvertor());
13633
+ convertors.push(new MySqlRenameViewConvertor());
13634
+ convertors.push(new MySqlAlterViewConvertor());
13635
+ convertors.push(new SqliteCreateViewConvertor());
13636
+ convertors.push(new SqliteDropViewConvertor());
13231
13637
  convertors.push(new CreateTypeEnumConvertor());
13638
+ convertors.push(new DropTypeEnumConvertor());
13639
+ convertors.push(new AlterTypeAddValueConvertor());
13640
+ convertors.push(new AlterTypeSetSchemaConvertor());
13641
+ convertors.push(new AlterRenameTypeConvertor());
13642
+ convertors.push(new AlterTypeDropValueConvertor());
13232
13643
  convertors.push(new CreatePgSequenceConvertor());
13233
13644
  convertors.push(new DropPgSequenceConvertor());
13234
13645
  convertors.push(new RenamePgSequenceConvertor());
@@ -13260,7 +13671,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
13260
13671
  convertors.push(new PgDropIndexConvertor());
13261
13672
  convertors.push(new SqliteDropIndexConvertor());
13262
13673
  convertors.push(new MySqlDropIndexConvertor());
13263
- convertors.push(new AlterTypeAddValueConvertor());
13264
13674
  convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
13265
13675
  convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
13266
13676
  convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
@@ -13561,7 +13971,7 @@ var init_sqlitePushUtils = __esm({
13561
13971
  });
13562
13972
 
13563
13973
  // src/jsonStatements.ts
13564
- 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;
13974
+ 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;
13565
13975
  var init_jsonStatements = __esm({
13566
13976
  "src/jsonStatements.ts"() {
13567
13977
  "use strict";
@@ -13651,6 +14061,27 @@ var init_jsonStatements = __esm({
13651
14061
  };
13652
14062
  });
13653
14063
  };
14064
+ prepareDropEnumValues = (name2, schema4, removedValues, json22) => {
14065
+ if (!removedValues.length) return [];
14066
+ const affectedColumns = [];
14067
+ for (const tableKey2 in json22.tables) {
14068
+ const table4 = json22.tables[tableKey2];
14069
+ for (const columnKey in table4.columns) {
14070
+ const column4 = table4.columns[columnKey];
14071
+ if (column4.type === name2 && column4.typeSchema === schema4) {
14072
+ affectedColumns.push({ schema: table4.schema || "public", table: table4.name, column: column4.name });
14073
+ }
14074
+ }
14075
+ }
14076
+ return [{
14077
+ type: "alter_type_drop_value",
14078
+ name: name2,
14079
+ schema: schema4,
14080
+ deletedValues: removedValues,
14081
+ newValues: json22.enums[`${schema4}.${name2}`].values,
14082
+ columnsWithEnum: affectedColumns
14083
+ }];
14084
+ };
13654
14085
  prepareDropEnumJson = (name2, schema4) => {
13655
14086
  return {
13656
14087
  type: "drop_type_enum",
@@ -14894,6 +15325,103 @@ var init_jsonStatements = __esm({
14894
15325
  };
14895
15326
  });
14896
15327
  };
15328
+ preparePgCreateViewJson = (name2, schema4, definition, materialized, withNoData = false, withOption, using, tablespace) => {
15329
+ return {
15330
+ type: "create_view",
15331
+ name: name2,
15332
+ schema: schema4,
15333
+ definition,
15334
+ with: withOption,
15335
+ materialized,
15336
+ withNoData,
15337
+ using,
15338
+ tablespace
15339
+ };
15340
+ };
15341
+ prepareMySqlCreateViewJson = (name2, definition, meta, replace = false) => {
15342
+ const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
15343
+ return {
15344
+ type: "mysql_create_view",
15345
+ name: name2,
15346
+ definition,
15347
+ algorithm,
15348
+ sqlSecurity,
15349
+ withCheckOption,
15350
+ replace
15351
+ };
15352
+ };
15353
+ prepareSqliteCreateViewJson = (name2, definition) => {
15354
+ return {
15355
+ type: "sqlite_create_view",
15356
+ name: name2,
15357
+ definition
15358
+ };
15359
+ };
15360
+ prepareDropViewJson = (name2, schema4, materialized) => {
15361
+ const resObject = { name: name2, type: "drop_view" };
15362
+ if (schema4) resObject["schema"] = schema4;
15363
+ if (materialized) resObject["materialized"] = materialized;
15364
+ return resObject;
15365
+ };
15366
+ prepareRenameViewJson = (to, from, schema4, materialized) => {
15367
+ const resObject = {
15368
+ type: "rename_view",
15369
+ nameTo: to,
15370
+ nameFrom: from
15371
+ };
15372
+ if (schema4) resObject["schema"] = schema4;
15373
+ if (materialized) resObject["materialized"] = materialized;
15374
+ return resObject;
15375
+ };
15376
+ preparePgAlterViewAlterSchemaJson = (to, from, name2, materialized) => {
15377
+ const returnObject = {
15378
+ type: "alter_view_alter_schema",
15379
+ fromSchema: from,
15380
+ toSchema: to,
15381
+ name: name2
15382
+ };
15383
+ if (materialized) returnObject["materialized"] = materialized;
15384
+ return returnObject;
15385
+ };
15386
+ preparePgAlterViewAddWithOptionJson = (name2, schema4, materialized, withOption) => {
15387
+ return {
15388
+ type: "alter_view_add_with_option",
15389
+ name: name2,
15390
+ schema: schema4,
15391
+ materialized,
15392
+ with: withOption
15393
+ };
15394
+ };
15395
+ preparePgAlterViewDropWithOptionJson = (name2, schema4, materialized, withOption) => {
15396
+ return {
15397
+ type: "alter_view_drop_with_option",
15398
+ name: name2,
15399
+ schema: schema4,
15400
+ materialized,
15401
+ with: withOption
15402
+ };
15403
+ };
15404
+ preparePgAlterViewAlterTablespaceJson = (name2, schema4, materialized, to) => {
15405
+ return {
15406
+ type: "alter_view_alter_tablespace",
15407
+ name: name2,
15408
+ schema: schema4,
15409
+ materialized,
15410
+ toTablespace: to
15411
+ };
15412
+ };
15413
+ preparePgAlterViewAlterUsingJson = (name2, schema4, materialized, to) => {
15414
+ return {
15415
+ type: "alter_view_alter_using",
15416
+ name: name2,
15417
+ schema: schema4,
15418
+ materialized,
15419
+ toUsing: to
15420
+ };
15421
+ };
15422
+ prepareMySqlAlterView = (view4) => {
15423
+ return { type: "alter_mysql_view", ...view4 };
15424
+ };
14897
15425
  }
14898
15426
  });
14899
15427
 
@@ -15181,6 +15709,7 @@ var init_statementCombiner = __esm({
15181
15709
  // src/snapshotsDiffer.ts
15182
15710
  var snapshotsDiffer_exports = {};
15183
15711
  __export(snapshotsDiffer_exports, {
15712
+ alteredPgViewSchema: () => alteredPgViewSchema,
15184
15713
  alteredTableScheme: () => alteredTableScheme,
15185
15714
  applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff,
15186
15715
  applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff,
@@ -15192,7 +15721,7 @@ __export(snapshotsDiffer_exports, {
15192
15721
  makePatched: () => makePatched,
15193
15722
  makeSelfOrPatched: () => makeSelfOrPatched
15194
15723
  });
15195
- var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
15724
+ 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;
15196
15725
  var init_snapshotsDiffer = __esm({
15197
15726
  "src/snapshotsDiffer.ts"() {
15198
15727
  "use strict";
@@ -15361,18 +15890,62 @@ var init_snapshotsDiffer = __esm({
15361
15890
  })
15362
15891
  )
15363
15892
  }).strict();
15893
+ alteredViewCommon = objectType({
15894
+ name: stringType(),
15895
+ alteredDefinition: objectType({
15896
+ __old: stringType(),
15897
+ __new: stringType()
15898
+ }).strict().optional(),
15899
+ alteredExisting: objectType({
15900
+ __old: booleanType(),
15901
+ __new: booleanType()
15902
+ }).strict().optional()
15903
+ });
15904
+ alteredPgViewSchema = alteredViewCommon.merge(
15905
+ objectType({
15906
+ schema: stringType(),
15907
+ deletedWithOption: mergedViewWithOption.optional(),
15908
+ addedWithOption: mergedViewWithOption.optional(),
15909
+ addedWith: mergedViewWithOption.optional(),
15910
+ deletedWith: mergedViewWithOption.optional(),
15911
+ alteredWith: mergedViewWithOption.optional(),
15912
+ alteredSchema: objectType({
15913
+ __old: stringType(),
15914
+ __new: stringType()
15915
+ }).strict().optional(),
15916
+ alteredTablespace: objectType({
15917
+ __old: stringType(),
15918
+ __new: stringType()
15919
+ }).strict().optional(),
15920
+ alteredUsing: objectType({
15921
+ __old: stringType(),
15922
+ __new: stringType()
15923
+ }).strict().optional()
15924
+ }).strict()
15925
+ );
15926
+ alteredMySqlViewSchema = alteredViewCommon.merge(
15927
+ objectType({
15928
+ alteredMeta: objectType({
15929
+ __old: stringType(),
15930
+ __new: stringType()
15931
+ }).strict().optional()
15932
+ }).strict()
15933
+ );
15364
15934
  diffResultScheme = objectType({
15365
15935
  alteredTablesWithColumns: alteredTableScheme.array(),
15366
15936
  alteredEnums: changedEnumSchema.array(),
15367
- alteredSequences: sequenceSquashed.array()
15937
+ alteredSequences: sequenceSquashed.array(),
15938
+ alteredViews: alteredPgViewSchema.array()
15368
15939
  }).strict();
15369
15940
  diffResultSchemeMysql = objectType({
15370
15941
  alteredTablesWithColumns: alteredTableScheme.array(),
15371
- alteredEnums: neverType().array()
15942
+ alteredEnums: neverType().array(),
15943
+ alteredViews: alteredMySqlViewSchema.array()
15372
15944
  });
15373
15945
  diffResultSchemeSQLite = objectType({
15374
15946
  alteredTablesWithColumns: alteredTableScheme.array(),
15375
- alteredEnums: neverType().array()
15947
+ alteredEnums: neverType().array(),
15948
+ alteredViews: alteredViewCommon.array()
15376
15949
  });
15377
15950
  schemaChangeFor = (table4, renamedSchemas) => {
15378
15951
  for (let ren of renamedSchemas) {
@@ -15419,7 +15992,7 @@ var init_snapshotsDiffer = __esm({
15419
15992
  }
15420
15993
  return column4;
15421
15994
  };
15422
- applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
15995
+ applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
15423
15996
  const schemasDiff = diffSchemasOrTables(json1.schemas, json22.schemas);
15424
15997
  const {
15425
15998
  created: createdSchemas,
@@ -15647,7 +16220,39 @@ var init_snapshotsDiffer = __esm({
15647
16220
  return [tableKey2, tableValue];
15648
16221
  }
15649
16222
  );
15650
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
16223
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
16224
+ const {
16225
+ created: createdViews,
16226
+ deleted: deletedViews,
16227
+ renamed: renamedViews,
16228
+ moved: movedViews
16229
+ } = await viewsResolver2({
16230
+ created: viewsDiff.added,
16231
+ deleted: viewsDiff.deleted
16232
+ });
16233
+ const renamesViewDic = {};
16234
+ renamedViews.forEach((it) => {
16235
+ renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
16236
+ });
16237
+ const movedViewDic = {};
16238
+ movedViews.forEach((it) => {
16239
+ movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
16240
+ });
16241
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
16242
+ viewsPatchedSnap1.views = mapEntries(
16243
+ viewsPatchedSnap1.views,
16244
+ (viewKey, viewValue) => {
16245
+ const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
16246
+ const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
16247
+ if (rename) {
16248
+ viewValue.name = rename.to;
16249
+ viewKey = `${viewValue.schema}.${viewValue.name}`;
16250
+ }
16251
+ if (moved) viewKey = `${moved.to}.${viewValue.name}`;
16252
+ return [viewKey, viewValue];
16253
+ }
16254
+ );
16255
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
15651
16256
  const typedResult = diffResultScheme.parse(diffResult);
15652
16257
  const jsonStatements = [];
15653
16258
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -15872,6 +16477,9 @@ var init_snapshotsDiffer = __esm({
15872
16477
  const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
15873
16478
  return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
15874
16479
  }).flat() ?? [];
16480
+ const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
16481
+ return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
16482
+ }).flat() ?? [];
15875
16483
  const createSequences = createdSequences.map((it) => {
15876
16484
  return prepareCreateSequenceJson(it);
15877
16485
  }) ?? [];
@@ -15899,6 +16507,137 @@ var init_snapshotsDiffer = __esm({
15899
16507
  const createTables = createdTables.map((it) => {
15900
16508
  return preparePgCreateTableJson(it, curFull);
15901
16509
  });
16510
+ const createViews = [];
16511
+ const dropViews = [];
16512
+ const renameViews = [];
16513
+ const alterViews = [];
16514
+ createViews.push(
16515
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
16516
+ return preparePgCreateViewJson(
16517
+ it.name,
16518
+ it.schema,
16519
+ it.definition,
16520
+ it.materialized,
16521
+ it.withNoData,
16522
+ it.with,
16523
+ it.using,
16524
+ it.tablespace
16525
+ );
16526
+ })
16527
+ );
16528
+ dropViews.push(
16529
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
16530
+ return prepareDropViewJson(it.name, it.schema, it.materialized);
16531
+ })
16532
+ );
16533
+ renameViews.push(
16534
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
16535
+ return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
16536
+ })
16537
+ );
16538
+ alterViews.push(
16539
+ ...movedViews.filter(
16540
+ (it) => !json22.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
16541
+ ).map((it) => {
16542
+ return preparePgAlterViewAlterSchemaJson(
16543
+ it.schemaTo,
16544
+ it.schemaFrom,
16545
+ it.name,
16546
+ json22.views[`${it.schemaTo}.${it.name}`].materialized
16547
+ );
16548
+ })
16549
+ );
16550
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[`${it.schema}.${it.name}`].isExisting);
16551
+ for (const alteredView of alteredViews) {
16552
+ const viewKey = `${alteredView.schema}.${alteredView.name}`;
16553
+ const { materialized, with: withOption, definition, withNoData, using, tablespace } = json22.views[viewKey];
16554
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
16555
+ dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
16556
+ createViews.push(
16557
+ preparePgCreateViewJson(
16558
+ alteredView.name,
16559
+ alteredView.schema,
16560
+ definition,
16561
+ materialized,
16562
+ withNoData,
16563
+ withOption,
16564
+ using,
16565
+ tablespace
16566
+ )
16567
+ );
16568
+ continue;
16569
+ }
16570
+ if (alteredView.addedWithOption) {
16571
+ alterViews.push(
16572
+ preparePgAlterViewAddWithOptionJson(
16573
+ alteredView.name,
16574
+ alteredView.schema,
16575
+ materialized,
16576
+ alteredView.addedWithOption
16577
+ )
16578
+ );
16579
+ }
16580
+ if (alteredView.deletedWithOption) {
16581
+ alterViews.push(
16582
+ preparePgAlterViewDropWithOptionJson(
16583
+ alteredView.name,
16584
+ alteredView.schema,
16585
+ materialized,
16586
+ alteredView.deletedWithOption
16587
+ )
16588
+ );
16589
+ }
16590
+ if (alteredView.addedWith) {
16591
+ alterViews.push(
16592
+ preparePgAlterViewAddWithOptionJson(
16593
+ alteredView.name,
16594
+ alteredView.schema,
16595
+ materialized,
16596
+ alteredView.addedWith
16597
+ )
16598
+ );
16599
+ }
16600
+ if (alteredView.deletedWith) {
16601
+ alterViews.push(
16602
+ preparePgAlterViewDropWithOptionJson(
16603
+ alteredView.name,
16604
+ alteredView.schema,
16605
+ materialized,
16606
+ alteredView.deletedWith
16607
+ )
16608
+ );
16609
+ }
16610
+ if (alteredView.alteredWith) {
16611
+ alterViews.push(
16612
+ preparePgAlterViewAddWithOptionJson(
16613
+ alteredView.name,
16614
+ alteredView.schema,
16615
+ materialized,
16616
+ alteredView.alteredWith
16617
+ )
16618
+ );
16619
+ }
16620
+ if (alteredView.alteredTablespace) {
16621
+ alterViews.push(
16622
+ preparePgAlterViewAlterTablespaceJson(
16623
+ alteredView.name,
16624
+ alteredView.schema,
16625
+ materialized,
16626
+ alteredView.alteredTablespace.__new
16627
+ )
16628
+ );
16629
+ }
16630
+ if (alteredView.alteredUsing) {
16631
+ alterViews.push(
16632
+ preparePgAlterViewAlterUsingJson(
16633
+ alteredView.name,
16634
+ alteredView.schema,
16635
+ materialized,
16636
+ alteredView.alteredUsing.__new
16637
+ )
16638
+ );
16639
+ }
16640
+ }
15902
16641
  jsonStatements.push(...createSchemas);
15903
16642
  jsonStatements.push(...renameSchemas);
15904
16643
  jsonStatements.push(...createEnums);
@@ -15910,6 +16649,9 @@ var init_snapshotsDiffer = __esm({
15910
16649
  jsonStatements.push(...renameSequences);
15911
16650
  jsonStatements.push(...jsonAlterSequences);
15912
16651
  jsonStatements.push(...createTables);
16652
+ jsonStatements.push(...dropViews);
16653
+ jsonStatements.push(...renameViews);
16654
+ jsonStatements.push(...alterViews);
15913
16655
  jsonStatements.push(...jsonDropTables);
15914
16656
  jsonStatements.push(...jsonSetTableSchemas);
15915
16657
  jsonStatements.push(...jsonRenameTables);
@@ -15929,6 +16671,8 @@ var init_snapshotsDiffer = __esm({
15929
16671
  jsonStatements.push(...jsonAlteredCompositePKs);
15930
16672
  jsonStatements.push(...jsonAddedUniqueConstraints);
15931
16673
  jsonStatements.push(...jsonAlteredUniqueConstraints);
16674
+ jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
16675
+ jsonStatements.push(...createViews);
15932
16676
  jsonStatements.push(...dropEnums);
15933
16677
  jsonStatements.push(...dropSequences);
15934
16678
  jsonStatements.push(...dropSchemas);
@@ -15949,7 +16693,17 @@ var init_snapshotsDiffer = __esm({
15949
16693
  }
15950
16694
  return true;
15951
16695
  });
15952
- const sqlStatements = fromJson(filteredJsonStatements, "postgresql");
16696
+ const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
16697
+ if (st.type === "alter_type_add_value") {
16698
+ if (jsonStatements.find(
16699
+ (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.schema === st.schema
16700
+ )) {
16701
+ return false;
16702
+ }
16703
+ }
16704
+ return true;
16705
+ });
16706
+ const sqlStatements = fromJson(filteredEnumsJsonStatements, "postgresql");
15953
16707
  const uniqueSqlStatements = [];
15954
16708
  sqlStatements.forEach((ss) => {
15955
16709
  if (!uniqueSqlStatements.includes(ss)) {
@@ -15965,12 +16719,12 @@ var init_snapshotsDiffer = __esm({
15965
16719
  });
15966
16720
  const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
15967
16721
  return {
15968
- statements: filteredJsonStatements,
16722
+ statements: filteredEnumsJsonStatements,
15969
16723
  sqlStatements: uniqueSqlStatements,
15970
16724
  _meta
15971
16725
  };
15972
16726
  };
15973
- applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
16727
+ applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
15974
16728
  for (const tableName in json1.tables) {
15975
16729
  const table4 = json1.tables[tableName];
15976
16730
  for (const indexName2 in table4.indexes) {
@@ -16067,7 +16821,33 @@ var init_snapshotsDiffer = __esm({
16067
16821
  return [tableKey2, tableValue];
16068
16822
  }
16069
16823
  );
16070
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
16824
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
16825
+ const {
16826
+ created: createdViews,
16827
+ deleted: deletedViews,
16828
+ renamed: renamedViews
16829
+ // renamed or moved
16830
+ } = await viewsResolver2({
16831
+ created: viewsDiff.added,
16832
+ deleted: viewsDiff.deleted
16833
+ });
16834
+ const renamesViewDic = {};
16835
+ renamedViews.forEach((it) => {
16836
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
16837
+ });
16838
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
16839
+ viewsPatchedSnap1.views = mapEntries(
16840
+ viewsPatchedSnap1.views,
16841
+ (viewKey, viewValue) => {
16842
+ const rename = renamesViewDic[viewValue.name];
16843
+ if (rename) {
16844
+ viewValue.name = rename.to;
16845
+ viewKey = rename.to;
16846
+ }
16847
+ return [viewKey, viewValue];
16848
+ }
16849
+ );
16850
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16071
16851
  const typedResult = diffResultSchemeMysql.parse(diffResult);
16072
16852
  const jsonStatements = [];
16073
16853
  const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
@@ -16249,10 +17029,68 @@ var init_snapshotsDiffer = __esm({
16249
17029
  curFull.internal
16250
17030
  );
16251
17031
  });
17032
+ const createViews = [];
17033
+ const dropViews = [];
17034
+ const renameViews = [];
17035
+ const alterViews = [];
17036
+ createViews.push(
17037
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17038
+ return prepareMySqlCreateViewJson(
17039
+ it.name,
17040
+ it.definition,
17041
+ it.meta
17042
+ );
17043
+ })
17044
+ );
17045
+ dropViews.push(
17046
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17047
+ return prepareDropViewJson(it.name);
17048
+ })
17049
+ );
17050
+ renameViews.push(
17051
+ ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
17052
+ return prepareRenameViewJson(it.to.name, it.from.name);
17053
+ })
17054
+ );
17055
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17056
+ for (const alteredView of alteredViews) {
17057
+ const { definition, meta } = json22.views[alteredView.name];
17058
+ if (alteredView.alteredExisting) {
17059
+ dropViews.push(prepareDropViewJson(alteredView.name));
17060
+ createViews.push(
17061
+ prepareMySqlCreateViewJson(
17062
+ alteredView.name,
17063
+ definition,
17064
+ meta
17065
+ )
17066
+ );
17067
+ continue;
17068
+ }
17069
+ if (alteredView.alteredDefinition && action !== "push") {
17070
+ createViews.push(
17071
+ prepareMySqlCreateViewJson(
17072
+ alteredView.name,
17073
+ definition,
17074
+ meta,
17075
+ true
17076
+ )
17077
+ );
17078
+ continue;
17079
+ }
17080
+ if (alteredView.alteredMeta) {
17081
+ const view4 = curFull["views"][alteredView.name];
17082
+ alterViews.push(
17083
+ prepareMySqlAlterView(view4)
17084
+ );
17085
+ }
17086
+ }
16252
17087
  jsonStatements.push(...jsonMySqlCreateTables);
16253
17088
  jsonStatements.push(...jsonDropTables);
16254
17089
  jsonStatements.push(...jsonRenameTables);
16255
17090
  jsonStatements.push(...jsonRenameColumnsStatements);
17091
+ jsonStatements.push(...dropViews);
17092
+ jsonStatements.push(...renameViews);
17093
+ jsonStatements.push(...alterViews);
16256
17094
  jsonStatements.push(...jsonDeletedUniqueConstraints);
16257
17095
  jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
16258
17096
  jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
@@ -16269,6 +17107,7 @@ var init_snapshotsDiffer = __esm({
16269
17107
  jsonStatements.push(...jsonDropColumnsStatemets);
16270
17108
  jsonStatements.push(...jsonAlteredCompositePKs);
16271
17109
  jsonStatements.push(...jsonAddedUniqueConstraints);
17110
+ jsonStatements.push(...createViews);
16272
17111
  jsonStatements.push(...jsonAlteredUniqueConstraints);
16273
17112
  const sqlStatements = fromJson(jsonStatements, "mysql");
16274
17113
  const uniqueSqlStatements = [];
@@ -16287,7 +17126,7 @@ var init_snapshotsDiffer = __esm({
16287
17126
  _meta
16288
17127
  };
16289
17128
  };
16290
- applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
17129
+ applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16291
17130
  const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
16292
17131
  const {
16293
17132
  created: createdTables,
@@ -16357,7 +17196,32 @@ var init_snapshotsDiffer = __esm({
16357
17196
  return [tableKey2, tableValue];
16358
17197
  }
16359
17198
  );
16360
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17199
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17200
+ const {
17201
+ created: createdViews,
17202
+ deleted: deletedViews,
17203
+ renamed: renamedViews
17204
+ // renamed or moved
17205
+ } = await viewsResolver2({
17206
+ created: viewsDiff.added,
17207
+ deleted: viewsDiff.deleted
17208
+ });
17209
+ const renamesViewDic = {};
17210
+ renamedViews.forEach((it) => {
17211
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17212
+ });
17213
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17214
+ viewsPatchedSnap1.views = mapEntries(
17215
+ viewsPatchedSnap1.views,
17216
+ (viewKey, viewValue) => {
17217
+ const rename = renamesViewDic[viewValue.name];
17218
+ if (rename) {
17219
+ viewValue.name = rename.to;
17220
+ }
17221
+ return [viewKey, viewValue];
17222
+ }
17223
+ );
17224
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16361
17225
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
16362
17226
  const tablesMap = {};
16363
17227
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -16536,6 +17400,44 @@ var init_snapshotsDiffer = __esm({
16536
17400
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
16537
17401
  (t) => t.type === "delete_reference"
16538
17402
  );
17403
+ const createViews = [];
17404
+ const dropViews = [];
17405
+ createViews.push(
17406
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17407
+ return prepareSqliteCreateViewJson(
17408
+ it.name,
17409
+ it.definition
17410
+ );
17411
+ })
17412
+ );
17413
+ dropViews.push(
17414
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17415
+ return prepareDropViewJson(it.name);
17416
+ })
17417
+ );
17418
+ dropViews.push(
17419
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17420
+ return prepareDropViewJson(it.from.name);
17421
+ })
17422
+ );
17423
+ createViews.push(
17424
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17425
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
17426
+ })
17427
+ );
17428
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17429
+ for (const alteredView of alteredViews) {
17430
+ const { definition } = json22.views[alteredView.name];
17431
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
17432
+ dropViews.push(prepareDropViewJson(alteredView.name));
17433
+ createViews.push(
17434
+ prepareSqliteCreateViewJson(
17435
+ alteredView.name,
17436
+ definition
17437
+ )
17438
+ );
17439
+ }
17440
+ }
16539
17441
  const jsonStatements = [];
16540
17442
  jsonStatements.push(...jsonCreateTables);
16541
17443
  jsonStatements.push(...jsonDropTables);
@@ -16553,6 +17455,8 @@ var init_snapshotsDiffer = __esm({
16553
17455
  jsonStatements.push(...jsonDropColumnsStatemets);
16554
17456
  jsonStatements.push(...jsonAlteredCompositePKs);
16555
17457
  jsonStatements.push(...jsonAlteredUniqueConstraints);
17458
+ jsonStatements.push(...dropViews);
17459
+ jsonStatements.push(...createViews);
16556
17460
  const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json22, action);
16557
17461
  const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
16558
17462
  const uniqueSqlStatements = [];
@@ -16571,7 +17475,7 @@ var init_snapshotsDiffer = __esm({
16571
17475
  _meta
16572
17476
  };
16573
17477
  };
16574
- applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
17478
+ applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
16575
17479
  const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
16576
17480
  const {
16577
17481
  created: createdTables,
@@ -16641,7 +17545,32 @@ var init_snapshotsDiffer = __esm({
16641
17545
  return [tableKey2, tableValue];
16642
17546
  }
16643
17547
  );
16644
- const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
17548
+ const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
17549
+ const {
17550
+ created: createdViews,
17551
+ deleted: deletedViews,
17552
+ renamed: renamedViews
17553
+ // renamed or moved
17554
+ } = await viewsResolver2({
17555
+ created: viewsDiff.added,
17556
+ deleted: viewsDiff.deleted
17557
+ });
17558
+ const renamesViewDic = {};
17559
+ renamedViews.forEach((it) => {
17560
+ renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
17561
+ });
17562
+ const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
17563
+ viewsPatchedSnap1.views = mapEntries(
17564
+ viewsPatchedSnap1.views,
17565
+ (viewKey, viewValue) => {
17566
+ const rename = renamesViewDic[viewValue.name];
17567
+ if (rename) {
17568
+ viewValue.name = rename.to;
17569
+ }
17570
+ return [viewKey, viewValue];
17571
+ }
17572
+ );
17573
+ const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
16645
17574
  const typedResult = diffResultSchemeSQLite.parse(diffResult);
16646
17575
  const tablesMap = {};
16647
17576
  typedResult.alteredTablesWithColumns.forEach((obj) => {
@@ -16825,6 +17754,44 @@ var init_snapshotsDiffer = __esm({
16825
17754
  const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
16826
17755
  (t) => t.type === "delete_reference"
16827
17756
  );
17757
+ const createViews = [];
17758
+ const dropViews = [];
17759
+ createViews.push(
17760
+ ...createdViews.filter((it) => !it.isExisting).map((it) => {
17761
+ return prepareSqliteCreateViewJson(
17762
+ it.name,
17763
+ it.definition
17764
+ );
17765
+ })
17766
+ );
17767
+ dropViews.push(
17768
+ ...deletedViews.filter((it) => !it.isExisting).map((it) => {
17769
+ return prepareDropViewJson(it.name);
17770
+ })
17771
+ );
17772
+ dropViews.push(
17773
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17774
+ return prepareDropViewJson(it.from.name);
17775
+ })
17776
+ );
17777
+ createViews.push(
17778
+ ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
17779
+ return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
17780
+ })
17781
+ );
17782
+ const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
17783
+ for (const alteredView of alteredViews) {
17784
+ const { definition } = json22.views[alteredView.name];
17785
+ if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
17786
+ dropViews.push(prepareDropViewJson(alteredView.name));
17787
+ createViews.push(
17788
+ prepareSqliteCreateViewJson(
17789
+ alteredView.name,
17790
+ definition
17791
+ )
17792
+ );
17793
+ }
17794
+ }
16828
17795
  const jsonStatements = [];
16829
17796
  jsonStatements.push(...jsonCreateTables);
16830
17797
  jsonStatements.push(...jsonDropTables);
@@ -16838,6 +17805,8 @@ var init_snapshotsDiffer = __esm({
16838
17805
  jsonStatements.push(...jsonAddColumnsStatemets);
16839
17806
  jsonStatements.push(...jsonCreateIndexesForCreatedTables);
16840
17807
  jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
17808
+ jsonStatements.push(...dropViews);
17809
+ jsonStatements.push(...createViews);
16841
17810
  jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
16842
17811
  jsonStatements.push(...jsonDropColumnsStatemets);
16843
17812
  jsonStatements.push(...jsonAlteredCompositePKs);
@@ -17000,7 +17969,7 @@ var init_outputs = __esm({
17000
17969
  });
17001
17970
 
17002
17971
  // src/cli/commands/migrate.ts
17003
- var import_hanji2, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
17972
+ var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
17004
17973
  var init_migrate = __esm({
17005
17974
  "src/cli/commands/migrate.ts"() {
17006
17975
  "use strict";
@@ -17045,6 +18014,60 @@ var init_migrate = __esm({
17045
18014
  throw e;
17046
18015
  }
17047
18016
  };
18017
+ viewsResolver = async (input) => {
18018
+ try {
18019
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18020
+ input.created,
18021
+ input.deleted,
18022
+ "view"
18023
+ );
18024
+ return {
18025
+ created,
18026
+ deleted,
18027
+ moved,
18028
+ renamed
18029
+ };
18030
+ } catch (e) {
18031
+ console.error(e);
18032
+ throw e;
18033
+ }
18034
+ };
18035
+ mySqlViewsResolver = async (input) => {
18036
+ try {
18037
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18038
+ input.created,
18039
+ input.deleted,
18040
+ "view"
18041
+ );
18042
+ return {
18043
+ created,
18044
+ deleted,
18045
+ moved,
18046
+ renamed
18047
+ };
18048
+ } catch (e) {
18049
+ console.error(e);
18050
+ throw e;
18051
+ }
18052
+ };
18053
+ sqliteViewsResolver = async (input) => {
18054
+ try {
18055
+ const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
18056
+ input.created,
18057
+ input.deleted,
18058
+ "view"
18059
+ );
18060
+ return {
18061
+ created,
18062
+ deleted,
18063
+ moved,
18064
+ renamed
18065
+ };
18066
+ } catch (e) {
18067
+ console.error(e);
18068
+ throw e;
18069
+ }
18070
+ };
17048
18071
  sequencesResolver = async (input) => {
17049
18072
  try {
17050
18073
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -19120,7 +20143,7 @@ function fillPlaceholders(params, values) {
19120
20143
  return p;
19121
20144
  });
19122
20145
  }
19123
- var _a20, FakePrimitiveParam, _a21, StringChunk, _a22, _SQL, SQL, _a23, Name, noopDecoder, noopEncoder, noopMapper, _a24, Param, _a25, Placeholder, _a26, _b10, View;
20146
+ var _a20, FakePrimitiveParam, _a21, StringChunk, _a22, _SQL, SQL, _a23, Name, noopDecoder, noopEncoder, noopMapper, _a24, Param, _a25, Placeholder, _a26, _b10, View3;
19124
20147
  var init_sql = __esm({
19125
20148
  "../drizzle-orm/dist/sql/sql.js"() {
19126
20149
  "use strict";
@@ -19223,7 +20246,7 @@ var init_sql = __esm({
19223
20246
  }
19224
20247
  return { sql: escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), params: [] };
19225
20248
  }
19226
- if (is(chunk, View)) {
20249
+ if (is(chunk, View3)) {
19227
20250
  const schemaName = chunk[ViewBaseConfig].schema;
19228
20251
  const viewName = chunk[ViewBaseConfig].name;
19229
20252
  return {
@@ -19442,7 +20465,7 @@ var init_sql = __esm({
19442
20465
  };
19443
20466
  __publicField(Placeholder, _a25, "Placeholder");
19444
20467
  _b10 = entityKind, _a26 = ViewBaseConfig;
19445
- View = class {
20468
+ View3 = class {
19446
20469
  constructor({ name: name2, schema: schema4, selectedFields, query }) {
19447
20470
  /** @internal */
19448
20471
  __publicField(this, _a26);
@@ -19460,7 +20483,7 @@ var init_sql = __esm({
19460
20483
  return new SQL([this]);
19461
20484
  }
19462
20485
  };
19463
- __publicField(View, _b10, "View");
20486
+ __publicField(View3, _b10, "View");
19464
20487
  Column2.prototype.getSQL = function() {
19465
20488
  return new SQL([this]);
19466
20489
  };
@@ -19611,7 +20634,7 @@ var init_errors = __esm({
19611
20634
 
19612
20635
  // ../drizzle-orm/dist/sql/expressions/conditions.js
19613
20636
  function bindIfParam(value, column4) {
19614
- if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table) && !is(value, View)) {
20637
+ if (isDriverValueEncoder(column4) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table) && !is(value, View3)) {
19615
20638
  return new Param(value, column4);
19616
20639
  }
19617
20640
  return value;
@@ -19982,7 +21005,7 @@ function getTableColumns(table4) {
19982
21005
  return table4[Table.Symbol.Columns];
19983
21006
  }
19984
21007
  function getTableLikeName(table4) {
19985
- 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];
21008
+ 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];
19986
21009
  }
19987
21010
  function getColumnNameAndConfig(a, b) {
19988
21011
  return {
@@ -20900,23 +21923,23 @@ function hexToBytes(hex) {
20900
21923
  }
20901
21924
  function bytesToFloat64(bytes, offset) {
20902
21925
  const buffer = new ArrayBuffer(8);
20903
- const view = new DataView(buffer);
21926
+ const view4 = new DataView(buffer);
20904
21927
  for (let i = 0; i < 8; i++) {
20905
- view.setUint8(i, bytes[offset + i]);
21928
+ view4.setUint8(i, bytes[offset + i]);
20906
21929
  }
20907
- return view.getFloat64(0, true);
21930
+ return view4.getFloat64(0, true);
20908
21931
  }
20909
21932
  function parseEWKB(hex) {
20910
21933
  const bytes = hexToBytes(hex);
20911
21934
  let offset = 0;
20912
21935
  const byteOrder = bytes[offset];
20913
21936
  offset += 1;
20914
- const view = new DataView(bytes.buffer);
20915
- const geomType = view.getUint32(offset, byteOrder === 1);
21937
+ const view4 = new DataView(bytes.buffer);
21938
+ const geomType = view4.getUint32(offset, byteOrder === 1);
20916
21939
  offset += 4;
20917
21940
  let _srid;
20918
21941
  if (geomType & 536870912) {
20919
- _srid = view.getUint32(offset, byteOrder === 1);
21942
+ _srid = view4.getUint32(offset, byteOrder === 1);
20920
21943
  offset += 4;
20921
21944
  }
20922
21945
  if ((geomType & 65535) === 1) {
@@ -22139,7 +23162,7 @@ __export(dist_exports, {
22139
23162
  Table: () => Table,
22140
23163
  TableAliasProxyHandler: () => TableAliasProxyHandler,
22141
23164
  TransactionRollbackError: () => TransactionRollbackError,
22142
- View: () => View,
23165
+ View: () => View3,
22143
23166
  ViewBaseConfig: () => ViewBaseConfig,
22144
23167
  WithSubquery: () => WithSubquery,
22145
23168
  aliasedRelation: () => aliasedRelation,
@@ -22573,7 +23596,7 @@ var init_view_base = __esm({
22573
23596
  "use strict";
22574
23597
  init_entity();
22575
23598
  init_sql();
22576
- PgViewBase = class extends (_b99 = View, _a128 = entityKind, _b99) {
23599
+ PgViewBase = class extends (_b99 = View3, _a128 = entityKind, _b99) {
22577
23600
  };
22578
23601
  __publicField(PgViewBase, _a128, "PgViewBase");
22579
23602
  }
@@ -22796,7 +23819,7 @@ var init_dialect = __esm({
22796
23819
  joinsArray.push(
22797
23820
  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}`
22798
23821
  );
22799
- } else if (is(table22, View)) {
23822
+ } else if (is(table22, View3)) {
22800
23823
  const viewName = table22[ViewBaseConfig].name;
22801
23824
  const viewSchema = table22[ViewBaseConfig].schema;
22802
23825
  const origViewName = table22[ViewBaseConfig].originalName;
@@ -22933,10 +23956,10 @@ var init_dialect = __esm({
22933
23956
  const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
22934
23957
  return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
22935
23958
  }
22936
- buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
23959
+ buildRefreshMaterializedViewQuery({ view: view4, concurrently, withNoData }) {
22937
23960
  const concurrentlySql = concurrently ? sql` concurrently` : void 0;
22938
23961
  const withNoDataSql = withNoData ? sql` with no data` : void 0;
22939
- return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
23962
+ return sql`refresh materialized view${concurrentlySql} ${view4}${withNoDataSql}`;
22940
23963
  }
22941
23964
  prepareTyping(encoder) {
22942
23965
  if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
@@ -23710,7 +24733,7 @@ var init_selection_proxy = __esm({
23710
24733
  if (typeof prop === "symbol") {
23711
24734
  return subquery[prop];
23712
24735
  }
23713
- const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
24736
+ const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View3) ? subquery[ViewBaseConfig].selectedFields : subquery;
23714
24737
  const value = columns[prop];
23715
24738
  if (is(value, SQL.Aliased)) {
23716
24739
  if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
@@ -24192,7 +25215,7 @@ var init_select2 = __esm({
24192
25215
  };
24193
25216
  }
24194
25217
  if (typeof tableName === "string" && !is(table4, SQL)) {
24195
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
25218
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
24196
25219
  this.config.fields[tableName] = selection;
24197
25220
  }
24198
25221
  }
@@ -24611,7 +25634,7 @@ var init_refresh_materialized_view = __esm({
24611
25634
  init_query_promise();
24612
25635
  init_tracing();
24613
25636
  PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
24614
- constructor(view, session, dialect4) {
25637
+ constructor(view4, session, dialect4) {
24615
25638
  super();
24616
25639
  __publicField(this, "config");
24617
25640
  __publicField(this, "execute", (placeholderValues) => {
@@ -24621,7 +25644,7 @@ var init_refresh_materialized_view = __esm({
24621
25644
  });
24622
25645
  this.session = session;
24623
25646
  this.dialect = dialect4;
24624
- this.config = { view };
25647
+ this.config = { view: view4 };
24625
25648
  }
24626
25649
  concurrently() {
24627
25650
  if (this.config.withNoData !== void 0) {
@@ -25252,8 +26275,8 @@ var init_db = __esm({
25252
26275
  delete(table4) {
25253
26276
  return new PgDeleteBase(table4, this.session, this.dialect);
25254
26277
  }
25255
- refreshMaterializedView(view) {
25256
- return new PgRefreshMaterializedView(view, this.session, this.dialect);
26278
+ refreshMaterializedView(view4) {
26279
+ return new PgRefreshMaterializedView(view4, this.session, this.dialect);
25257
26280
  }
25258
26281
  execute(query) {
25259
26282
  const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
@@ -25443,7 +26466,13 @@ function pgMaterializedViewWithSchema(name2, selection, schema4) {
25443
26466
  }
25444
26467
  return new MaterializedViewBuilder(name2, schema4);
25445
26468
  }
25446
- 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;
26469
+ function isPgView(obj) {
26470
+ return is(obj, PgView2);
26471
+ }
26472
+ function isPgMaterializedView(obj) {
26473
+ return is(obj, PgMaterializedView);
26474
+ }
26475
+ 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;
25447
26476
  var init_view = __esm({
25448
26477
  "../drizzle-orm/dist/pg-core/view.js"() {
25449
26478
  "use strict";
@@ -25480,7 +26509,7 @@ var init_view = __esm({
25480
26509
  });
25481
26510
  const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
25482
26511
  return new Proxy(
25483
- new PgView({
26512
+ new PgView2({
25484
26513
  pgConfig: this.config,
25485
26514
  config: {
25486
26515
  name: this.name,
@@ -25502,7 +26531,7 @@ var init_view = __esm({
25502
26531
  }
25503
26532
  existing() {
25504
26533
  return new Proxy(
25505
- new PgView({
26534
+ new PgView2({
25506
26535
  pgConfig: void 0,
25507
26536
  config: {
25508
26537
  name: this.name,
@@ -25521,7 +26550,7 @@ var init_view = __esm({
25521
26550
  }
25522
26551
  as(query) {
25523
26552
  return new Proxy(
25524
- new PgView({
26553
+ new PgView2({
25525
26554
  pgConfig: this.config,
25526
26555
  config: {
25527
26556
  name: this.name,
@@ -25606,7 +26635,12 @@ var init_view = __esm({
25606
26635
  existing() {
25607
26636
  return new Proxy(
25608
26637
  new PgMaterializedView({
25609
- pgConfig: void 0,
26638
+ pgConfig: {
26639
+ tablespace: this.config.tablespace,
26640
+ using: this.config.using,
26641
+ with: this.config.with,
26642
+ withNoData: this.config.withNoData
26643
+ },
25610
26644
  config: {
25611
26645
  name: this.name,
25612
26646
  schema: this.schema,
@@ -25625,7 +26659,12 @@ var init_view = __esm({
25625
26659
  as(query) {
25626
26660
  return new Proxy(
25627
26661
  new PgMaterializedView({
25628
- pgConfig: void 0,
26662
+ pgConfig: {
26663
+ tablespace: this.config.tablespace,
26664
+ using: this.config.using,
26665
+ with: this.config.with,
26666
+ withNoData: this.config.withNoData
26667
+ },
25629
26668
  config: {
25630
26669
  name: this.name,
25631
26670
  schema: this.schema,
@@ -25643,7 +26682,7 @@ var init_view = __esm({
25643
26682
  }
25644
26683
  };
25645
26684
  __publicField(ManualMaterializedViewBuilder, _a153, "PgManualMaterializedViewBuilder");
25646
- PgView = class extends (_c4 = PgViewBase, _b111 = entityKind, _a154 = PgViewConfig, _c4) {
26685
+ PgView2 = class extends (_c4 = PgViewBase, _b111 = entityKind, _a154 = PgViewConfig, _c4) {
25647
26686
  constructor({ pgConfig, config }) {
25648
26687
  super(config);
25649
26688
  __publicField(this, _a154);
@@ -25654,7 +26693,7 @@ var init_view = __esm({
25654
26693
  }
25655
26694
  }
25656
26695
  };
25657
- __publicField(PgView, _b111, "PgView");
26696
+ __publicField(PgView2, _b111, "PgView");
25658
26697
  PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
25659
26698
  PgMaterializedView = class extends (_c5 = PgViewBase, _b112 = entityKind, _a155 = PgMaterializedViewConfig, _c5) {
25660
26699
  constructor({ pgConfig, config }) {
@@ -25849,17 +26888,32 @@ function getTableConfig(table4) {
25849
26888
  schema: schema4
25850
26889
  };
25851
26890
  }
26891
+ function getViewConfig(view4) {
26892
+ return {
26893
+ ...view4[ViewBaseConfig],
26894
+ ...view4[PgViewConfig]
26895
+ };
26896
+ }
26897
+ function getMaterializedViewConfig(view4) {
26898
+ return {
26899
+ ...view4[ViewBaseConfig],
26900
+ ...view4[PgMaterializedViewConfig]
26901
+ };
26902
+ }
25852
26903
  var init_utils4 = __esm({
25853
26904
  "../drizzle-orm/dist/pg-core/utils.js"() {
25854
26905
  "use strict";
25855
26906
  init_entity();
25856
26907
  init_table2();
25857
26908
  init_table();
26909
+ init_view_common();
25858
26910
  init_checks();
25859
26911
  init_foreign_keys();
25860
26912
  init_indexes();
25861
26913
  init_primary_keys();
25862
26914
  init_unique_constraint();
26915
+ init_view_common2();
26916
+ init_view();
25863
26917
  }
25864
26918
  });
25865
26919
 
@@ -25934,7 +26988,7 @@ function buildArrayString(array, sqlType) {
25934
26988
  }).join(",");
25935
26989
  return `{${values}}`;
25936
26990
  }
25937
- var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn;
26991
+ var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery;
25938
26992
  var init_pgSerializer = __esm({
25939
26993
  "src/serializer/pgSerializer.ts"() {
25940
26994
  "use strict";
@@ -25949,22 +27003,14 @@ var init_pgSerializer = __esm({
25949
27003
  indexName = (tableName, columns) => {
25950
27004
  return `${tableName}_${columns.join("_")}_index`;
25951
27005
  };
25952
- generatePgSnapshot = (tables, enums, schemas, sequences, casing2, schemaFilter) => {
27006
+ generatePgSnapshot = (tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter) => {
25953
27007
  const dialect4 = new PgDialect({ casing: casing2 });
25954
27008
  const result = {};
27009
+ const resultViews = {};
25955
27010
  const sequencesToReturn = {};
25956
27011
  const indexesInSchema = {};
25957
27012
  for (const table4 of tables) {
25958
- const {
25959
- name: tableName,
25960
- columns,
25961
- indexes,
25962
- foreignKeys,
25963
- checks,
25964
- schema: schema4,
25965
- primaryKeys,
25966
- uniqueConstraints
25967
- } = getTableConfig(table4);
27013
+ const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema4, primaryKeys, uniqueConstraints } = getTableConfig(table4);
25968
27014
  if (schemaFilter && !schemaFilter.includes(schema4 ?? "public")) {
25969
27015
  continue;
25970
27016
  }
@@ -26020,7 +27066,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26020
27066
  column4.uniqueName
26021
27067
  )} on the ${source_default.underline.blue(
26022
27068
  name2
26023
- )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
27069
+ )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
26024
27070
  existingUnique.columns.join(",")
26025
27071
  )} columns
26026
27072
  `)}`
@@ -26041,9 +27087,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26041
27087
  columnToSet.default = `'${column4.default}'`;
26042
27088
  } else {
26043
27089
  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
26044
- columnToSet.default = `'${JSON.stringify(
26045
- column4.default
26046
- )}'::${sqlTypeLowered}`;
27090
+ columnToSet.default = `'${JSON.stringify(column4.default)}'::${sqlTypeLowered}`;
26047
27091
  } else if (column4.default instanceof Date) {
26048
27092
  if (sqlTypeLowered === "date") {
26049
27093
  columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
@@ -26053,10 +27097,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26053
27097
  columnToSet.default = `'${column4.default.toISOString()}'`;
26054
27098
  }
26055
27099
  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column4.default)) {
26056
- columnToSet.default = `'${buildArrayString(
26057
- column4.default,
26058
- sqlTypeLowered
26059
- )}'`;
27100
+ columnToSet.default = `'${buildArrayString(column4.default, sqlTypeLowered)}'`;
26060
27101
  } else {
26061
27102
  columnToSet.default = column4.default;
26062
27103
  }
@@ -26086,17 +27127,13 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26086
27127
  if (typeof existingUnique !== "undefined") {
26087
27128
  console.log(
26088
27129
  `
26089
- ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
26090
- tableName
26091
- )} table.
26092
- The unique constraint ${source_default.underline.blue(
26093
- name2
26094
- )} on the ${source_default.underline.blue(
26095
- columnNames.join(",")
26096
- )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
26097
- existingUnique.columns.join(",")
26098
- )} columns
26099
- `)}`
27130
+ ${withStyle.errorWarning(
27131
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table.
27132
+ The unique constraint ${source_default.underline.blue(name2)} on the ${source_default.underline.blue(
27133
+ columnNames.join(",")
27134
+ )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
27135
+ `
27136
+ )}`
26100
27137
  );
26101
27138
  process.exit(1);
26102
27139
  }
@@ -26149,9 +27186,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
26149
27186
  console.log(
26150
27187
  `
26151
27188
  ${withStyle.errorWarning(
26152
- `Please specify an index name in ${getTableName(
26153
- value.config.table
26154
- )} 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.`
27189
+ `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.`
26155
27190
  )}`
26156
27191
  );
26157
27192
  process.exit(1);
@@ -26169,9 +27204,7 @@ ${withStyle.errorWarning(
26169
27204
  tableName
26170
27205
  )} table with the ${source_default.blueBright(
26171
27206
  "vector"
26172
- )} 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(
26173
- ", "
26174
- )}].
27207
+ )} 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(", ")}].
26175
27208
 
26176
27209
  You can specify it using current syntax: ${source_default.underline(
26177
27210
  `index("${value.config.name}").using("${value.config.method}", table.${name3}.op("${vectorOps[0]}"))`
@@ -26212,9 +27245,7 @@ You can check the "pg_vector" docs for more info: https://github.com/pgvector/pg
26212
27245
  console.log(
26213
27246
  `
26214
27247
  ${withStyle.errorWarning(
26215
- `We've found duplicated index name across ${source_default.underline.blue(
26216
- schema4 ?? "public"
26217
- )} schema. Please rename your index in either the ${source_default.underline.blue(
27248
+ `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(
26218
27249
  tableName
26219
27250
  )} table or the table with the duplicated index name`
26220
27251
  )}`
@@ -26267,6 +27298,136 @@ ${withStyle.errorWarning(
26267
27298
  } else {
26268
27299
  }
26269
27300
  }
27301
+ const combinedViews = [...views, ...matViews];
27302
+ for (const view4 of combinedViews) {
27303
+ let viewName;
27304
+ let schema4;
27305
+ let query;
27306
+ let selectedFields;
27307
+ let isExisting;
27308
+ let withOption;
27309
+ let tablespace;
27310
+ let using;
27311
+ let withNoData;
27312
+ let materialized = false;
27313
+ if (is(view4, PgView2)) {
27314
+ ({ name: viewName, schema: schema4, query, selectedFields, isExisting, with: withOption } = getViewConfig(view4));
27315
+ } else {
27316
+ ({ name: viewName, schema: schema4, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = getMaterializedViewConfig(view4));
27317
+ materialized = true;
27318
+ }
27319
+ const viewSchema = schema4 ?? "public";
27320
+ const viewKey = `${viewSchema}.${viewName}`;
27321
+ const columnsObject = {};
27322
+ const uniqueConstraintObject = {};
27323
+ const existingView = resultViews[viewKey];
27324
+ if (typeof existingView !== "undefined") {
27325
+ console.log(
27326
+ `
27327
+ ${withStyle.errorWarning(
27328
+ `We've found duplicated view name across ${source_default.underline.blue(schema4 ?? "public")} schema. Please rename your view`
27329
+ )}`
27330
+ );
27331
+ process.exit(1);
27332
+ }
27333
+ for (const key in selectedFields) {
27334
+ if (is(selectedFields[key], PgColumn)) {
27335
+ const column4 = selectedFields[key];
27336
+ const notNull = column4.notNull;
27337
+ const primaryKey = column4.primary;
27338
+ const sqlTypeLowered = column4.getSQLType().toLowerCase();
27339
+ const typeSchema = is(column4, PgEnumColumn) ? column4.enum.schema || "public" : void 0;
27340
+ const generated = column4.generated;
27341
+ const identity = column4.generatedIdentity;
27342
+ const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
27343
+ const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column4.columnType) : "1");
27344
+ const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column4.getSQLType()));
27345
+ const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
27346
+ const cache = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
27347
+ const columnToSet = {
27348
+ name: column4.name,
27349
+ type: column4.getSQLType(),
27350
+ typeSchema,
27351
+ primaryKey,
27352
+ notNull,
27353
+ generated: generated ? {
27354
+ as: is(generated.as, SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
27355
+ type: "stored"
27356
+ } : void 0,
27357
+ identity: identity ? {
27358
+ type: identity.type,
27359
+ name: identity.sequenceName ?? `${viewName}_${column4.name}_seq`,
27360
+ schema: schema4 ?? "public",
27361
+ increment,
27362
+ startWith,
27363
+ minValue,
27364
+ maxValue,
27365
+ cache,
27366
+ cycle: identity?.sequenceOptions?.cycle ?? false
27367
+ } : void 0
27368
+ };
27369
+ if (column4.isUnique) {
27370
+ const existingUnique = uniqueConstraintObject[column4.uniqueName];
27371
+ if (typeof existingUnique !== "undefined") {
27372
+ console.log(
27373
+ `
27374
+ ${withStyle.errorWarning(
27375
+ `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table.
27376
+ The unique constraint ${source_default.underline.blue(column4.uniqueName)} on the ${source_default.underline.blue(
27377
+ column4.name
27378
+ )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
27379
+ `
27380
+ )}`
27381
+ );
27382
+ process.exit(1);
27383
+ }
27384
+ uniqueConstraintObject[column4.uniqueName] = {
27385
+ name: column4.uniqueName,
27386
+ nullsNotDistinct: column4.uniqueType === "not distinct",
27387
+ columns: [columnToSet.name]
27388
+ };
27389
+ }
27390
+ if (column4.default !== void 0) {
27391
+ if (is(column4.default, SQL)) {
27392
+ columnToSet.default = sqlToStr(column4.default, casing2);
27393
+ } else {
27394
+ if (typeof column4.default === "string") {
27395
+ columnToSet.default = `'${column4.default}'`;
27396
+ } else {
27397
+ if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
27398
+ columnToSet.default = `'${JSON.stringify(column4.default)}'::${sqlTypeLowered}`;
27399
+ } else if (column4.default instanceof Date) {
27400
+ if (sqlTypeLowered === "date") {
27401
+ columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
27402
+ } else if (sqlTypeLowered === "timestamp") {
27403
+ columnToSet.default = `'${column4.default.toISOString().replace("T", " ").slice(0, 23)}'`;
27404
+ } else {
27405
+ columnToSet.default = `'${column4.default.toISOString()}'`;
27406
+ }
27407
+ } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column4.default)) {
27408
+ columnToSet.default = `'${buildArrayString(column4.default, sqlTypeLowered)}'`;
27409
+ } else {
27410
+ columnToSet.default = column4.default;
27411
+ }
27412
+ }
27413
+ }
27414
+ }
27415
+ columnsObject[column4.name] = columnToSet;
27416
+ }
27417
+ }
27418
+ resultViews[viewKey] = {
27419
+ columns: columnsObject,
27420
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
27421
+ name: viewName,
27422
+ schema: viewSchema,
27423
+ isExisting,
27424
+ with: withOption,
27425
+ withNoData,
27426
+ materialized,
27427
+ tablespace,
27428
+ using
27429
+ };
27430
+ }
26270
27431
  const enumsToReturn = enums.reduce((map, obj) => {
26271
27432
  const enumSchema3 = obj.schema || "public";
26272
27433
  const key = `${enumSchema3}.${obj.enumName}`;
@@ -26293,6 +27454,7 @@ ${withStyle.errorWarning(
26293
27454
  enums: enumsToReturn,
26294
27455
  schemas: schemasObject,
26295
27456
  sequences: sequencesToReturn,
27457
+ views: resultViews,
26296
27458
  _meta: {
26297
27459
  schemas: {},
26298
27460
  tables: {},
@@ -26309,10 +27471,25 @@ ${withStyle.errorWarning(
26309
27471
  };
26310
27472
  fromDatabase = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
26311
27473
  const result = {};
27474
+ const views = {};
26312
27475
  const internals = { tables: {} };
26313
- const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
27476
+ const where = schemaFilters.map((t) => `n.nspname = '${t}'`).join(" or ");
26314
27477
  const allTables = await db.query(
26315
- `SELECT table_schema, table_name FROM information_schema.tables${where === "" ? "" : ` WHERE ${where}`};`
27478
+ `SELECT
27479
+ n.nspname AS table_schema,
27480
+ c.relname AS table_name,
27481
+ CASE
27482
+ WHEN c.relkind = 'r' THEN 'table'
27483
+ WHEN c.relkind = 'v' THEN 'view'
27484
+ WHEN c.relkind = 'm' THEN 'materialized_view'
27485
+ END AS type
27486
+ FROM
27487
+ pg_catalog.pg_class c
27488
+ JOIN
27489
+ pg_catalog.pg_namespace n ON n.oid = c.relnamespace
27490
+ WHERE
27491
+ c.relkind IN ('r', 'v', 'm')
27492
+ ${where === "" ? "" : ` AND ${where}`};`
26316
27493
  );
26317
27494
  const schemas = new Set(allTables.map((it) => it.table_schema));
26318
27495
  schemas.delete("public");
@@ -26332,6 +27509,7 @@ ${withStyle.errorWarning(
26332
27509
  let indexesCount = 0;
26333
27510
  let foreignKeysCount = 0;
26334
27511
  let tableCount = 0;
27512
+ let viewsCount = 0;
26335
27513
  const sequencesToReturn = {};
26336
27514
  const seqWhere = schemaFilters.map((t) => `schemaname = '${t}'`).join(" or ");
26337
27515
  const allSequences = await db.query(
@@ -26390,7 +27568,7 @@ ${withStyle.errorWarning(
26390
27568
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
26391
27569
  }
26392
27570
  const sequencesInColumns = [];
26393
- const all = allTables.map((row) => {
27571
+ const all = allTables.filter((it) => it.type === "table").map((row) => {
26394
27572
  return new Promise(async (res, rej) => {
26395
27573
  const tableName = row.table_name;
26396
27574
  if (!tablesFilter(tableName)) return res("");
@@ -26402,42 +27580,7 @@ ${withStyle.errorWarning(
26402
27580
  const foreignKeysToReturn = {};
26403
27581
  const primaryKeys = {};
26404
27582
  const uniqueConstrains = {};
26405
- const tableResponse = await db.query(
26406
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
26407
- , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
26408
- AND EXISTS (
26409
- SELECT FROM pg_attrdef ad
26410
- WHERE ad.adrelid = a.attrelid
26411
- AND ad.adnum = a.attnum
26412
- AND pg_get_expr(ad.adbin, ad.adrelid)
26413
- = 'nextval('''
26414
- || (pg_get_serial_sequence (a.attrelid::regclass::text
26415
- , a.attname))::regclass
26416
- || '''::regclass)'
26417
- )
26418
- THEN CASE a.atttypid
26419
- WHEN 'int'::regtype THEN 'serial'
26420
- WHEN 'int8'::regtype THEN 'bigserial'
26421
- WHEN 'int2'::regtype THEN 'smallserial'
26422
- END
26423
- ELSE format_type(a.atttypid, a.atttypmod)
26424
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
26425
- pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
26426
- INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
26427
- INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
26428
- INFORMATION_SCHEMA.COLUMNS.is_generated, generation_expression,
26429
- INFORMATION_SCHEMA.COLUMNS.is_identity,INFORMATION_SCHEMA.COLUMNS.identity_generation,
26430
- INFORMATION_SCHEMA.COLUMNS.identity_start, INFORMATION_SCHEMA.COLUMNS.identity_increment,
26431
- INFORMATION_SCHEMA.COLUMNS.identity_maximum, INFORMATION_SCHEMA.COLUMNS.identity_minimum,
26432
- INFORMATION_SCHEMA.COLUMNS.identity_cycle
26433
- FROM pg_attribute a
26434
- JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
26435
- JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
26436
- WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
26437
- AND a.attnum > 0
26438
- AND NOT a.attisdropped
26439
- ORDER BY a.attnum;`
26440
- );
27583
+ const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
26441
27584
  const tableConstraints = await db.query(
26442
27585
  `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
26443
27586
  FROM information_schema.table_constraints tc
@@ -26519,13 +27662,9 @@ ${withStyle.errorWarning(
26519
27662
  foreignKeysToReturn[foreignKeyName].columnsFrom = [
26520
27663
  ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
26521
27664
  ];
26522
- foreignKeysToReturn[foreignKeyName].columnsTo = [
26523
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
26524
- ];
27665
+ foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
26525
27666
  }
26526
- const uniqueConstrainsRows = tableConstraints.filter(
26527
- (mapRow) => mapRow.constraint_type === "UNIQUE"
26528
- );
27667
+ const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
26529
27668
  for (const unqs of uniqueConstrainsRows) {
26530
27669
  const columnName = unqs.column_name;
26531
27670
  const constraintName = unqs.constraint_name;
@@ -26540,7 +27679,7 @@ ${withStyle.errorWarning(
26540
27679
  }
26541
27680
  }
26542
27681
  for (const columnResponse of tableResponse) {
26543
- const columnName = columnResponse.attname;
27682
+ const columnName = columnResponse.column_name;
26544
27683
  const columnAdditionalDT = columnResponse.additional_dt;
26545
27684
  const columnDimensions = columnResponse.array_dimensions;
26546
27685
  const enumType2 = columnResponse.enum_name;
@@ -26560,9 +27699,7 @@ ${withStyle.errorWarning(
26560
27699
  const primaryKey = tableConstraints.filter(
26561
27700
  (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
26562
27701
  );
26563
- const cprimaryKey = tableConstraints.filter(
26564
- (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
26565
- );
27702
+ const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
26566
27703
  if (cprimaryKey.length > 1) {
26567
27704
  const tableCompositePkName = await db.query(
26568
27705
  `SELECT conname AS primary_key
@@ -26585,10 +27722,7 @@ ${withStyle.errorWarning(
26585
27722
  [columnName]: {
26586
27723
  isArray: true,
26587
27724
  dimensions: columnDimensions,
26588
- rawType: columnTypeMapped.substring(
26589
- 0,
26590
- columnTypeMapped.length - 2
26591
- )
27725
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
26592
27726
  }
26593
27727
  }
26594
27728
  };
@@ -26597,19 +27731,12 @@ ${withStyle.errorWarning(
26597
27731
  internals.tables[tableName].columns[columnName] = {
26598
27732
  isArray: true,
26599
27733
  dimensions: columnDimensions,
26600
- rawType: columnTypeMapped.substring(
26601
- 0,
26602
- columnTypeMapped.length - 2
26603
- )
27734
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
26604
27735
  };
26605
27736
  }
26606
27737
  }
26607
27738
  }
26608
- const defaultValue = defaultForColumn(
26609
- columnResponse,
26610
- internals,
26611
- tableName
26612
- );
27739
+ const defaultValue = defaultForColumn(columnResponse, internals, tableName);
26613
27740
  if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
26614
27741
  if (typeof internals.tables[tableName] === "undefined") {
26615
27742
  internals.tables[tableName] = {
@@ -26722,7 +27849,9 @@ ${withStyle.errorWarning(
26722
27849
  WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
26723
27850
  group by index_name, table_name,schemaname, generated_by_constraint;`
26724
27851
  );
26725
- const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
27852
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
27853
+ (it) => it.index_name
27854
+ );
26726
27855
  for (const dbIndex of dbIndexes) {
26727
27856
  const indexName2 = dbIndex.indexname;
26728
27857
  const indexColumnName = dbIndex.column_name;
@@ -26796,10 +27925,180 @@ ${withStyle.errorWarning(
26796
27925
  }
26797
27926
  for await (const _2 of all) {
26798
27927
  }
27928
+ const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
27929
+ return new Promise(async (res, rej) => {
27930
+ const viewName = row.table_name;
27931
+ if (!tablesFilter(viewName)) return res("");
27932
+ tableCount += 1;
27933
+ const viewSchema = row.table_schema;
27934
+ try {
27935
+ const columnToReturn = {};
27936
+ const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
27937
+ for (const viewResponse of viewResponses) {
27938
+ const columnName = viewResponse.column_name;
27939
+ const columnAdditionalDT = viewResponse.additional_dt;
27940
+ const columnDimensions = viewResponse.array_dimensions;
27941
+ const enumType2 = viewResponse.enum_name;
27942
+ let columnType = viewResponse.data_type;
27943
+ const typeSchema = viewResponse.type_schema;
27944
+ const isGenerated = viewResponse.is_generated === "ALWAYS";
27945
+ const generationExpression = viewResponse.generation_expression;
27946
+ const isIdentity = viewResponse.is_identity === "YES";
27947
+ const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
27948
+ const identityStart = viewResponse.identity_start;
27949
+ const identityIncrement = viewResponse.identity_increment;
27950
+ const identityMaximum = viewResponse.identity_maximum;
27951
+ const identityMinimum = viewResponse.identity_minimum;
27952
+ const identityCycle = viewResponse.identity_cycle === "YES";
27953
+ const identityName = viewResponse.seq_name;
27954
+ const defaultValueRes = viewResponse.column_default;
27955
+ const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
27956
+ let columnTypeMapped = columnType;
27957
+ if (columnAdditionalDT === "ARRAY") {
27958
+ if (typeof internals.tables[viewName] === "undefined") {
27959
+ internals.tables[viewName] = {
27960
+ columns: {
27961
+ [columnName]: {
27962
+ isArray: true,
27963
+ dimensions: columnDimensions,
27964
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
27965
+ }
27966
+ }
27967
+ };
27968
+ } else {
27969
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
27970
+ internals.tables[viewName].columns[columnName] = {
27971
+ isArray: true,
27972
+ dimensions: columnDimensions,
27973
+ rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
27974
+ };
27975
+ }
27976
+ }
27977
+ }
27978
+ const defaultValue = defaultForColumn(viewResponse, internals, viewName);
27979
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
27980
+ if (typeof internals.tables[viewName] === "undefined") {
27981
+ internals.tables[viewName] = {
27982
+ columns: {
27983
+ [columnName]: {
27984
+ isDefaultAnExpression: true
27985
+ }
27986
+ }
27987
+ };
27988
+ } else {
27989
+ if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
27990
+ internals.tables[viewName].columns[columnName] = {
27991
+ isDefaultAnExpression: true
27992
+ };
27993
+ } else {
27994
+ internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
27995
+ }
27996
+ }
27997
+ }
27998
+ const isSerial = columnType === "serial";
27999
+ if (columnTypeMapped.startsWith("numeric(")) {
28000
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
28001
+ }
28002
+ if (columnAdditionalDT === "ARRAY") {
28003
+ for (let i = 1; i < Number(columnDimensions); i++) {
28004
+ columnTypeMapped += "[]";
28005
+ }
28006
+ }
28007
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
28008
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
28009
+ columnToReturn[columnName] = {
28010
+ name: columnName,
28011
+ type: (
28012
+ // filter vectors, but in future we should filter any extension that was installed by user
28013
+ columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
28014
+ ),
28015
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
28016
+ primaryKey,
28017
+ notNull: viewResponse.is_nullable === "NO",
28018
+ generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
28019
+ identity: isIdentity ? {
28020
+ type: identityGeneration,
28021
+ name: identityName,
28022
+ increment: stringFromDatabaseIdentityProperty(identityIncrement),
28023
+ minValue: stringFromDatabaseIdentityProperty(identityMinimum),
28024
+ maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
28025
+ startWith: stringFromDatabaseIdentityProperty(identityStart),
28026
+ cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${viewSchema}.${identityName}`]?.cache ? sequencesToReturn[`${viewSchema}.${identityName}`]?.cache : void 0,
28027
+ cycle: identityCycle,
28028
+ schema: viewSchema
28029
+ } : void 0
28030
+ };
28031
+ if (identityName) {
28032
+ delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
28033
+ delete sequencesToReturn[identityName];
28034
+ }
28035
+ if (!isSerial && typeof defaultValue !== "undefined") {
28036
+ columnToReturn[columnName].default = defaultValue;
28037
+ }
28038
+ }
28039
+ const [viewInfo] = await db.query(`
28040
+ SELECT
28041
+ c.relname AS view_name,
28042
+ n.nspname AS schema_name,
28043
+ pg_get_viewdef(c.oid, true) AS definition,
28044
+ ts.spcname AS tablespace_name,
28045
+ c.reloptions AS options,
28046
+ pg_tablespace_location(ts.oid) AS location
28047
+ FROM
28048
+ pg_class c
28049
+ JOIN
28050
+ pg_namespace n ON c.relnamespace = n.oid
28051
+ LEFT JOIN
28052
+ pg_tablespace ts ON c.reltablespace = ts.oid
28053
+ WHERE
28054
+ (c.relkind = 'm' OR c.relkind = 'v')
28055
+ AND n.nspname = '${viewSchema}'
28056
+ AND c.relname = '${viewName}';`);
28057
+ const resultWith = {};
28058
+ if (viewInfo.options) {
28059
+ viewInfo.options.forEach((pair) => {
28060
+ const splitted = pair.split("=");
28061
+ const key = splitted[0];
28062
+ const value = splitted[1];
28063
+ if (value === "true") {
28064
+ resultWith[key] = true;
28065
+ } else if (value === "false") {
28066
+ resultWith[key] = false;
28067
+ } else if (!isNaN(Number(value))) {
28068
+ resultWith[key] = Number(value);
28069
+ } else {
28070
+ resultWith[key] = value;
28071
+ }
28072
+ });
28073
+ }
28074
+ const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
28075
+ const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
28076
+ const materialized = row.type === "materialized_view";
28077
+ views[`${viewSchema}.${viewName}`] = {
28078
+ name: viewName,
28079
+ schema: viewSchema,
28080
+ columns: columnToReturn,
28081
+ isExisting: false,
28082
+ definition,
28083
+ materialized,
28084
+ with: withOption,
28085
+ tablespace: viewInfo.tablespace_name ?? void 0
28086
+ };
28087
+ } catch (e) {
28088
+ rej(e);
28089
+ return;
28090
+ }
28091
+ res("");
28092
+ });
28093
+ });
28094
+ viewsCount = allViews.length;
28095
+ for await (const _2 of allViews) {
28096
+ }
26799
28097
  if (progressCallback) {
26800
28098
  progressCallback("columns", columnsCount, "done");
26801
28099
  progressCallback("indexes", indexesCount, "done");
26802
28100
  progressCallback("fks", foreignKeysCount, "done");
28101
+ progressCallback("views", viewsCount, "done");
26803
28102
  }
26804
28103
  const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
26805
28104
  return {
@@ -26809,6 +28108,7 @@ ${withStyle.errorWarning(
26809
28108
  enums: enumsToReturn,
26810
28109
  schemas: schemasObject,
26811
28110
  sequences: sequencesToReturn,
28111
+ views,
26812
28112
  _meta: {
26813
28113
  schemas: {},
26814
28114
  tables: {},
@@ -26818,7 +28118,7 @@ ${withStyle.errorWarning(
26818
28118
  };
26819
28119
  };
26820
28120
  defaultForColumn = (column4, internals, tableName) => {
26821
- const columnName = column4.attname;
28121
+ const columnName = column4.column_name;
26822
28122
  const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false;
26823
28123
  if (column4.column_default === null) {
26824
28124
  return void 0;
@@ -26871,6 +28171,8 @@ ${withStyle.errorWarning(
26871
28171
  }
26872
28172
  return columnDefaultAsString;
26873
28173
  }
28174
+ } else if (column4.data_type.includes("numeric")) {
28175
+ return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
26874
28176
  } else if (column4.data_type === "json" || column4.data_type === "jsonb") {
26875
28177
  const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
26876
28178
  return `'${jsonWithoutSpaces}'::${column4.data_type}`;
@@ -26884,6 +28186,75 @@ ${withStyle.errorWarning(
26884
28186
  return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
26885
28187
  }
26886
28188
  };
28189
+ getColumnsInfoQuery = ({ schema: schema4, table: table4, db }) => {
28190
+ return db.query(
28191
+ `SELECT
28192
+ a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
28193
+ a.attname AS column_name, -- Column name
28194
+ CASE
28195
+ WHEN NOT a.attisdropped THEN
28196
+ CASE
28197
+ WHEN a.attnotnull THEN 'NO'
28198
+ ELSE 'YES'
28199
+ END
28200
+ ELSE NULL
28201
+ END AS is_nullable, -- NULL or NOT NULL constraint
28202
+ a.attndims AS array_dimensions, -- Array dimensions
28203
+ CASE
28204
+ WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
28205
+ AND EXISTS (
28206
+ SELECT FROM pg_attrdef ad
28207
+ WHERE ad.adrelid = a.attrelid
28208
+ AND ad.adnum = a.attnum
28209
+ AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
28210
+ || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
28211
+ )
28212
+ THEN CASE a.atttypid
28213
+ WHEN 'int'::regtype THEN 'serial'
28214
+ WHEN 'int8'::regtype THEN 'bigserial'
28215
+ WHEN 'int2'::regtype THEN 'smallserial'
28216
+ END
28217
+ ELSE format_type(a.atttypid, a.atttypmod)
28218
+ END AS data_type, -- Column data type
28219
+ -- ns.nspname AS type_schema, -- Schema name
28220
+ pg_get_serial_sequence('"${schema4}"."${table4}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any)
28221
+ c.column_default, -- Column default value
28222
+ c.data_type AS additional_dt, -- Data type from information_schema
28223
+ c.udt_name AS enum_name, -- Enum type (if applicable)
28224
+ c.is_generated, -- Is it a generated column?
28225
+ c.generation_expression, -- Generation expression (if generated)
28226
+ c.is_identity, -- Is it an identity column?
28227
+ c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT)
28228
+ c.identity_start, -- Start value of identity column
28229
+ c.identity_increment, -- Increment for identity column
28230
+ c.identity_maximum, -- Maximum value for identity column
28231
+ c.identity_minimum, -- Minimum value for identity column
28232
+ c.identity_cycle, -- Does the identity column cycle?
28233
+ enum_ns.nspname AS type_schema -- Schema of the enum type
28234
+ FROM
28235
+ pg_attribute a
28236
+ JOIN
28237
+ pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
28238
+ JOIN
28239
+ pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
28240
+ LEFT JOIN
28241
+ information_schema.columns c ON c.column_name = a.attname
28242
+ AND c.table_schema = ns.nspname
28243
+ AND c.table_name = cls.relname -- Match schema and table/view name
28244
+ LEFT JOIN
28245
+ pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
28246
+ LEFT JOIN
28247
+ pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
28248
+ WHERE
28249
+ a.attnum > 0 -- Valid column numbers only
28250
+ AND NOT a.attisdropped -- Skip dropped columns
28251
+ AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
28252
+ AND ns.nspname = '${schema4}' -- Filter by schema
28253
+ AND cls.relname = '${table4}' -- Filter by table name
28254
+ ORDER BY
28255
+ a.attnum; -- Order by column number`
28256
+ );
28257
+ };
26887
28258
  }
26888
28259
  });
26889
28260
 
@@ -27638,7 +29009,9 @@ var init_delete2 = __esm({
27638
29009
  "use strict";
27639
29010
  init_entity();
27640
29011
  init_query_promise();
29012
+ init_selection_proxy();
27641
29013
  init_table3();
29014
+ init_table();
27642
29015
  init_utils2();
27643
29016
  SQLiteDeleteBase = class extends (_b141 = QueryPromise, _a194 = entityKind, _b141) {
27644
29017
  constructor(table4, session, dialect4, withList) {
@@ -27695,6 +29068,26 @@ var init_delete2 = __esm({
27695
29068
  this.config.where = where;
27696
29069
  return this;
27697
29070
  }
29071
+ orderBy(...columns) {
29072
+ if (typeof columns[0] === "function") {
29073
+ const orderBy = columns[0](
29074
+ new Proxy(
29075
+ this.config.table[Table.Symbol.Columns],
29076
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
29077
+ )
29078
+ );
29079
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
29080
+ this.config.orderBy = orderByArray;
29081
+ } else {
29082
+ const orderByArray = columns;
29083
+ this.config.orderBy = orderByArray;
29084
+ }
29085
+ return this;
29086
+ }
29087
+ limit(limit) {
29088
+ this.config.limit = limit;
29089
+ return this;
29090
+ }
27698
29091
  returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
27699
29092
  this.config.returning = orderSelectedFields(fields);
27700
29093
  return this;
@@ -27905,7 +29298,7 @@ var init_view_base2 = __esm({
27905
29298
  "use strict";
27906
29299
  init_entity();
27907
29300
  init_sql();
27908
- SQLiteViewBase = class extends (_b143 = View, _a197 = entityKind, _b143) {
29301
+ SQLiteViewBase = class extends (_b143 = View3, _a197 = entityKind, _b143) {
27909
29302
  };
27910
29303
  __publicField(SQLiteViewBase, _a197, "SQLiteViewBase");
27911
29304
  }
@@ -27960,11 +29353,13 @@ var init_dialect2 = __esm({
27960
29353
  withSqlChunks.push(sql` `);
27961
29354
  return sql.join(withSqlChunks);
27962
29355
  }
27963
- buildDeleteQuery({ table: table4, where, returning, withList }) {
29356
+ buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
27964
29357
  const withSql = this.buildWithCTE(withList);
27965
29358
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
27966
29359
  const whereSql = where ? sql` where ${where}` : void 0;
27967
- return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
29360
+ const orderBySql = this.buildOrderBy(orderBy);
29361
+ const limitSql = this.buildLimit(limit);
29362
+ return sql`${withSql}delete from ${table4}${whereSql}${returningSql}${orderBySql}${limitSql}`;
27968
29363
  }
27969
29364
  buildUpdateSet(table4, set) {
27970
29365
  const tableColumns = table4[Table.Symbol.Columns];
@@ -27982,12 +29377,14 @@ var init_dialect2 = __esm({
27982
29377
  return [res];
27983
29378
  }));
27984
29379
  }
27985
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
29380
+ buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
27986
29381
  const withSql = this.buildWithCTE(withList);
27987
29382
  const setSql = this.buildUpdateSet(table4, set);
27988
29383
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
27989
29384
  const whereSql = where ? sql` where ${where}` : void 0;
27990
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
29385
+ const orderBySql = this.buildOrderBy(orderBy);
29386
+ const limitSql = this.buildLimit(limit);
29387
+ return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
27991
29388
  }
27992
29389
  /**
27993
29390
  * Builds selection SQL with provided fields/expressions
@@ -28040,6 +29437,21 @@ var init_dialect2 = __esm({
28040
29437
  });
28041
29438
  return sql.join(chunks);
28042
29439
  }
29440
+ buildLimit(limit) {
29441
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
29442
+ }
29443
+ buildOrderBy(orderBy) {
29444
+ const orderByList = [];
29445
+ if (orderBy) {
29446
+ for (const [index4, orderByValue] of orderBy.entries()) {
29447
+ orderByList.push(orderByValue);
29448
+ if (index4 < orderBy.length - 1) {
29449
+ orderByList.push(sql`, `);
29450
+ }
29451
+ }
29452
+ }
29453
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
29454
+ }
28043
29455
  buildSelectQuery({
28044
29456
  withList,
28045
29457
  fields,
@@ -28104,15 +29516,6 @@ var init_dialect2 = __esm({
28104
29516
  const joinsSql = sql.join(joinsArray);
28105
29517
  const whereSql = where ? sql` where ${where}` : void 0;
28106
29518
  const havingSql = having ? sql` having ${having}` : void 0;
28107
- const orderByList = [];
28108
- if (orderBy) {
28109
- for (const [index4, orderByValue] of orderBy.entries()) {
28110
- orderByList.push(orderByValue);
28111
- if (index4 < orderBy.length - 1) {
28112
- orderByList.push(sql`, `);
28113
- }
28114
- }
28115
- }
28116
29519
  const groupByList = [];
28117
29520
  if (groupBy) {
28118
29521
  for (const [index4, groupByValue] of groupBy.entries()) {
@@ -28123,8 +29526,8 @@ var init_dialect2 = __esm({
28123
29526
  }
28124
29527
  }
28125
29528
  const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0;
28126
- const orderBySql = orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
28127
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
29529
+ const orderBySql = this.buildOrderBy(orderBy);
29530
+ const limitSql = this.buildLimit(limit);
28128
29531
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
28129
29532
  const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
28130
29533
  if (setOperators.length > 0) {
@@ -28843,7 +30246,7 @@ var init_select3 = __esm({
28843
30246
  };
28844
30247
  }
28845
30248
  if (typeof tableName === "string" && !is(table4, SQL)) {
28846
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
30249
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
28847
30250
  this.config.fields[tableName] = selection;
28848
30251
  }
28849
30252
  }
@@ -29235,7 +30638,9 @@ var init_update2 = __esm({
29235
30638
  "use strict";
29236
30639
  init_entity();
29237
30640
  init_query_promise();
30641
+ init_selection_proxy();
29238
30642
  init_table3();
30643
+ init_table();
29239
30644
  init_utils2();
29240
30645
  _a205 = entityKind;
29241
30646
  SQLiteUpdateBuilder = class {
@@ -29314,6 +30719,26 @@ var init_update2 = __esm({
29314
30719
  this.config.where = where;
29315
30720
  return this;
29316
30721
  }
30722
+ orderBy(...columns) {
30723
+ if (typeof columns[0] === "function") {
30724
+ const orderBy = columns[0](
30725
+ new Proxy(
30726
+ this.config.table[Table.Symbol.Columns],
30727
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
30728
+ )
30729
+ );
30730
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
30731
+ this.config.orderBy = orderByArray;
30732
+ } else {
30733
+ const orderByArray = columns;
30734
+ this.config.orderBy = orderByArray;
30735
+ }
30736
+ return this;
30737
+ }
30738
+ limit(limit) {
30739
+ this.config.limit = limit;
30740
+ return this;
30741
+ }
29317
30742
  returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
29318
30743
  this.config.returning = orderSelectedFields(fields);
29319
30744
  return this;
@@ -30129,15 +31554,6 @@ var init_subquery3 = __esm({
30129
31554
  }
30130
31555
  });
30131
31556
 
30132
- // ../drizzle-orm/dist/sqlite-core/view-common.js
30133
- var SQLiteViewConfig;
30134
- var init_view_common3 = __esm({
30135
- "../drizzle-orm/dist/sqlite-core/view-common.js"() {
30136
- "use strict";
30137
- SQLiteViewConfig = Symbol.for("drizzle:SQLiteViewConfig");
30138
- }
30139
- });
30140
-
30141
31557
  // ../drizzle-orm/dist/sqlite-core/utils.js
30142
31558
  function getTableConfig2(table4) {
30143
31559
  const columns = Object.values(table4[SQLiteTable.Symbol.Columns]);
@@ -30174,11 +31590,18 @@ function getTableConfig2(table4) {
30174
31590
  name: name2
30175
31591
  };
30176
31592
  }
31593
+ function getViewConfig2(view4) {
31594
+ return {
31595
+ ...view4[ViewBaseConfig]
31596
+ // ...view[SQLiteViewConfig],
31597
+ };
31598
+ }
30177
31599
  var init_utils6 = __esm({
30178
31600
  "../drizzle-orm/dist/sqlite-core/utils.js"() {
30179
31601
  "use strict";
30180
31602
  init_entity();
30181
31603
  init_table();
31604
+ init_view_common();
30182
31605
  init_checks2();
30183
31606
  init_foreign_keys2();
30184
31607
  init_indexes2();
@@ -30189,7 +31612,7 @@ var init_utils6 = __esm({
30189
31612
  });
30190
31613
 
30191
31614
  // ../drizzle-orm/dist/sqlite-core/view.js
30192
- var _a222, ViewBuilderCore, _a223, _b155, ViewBuilder2, _a224, _b156, ManualViewBuilder2, _a225, _b157, _c8, SQLiteView;
31615
+ var _a222, ViewBuilderCore, _a223, _b155, ViewBuilder2, _a224, _b156, ManualViewBuilder2, _a225, _b157, SQLiteView2;
30193
31616
  var init_view2 = __esm({
30194
31617
  "../drizzle-orm/dist/sqlite-core/view.js"() {
30195
31618
  "use strict";
@@ -30199,7 +31622,6 @@ var init_view2 = __esm({
30199
31622
  init_query_builder3();
30200
31623
  init_table3();
30201
31624
  init_view_base2();
30202
- init_view_common3();
30203
31625
  _a222 = entityKind;
30204
31626
  ViewBuilderCore = class {
30205
31627
  constructor(name2) {
@@ -30221,8 +31643,8 @@ var init_view2 = __esm({
30221
31643
  });
30222
31644
  const aliasedSelectedFields = qb.getSelectedFields();
30223
31645
  return new Proxy(
30224
- new SQLiteView({
30225
- sqliteConfig: this.config,
31646
+ new SQLiteView2({
31647
+ // sqliteConfig: this.config,
30226
31648
  config: {
30227
31649
  name: this.name,
30228
31650
  schema: void 0,
@@ -30243,8 +31665,7 @@ var init_view2 = __esm({
30243
31665
  }
30244
31666
  existing() {
30245
31667
  return new Proxy(
30246
- new SQLiteView({
30247
- sqliteConfig: void 0,
31668
+ new SQLiteView2({
30248
31669
  config: {
30249
31670
  name: this.name,
30250
31671
  schema: void 0,
@@ -30262,8 +31683,7 @@ var init_view2 = __esm({
30262
31683
  }
30263
31684
  as(query) {
30264
31685
  return new Proxy(
30265
- new SQLiteView({
30266
- sqliteConfig: this.config,
31686
+ new SQLiteView2({
30267
31687
  config: {
30268
31688
  name: this.name,
30269
31689
  schema: void 0,
@@ -30281,15 +31701,12 @@ var init_view2 = __esm({
30281
31701
  }
30282
31702
  };
30283
31703
  __publicField(ManualViewBuilder2, _a224, "SQLiteManualViewBuilder");
30284
- SQLiteView = class extends (_c8 = SQLiteViewBase, _b157 = entityKind, _a225 = SQLiteViewConfig, _c8) {
30285
- constructor({ sqliteConfig, config }) {
31704
+ SQLiteView2 = class extends (_b157 = SQLiteViewBase, _a225 = entityKind, _b157) {
31705
+ constructor({ config }) {
30286
31706
  super(config);
30287
- /** @internal */
30288
- __publicField(this, _a225);
30289
- this[SQLiteViewConfig] = sqliteConfig;
30290
31707
  }
30291
31708
  };
30292
- __publicField(SQLiteView, _b157, "SQLiteView");
31709
+ __publicField(SQLiteView2, _a225, "SQLiteView");
30293
31710
  }
30294
31711
  });
30295
31712
 
@@ -30387,9 +31804,10 @@ var init_sqliteSerializer = __esm({
30387
31804
  init_outputs();
30388
31805
  init_utils();
30389
31806
  init_serializer();
30390
- generateSqliteSnapshot = (tables, casing2) => {
31807
+ generateSqliteSnapshot = (tables, views, casing2) => {
30391
31808
  const dialect4 = new SQLiteSyncDialect({ casing: casing2 });
30392
31809
  const result = {};
31810
+ const resultViews = {};
30393
31811
  const internal = { indexes: {} };
30394
31812
  for (const table4 of tables) {
30395
31813
  const columnsObject = {};
@@ -30585,10 +32003,60 @@ The unique constraint ${source_default.underline.blue(
30585
32003
  uniqueConstraints: uniqueConstraintObject
30586
32004
  };
30587
32005
  }
32006
+ for (const view4 of views) {
32007
+ const { name: name2, isExisting, selectedFields, query, schema: schema4 } = getViewConfig2(view4);
32008
+ const columnsObject = {};
32009
+ const existingView = resultViews[name2];
32010
+ if (typeof existingView !== "undefined") {
32011
+ console.log(
32012
+ `
32013
+ ${withStyle.errorWarning(
32014
+ `We've found duplicated view name across ${source_default.underline.blue(
32015
+ schema4 ?? "public"
32016
+ )} schema. Please rename your view`
32017
+ )}`
32018
+ );
32019
+ process.exit(1);
32020
+ }
32021
+ for (const key in selectedFields) {
32022
+ if (is(selectedFields[key], SQLiteColumn)) {
32023
+ const column4 = selectedFields[key];
32024
+ const notNull = column4.notNull;
32025
+ const primaryKey = column4.primary;
32026
+ const generated = column4.generated;
32027
+ const columnToSet = {
32028
+ name: column4.name,
32029
+ type: column4.getSQLType(),
32030
+ primaryKey,
32031
+ notNull,
32032
+ autoincrement: is(column4, SQLiteBaseInteger) ? column4.autoIncrement : false,
32033
+ generated: generated ? {
32034
+ as: is(generated.as, SQL) ? `(${dialect4.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect4.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
32035
+ type: generated.mode ?? "virtual"
32036
+ } : void 0
32037
+ };
32038
+ if (column4.default !== void 0) {
32039
+ if (is(column4.default, SQL)) {
32040
+ columnToSet.default = sqlToStr(column4.default, casing2);
32041
+ } else {
32042
+ columnToSet.default = typeof column4.default === "string" ? `'${column4.default}'` : typeof column4.default === "object" || Array.isArray(column4.default) ? `'${JSON.stringify(column4.default)}'` : column4.default;
32043
+ }
32044
+ }
32045
+ columnsObject[column4.name] = columnToSet;
32046
+ }
32047
+ }
32048
+ resultViews[name2] = {
32049
+ columns: columnsObject,
32050
+ name: name2,
32051
+ isExisting,
32052
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql
32053
+ };
32054
+ }
30588
32055
  return {
30589
32056
  version: "6",
30590
32057
  dialect: "sqlite",
30591
32058
  tables: result,
32059
+ views: resultViews,
30592
32060
  enums: {},
30593
32061
  _meta: {
30594
32062
  tables: {},
@@ -30599,11 +32067,12 @@ The unique constraint ${source_default.underline.blue(
30599
32067
  };
30600
32068
  fromDatabase2 = async (db, tablesFilter = (table4) => true, progressCallback) => {
30601
32069
  const result = {};
32070
+ const resultViews = {};
30602
32071
  const columns = await db.query(
30603
32072
  `SELECT
30604
- 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
32073
+ 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
30605
32074
  FROM sqlite_master AS m JOIN pragma_table_xinfo(m.name) AS p
30606
- WHERE m.type = 'table'
32075
+ WHERE (m.type = 'table' OR m.type = 'view')
30607
32076
  and m.tbl_name != 'sqlite_sequence'
30608
32077
  and m.tbl_name != 'sqlite_stat1'
30609
32078
  and m.tbl_name != '_litestream_seq'
@@ -30629,11 +32098,14 @@ The unique constraint ${source_default.underline.blue(
30629
32098
  let tablesCount = /* @__PURE__ */ new Set();
30630
32099
  let indexesCount = 0;
30631
32100
  let foreignKeysCount = 0;
32101
+ let viewsCount = 0;
30632
32102
  const tableToPk = {};
30633
32103
  let tableToGeneratedColumnsInfo = {};
30634
32104
  for (const column4 of columns) {
30635
32105
  if (!tablesFilter(column4.tableName)) continue;
30636
- columnsCount += 1;
32106
+ if (column4.type !== "view") {
32107
+ columnsCount += 1;
32108
+ }
30637
32109
  if (progressCallback) {
30638
32110
  progressCallback("columns", columnsCount, "fetching");
30639
32111
  }
@@ -30800,10 +32272,40 @@ WHERE
30800
32272
  progressCallback("indexes", indexesCount, "done");
30801
32273
  progressCallback("enums", 0, "done");
30802
32274
  }
32275
+ const views = await db.query(
32276
+ `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
32277
+ );
32278
+ viewsCount = views.length;
32279
+ if (progressCallback) {
32280
+ progressCallback("views", viewsCount, "fetching");
32281
+ }
32282
+ for (const view4 of views) {
32283
+ const viewName = view4["view_name"];
32284
+ const sql2 = view4["sql"];
32285
+ const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
32286
+ const match2 = sql2.match(regex);
32287
+ if (!match2) {
32288
+ console.log("Could not process view");
32289
+ process.exit(1);
32290
+ }
32291
+ const viewDefinition = match2[1];
32292
+ const columns2 = result[viewName].columns;
32293
+ delete result[viewName];
32294
+ resultViews[viewName] = {
32295
+ columns: columns2,
32296
+ isExisting: false,
32297
+ name: viewName,
32298
+ definition: viewDefinition
32299
+ };
32300
+ }
32301
+ if (progressCallback) {
32302
+ progressCallback("views", viewsCount, "done");
32303
+ }
30803
32304
  return {
30804
32305
  version: "6",
30805
32306
  dialect: "sqlite",
30806
32307
  tables: result,
32308
+ views: resultViews,
30807
32309
  enums: {},
30808
32310
  _meta: {
30809
32311
  tables: {},
@@ -32192,13 +33694,13 @@ var init_columns3 = __esm({
32192
33694
  });
32193
33695
 
32194
33696
  // ../drizzle-orm/dist/mysql-core/query-builders/count.js
32195
- var _a295, _b220, _c9, _MySqlCountBuilder, MySqlCountBuilder;
33697
+ var _a295, _b220, _c8, _MySqlCountBuilder, MySqlCountBuilder;
32196
33698
  var init_count3 = __esm({
32197
33699
  "../drizzle-orm/dist/mysql-core/query-builders/count.js"() {
32198
33700
  "use strict";
32199
33701
  init_entity();
32200
33702
  init_sql();
32201
- _MySqlCountBuilder = class _MySqlCountBuilder extends (_c9 = SQL, _b220 = entityKind, _a295 = Symbol.toStringTag, _c9) {
33703
+ _MySqlCountBuilder = class _MySqlCountBuilder extends (_c8 = SQL, _b220 = entityKind, _a295 = Symbol.toStringTag, _c8) {
32202
33704
  constructor(params) {
32203
33705
  super(_MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
32204
33706
  __publicField(this, "sql");
@@ -32252,6 +33754,8 @@ var init_delete3 = __esm({
32252
33754
  "use strict";
32253
33755
  init_entity();
32254
33756
  init_query_promise();
33757
+ init_selection_proxy();
33758
+ init_table();
32255
33759
  MySqlDeleteBase = class extends (_b221 = QueryPromise, _a296 = entityKind, _b221) {
32256
33760
  constructor(table4, session, dialect4, withList) {
32257
33761
  super();
@@ -32304,6 +33808,26 @@ var init_delete3 = __esm({
32304
33808
  this.config.where = where;
32305
33809
  return this;
32306
33810
  }
33811
+ orderBy(...columns) {
33812
+ if (typeof columns[0] === "function") {
33813
+ const orderBy = columns[0](
33814
+ new Proxy(
33815
+ this.config.table[Table.Symbol.Columns],
33816
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
33817
+ )
33818
+ );
33819
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
33820
+ this.config.orderBy = orderByArray;
33821
+ } else {
33822
+ const orderByArray = columns;
33823
+ this.config.orderBy = orderByArray;
33824
+ }
33825
+ return this;
33826
+ }
33827
+ limit(limit) {
33828
+ this.config.limit = limit;
33829
+ return this;
33830
+ }
32307
33831
  /** @internal */
32308
33832
  getSQL() {
32309
33833
  return this.dialect.buildDeleteQuery(this.config);
@@ -32531,7 +34055,7 @@ function mysqlTableWithSchema(name2, columns, extraConfig, schema4, baseName = n
32531
34055
  }
32532
34056
  return table4;
32533
34057
  }
32534
- var InlineForeignKeys3, _a299, _b223, _c10, _d4, _e3, MySqlTable, mysqlTable;
34058
+ var InlineForeignKeys3, _a299, _b223, _c9, _d4, _e3, MySqlTable, mysqlTable;
32535
34059
  var init_table4 = __esm({
32536
34060
  "../drizzle-orm/dist/mysql-core/table.js"() {
32537
34061
  "use strict";
@@ -32539,11 +34063,11 @@ var init_table4 = __esm({
32539
34063
  init_table();
32540
34064
  init_all3();
32541
34065
  InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
32542
- MySqlTable = class extends (_e3 = Table, _d4 = entityKind, _c10 = Table.Symbol.Columns, _b223 = InlineForeignKeys3, _a299 = Table.Symbol.ExtraConfigBuilder, _e3) {
34066
+ MySqlTable = class extends (_e3 = Table, _d4 = entityKind, _c9 = Table.Symbol.Columns, _b223 = InlineForeignKeys3, _a299 = Table.Symbol.ExtraConfigBuilder, _e3) {
32543
34067
  constructor() {
32544
34068
  super(...arguments);
32545
34069
  /** @internal */
32546
- __publicField(this, _c10);
34070
+ __publicField(this, _c9);
32547
34071
  /** @internal */
32548
34072
  __publicField(this, _b223, []);
32549
34073
  /** @internal */
@@ -32568,7 +34092,7 @@ var init_view_base3 = __esm({
32568
34092
  "use strict";
32569
34093
  init_entity();
32570
34094
  init_sql();
32571
- MySqlViewBase = class extends (_b224 = View, _a300 = entityKind, _b224) {
34095
+ MySqlViewBase = class extends (_b224 = View3, _a300 = entityKind, _b224) {
32572
34096
  };
32573
34097
  __publicField(MySqlViewBase, _a300, "MySqlViewBase");
32574
34098
  }
@@ -32650,11 +34174,13 @@ var init_dialect3 = __esm({
32650
34174
  withSqlChunks.push(sql` `);
32651
34175
  return sql.join(withSqlChunks);
32652
34176
  }
32653
- buildDeleteQuery({ table: table4, where, returning, withList }) {
34177
+ buildDeleteQuery({ table: table4, where, returning, withList, limit, orderBy }) {
32654
34178
  const withSql = this.buildWithCTE(withList);
32655
34179
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32656
34180
  const whereSql = where ? sql` where ${where}` : void 0;
32657
- return sql`${withSql}delete from ${table4}${whereSql}${returningSql}`;
34181
+ const orderBySql = this.buildOrderBy(orderBy);
34182
+ const limitSql = this.buildLimit(limit);
34183
+ return sql`${withSql}delete from ${table4}${whereSql}${orderBySql}${limitSql}${returningSql}`;
32658
34184
  }
32659
34185
  buildUpdateSet(table4, set) {
32660
34186
  const tableColumns = table4[Table.Symbol.Columns];
@@ -32672,12 +34198,14 @@ var init_dialect3 = __esm({
32672
34198
  return [res];
32673
34199
  }));
32674
34200
  }
32675
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
34201
+ buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
32676
34202
  const withSql = this.buildWithCTE(withList);
32677
34203
  const setSql = this.buildUpdateSet(table4, set);
32678
34204
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32679
34205
  const whereSql = where ? sql` where ${where}` : void 0;
32680
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
34206
+ const orderBySql = this.buildOrderBy(orderBy);
34207
+ const limitSql = this.buildLimit(limit);
34208
+ return sql`${withSql}update ${table4} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
32681
34209
  }
32682
34210
  /**
32683
34211
  * Builds selection SQL with provided fields/expressions
@@ -32729,6 +34257,12 @@ var init_dialect3 = __esm({
32729
34257
  });
32730
34258
  return sql.join(chunks);
32731
34259
  }
34260
+ buildLimit(limit) {
34261
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
34262
+ }
34263
+ buildOrderBy(orderBy) {
34264
+ return orderBy && orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0;
34265
+ }
32732
34266
  buildSelectQuery({
32733
34267
  withList,
32734
34268
  fields,
@@ -32782,7 +34316,7 @@ var init_dialect3 = __esm({
32782
34316
  joinsArray.push(
32783
34317
  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}`
32784
34318
  );
32785
- } else if (is(table22, View)) {
34319
+ } else if (is(table22, View3)) {
32786
34320
  const viewName = table22[ViewBaseConfig].name;
32787
34321
  const viewSchema = table22[ViewBaseConfig].schema;
32788
34322
  const origViewName = table22[ViewBaseConfig].originalName;
@@ -32803,15 +34337,9 @@ var init_dialect3 = __esm({
32803
34337
  const joinsSql = sql.join(joinsArray);
32804
34338
  const whereSql = where ? sql` where ${where}` : void 0;
32805
34339
  const havingSql = having ? sql` having ${having}` : void 0;
32806
- let orderBySql;
32807
- if (orderBy && orderBy.length > 0) {
32808
- orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
32809
- }
32810
- let groupBySql;
32811
- if (groupBy && groupBy.length > 0) {
32812
- groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
32813
- }
32814
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
34340
+ const orderBySql = this.buildOrderBy(orderBy);
34341
+ const groupBySql = groupBy && groupBy.length > 0 ? sql` group by ${sql.join(groupBy, sql`, `)}` : void 0;
34342
+ const limitSql = this.buildLimit(limit);
32815
34343
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
32816
34344
  let lockingClausesSql;
32817
34345
  if (lockingClause) {
@@ -33798,7 +35326,7 @@ var init_select4 = __esm({
33798
35326
  };
33799
35327
  }
33800
35328
  if (typeof tableName === "string" && !is(table4, SQL)) {
33801
- const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
35329
+ const selection = is(table4, Subquery) ? table4._.selectedFields : is(table4, View3) ? table4[ViewBaseConfig].selectedFields : table4[Table.Symbol.Columns];
33802
35330
  this.config.fields[tableName] = selection;
33803
35331
  }
33804
35332
  }
@@ -34194,6 +35722,8 @@ var init_update3 = __esm({
34194
35722
  "use strict";
34195
35723
  init_entity();
34196
35724
  init_query_promise();
35725
+ init_selection_proxy();
35726
+ init_table();
34197
35727
  init_utils2();
34198
35728
  _a306 = entityKind;
34199
35729
  MySqlUpdateBuilder = class {
@@ -34263,6 +35793,26 @@ var init_update3 = __esm({
34263
35793
  this.config.where = where;
34264
35794
  return this;
34265
35795
  }
35796
+ orderBy(...columns) {
35797
+ if (typeof columns[0] === "function") {
35798
+ const orderBy = columns[0](
35799
+ new Proxy(
35800
+ this.config.table[Table.Symbol.Columns],
35801
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
35802
+ )
35803
+ );
35804
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
35805
+ this.config.orderBy = orderByArray;
35806
+ } else {
35807
+ const orderByArray = columns;
35808
+ this.config.orderBy = orderByArray;
35809
+ }
35810
+ return this;
35811
+ }
35812
+ limit(limit) {
35813
+ this.config.limit = limit;
35814
+ return this;
35815
+ }
34266
35816
  /** @internal */
34267
35817
  getSQL() {
34268
35818
  return this.dialect.buildUpdateQuery(this.config);
@@ -34744,7 +36294,7 @@ var init_primary_keys3 = __esm({
34744
36294
 
34745
36295
  // ../drizzle-orm/dist/mysql-core/view-common.js
34746
36296
  var MySqlViewConfig;
34747
- var init_view_common4 = __esm({
36297
+ var init_view_common3 = __esm({
34748
36298
  "../drizzle-orm/dist/mysql-core/view-common.js"() {
34749
36299
  "use strict";
34750
36300
  MySqlViewConfig = Symbol.for("drizzle:MySqlViewConfig");
@@ -34758,7 +36308,7 @@ function mysqlViewWithSchema(name2, selection, schema4) {
34758
36308
  }
34759
36309
  return new ViewBuilder3(name2, schema4);
34760
36310
  }
34761
- var _a316, ViewBuilderCore2, _a317, _b229, ViewBuilder3, _a318, _b230, ManualViewBuilder3, _a319, _b231, _c11, MySqlView;
36311
+ var _a316, ViewBuilderCore2, _a317, _b229, ViewBuilder3, _a318, _b230, ManualViewBuilder3, _a319, _b231, _c10, MySqlView2;
34762
36312
  var init_view3 = __esm({
34763
36313
  "../drizzle-orm/dist/mysql-core/view.js"() {
34764
36314
  "use strict";
@@ -34768,7 +36318,7 @@ var init_view3 = __esm({
34768
36318
  init_query_builder4();
34769
36319
  init_table4();
34770
36320
  init_view_base3();
34771
- init_view_common4();
36321
+ init_view_common3();
34772
36322
  _a316 = entityKind;
34773
36323
  ViewBuilderCore2 = class {
34774
36324
  constructor(name2, schema4) {
@@ -34780,10 +36330,6 @@ var init_view3 = __esm({
34780
36330
  this.config.algorithm = algorithm;
34781
36331
  return this;
34782
36332
  }
34783
- definer(definer) {
34784
- this.config.definer = definer;
34785
- return this;
34786
- }
34787
36333
  sqlSecurity(sqlSecurity) {
34788
36334
  this.config.sqlSecurity = sqlSecurity;
34789
36335
  return this;
@@ -34807,7 +36353,7 @@ var init_view3 = __esm({
34807
36353
  });
34808
36354
  const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
34809
36355
  return new Proxy(
34810
- new MySqlView({
36356
+ new MySqlView2({
34811
36357
  mysqlConfig: this.config,
34812
36358
  config: {
34813
36359
  name: this.name,
@@ -34829,7 +36375,7 @@ var init_view3 = __esm({
34829
36375
  }
34830
36376
  existing() {
34831
36377
  return new Proxy(
34832
- new MySqlView({
36378
+ new MySqlView2({
34833
36379
  mysqlConfig: void 0,
34834
36380
  config: {
34835
36381
  name: this.name,
@@ -34848,7 +36394,7 @@ var init_view3 = __esm({
34848
36394
  }
34849
36395
  as(query) {
34850
36396
  return new Proxy(
34851
- new MySqlView({
36397
+ new MySqlView2({
34852
36398
  mysqlConfig: this.config,
34853
36399
  config: {
34854
36400
  name: this.name,
@@ -34867,14 +36413,14 @@ var init_view3 = __esm({
34867
36413
  }
34868
36414
  };
34869
36415
  __publicField(ManualViewBuilder3, _a318, "MySqlManualViewBuilder");
34870
- MySqlView = class extends (_c11 = MySqlViewBase, _b231 = entityKind, _a319 = MySqlViewConfig, _c11) {
36416
+ MySqlView2 = class extends (_c10 = MySqlViewBase, _b231 = entityKind, _a319 = MySqlViewConfig, _c10) {
34871
36417
  constructor({ mysqlConfig, config }) {
34872
36418
  super(config);
34873
36419
  __publicField(this, _a319);
34874
36420
  this[MySqlViewConfig] = mysqlConfig;
34875
36421
  }
34876
36422
  };
34877
- __publicField(MySqlView, _b231, "MySqlView");
36423
+ __publicField(MySqlView2, _b231, "MySqlView");
34878
36424
  }
34879
36425
  });
34880
36426
 
@@ -35016,17 +36562,25 @@ function getTableConfig3(table4) {
35016
36562
  baseName
35017
36563
  };
35018
36564
  }
36565
+ function getViewConfig3(view4) {
36566
+ return {
36567
+ ...view4[ViewBaseConfig],
36568
+ ...view4[MySqlViewConfig]
36569
+ };
36570
+ }
35019
36571
  var init_utils7 = __esm({
35020
36572
  "../drizzle-orm/dist/mysql-core/utils.js"() {
35021
36573
  "use strict";
35022
36574
  init_entity();
35023
36575
  init_table();
36576
+ init_view_common();
35024
36577
  init_checks3();
35025
36578
  init_foreign_keys3();
35026
36579
  init_indexes3();
35027
36580
  init_primary_keys3();
35028
36581
  init_table4();
35029
36582
  init_unique_constraint3();
36583
+ init_view_common3();
35030
36584
  }
35031
36585
  });
35032
36586
 
@@ -35049,7 +36603,7 @@ var init_mysql_core = __esm({
35049
36603
  init_table4();
35050
36604
  init_unique_constraint3();
35051
36605
  init_utils7();
35052
- init_view_common4();
36606
+ init_view_common3();
35053
36607
  init_view3();
35054
36608
  }
35055
36609
  });
@@ -35081,12 +36635,14 @@ var init_mysqlSerializer = __esm({
35081
36635
  init_dist();
35082
36636
  init_mysql_core();
35083
36637
  init_mysql_core();
36638
+ init_mysql_core();
35084
36639
  init_outputs();
35085
36640
  init_utils();
35086
36641
  init_serializer();
35087
- generateMySqlSnapshot = (tables, casing2) => {
36642
+ generateMySqlSnapshot = (tables, views, casing2) => {
35088
36643
  const dialect4 = new MySqlDialect({ casing: casing2 });
35089
36644
  const result = {};
36645
+ const resultViews = {};
35090
36646
  const internal = { tables: {}, indexes: {} };
35091
36647
  for (const table4 of tables) {
35092
36648
  const {
@@ -35344,10 +36900,95 @@ We have encountered a collision between the index name on columns ${source_defau
35344
36900
  };
35345
36901
  }
35346
36902
  }
36903
+ for (const view4 of views) {
36904
+ const {
36905
+ isExisting,
36906
+ name: name2,
36907
+ query,
36908
+ schema: schema4,
36909
+ selectedFields,
36910
+ algorithm,
36911
+ sqlSecurity,
36912
+ withCheckOption
36913
+ } = getViewConfig3(view4);
36914
+ const columnsObject = {};
36915
+ const existingView = resultViews[name2];
36916
+ if (typeof existingView !== "undefined") {
36917
+ console.log(
36918
+ `
36919
+ ${withStyle.errorWarning(
36920
+ `We've found duplicated view name across ${source_default.underline.blue(
36921
+ schema4 ?? "public"
36922
+ )} schema. Please rename your view`
36923
+ )}`
36924
+ );
36925
+ process.exit(1);
36926
+ }
36927
+ for (const key in selectedFields) {
36928
+ if (is(selectedFields[key], MySqlColumn)) {
36929
+ const column4 = selectedFields[key];
36930
+ const notNull = column4.notNull;
36931
+ const sqlTypeLowered = column4.getSQLType().toLowerCase();
36932
+ const autoIncrement = typeof column4.autoIncrement === "undefined" ? false : column4.autoIncrement;
36933
+ const generated = column4.generated;
36934
+ const columnToSet = {
36935
+ name: column4.name,
36936
+ type: column4.getSQLType(),
36937
+ primaryKey: false,
36938
+ // If field is autoincrement it's notNull by default
36939
+ // notNull: autoIncrement ? true : notNull,
36940
+ notNull,
36941
+ autoincrement: autoIncrement,
36942
+ onUpdate: column4.hasOnUpdateNow,
36943
+ generated: generated ? {
36944
+ as: is(generated.as, SQL) ? dialect4.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect4.sqlToQuery(generated.as()).sql : generated.as,
36945
+ type: generated.mode ?? "stored"
36946
+ } : void 0
36947
+ };
36948
+ if (column4.default !== void 0) {
36949
+ if (is(column4.default, SQL)) {
36950
+ columnToSet.default = sqlToStr(column4.default, casing2);
36951
+ } else {
36952
+ if (typeof column4.default === "string") {
36953
+ columnToSet.default = `'${column4.default}'`;
36954
+ } else {
36955
+ if (sqlTypeLowered === "json") {
36956
+ columnToSet.default = `'${JSON.stringify(column4.default)}'`;
36957
+ } else if (column4.default instanceof Date) {
36958
+ if (sqlTypeLowered === "date") {
36959
+ columnToSet.default = `'${column4.default.toISOString().split("T")[0]}'`;
36960
+ } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
36961
+ columnToSet.default = `'${column4.default.toISOString().replace("T", " ").slice(0, 23)}'`;
36962
+ }
36963
+ } else {
36964
+ columnToSet.default = column4.default;
36965
+ }
36966
+ }
36967
+ if (["blob", "text", "json"].includes(column4.getSQLType())) {
36968
+ columnToSet.default = `(${columnToSet.default})`;
36969
+ }
36970
+ }
36971
+ }
36972
+ columnsObject[column4.name] = columnToSet;
36973
+ }
36974
+ }
36975
+ resultViews[name2] = {
36976
+ columns: columnsObject,
36977
+ name: name2,
36978
+ isExisting,
36979
+ definition: isExisting ? void 0 : dialect4.sqlToQuery(query).sql,
36980
+ withCheckOption,
36981
+ algorithm: algorithm ?? "undefined",
36982
+ // set default values
36983
+ sqlSecurity: sqlSecurity ?? "definer"
36984
+ // set default values
36985
+ };
36986
+ }
35347
36987
  return {
35348
36988
  version: "5",
35349
36989
  dialect: "mysql",
35350
36990
  tables: result,
36991
+ views: resultViews,
35351
36992
  _meta: {
35352
36993
  tables: {},
35353
36994
  columns: {}
@@ -35367,6 +37008,7 @@ We have encountered a collision between the index name on columns ${source_defau
35367
37008
  let tablesCount = /* @__PURE__ */ new Set();
35368
37009
  let indexesCount = 0;
35369
37010
  let foreignKeysCount = 0;
37011
+ let viewsCount = 0;
35370
37012
  const idxs = await db.query(
35371
37013
  `select * from INFORMATION_SCHEMA.STATISTICS
35372
37014
  WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
@@ -35606,14 +37248,44 @@ We have encountered a collision between the index name on columns ${source_defau
35606
37248
  }
35607
37249
  }
35608
37250
  }
37251
+ const views = await db.query(
37252
+ `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
37253
+ );
37254
+ const resultViews = {};
37255
+ viewsCount = views.length;
37256
+ if (progressCallback) {
37257
+ progressCallback("views", viewsCount, "fetching");
37258
+ }
37259
+ for await (const view4 of views) {
37260
+ const viewName = view4["TABLE_NAME"];
37261
+ const definition = view4["VIEW_DEFINITION"];
37262
+ const withCheckOption = view4["CHECK_OPTION"] === "NONE" ? void 0 : view4["CHECK_OPTION"].toLowerCase();
37263
+ const sqlSecurity = view4["SECURITY_TYPE"].toLowerCase();
37264
+ const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
37265
+ const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
37266
+ const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
37267
+ const columns2 = result[viewName].columns;
37268
+ delete result[viewName];
37269
+ resultViews[viewName] = {
37270
+ columns: columns2,
37271
+ isExisting: false,
37272
+ name: viewName,
37273
+ algorithm,
37274
+ definition,
37275
+ sqlSecurity,
37276
+ withCheckOption
37277
+ };
37278
+ }
35609
37279
  if (progressCallback) {
35610
37280
  progressCallback("indexes", indexesCount, "done");
35611
37281
  progressCallback("enums", 0, "done");
37282
+ progressCallback("views", viewsCount, "done");
35612
37283
  }
35613
37284
  return {
35614
37285
  version: "5",
35615
37286
  dialect: "mysql",
35616
37287
  tables: result,
37288
+ views: resultViews,
35617
37289
  _meta: {
35618
37290
  tables: {},
35619
37291
  columns: {}
@@ -35929,6 +37601,8 @@ var init_pgImports = __esm({
35929
37601
  const enums = [];
35930
37602
  const schemas = [];
35931
37603
  const sequences = [];
37604
+ const views = [];
37605
+ const matViews = [];
35932
37606
  const i0values = Object.values(exports);
35933
37607
  i0values.forEach((t) => {
35934
37608
  if (isPgEnum(t)) {
@@ -35941,11 +37615,17 @@ var init_pgImports = __esm({
35941
37615
  if (is(t, PgSchema5)) {
35942
37616
  schemas.push(t);
35943
37617
  }
37618
+ if (isPgView(t)) {
37619
+ views.push(t);
37620
+ }
37621
+ if (isPgMaterializedView(t)) {
37622
+ matViews.push(t);
37623
+ }
35944
37624
  if (isPgSequence(t)) {
35945
37625
  sequences.push(t);
35946
37626
  }
35947
37627
  });
35948
- return { tables, enums, schemas, sequences };
37628
+ return { tables, enums, schemas, sequences, views, matViews };
35949
37629
  };
35950
37630
  }
35951
37631
  });
@@ -35965,25 +37645,31 @@ var init_sqliteImports = __esm({
35965
37645
  init_utils8();
35966
37646
  prepareFromExports2 = (exports) => {
35967
37647
  const tables = [];
37648
+ const views = [];
35968
37649
  const i0values = Object.values(exports);
35969
37650
  i0values.forEach((t) => {
35970
37651
  if (is(t, SQLiteTable)) {
35971
37652
  tables.push(t);
35972
37653
  }
37654
+ if (is(t, SQLiteView2)) {
37655
+ views.push(t);
37656
+ }
35973
37657
  });
35974
- return { tables };
37658
+ return { tables, views };
35975
37659
  };
35976
37660
  prepareFromSqliteImports = async (imports) => {
35977
37661
  const tables = [];
37662
+ const views = [];
35978
37663
  const { unregister } = await safeRegister();
35979
37664
  for (let i = 0; i < imports.length; i++) {
35980
37665
  const it = imports[i];
35981
37666
  const i0 = __require(`${it}`);
35982
37667
  const prepared = prepareFromExports2(i0);
35983
37668
  tables.push(...prepared.tables);
37669
+ views.push(...prepared.views);
35984
37670
  }
35985
37671
  unregister();
35986
- return { tables: Array.from(new Set(tables)) };
37672
+ return { tables: Array.from(new Set(tables)), views };
35987
37673
  };
35988
37674
  }
35989
37675
  });
@@ -36003,25 +37689,31 @@ var init_mysqlImports = __esm({
36003
37689
  init_utils8();
36004
37690
  prepareFromExports3 = (exports) => {
36005
37691
  const tables = [];
37692
+ const views = [];
36006
37693
  const i0values = Object.values(exports);
36007
37694
  i0values.forEach((t) => {
36008
37695
  if (is(t, MySqlTable)) {
36009
37696
  tables.push(t);
36010
37697
  }
37698
+ if (is(t, MySqlView2)) {
37699
+ views.push(t);
37700
+ }
36011
37701
  });
36012
- return { tables };
37702
+ return { tables, views };
36013
37703
  };
36014
37704
  prepareFromMySqlImports = async (imports) => {
36015
37705
  const tables = [];
37706
+ const views = [];
36016
37707
  const { unregister } = await safeRegister();
36017
37708
  for (let i = 0; i < imports.length; i++) {
36018
37709
  const it = imports[i];
36019
37710
  const i0 = __require(`${it}`);
36020
37711
  const prepared = prepareFromExports3(i0);
36021
37712
  tables.push(...prepared.tables);
37713
+ views.push(...prepared.views);
36022
37714
  }
36023
37715
  unregister();
36024
- return { tables: Array.from(new Set(tables)) };
37716
+ return { tables: Array.from(new Set(tables)), views };
36025
37717
  };
36026
37718
  }
36027
37719
  });
@@ -36396,6 +38088,7 @@ var pgSuggestions = async (db, statements) => {
36396
38088
  const columnsToRemove = [];
36397
38089
  const schemasToRemove = [];
36398
38090
  const tablesToTruncate = [];
38091
+ const matViewsToRemove = [];
36399
38092
  let renamedSchemas = {};
36400
38093
  let renamedTables = {};
36401
38094
  for (const statement of statements) {
@@ -36405,38 +38098,32 @@ var pgSuggestions = async (db, statements) => {
36405
38098
  renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
36406
38099
  } else if (statement.type === "drop_table") {
36407
38100
  const res = await db.query(
36408
- `select count(*) as count from ${tableNameWithSchemaFrom(
36409
- statement.schema,
36410
- statement.tableName,
36411
- renamedSchemas,
36412
- renamedTables
36413
- )}`
38101
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36414
38102
  );
36415
38103
  const count2 = Number(res[0].count);
38104
+ if (count2 > 0) {
38105
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count2} items`);
38106
+ tablesToRemove.push(statement.tableName);
38107
+ shouldAskForApprove = true;
38108
+ }
38109
+ } else if (statement.type === "drop_view" && statement.materialized) {
38110
+ const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
38111
+ const count2 = Number(res[0].count);
36416
38112
  if (count2 > 0) {
36417
38113
  infoToPrint.push(
36418
- `\xB7 You're about to delete ${source_default.underline(
36419
- statement.tableName
36420
- )} table with ${count2} items`
38114
+ `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count2} items`
36421
38115
  );
36422
- tablesToRemove.push(statement.tableName);
38116
+ matViewsToRemove.push(statement.name);
36423
38117
  shouldAskForApprove = true;
36424
38118
  }
36425
38119
  } else if (statement.type === "alter_table_drop_column") {
36426
38120
  const res = await db.query(
36427
- `select count(*) as count from ${tableNameWithSchemaFrom(
36428
- statement.schema,
36429
- statement.tableName,
36430
- renamedSchemas,
36431
- renamedTables
36432
- )}`
38121
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36433
38122
  );
36434
38123
  const count2 = Number(res[0].count);
36435
38124
  if (count2 > 0) {
36436
38125
  infoToPrint.push(
36437
- `\xB7 You're about to delete ${source_default.underline(
36438
- statement.columnName
36439
- )} column in ${statement.tableName} table with ${count2} items`
38126
+ `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count2} items`
36440
38127
  );
36441
38128
  columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
36442
38129
  shouldAskForApprove = true;
@@ -36447,58 +38134,35 @@ var pgSuggestions = async (db, statements) => {
36447
38134
  );
36448
38135
  const count2 = Number(res[0].count);
36449
38136
  if (count2 > 0) {
36450
- infoToPrint.push(
36451
- `\xB7 You're about to delete ${source_default.underline(
36452
- statement.name
36453
- )} schema with ${count2} tables`
36454
- );
38137
+ infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count2} tables`);
36455
38138
  schemasToRemove.push(statement.name);
36456
38139
  shouldAskForApprove = true;
36457
38140
  }
36458
38141
  } else if (statement.type === "alter_table_alter_column_set_type") {
36459
38142
  const res = await db.query(
36460
- `select count(*) as count from ${tableNameWithSchemaFrom(
36461
- statement.schema,
36462
- statement.tableName,
36463
- renamedSchemas,
36464
- renamedTables
36465
- )}`
38143
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36466
38144
  );
36467
38145
  const count2 = Number(res[0].count);
36468
38146
  if (count2 > 0) {
36469
38147
  infoToPrint.push(
36470
- `\xB7 You're about to change ${source_default.underline(
36471
- statement.columnName
36472
- )} column type from ${source_default.underline(
36473
- statement.oldDataType
36474
- )} to ${source_default.underline(statement.newDataType)} with ${count2} items`
38148
+ `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
38149
+ statement.newDataType
38150
+ )} with ${count2} items`
36475
38151
  );
36476
38152
  statementsToExecute.push(
36477
- `truncate table ${tableNameWithSchemaFrom(
36478
- statement.schema,
36479
- statement.tableName,
36480
- renamedSchemas,
36481
- renamedTables
36482
- )} cascade;`
38153
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36483
38154
  );
36484
38155
  tablesToTruncate.push(statement.tableName);
36485
38156
  shouldAskForApprove = true;
36486
38157
  }
36487
38158
  } else if (statement.type === "alter_table_alter_column_drop_pk") {
36488
38159
  const res = await db.query(
36489
- `select count(*) as count from ${tableNameWithSchemaFrom(
36490
- statement.schema,
36491
- statement.tableName,
36492
- renamedSchemas,
36493
- renamedTables
36494
- )}`
38160
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36495
38161
  );
36496
38162
  const count2 = Number(res[0].count);
36497
38163
  if (count2 > 0) {
36498
38164
  infoToPrint.push(
36499
- `\xB7 You're about to change ${source_default.underline(
36500
- statement.tableName
36501
- )} primary key. This statements may fail and you table may left without primary key`
38165
+ `\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`
36502
38166
  );
36503
38167
  tablesToTruncate.push(statement.tableName);
36504
38168
  shouldAskForApprove = true;
@@ -36522,40 +38186,23 @@ var pgSuggestions = async (db, statements) => {
36522
38186
  } else if (statement.type === "alter_table_add_column") {
36523
38187
  if (statement.column.notNull && typeof statement.column.default === "undefined") {
36524
38188
  const res = await db.query(
36525
- `select count(*) as count from ${tableNameWithSchemaFrom(
36526
- statement.schema,
36527
- statement.tableName,
36528
- renamedSchemas,
36529
- renamedTables
36530
- )}`
38189
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36531
38190
  );
36532
38191
  const count2 = Number(res[0].count);
36533
38192
  if (count2 > 0) {
36534
38193
  infoToPrint.push(
36535
- `\xB7 You're about to add not-null ${source_default.underline(
36536
- statement.column.name
36537
- )} column without default value, which contains ${count2} items`
38194
+ `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count2} items`
36538
38195
  );
36539
38196
  tablesToTruncate.push(statement.tableName);
36540
38197
  statementsToExecute.push(
36541
- `truncate table ${tableNameWithSchemaFrom(
36542
- statement.schema,
36543
- statement.tableName,
36544
- renamedSchemas,
36545
- renamedTables
36546
- )} cascade;`
38198
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36547
38199
  );
36548
38200
  shouldAskForApprove = true;
36549
38201
  }
36550
38202
  }
36551
38203
  } else if (statement.type === "create_unique_constraint") {
36552
38204
  const res = await db.query(
36553
- `select count(*) as count from ${tableNameWithSchemaFrom(
36554
- statement.schema,
36555
- statement.tableName,
36556
- renamedSchemas,
36557
- renamedTables
36558
- )}`
38205
+ `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
36559
38206
  );
36560
38207
  const count2 = Number(res[0].count);
36561
38208
  if (count2 > 0) {
@@ -36569,20 +38216,12 @@ var pgSuggestions = async (db, statements) => {
36569
38216
  `
36570
38217
  );
36571
38218
  const { status, data } = await (0, import_hanji5.render)(
36572
- new Select([
36573
- "No, add the constraint without truncating the table",
36574
- `Yes, truncate the table`
36575
- ])
38219
+ new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
36576
38220
  );
36577
38221
  if (data?.index === 1) {
36578
38222
  tablesToTruncate.push(statement.tableName);
36579
38223
  statementsToExecute.push(
36580
- `truncate table ${tableNameWithSchemaFrom(
36581
- statement.schema,
36582
- statement.tableName,
36583
- renamedSchemas,
36584
- renamedTables
36585
- )} cascade;`
38224
+ `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
36586
38225
  );
36587
38226
  shouldAskForApprove = true;
36588
38227
  }
@@ -36592,10 +38231,7 @@ var pgSuggestions = async (db, statements) => {
36592
38231
  if (typeof stmnt !== "undefined") {
36593
38232
  if (statement.type === "drop_table") {
36594
38233
  statementsToExecute.push(
36595
- `DROP TABLE ${concatSchemaAndTableName(
36596
- statement.schema,
36597
- statement.tableName
36598
- )} CASCADE;`
38234
+ `DROP TABLE ${concatSchemaAndTableName(statement.schema, statement.tableName)} CASCADE;`
36599
38235
  );
36600
38236
  } else {
36601
38237
  statementsToExecute.push(...stmnt);
@@ -36606,6 +38242,7 @@ var pgSuggestions = async (db, statements) => {
36606
38242
  statementsToExecute,
36607
38243
  shouldAskForApprove,
36608
38244
  infoToPrint,
38245
+ matViewsToRemove: [...new Set(matViewsToRemove)],
36609
38246
  columnsToRemove: [...new Set(columnsToRemove)],
36610
38247
  schemasToRemove: [...new Set(schemasToRemove)],
36611
38248
  tablesToTruncate: [...new Set(tablesToTruncate)],
@@ -36785,6 +38422,9 @@ String.prototype.capitalise = function() {
36785
38422
  String.prototype.concatIf = function(it, condition) {
36786
38423
  return condition ? `${this}${it}` : String(this);
36787
38424
  };
38425
+ String.prototype.snake_case = function() {
38426
+ return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
38427
+ };
36788
38428
  Array.prototype.random = function() {
36789
38429
  return this[~~(Math.random() * this.length)];
36790
38430
  };
@@ -36845,6 +38485,8 @@ var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
36845
38485
  prepared.enums,
36846
38486
  prepared.schemas,
36847
38487
  prepared.sequences,
38488
+ prepared.views,
38489
+ prepared.matViews,
36848
38490
  casing2,
36849
38491
  schemaFilters
36850
38492
  );
@@ -36868,6 +38510,7 @@ var generateMigration = async (prev, cur) => {
36868
38510
  sequencesResolver,
36869
38511
  tablesResolver,
36870
38512
  columnsResolver,
38513
+ viewsResolver,
36871
38514
  validatedPrev,
36872
38515
  validatedCur
36873
38516
  );
@@ -36900,6 +38543,7 @@ var pushSchema = async (imports, drizzleInstance, schemaFilters) => {
36900
38543
  sequencesResolver,
36901
38544
  tablesResolver,
36902
38545
  columnsResolver,
38546
+ viewsResolver,
36903
38547
  validatedPrev,
36904
38548
  validatedCur,
36905
38549
  "push"
@@ -36920,7 +38564,7 @@ var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
36920
38564
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
36921
38565
  const prepared = prepareFromExports4(imports);
36922
38566
  const id = randomUUID();
36923
- const snapshot = generateSqliteSnapshot(prepared.tables, casing2);
38567
+ const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
36924
38568
  return {
36925
38569
  ...snapshot,
36926
38570
  id,
@@ -36938,6 +38582,7 @@ var generateSQLiteMigration = async (prev, cur) => {
36938
38582
  squashedCur,
36939
38583
  tablesResolver,
36940
38584
  columnsResolver,
38585
+ sqliteViewsResolver,
36941
38586
  validatedPrev,
36942
38587
  validatedCur
36943
38588
  );
@@ -36969,6 +38614,7 @@ var pushSQLiteSchema = async (imports, drizzleInstance) => {
36969
38614
  squashedCur,
36970
38615
  tablesResolver,
36971
38616
  columnsResolver,
38617
+ sqliteViewsResolver,
36972
38618
  validatedPrev,
36973
38619
  validatedCur,
36974
38620
  "push"
@@ -36995,7 +38641,7 @@ var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
36995
38641
  const { prepareFromExports: prepareFromExports4 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
36996
38642
  const prepared = prepareFromExports4(imports);
36997
38643
  const id = randomUUID();
36998
- const snapshot = generateMySqlSnapshot(prepared.tables, casing2);
38644
+ const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
36999
38645
  return {
37000
38646
  ...snapshot,
37001
38647
  id,
@@ -37013,6 +38659,7 @@ var generateMySQLMigration = async (prev, cur) => {
37013
38659
  squashedCur,
37014
38660
  tablesResolver,
37015
38661
  columnsResolver,
38662
+ mySqlViewsResolver,
37016
38663
  validatedPrev,
37017
38664
  validatedCur
37018
38665
  );
@@ -37040,6 +38687,7 @@ var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
37040
38687
  squashedCur,
37041
38688
  tablesResolver,
37042
38689
  columnsResolver,
38690
+ mySqlViewsResolver,
37043
38691
  validatedPrev,
37044
38692
  validatedCur,
37045
38693
  "push"