drizzle-kit 0.25.0-a5a41e0 → 0.25.0-b75016b

Sign up to get free protection for your applications and to get access to all the features.
Files changed (10) hide show
  1. package/api.d.mts +92 -470
  2. package/api.d.ts +92 -470
  3. package/api.js +16079 -95732
  4. package/api.mjs +16119 -95768
  5. package/bin.cjs +1050 -1255
  6. package/index.d.mts +7 -0
  7. package/index.d.ts +7 -0
  8. package/package.json +2 -2
  9. package/utils.js +29 -51
  10. package/utils.mjs +29 -51
package/bin.cjs CHANGED
@@ -922,8 +922,8 @@ var require_hanji = __commonJS({
922
922
  };
923
923
  exports2.deferred = deferred;
924
924
  var Terminal = class {
925
- constructor(view2, stdin, stdout, closable) {
926
- this.view = view2;
925
+ constructor(view, stdin, stdout, closable) {
926
+ this.view = view;
927
927
  this.stdin = stdin;
928
928
  this.stdout = stdout;
929
929
  this.closable = closable;
@@ -961,7 +961,7 @@ var require_hanji = __commonJS({
961
961
  this.resolve({ status: "submitted", data: this.view.result() });
962
962
  return;
963
963
  }
964
- view2.input(str, key);
964
+ view.input(str, key);
965
965
  };
966
966
  this.stdin.on("keypress", keypress);
967
967
  this.view.attach(this);
@@ -1023,8 +1023,8 @@ var require_hanji = __commonJS({
1023
1023
  };
1024
1024
  exports2.TaskView = TaskView2;
1025
1025
  var TaskTerminal = class {
1026
- constructor(view2, stdout) {
1027
- this.view = view2;
1026
+ constructor(view, stdout) {
1027
+ this.view = view;
1028
1028
  this.stdout = stdout;
1029
1029
  this.text = "";
1030
1030
  this.view.attach(this);
@@ -1043,22 +1043,22 @@ var require_hanji = __commonJS({
1043
1043
  }
1044
1044
  };
1045
1045
  exports2.TaskTerminal = TaskTerminal;
1046
- function render9(view2) {
1046
+ function render9(view) {
1047
1047
  const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
1048
- if (view2 instanceof Prompt3) {
1049
- const terminal = new Terminal(view2, stdin, stdout, closable);
1048
+ if (view instanceof Prompt3) {
1049
+ const terminal = new Terminal(view, stdin, stdout, closable);
1050
1050
  terminal.requestLayout();
1051
1051
  return terminal.result();
1052
1052
  }
1053
- stdout.write(`${view2}
1053
+ stdout.write(`${view}
1054
1054
  `);
1055
1055
  closable.close();
1056
1056
  return;
1057
1057
  }
1058
1058
  exports2.render = render9;
1059
- function renderWithTask6(view2, task) {
1059
+ function renderWithTask6(view, task) {
1060
1060
  return __awaiter2(this, void 0, void 0, function* () {
1061
- const terminal = new TaskTerminal(view2, process.stdout);
1061
+ const terminal = new TaskTerminal(view, process.stdout);
1062
1062
  terminal.requestLayout();
1063
1063
  const result = yield task;
1064
1064
  terminal.clear();
@@ -1075,7 +1075,7 @@ var require_hanji = __commonJS({
1075
1075
  });
1076
1076
 
1077
1077
  // src/cli/views.ts
1078
- var import_hanji, warning, err, info, grey, error, schema, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, MigrateProgress, ProgressView, DropMigrationView, trimmedRange;
1078
+ var import_hanji, warning, err, info, grey, error, schema, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, MigrateProgress, ProgressView, DropMigrationView, trimmedRange;
1079
1079
  var init_views = __esm({
1080
1080
  "src/cli/views.ts"() {
1081
1081
  "use strict";
@@ -1178,6 +1178,53 @@ Is ${source_default.bold.blue(
1178
1178
  tableKey = (it) => {
1179
1179
  return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
1180
1180
  };
1181
+ ResolveSelectNamed = class extends import_hanji.Prompt {
1182
+ constructor(base, data, entityType) {
1183
+ super();
1184
+ this.base = base;
1185
+ this.entityType = entityType;
1186
+ this.on("attach", (terminal) => terminal.toggleCursor("hide"));
1187
+ this.state = new import_hanji.SelectState(data);
1188
+ this.state.bind(this);
1189
+ this.base = base;
1190
+ }
1191
+ render(status) {
1192
+ if (status === "submitted" || status === "aborted") {
1193
+ return "";
1194
+ }
1195
+ const key = this.base.name;
1196
+ let text = `
1197
+ Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
1198
+ `;
1199
+ const isSelectedRenamed = isRenamePromptItem(
1200
+ this.state.items[this.state.selectedIdx]
1201
+ );
1202
+ const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
1203
+ const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_2) => {
1204
+ const it = _2;
1205
+ const keyFrom = it.from.name;
1206
+ return key.length + 3 + keyFrom.length;
1207
+ }).reduce((a, b) => {
1208
+ if (a > b) {
1209
+ return a;
1210
+ }
1211
+ return b;
1212
+ }, 0);
1213
+ const entityType = this.entityType;
1214
+ this.state.items.forEach((it, idx) => {
1215
+ const isSelected = idx === this.state.selectedIdx;
1216
+ const isRenamed = isRenamePromptItem(it);
1217
+ const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
1218
+ const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
1219
+ text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
1220
+ text += idx != this.state.items.length - 1 ? "\n" : "";
1221
+ });
1222
+ return text;
1223
+ }
1224
+ result() {
1225
+ return this.state.items[this.state.selectedIdx];
1226
+ }
1227
+ };
1181
1228
  ResolveSelect = class extends import_hanji.Prompt {
1182
1229
  constructor(base, data, entityType) {
1183
1230
  super();
@@ -1736,8 +1783,8 @@ var init_lib = __esm({
1736
1783
  return void 0;
1737
1784
  };
1738
1785
  util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && isFinite(val2) && Math.floor(val2) === val2;
1739
- function joinValues(array, separator = " | ") {
1740
- return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
1786
+ function joinValues(array2, separator = " | ") {
1787
+ return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
1741
1788
  }
1742
1789
  util2.joinValues = joinValues;
1743
1790
  util2.jsonStringifyReplacer = (_2, value) => {
@@ -5706,7 +5753,7 @@ var init_vector = __esm({
5706
5753
  });
5707
5754
 
5708
5755
  // src/serializer/pgSchema.ts
5709
- var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, viewWithOption, matViewWithOption, mergedViewWithOption, view, 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;
5756
+ var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, roleSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, policy, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5710
5757
  var init_pgSchema = __esm({
5711
5758
  "src/serializer/pgSchema.ts"() {
5712
5759
  "use strict";
@@ -5838,6 +5885,12 @@ var init_pgSchema = __esm({
5838
5885
  cycle: booleanType().optional(),
5839
5886
  schema: stringType()
5840
5887
  }).strict();
5888
+ roleSchema = objectType({
5889
+ name: stringType(),
5890
+ createDb: booleanType().optional(),
5891
+ createRole: booleanType().optional(),
5892
+ inherit: booleanType().optional()
5893
+ }).strict();
5841
5894
  sequenceSquashed = objectType({
5842
5895
  name: stringType(),
5843
5896
  schema: stringType(),
@@ -5901,43 +5954,13 @@ var init_pgSchema = __esm({
5901
5954
  columns: stringType().array(),
5902
5955
  nullsNotDistinct: booleanType()
5903
5956
  }).strict();
5904
- viewWithOption = objectType({
5905
- checkOption: enumType(["local", "cascaded"]).optional(),
5906
- securityBarrier: booleanType().optional(),
5907
- securityInvoker: booleanType().optional()
5908
- }).strict();
5909
- matViewWithOption = objectType({
5910
- fillfactor: numberType().optional(),
5911
- toastTupleTarget: numberType().optional(),
5912
- parallelWorkers: numberType().optional(),
5913
- autovacuumEnabled: booleanType().optional(),
5914
- vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
5915
- vacuumTruncate: booleanType().optional(),
5916
- autovacuumVacuumThreshold: numberType().optional(),
5917
- autovacuumVacuumScaleFactor: numberType().optional(),
5918
- autovacuumVacuumCostDelay: numberType().optional(),
5919
- autovacuumVacuumCostLimit: numberType().optional(),
5920
- autovacuumFreezeMinAge: numberType().optional(),
5921
- autovacuumFreezeMaxAge: numberType().optional(),
5922
- autovacuumFreezeTableAge: numberType().optional(),
5923
- autovacuumMultixactFreezeMinAge: numberType().optional(),
5924
- autovacuumMultixactFreezeMaxAge: numberType().optional(),
5925
- autovacuumMultixactFreezeTableAge: numberType().optional(),
5926
- logAutovacuumMinDuration: numberType().optional(),
5927
- userCatalogTable: booleanType().optional()
5928
- }).strict();
5929
- mergedViewWithOption = viewWithOption.merge(matViewWithOption);
5930
- view = objectType({
5957
+ policy = objectType({
5931
5958
  name: stringType(),
5932
- schema: stringType(),
5933
- columns: recordType(stringType(), column2),
5934
- definition: stringType().optional(),
5935
- materialized: booleanType(),
5936
- with: mergedViewWithOption.optional(),
5937
- isExisting: booleanType(),
5938
- withNoData: booleanType().optional(),
5959
+ as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
5960
+ for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
5961
+ to: stringType().array().optional(),
5939
5962
  using: stringType().optional(),
5940
- tablespace: stringType().optional()
5963
+ withCheck: stringType().optional()
5941
5964
  }).strict();
5942
5965
  tableV42 = objectType({
5943
5966
  name: stringType(),
@@ -5980,7 +6003,8 @@ var init_pgSchema = __esm({
5980
6003
  indexes: recordType(stringType(), index2),
5981
6004
  foreignKeys: recordType(stringType(), fk2),
5982
6005
  compositePrimaryKeys: recordType(stringType(), compositePK2),
5983
- uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
6006
+ uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
6007
+ policies: recordType(stringType(), policy).default({})
5984
6008
  }).strict();
5985
6009
  schemaHash2 = objectType({
5986
6010
  id: stringType(),
@@ -6073,8 +6097,8 @@ var init_pgSchema = __esm({
6073
6097
  tables: recordType(stringType(), table2),
6074
6098
  enums: recordType(stringType(), enumSchema),
6075
6099
  schemas: recordType(stringType(), stringType()),
6076
- views: recordType(stringType(), view).default({}),
6077
6100
  sequences: recordType(stringType(), sequenceSchema).default({}),
6101
+ roles: recordType(stringType(), roleSchema).default({}),
6078
6102
  _meta: objectType({
6079
6103
  schemas: recordType(stringType(), stringType()),
6080
6104
  tables: recordType(stringType(), stringType()),
@@ -6089,7 +6113,8 @@ var init_pgSchema = __esm({
6089
6113
  indexes: recordType(stringType(), stringType()),
6090
6114
  foreignKeys: recordType(stringType(), stringType()),
6091
6115
  compositePrimaryKeys: recordType(stringType(), stringType()),
6092
- uniqueConstraints: recordType(stringType(), stringType())
6116
+ uniqueConstraints: recordType(stringType(), stringType()),
6117
+ policies: recordType(stringType(), stringType())
6093
6118
  }).strict();
6094
6119
  tableSquashedV42 = objectType({
6095
6120
  name: stringType(),
@@ -6118,8 +6143,8 @@ var init_pgSchema = __esm({
6118
6143
  tables: recordType(stringType(), tableSquashed2),
6119
6144
  enums: recordType(stringType(), enumSchema),
6120
6145
  schemas: recordType(stringType(), stringType()),
6121
- views: recordType(stringType(), view),
6122
- sequences: recordType(stringType(), sequenceSquashed)
6146
+ sequences: recordType(stringType(), sequenceSquashed),
6147
+ roles: recordType(stringType(), roleSchema).default({})
6123
6148
  }).strict();
6124
6149
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
6125
6150
  pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
@@ -6202,6 +6227,25 @@ var init_pgSchema = __esm({
6202
6227
  squashFK: (fk4) => {
6203
6228
  return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""};${fk4.schemaTo || "public"}`;
6204
6229
  },
6230
+ squashPolicy: (policy2) => {
6231
+ var _a;
6232
+ return `${policy2.name}--${policy2.as}--${policy2.for}--${(_a = policy2.to) == null ? void 0 : _a.join(",")}--${policy2.using}--${policy2.withCheck}`;
6233
+ },
6234
+ unsquashPolicy: (policy2) => {
6235
+ const splitted = policy2.split("--");
6236
+ return {
6237
+ name: splitted[0],
6238
+ as: splitted[1],
6239
+ for: splitted[2],
6240
+ to: splitted[3].split(","),
6241
+ using: splitted[4] !== "undefined" ? splitted[4] : void 0,
6242
+ withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0
6243
+ };
6244
+ },
6245
+ squashPolicyPush: (policy2) => {
6246
+ var _a;
6247
+ return `${policy2.name}--${policy2.as}--${policy2.for}--${(_a = policy2.to) == null ? void 0 : _a.join(",")}`;
6248
+ },
6205
6249
  squashPK: (pk) => {
6206
6250
  return `${pk.columns.join(",")};${pk.name}`;
6207
6251
  },
@@ -6304,6 +6348,9 @@ var init_pgSchema = __esm({
6304
6348
  return PgSquasher.squashUnique(unq);
6305
6349
  }
6306
6350
  );
6351
+ const squashedPolicies = mapValues(it[1].policies, (policy2) => {
6352
+ return action === "push" ? PgSquasher.squashPolicyPush(policy2) : PgSquasher.squashPolicy(policy2);
6353
+ });
6307
6354
  return [
6308
6355
  it[0],
6309
6356
  {
@@ -6313,7 +6360,8 @@ var init_pgSchema = __esm({
6313
6360
  indexes: squashedIndexes,
6314
6361
  foreignKeys: squashedFKs,
6315
6362
  compositePrimaryKeys: squashedPKs,
6316
- uniqueConstraints: squashedUniqueConstraints
6363
+ uniqueConstraints: squashedUniqueConstraints,
6364
+ policies: squashedPolicies
6317
6365
  }
6318
6366
  ];
6319
6367
  })
@@ -6336,8 +6384,8 @@ var init_pgSchema = __esm({
6336
6384
  tables: mappedTables,
6337
6385
  enums: json.enums,
6338
6386
  schemas: json.schemas,
6339
- views: json.views,
6340
- sequences: mappedSequences
6387
+ sequences: mappedSequences,
6388
+ roles: json.roles
6341
6389
  };
6342
6390
  };
6343
6391
  dryPg = pgSchema.parse({
@@ -8852,9 +8900,6 @@ var init_utils3 = __esm({
8852
8900
  String.prototype.concatIf = function(it, condition) {
8853
8901
  return condition ? `${this}${it}` : String(this);
8854
8902
  };
8855
- String.prototype.snake_case = function() {
8856
- return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
8857
- };
8858
8903
  Array.prototype.random = function() {
8859
8904
  return this[~~(Math.random() * this.length)];
8860
8905
  };
@@ -10634,10 +10679,10 @@ var require_inflight = __commonJS({
10634
10679
  }
10635
10680
  function slice(args) {
10636
10681
  var length = args.length;
10637
- var array = [];
10682
+ var array2 = [];
10638
10683
  for (var i2 = 0; i2 < length; i2++)
10639
- array[i2] = args[i2];
10640
- return array;
10684
+ array2[i2] = args[i2];
10685
+ return array2;
10641
10686
  }
10642
10687
  }
10643
10688
  });
@@ -11456,6 +11501,13 @@ var init_cli = __esm({
11456
11501
  breakpoints: booleanType().optional().default(true),
11457
11502
  migrations: objectType({
11458
11503
  prefix: prefix.optional().default("index")
11504
+ }).optional(),
11505
+ entities: objectType({
11506
+ roles: booleanType().or(objectType({
11507
+ provider: stringType().optional(),
11508
+ include: stringType().array().optional(),
11509
+ exclude: stringType().array().optional()
11510
+ })).optional().default(false)
11459
11511
  }).optional()
11460
11512
  }).passthrough();
11461
11513
  configCheck = objectType({
@@ -12551,11 +12603,11 @@ var require_node2 = __commonJS({
12551
12603
  };
12552
12604
  var require_base64 = __commonJS3((exports3) => {
12553
12605
  var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
12554
- exports3.encode = function(number2) {
12555
- if (0 <= number2 && number2 < intToCharMap.length) {
12556
- return intToCharMap[number2];
12606
+ exports3.encode = function(number3) {
12607
+ if (0 <= number3 && number3 < intToCharMap.length) {
12608
+ return intToCharMap[number3];
12557
12609
  }
12558
- throw new TypeError("Must be between 0 and 63: " + number2);
12610
+ throw new TypeError("Must be between 0 and 63: " + number3);
12559
12611
  };
12560
12612
  exports3.decode = function(charCode) {
12561
12613
  var bigA = 65;
@@ -17638,7 +17690,8 @@ var init_utils4 = __esm({
17638
17690
  credentials: parsed2.data,
17639
17691
  tablesFilter,
17640
17692
  schemasFilter,
17641
- prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index"
17693
+ prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index",
17694
+ entities: config.entities
17642
17695
  };
17643
17696
  }
17644
17697
  if (dialect7 === "mysql") {
@@ -17655,7 +17708,8 @@ var init_utils4 = __esm({
17655
17708
  credentials: parsed2.data,
17656
17709
  tablesFilter,
17657
17710
  schemasFilter,
17658
- prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index"
17711
+ prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index",
17712
+ entities: config.entities
17659
17713
  };
17660
17714
  }
17661
17715
  if (dialect7 === "sqlite") {
@@ -17672,7 +17726,8 @@ var init_utils4 = __esm({
17672
17726
  credentials: parsed2.data,
17673
17727
  tablesFilter,
17674
17728
  schemasFilter,
17675
- prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index"
17729
+ prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index",
17730
+ entities: config.entities
17676
17731
  };
17677
17732
  }
17678
17733
  if (dialect7 === "turso") {
@@ -18508,8 +18563,7 @@ var init_pgImports = __esm({
18508
18563
  const enums = [];
18509
18564
  const schemas = [];
18510
18565
  const sequences = [];
18511
- const views = [];
18512
- const matViews = [];
18566
+ const roles = [];
18513
18567
  const i0values = Object.values(exports2);
18514
18568
  i0values.forEach((t2) => {
18515
18569
  if ((0, import_pg_core.isPgEnum)(t2)) {
@@ -18522,25 +18576,21 @@ var init_pgImports = __esm({
18522
18576
  if ((0, import_drizzle_orm4.is)(t2, import_pg_core.PgSchema)) {
18523
18577
  schemas.push(t2);
18524
18578
  }
18525
- if ((0, import_pg_core.isPgView)(t2)) {
18526
- views.push(t2);
18527
- }
18528
- if ((0, import_pg_core.isPgMaterializedView)(t2)) {
18529
- matViews.push(t2);
18530
- }
18531
18579
  if ((0, import_pg_core.isPgSequence)(t2)) {
18532
18580
  sequences.push(t2);
18533
18581
  }
18582
+ if ((0, import_drizzle_orm4.is)(t2, import_pg_core.PgRole)) {
18583
+ roles.push(t2);
18584
+ }
18534
18585
  });
18535
- return { tables, enums, schemas, sequences, views, matViews };
18586
+ return { tables, enums, schemas, sequences, roles };
18536
18587
  };
18537
18588
  prepareFromPgImports = async (imports) => {
18538
- const tables = [];
18539
- const enums = [];
18540
- const schemas = [];
18541
- const sequences = [];
18542
- const views = [];
18543
- const matViews = [];
18589
+ let tables = [];
18590
+ let enums = [];
18591
+ let schemas = [];
18592
+ let sequences = [];
18593
+ let roles = [];
18544
18594
  const { unregister } = await safeRegister();
18545
18595
  for (let i2 = 0; i2 < imports.length; i2++) {
18546
18596
  const it = imports[i2];
@@ -18550,11 +18600,10 @@ var init_pgImports = __esm({
18550
18600
  enums.push(...prepared.enums);
18551
18601
  schemas.push(...prepared.schemas);
18552
18602
  sequences.push(...prepared.sequences);
18553
- views.push(...prepared.views);
18554
- matViews.push(...prepared.matViews);
18603
+ roles.push(...prepared.roles);
18555
18604
  }
18556
18605
  unregister();
18557
- return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews };
18606
+ return { tables: Array.from(new Set(tables)), enums, schemas, sequences, roles };
18558
18607
  };
18559
18608
  }
18560
18609
  });
@@ -18562,9 +18611,11 @@ var init_pgImports = __esm({
18562
18611
  // src/serializer/pgSerializer.ts
18563
18612
  var pgSerializer_exports = {};
18564
18613
  __export(pgSerializer_exports, {
18614
+ buildArrayString: () => buildArrayString,
18565
18615
  fromDatabase: () => fromDatabase2,
18566
18616
  generatePgSnapshot: () => generatePgSnapshot,
18567
- indexName: () => indexName2
18617
+ indexName: () => indexName2,
18618
+ minRangeForIdentityBasedOn: () => minRangeForIdentityBasedOn
18568
18619
  });
18569
18620
  function stringFromIdentityProperty(field) {
18570
18621
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
@@ -18578,9 +18629,9 @@ function minRangeForIdentityBasedOn(columnType) {
18578
18629
  function stringFromDatabaseIdentityProperty(field) {
18579
18630
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
18580
18631
  }
18581
- function buildArrayString(array, sqlType) {
18632
+ function buildArrayString(array2, sqlType) {
18582
18633
  sqlType = sqlType.split("[")[0];
18583
- const values = array.map((value) => {
18634
+ const values = array2.map((value) => {
18584
18635
  if (typeof value === "number" || typeof value === "bigint") {
18585
18636
  return value.toString();
18586
18637
  } else if (typeof value === "boolean") {
@@ -18602,6 +18653,40 @@ function buildArrayString(array, sqlType) {
18602
18653
  }).join(",");
18603
18654
  return `{${values}}`;
18604
18655
  }
18656
+ function prepareRoles(entities) {
18657
+ let useRoles = false;
18658
+ const includeRoles = [];
18659
+ const excludeRoles = [];
18660
+ if (entities && entities.roles) {
18661
+ if (typeof entities.roles === "object") {
18662
+ if (entities.roles.provider) {
18663
+ if (entities.roles.provider === "supabase") {
18664
+ excludeRoles.push(...[
18665
+ "anon",
18666
+ "authenticator",
18667
+ "authenticated",
18668
+ "service_role",
18669
+ "supabase_auth_admin",
18670
+ "supabase_storage_admin",
18671
+ "dashboard_user",
18672
+ "supabase_admin"
18673
+ ]);
18674
+ } else if (entities.roles.provider === "neon") {
18675
+ excludeRoles.push(...["authenticated", "anonymous"]);
18676
+ }
18677
+ }
18678
+ if (entities.roles.include) {
18679
+ includeRoles.push(...entities.roles.include);
18680
+ }
18681
+ if (entities.roles.exclude) {
18682
+ excludeRoles.push(...entities.roles.exclude);
18683
+ }
18684
+ } else {
18685
+ useRoles = entities.roles;
18686
+ }
18687
+ }
18688
+ return { useRoles, includeRoles, excludeRoles };
18689
+ }
18605
18690
  var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn;
18606
18691
  var init_pgSerializer = __esm({
18607
18692
  "src/serializer/pgSerializer.ts"() {
@@ -18618,11 +18703,11 @@ var init_pgSerializer = __esm({
18618
18703
  indexName2 = (tableName, columns) => {
18619
18704
  return `${tableName}_${columns.join("_")}_index`;
18620
18705
  };
18621
- generatePgSnapshot = (tables, enums, schemas, sequences, views, matViews, schemaFilter) => {
18622
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
18706
+ generatePgSnapshot = (tables, enums, schemas, sequences, roles, schemaFilter) => {
18707
+ var _a, _b, _c, _d, _e, _f;
18623
18708
  const result = {};
18624
- const resultViews = {};
18625
18709
  const sequencesToReturn = {};
18710
+ const rolesToReturn = {};
18626
18711
  const indexesInSchema = {};
18627
18712
  for (const table4 of tables) {
18628
18713
  const {
@@ -18633,7 +18718,8 @@ var init_pgSerializer = __esm({
18633
18718
  checks,
18634
18719
  schema: schema5,
18635
18720
  primaryKeys,
18636
- uniqueConstraints
18721
+ uniqueConstraints,
18722
+ policies
18637
18723
  } = (0, import_pg_core3.getTableConfig)(table4);
18638
18724
  if (schemaFilter && !schemaFilter.includes(schema5 ?? "public")) {
18639
18725
  continue;
@@ -18643,6 +18729,7 @@ var init_pgSerializer = __esm({
18643
18729
  const foreignKeysObject = {};
18644
18730
  const primaryKeysObject = {};
18645
18731
  const uniqueConstraintObject = {};
18732
+ const policiesObject = {};
18646
18733
  columns.forEach((column7) => {
18647
18734
  var _a2, _b2, _c2, _d2, _e2, _f2;
18648
18735
  const notNull = column7.notNull;
@@ -18888,6 +18975,35 @@ ${withStyle.errorWarning(
18888
18975
  with: value.config.with ?? {}
18889
18976
  };
18890
18977
  });
18978
+ policies.forEach((policy2) => {
18979
+ var _a2, _b2;
18980
+ const mappedTo = [];
18981
+ if (!policy2.to) {
18982
+ mappedTo.push("public");
18983
+ } else {
18984
+ if (policy2.to && typeof policy2.to === "string") {
18985
+ mappedTo.push(policy2.to);
18986
+ } else if (policy2.to && (0, import_drizzle_orm5.is)(policy2.to, import_pg_core2.PgRole)) {
18987
+ mappedTo.push(policy2.to.name);
18988
+ } else if (policy2.to && Array.isArray(policy2.to)) {
18989
+ policy2.to.forEach((it) => {
18990
+ if (typeof it === "string") {
18991
+ mappedTo.push(it);
18992
+ } else if ((0, import_drizzle_orm5.is)(it, import_pg_core2.PgRole)) {
18993
+ mappedTo.push(it.name);
18994
+ }
18995
+ });
18996
+ }
18997
+ }
18998
+ policiesObject[policy2.name] = {
18999
+ name: policy2.name,
19000
+ as: ((_a2 = policy2.as) == null ? void 0 : _a2.toUpperCase()) ?? "PERMISSIVE",
19001
+ for: ((_b2 = policy2.for) == null ? void 0 : _b2.toUpperCase()) ?? "ALL",
19002
+ to: mappedTo.sort(),
19003
+ using: (0, import_drizzle_orm5.is)(policy2.using, import_drizzle_orm5.SQL) ? dialect5.sqlToQuery(policy2.using).sql : void 0,
19004
+ withCheck: (0, import_drizzle_orm5.is)(policy2.withCheck, import_drizzle_orm5.SQL) ? dialect5.sqlToQuery(policy2.withCheck).sql : void 0
19005
+ };
19006
+ });
18891
19007
  const tableKey2 = `${schema5 ?? "public"}.${tableName}`;
18892
19008
  result[tableKey2] = {
18893
19009
  name: tableName,
@@ -18896,7 +19012,8 @@ ${withStyle.errorWarning(
18896
19012
  indexes: indexesObject,
18897
19013
  foreignKeys: foreignKeysObject,
18898
19014
  compositePrimaryKeys: primaryKeysObject,
18899
- uniqueConstraints: uniqueConstraintObject
19015
+ uniqueConstraints: uniqueConstraintObject,
19016
+ policies: policiesObject
18900
19017
  };
18901
19018
  }
18902
19019
  for (const sequence of sequences) {
@@ -18920,148 +19037,15 @@ ${withStyle.errorWarning(
18920
19037
  } else {
18921
19038
  }
18922
19039
  }
18923
- const combinedViews = [...views, ...matViews];
18924
- for (const view2 of combinedViews) {
18925
- let viewName;
18926
- let schema5;
18927
- let query;
18928
- let selectedFields;
18929
- let isExisting;
18930
- let withOption;
18931
- let tablespace;
18932
- let using;
18933
- let withNoData;
18934
- let materialized = false;
18935
- if ((0, import_drizzle_orm5.is)(view2, import_pg_core2.PgView)) {
18936
- ({ name: viewName, schema: schema5, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core2.getViewConfig)(view2));
18937
- } else {
18938
- ({ name: viewName, schema: schema5, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core2.getMaterializedViewConfig)(
18939
- view2
18940
- ));
18941
- materialized = true;
18942
- }
18943
- const viewSchema = schema5 ?? "public";
18944
- const viewKey = `${viewSchema}.${viewName}`;
18945
- const columnsObject = {};
18946
- const uniqueConstraintObject = {};
18947
- const existingView = resultViews[viewKey];
18948
- if (typeof existingView !== "undefined") {
18949
- console.log(
18950
- `
18951
- ${withStyle.errorWarning(
18952
- `We've found duplicated view name across ${source_default.underline.blue(
18953
- schema5 ?? "public"
18954
- )} schema. Please rename your view`
18955
- )}`
18956
- );
18957
- process.exit(1);
18958
- }
18959
- for (const key in selectedFields) {
18960
- if ((0, import_drizzle_orm5.is)(selectedFields[key], import_pg_core2.PgColumn)) {
18961
- const column7 = selectedFields[key];
18962
- const notNull = column7.notNull;
18963
- const primaryKey = column7.primary;
18964
- const sqlTypeLowered = column7.getSQLType().toLowerCase();
18965
- const typeSchema = (0, import_drizzle_orm5.is)(column7, import_pg_core2.PgEnumColumn) ? column7.enum.schema || "public" : void 0;
18966
- const generated = column7.generated;
18967
- const identity = column7.generatedIdentity;
18968
- const increment = stringFromIdentityProperty((_g = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _g.increment) ?? "1";
18969
- const minValue = stringFromIdentityProperty((_h = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _h.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column7.columnType) : "1");
18970
- const maxValue = stringFromIdentityProperty((_i = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _i.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column7.getSQLType()));
18971
- const startWith = stringFromIdentityProperty((_j = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _j.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
18972
- const cache = stringFromIdentityProperty((_k = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _k.cache) ?? "1";
18973
- const columnToSet = {
18974
- name: column7.name,
18975
- type: column7.getSQLType(),
18976
- typeSchema,
18977
- primaryKey,
18978
- notNull,
18979
- generated: generated ? {
18980
- as: (0, import_drizzle_orm5.is)(generated.as, import_drizzle_orm5.SQL) ? dialect5.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect5.sqlToQuery(generated.as()).sql : generated.as,
18981
- type: "stored"
18982
- } : void 0,
18983
- identity: identity ? {
18984
- type: identity.type,
18985
- name: identity.sequenceName ?? `${viewName}_${column7.name}_seq`,
18986
- schema: schema5 ?? "public",
18987
- increment,
18988
- startWith,
18989
- minValue,
18990
- maxValue,
18991
- cache,
18992
- cycle: ((_l = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _l.cycle) ?? false
18993
- } : void 0
18994
- };
18995
- if (column7.isUnique) {
18996
- const existingUnique = uniqueConstraintObject[column7.uniqueName];
18997
- if (typeof existingUnique !== "undefined") {
18998
- console.log(
18999
- `
19000
- ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
19001
- viewName
19002
- )} table.
19003
- The unique constraint ${source_default.underline.blue(
19004
- column7.uniqueName
19005
- )} on the ${source_default.underline.blue(
19006
- column7.name
19007
- )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
19008
- existingUnique.columns.join(",")
19009
- )} columns
19010
- `)}`
19011
- );
19012
- process.exit(1);
19013
- }
19014
- uniqueConstraintObject[column7.uniqueName] = {
19015
- name: column7.uniqueName,
19016
- nullsNotDistinct: column7.uniqueType === "not distinct",
19017
- columns: [columnToSet.name]
19018
- };
19019
- }
19020
- if (column7.default !== void 0) {
19021
- if ((0, import_drizzle_orm5.is)(column7.default, import_drizzle_orm5.SQL)) {
19022
- columnToSet.default = sqlToStr(column7.default);
19023
- } else {
19024
- if (typeof column7.default === "string") {
19025
- columnToSet.default = `'${column7.default}'`;
19026
- } else {
19027
- if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
19028
- columnToSet.default = `'${JSON.stringify(
19029
- column7.default
19030
- )}'::${sqlTypeLowered}`;
19031
- } else if (column7.default instanceof Date) {
19032
- if (sqlTypeLowered === "date") {
19033
- columnToSet.default = `'${column7.default.toISOString().split("T")[0]}'`;
19034
- } else if (sqlTypeLowered === "timestamp") {
19035
- columnToSet.default = `'${column7.default.toISOString().replace("T", " ").slice(0, 23)}'`;
19036
- } else {
19037
- columnToSet.default = `'${column7.default.toISOString()}'`;
19038
- }
19039
- } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column7.default)) {
19040
- columnToSet.default = `'${buildArrayString(
19041
- column7.default,
19042
- sqlTypeLowered
19043
- )}'`;
19044
- } else {
19045
- columnToSet.default = column7.default;
19046
- }
19047
- }
19048
- }
19049
- }
19050
- columnsObject[column7.name] = columnToSet;
19051
- }
19040
+ for (const role of roles) {
19041
+ if (!role._existing) {
19042
+ rolesToReturn[role.name] = {
19043
+ name: role.name,
19044
+ createDb: role.createDb === void 0 ? false : role.createDb,
19045
+ createRole: role.createRole === void 0 ? false : role.createRole,
19046
+ inherit: role.inherit === void 0 ? true : role.inherit
19047
+ };
19052
19048
  }
19053
- resultViews[viewKey] = {
19054
- columns: columnsObject,
19055
- definition: isExisting ? void 0 : dialect5.sqlToQuery(query).sql,
19056
- name: viewName,
19057
- schema: viewSchema,
19058
- isExisting,
19059
- with: withOption,
19060
- withNoData,
19061
- materialized,
19062
- tablespace,
19063
- using
19064
- };
19065
19049
  }
19066
19050
  const enumsToReturn = enums.reduce((map, obj) => {
19067
19051
  const enumSchema3 = obj.schema || "public";
@@ -19089,7 +19073,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
19089
19073
  enums: enumsToReturn,
19090
19074
  schemas: schemasObject,
19091
19075
  sequences: sequencesToReturn,
19092
- views: resultViews,
19076
+ roles: rolesToReturn,
19093
19077
  _meta: {
19094
19078
  schemas: {},
19095
19079
  tables: {},
@@ -19106,27 +19090,12 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
19106
19090
  --end;
19107
19091
  return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
19108
19092
  };
19109
- fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
19093
+ fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback) => {
19110
19094
  const result = {};
19111
- const views = {};
19112
19095
  const internals = { tables: {} };
19113
- const where = schemaFilters.map((t2) => `n.nspname = '${t2}'`).join(" or ");
19096
+ const where = schemaFilters.map((t2) => `table_schema = '${t2}'`).join(" or ");
19114
19097
  const allTables = await db.query(
19115
- `SELECT
19116
- n.nspname AS table_schema,
19117
- c.relname AS table_name,
19118
- CASE
19119
- WHEN c.relkind = 'r' THEN 'table'
19120
- WHEN c.relkind = 'v' THEN 'view'
19121
- WHEN c.relkind = 'm' THEN 'materialized_view'
19122
- END AS type
19123
- FROM
19124
- pg_catalog.pg_class c
19125
- JOIN
19126
- pg_catalog.pg_namespace n ON n.oid = c.relnamespace
19127
- WHERE
19128
- c.relkind IN ('r', 'v', 'm')
19129
- ${where === "" ? "" : ` AND ${where}`};`
19098
+ `SELECT table_schema, table_name FROM information_schema.tables${where === "" ? "" : ` WHERE ${where}`};`
19130
19099
  );
19131
19100
  const schemas = new Set(allTables.map((it) => it.table_schema));
19132
19101
  schemas.delete("public");
@@ -19203,8 +19172,57 @@ WHERE
19203
19172
  if (progressCallback) {
19204
19173
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
19205
19174
  }
19175
+ const allRoles = await db.query(
19176
+ `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
19177
+ );
19178
+ const rolesToReturn = {};
19179
+ const preparedRoles = prepareRoles(entities);
19180
+ if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
19181
+ for (const dbRole of allRoles) {
19182
+ if (preparedRoles.useRoles) {
19183
+ rolesToReturn[dbRole.rolname] = {
19184
+ createDb: dbRole.rolcreatedb,
19185
+ createRole: dbRole.rolcreatedb,
19186
+ inherit: dbRole.rolinherit,
19187
+ name: dbRole.rolname
19188
+ };
19189
+ } else {
19190
+ if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)
19191
+ continue;
19192
+ if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname))
19193
+ continue;
19194
+ if (preparedRoles.excludeRoles.includes(dbRole.rolname))
19195
+ continue;
19196
+ if (!preparedRoles.includeRoles.includes(dbRole.rolname))
19197
+ continue;
19198
+ rolesToReturn[dbRole.rolname] = {
19199
+ createDb: dbRole.rolcreatedb,
19200
+ createRole: dbRole.rolcreaterole,
19201
+ inherit: dbRole.rolinherit,
19202
+ name: dbRole.rolname
19203
+ };
19204
+ }
19205
+ }
19206
+ }
19207
+ const wherePolicies = schemaFilters.map((t2) => `schemaname = '${t2}'`).join(" or ");
19208
+ const policiesByTable = {};
19209
+ const allPolicies = await db.query(`SELECT schemaname, tablename, policyname as name, permissive as "as", roles as to, cmd as for, qual as using, with_check as "withCheck" FROM pg_policies${wherePolicies === "" ? "" : ` WHERE ${wherePolicies}`};`);
19210
+ for (const dbPolicy of allPolicies) {
19211
+ const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
19212
+ const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
19213
+ const parsedTo = to === "{}" ? [] : to.substring(1, to.length - 1).split(/\s*,\s*/g).sort();
19214
+ const parsedWithCheck = withCheck === null ? void 0 : withCheck;
19215
+ const parsedUsing = using === null ? void 0 : using;
19216
+ if (tableForPolicy) {
19217
+ tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
19218
+ } else {
19219
+ policiesByTable[`${schemaname}.${tablename}`] = {
19220
+ [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
19221
+ };
19222
+ }
19223
+ }
19206
19224
  const sequencesInColumns = [];
19207
- const all = allTables.filter((it) => it.type === "table").map((row) => {
19225
+ const all = allTables.map((row) => {
19208
19226
  return new Promise(async (res, rej) => {
19209
19227
  var _a, _b, _c, _d, _e, _f;
19210
19228
  const tableName = row.table_name;
@@ -19599,7 +19617,8 @@ WHERE
19599
19617
  indexes: indexToReturn,
19600
19618
  foreignKeys: foreignKeysToReturn,
19601
19619
  compositePrimaryKeys: primaryKeys,
19602
- uniqueConstraints: uniqueConstrains
19620
+ uniqueConstraints: uniqueConstrains,
19621
+ policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {}
19603
19622
  };
19604
19623
  } catch (e2) {
19605
19624
  rej(e2);
@@ -19613,336 +19632,6 @@ WHERE
19613
19632
  }
19614
19633
  for await (const _2 of all) {
19615
19634
  }
19616
- const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
19617
- return new Promise(async (res, rej) => {
19618
- var _a, _b, _c, _d;
19619
- const viewName = row.table_name;
19620
- if (!tablesFilter(viewName))
19621
- return res("");
19622
- tableCount += 1;
19623
- const viewSchema = row.table_schema;
19624
- try {
19625
- const columnToReturn = {};
19626
- const viewResponses = await db.query(`WITH view_columns AS (
19627
- SELECT DISTINCT
19628
- nv.nspname::information_schema.sql_identifier AS view_schema,
19629
- v.relname::information_schema.sql_identifier AS view_name,
19630
- nt.nspname::information_schema.sql_identifier AS table_schema,
19631
- t.relname::information_schema.sql_identifier AS table_name,
19632
- a.attname::information_schema.sql_identifier AS column_name
19633
- FROM pg_namespace nv
19634
- JOIN pg_class v ON nv.oid = v.relnamespace
19635
- JOIN pg_depend dv ON v.oid = dv.refobjid
19636
- JOIN pg_depend dt ON dv.objid = dt.objid
19637
- JOIN pg_class t ON dt.refobjid = t.oid
19638
- JOIN pg_namespace nt ON t.relnamespace = nt.oid
19639
- JOIN pg_attribute a ON t.oid = a.attrelid
19640
- WHERE (v.relkind = 'v'::"char" OR v.relkind = 'm'::"char")
19641
- AND dv.refclassid = 'pg_class'::regclass::oid
19642
- AND dv.classid = 'pg_rewrite'::regclass::oid
19643
- AND dv.deptype = 'i'::"char"
19644
- AND dv.objid = dt.objid
19645
- AND dv.refobjid <> dt.refobjid
19646
- AND dt.classid = 'pg_rewrite'::regclass::oid
19647
- AND dt.refclassid = 'pg_class'::regclass::oid
19648
- AND t.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char", 'p'::"char"])
19649
- AND dt.refobjsubid = a.attnum
19650
- AND pg_has_role(t.relowner, 'USAGE'::text)
19651
- AND nv.nspname::information_schema.sql_identifier = '${viewSchema}'
19652
- AND v.relname::information_schema.sql_identifier = '${viewName}'
19653
- ),
19654
- column_descriptions AS (
19655
- SELECT DISTINCT
19656
- a.attrelid::regclass::text AS table_name,
19657
- a.attname AS column_name,
19658
- c.is_nullable,
19659
- a.attndims AS array_dimensions,
19660
- CASE
19661
- WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) AND EXISTS (
19662
- SELECT FROM pg_attrdef ad
19663
- WHERE ad.adrelid = a.attrelid
19664
- AND ad.adnum = a.attnum
19665
- AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
19666
- )
19667
- THEN CASE a.atttypid
19668
- WHEN 'int'::regtype THEN 'serial'
19669
- WHEN 'int8'::regtype THEN 'bigserial'
19670
- WHEN 'int2'::regtype THEN 'smallserial'
19671
- END
19672
- ELSE format_type(a.atttypid, a.atttypmod)
19673
- END AS data_type,
19674
- pg_get_serial_sequence('"' || c.table_schema || '"."' || c.table_name || '"', a.attname)::regclass AS seq_name,
19675
- c.column_default,
19676
- c.data_type AS additional_dt,
19677
- c.udt_name AS enum_name,
19678
- c.is_generated,
19679
- c.generation_expression,
19680
- c.is_identity,
19681
- c.identity_generation,
19682
- c.identity_start,
19683
- c.identity_increment,
19684
- c.identity_maximum,
19685
- c.identity_minimum,
19686
- c.identity_cycle
19687
- FROM pg_attribute a
19688
- JOIN information_schema.columns c ON c.column_name = a.attname
19689
- JOIN pg_type t ON t.oid = a.atttypid
19690
- LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
19691
- WHERE a.attnum > 0
19692
- AND NOT a.attisdropped
19693
- ),
19694
- table_constraints AS (
19695
- SELECT DISTINCT ON (ccu.column_name)
19696
- ccu.column_name,
19697
- c.data_type,
19698
- tc.constraint_type,
19699
- tc.constraint_name,
19700
- tc.constraint_schema,
19701
- tc.table_name
19702
- FROM information_schema.table_constraints tc
19703
- JOIN information_schema.constraint_column_usage ccu USING (constraint_schema, constraint_name)
19704
- JOIN information_schema.columns c ON c.table_schema = tc.constraint_schema
19705
- AND tc.table_name = c.table_name
19706
- AND ccu.column_name = c.column_name
19707
- ),
19708
- additional_column_info AS (
19709
- SELECT DISTINCT
19710
- a.attrelid::regclass::text AS table_name,
19711
- a.attname AS column_name,
19712
- is_nullable,
19713
- a.attndims AS array_dimensions,
19714
- CASE
19715
- WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) AND EXISTS (
19716
- SELECT FROM pg_attrdef ad
19717
- WHERE ad.adrelid = a.attrelid
19718
- AND ad.adnum = a.attnum
19719
- AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
19720
- )
19721
- THEN CASE a.atttypid
19722
- WHEN 'int'::regtype THEN 'serial'
19723
- WHEN 'int8'::regtype THEN 'bigserial'
19724
- WHEN 'int2'::regtype THEN 'smallserial'
19725
- END
19726
- ELSE format_type(a.atttypid, a.atttypmod)
19727
- END AS data_type,
19728
- pg_get_serial_sequence('"' || c.table_schema || '"."' || c.table_name || '"', a.attname)::regclass AS seq_name,
19729
- c.column_default,
19730
- c.data_type AS additional_dt,
19731
- c.udt_name AS enum_name,
19732
- c.is_generated,
19733
- generation_expression,
19734
- is_identity,
19735
- identity_generation,
19736
- identity_start,
19737
- identity_increment,
19738
- identity_maximum,
19739
- identity_minimum,
19740
- identity_cycle
19741
- FROM pg_attribute a
19742
- JOIN information_schema.columns c ON c.column_name = a.attname
19743
- LEFT JOIN pg_type t ON t.oid = a.atttypid
19744
- LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
19745
- WHERE a.attnum > 0
19746
- AND NOT a.attisdropped
19747
- )
19748
- SELECT DISTINCT ON (vc.table_name, vc.column_name)
19749
- vc.view_schema,
19750
- vc.view_name,
19751
- vc.table_schema,
19752
- vc.table_name,
19753
- vc.column_name,
19754
- COALESCE(cd.data_type, aci.data_type) AS data_type,
19755
- tc.constraint_type,
19756
- tc.constraint_name,
19757
- aci.is_nullable,
19758
- aci.array_dimensions,
19759
- aci.seq_name,
19760
- aci.column_default,
19761
- aci.additional_dt,
19762
- aci.enum_name,
19763
- aci.is_generated,
19764
- aci.generation_expression,
19765
- aci.is_identity,
19766
- aci.identity_generation,
19767
- aci.identity_start,
19768
- aci.identity_increment,
19769
- aci.identity_maximum,
19770
- aci.identity_minimum,
19771
- aci.identity_cycle
19772
- FROM view_columns vc
19773
- LEFT JOIN column_descriptions cd ON vc.table_name = cd.table_name AND vc.column_name = cd.column_name
19774
- LEFT JOIN table_constraints tc ON vc.table_name = tc.table_name AND vc.column_name = tc.column_name
19775
- LEFT JOIN additional_column_info aci ON vc.table_name = aci.table_name AND vc.column_name = aci.column_name
19776
- ORDER BY vc.table_name, vc.column_name;`);
19777
- for (const viewResponse of viewResponses) {
19778
- const columnName = viewResponse.column_name;
19779
- const columnAdditionalDT = viewResponse.additional_dt;
19780
- const columnDimensions = viewResponse.array_dimensions;
19781
- const enumType2 = viewResponse.enum_name;
19782
- let columnType = viewResponse.data_type;
19783
- const typeSchema = viewResponse.type_schema;
19784
- const isGenerated = viewResponse.is_generated === "ALWAYS";
19785
- const generationExpression = viewResponse.generation_expression;
19786
- const isIdentity = viewResponse.is_identity === "YES";
19787
- const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
19788
- const identityStart = viewResponse.identity_start;
19789
- const identityIncrement = viewResponse.identity_increment;
19790
- const identityMaximum = viewResponse.identity_maximum;
19791
- const identityMinimum = viewResponse.identity_minimum;
19792
- const identityCycle = viewResponse.identity_cycle === "YES";
19793
- const identityName = viewResponse.seq_name;
19794
- const defaultValueRes = viewResponse.column_default;
19795
- const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
19796
- let columnTypeMapped = columnType;
19797
- if (columnAdditionalDT === "ARRAY") {
19798
- if (typeof internals.tables[viewName] === "undefined") {
19799
- internals.tables[viewName] = {
19800
- columns: {
19801
- [columnName]: {
19802
- isArray: true,
19803
- dimensions: columnDimensions,
19804
- rawType: columnTypeMapped.substring(
19805
- 0,
19806
- columnTypeMapped.length - 2
19807
- )
19808
- }
19809
- }
19810
- };
19811
- } else {
19812
- if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
19813
- internals.tables[viewName].columns[columnName] = {
19814
- isArray: true,
19815
- dimensions: columnDimensions,
19816
- rawType: columnTypeMapped.substring(
19817
- 0,
19818
- columnTypeMapped.length - 2
19819
- )
19820
- };
19821
- }
19822
- }
19823
- }
19824
- const defaultValue = defaultForColumn(
19825
- viewResponse,
19826
- internals,
19827
- viewName
19828
- );
19829
- if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
19830
- if (typeof internals.tables[viewName] === "undefined") {
19831
- internals.tables[viewName] = {
19832
- columns: {
19833
- [columnName]: {
19834
- isDefaultAnExpression: true
19835
- }
19836
- }
19837
- };
19838
- } else {
19839
- if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
19840
- internals.tables[viewName].columns[columnName] = {
19841
- isDefaultAnExpression: true
19842
- };
19843
- } else {
19844
- internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
19845
- }
19846
- }
19847
- }
19848
- const isSerial = columnType === "serial";
19849
- if (columnTypeMapped.startsWith("numeric(")) {
19850
- columnTypeMapped = columnTypeMapped.replace(",", ", ");
19851
- }
19852
- if (columnAdditionalDT === "ARRAY") {
19853
- for (let i2 = 1; i2 < Number(columnDimensions); i2++) {
19854
- columnTypeMapped += "[]";
19855
- }
19856
- }
19857
- columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
19858
- columnTypeMapped = trimChar(columnTypeMapped, '"');
19859
- columnToReturn[columnName] = {
19860
- name: columnName,
19861
- type: (
19862
- // filter vectors, but in future we should filter any extension that was installed by user
19863
- columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
19864
- ),
19865
- typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
19866
- primaryKey,
19867
- notNull: viewResponse.is_nullable === "NO",
19868
- generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
19869
- identity: isIdentity ? {
19870
- type: identityGeneration,
19871
- name: identityName,
19872
- increment: stringFromDatabaseIdentityProperty(identityIncrement),
19873
- minValue: stringFromDatabaseIdentityProperty(identityMinimum),
19874
- maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
19875
- startWith: stringFromDatabaseIdentityProperty(identityStart),
19876
- cache: ((_a = sequencesToReturn[identityName]) == null ? void 0 : _a.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _d.cache : void 0,
19877
- cycle: identityCycle,
19878
- schema: viewSchema
19879
- } : void 0
19880
- };
19881
- if (identityName) {
19882
- delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
19883
- delete sequencesToReturn[identityName];
19884
- }
19885
- if (!isSerial && typeof defaultValue !== "undefined") {
19886
- columnToReturn[columnName].default = defaultValue;
19887
- }
19888
- }
19889
- const [viewInfo] = await db.query(`
19890
- SELECT
19891
- c.relname AS view_name,
19892
- n.nspname AS schema_name,
19893
- pg_get_viewdef(c.oid, true) AS definition,
19894
- ts.spcname AS tablespace_name,
19895
- c.reloptions AS options,
19896
- pg_tablespace_location(ts.oid) AS location
19897
- FROM
19898
- pg_class c
19899
- JOIN
19900
- pg_namespace n ON c.relnamespace = n.oid
19901
- LEFT JOIN
19902
- pg_tablespace ts ON c.reltablespace = ts.oid
19903
- WHERE
19904
- (c.relkind = 'm' OR c.relkind = 'v')
19905
- AND n.nspname = '${viewSchema}'
19906
- AND c.relname = '${viewName}';`);
19907
- const resultWith = {};
19908
- if (viewInfo.options) {
19909
- viewInfo.options.forEach((pair) => {
19910
- const splitted = pair.split("=");
19911
- const key = splitted[0];
19912
- const value = splitted[1];
19913
- if (value === "true") {
19914
- resultWith[key] = true;
19915
- } else if (value === "false") {
19916
- resultWith[key] = false;
19917
- } else if (!isNaN(Number(value))) {
19918
- resultWith[key] = Number(value);
19919
- } else {
19920
- resultWith[key] = value;
19921
- }
19922
- });
19923
- }
19924
- const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
19925
- const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
19926
- const materialized = row.type === "materialized_view";
19927
- views[`${viewSchema}.${viewName}`] = {
19928
- name: viewName,
19929
- schema: viewSchema,
19930
- columns: columnToReturn,
19931
- isExisting: false,
19932
- definition,
19933
- materialized,
19934
- with: withOption,
19935
- tablespace: viewInfo.tablespace_name ?? void 0
19936
- };
19937
- } catch (e2) {
19938
- rej(e2);
19939
- return;
19940
- }
19941
- res("");
19942
- });
19943
- });
19944
- for await (const _2 of allViews) {
19945
- }
19946
19635
  if (progressCallback) {
19947
19636
  progressCallback("columns", columnsCount, "done");
19948
19637
  progressCallback("indexes", indexesCount, "done");
@@ -19956,7 +19645,7 @@ WHERE
19956
19645
  enums: enumsToReturn,
19957
19646
  schemas: schemasObject,
19958
19647
  sequences: sequencesToReturn,
19959
- views,
19648
+ roles: rolesToReturn,
19960
19649
  _meta: {
19961
19650
  schemas: {},
19962
19651
  tables: {},
@@ -20599,10 +20288,10 @@ ${filenames.join("\n")}
20599
20288
  const filenames = prepareFilenames(path5);
20600
20289
  const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
20601
20290
  const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
20602
- const { tables, enums, schemas, sequences, views, matViews } = await prepareFromPgImports2(
20291
+ const { tables, enums, schemas, sequences, roles } = await prepareFromPgImports2(
20603
20292
  filenames
20604
20293
  );
20605
- return generatePgSnapshot2(tables, enums, schemas, sequences, views, matViews, schemaFilter);
20294
+ return generatePgSnapshot2(tables, enums, schemas, sequences, roles, schemaFilter);
20606
20295
  };
20607
20296
  serializeSQLite = async (path5) => {
20608
20297
  const filenames = prepareFilenames(path5);
@@ -20797,57 +20486,57 @@ var require_heap = __commonJS({
20797
20486
  }
20798
20487
  return [].splice.apply(a, [lo, lo - lo].concat(x2)), x2;
20799
20488
  };
20800
- heappush = function(array, item, cmp) {
20489
+ heappush = function(array2, item, cmp) {
20801
20490
  if (cmp == null) {
20802
20491
  cmp = defaultCmp;
20803
20492
  }
20804
- array.push(item);
20805
- return _siftdown(array, 0, array.length - 1, cmp);
20493
+ array2.push(item);
20494
+ return _siftdown(array2, 0, array2.length - 1, cmp);
20806
20495
  };
20807
- heappop = function(array, cmp) {
20496
+ heappop = function(array2, cmp) {
20808
20497
  var lastelt, returnitem;
20809
20498
  if (cmp == null) {
20810
20499
  cmp = defaultCmp;
20811
20500
  }
20812
- lastelt = array.pop();
20813
- if (array.length) {
20814
- returnitem = array[0];
20815
- array[0] = lastelt;
20816
- _siftup(array, 0, cmp);
20501
+ lastelt = array2.pop();
20502
+ if (array2.length) {
20503
+ returnitem = array2[0];
20504
+ array2[0] = lastelt;
20505
+ _siftup(array2, 0, cmp);
20817
20506
  } else {
20818
20507
  returnitem = lastelt;
20819
20508
  }
20820
20509
  return returnitem;
20821
20510
  };
20822
- heapreplace = function(array, item, cmp) {
20511
+ heapreplace = function(array2, item, cmp) {
20823
20512
  var returnitem;
20824
20513
  if (cmp == null) {
20825
20514
  cmp = defaultCmp;
20826
20515
  }
20827
- returnitem = array[0];
20828
- array[0] = item;
20829
- _siftup(array, 0, cmp);
20516
+ returnitem = array2[0];
20517
+ array2[0] = item;
20518
+ _siftup(array2, 0, cmp);
20830
20519
  return returnitem;
20831
20520
  };
20832
- heappushpop = function(array, item, cmp) {
20521
+ heappushpop = function(array2, item, cmp) {
20833
20522
  var _ref;
20834
20523
  if (cmp == null) {
20835
20524
  cmp = defaultCmp;
20836
20525
  }
20837
- if (array.length && cmp(array[0], item) < 0) {
20838
- _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
20839
- _siftup(array, 0, cmp);
20526
+ if (array2.length && cmp(array2[0], item) < 0) {
20527
+ _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
20528
+ _siftup(array2, 0, cmp);
20840
20529
  }
20841
20530
  return item;
20842
20531
  };
20843
- heapify = function(array, cmp) {
20532
+ heapify = function(array2, cmp) {
20844
20533
  var i2, _i, _j, _len, _ref, _ref1, _results, _results1;
20845
20534
  if (cmp == null) {
20846
20535
  cmp = defaultCmp;
20847
20536
  }
20848
20537
  _ref1 = function() {
20849
20538
  _results1 = [];
20850
- for (var _j2 = 0, _ref2 = floor(array.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
20539
+ for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
20851
20540
  _results1.push(_j2);
20852
20541
  }
20853
20542
  return _results1;
@@ -20855,51 +20544,51 @@ var require_heap = __commonJS({
20855
20544
  _results = [];
20856
20545
  for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
20857
20546
  i2 = _ref1[_i];
20858
- _results.push(_siftup(array, i2, cmp));
20547
+ _results.push(_siftup(array2, i2, cmp));
20859
20548
  }
20860
20549
  return _results;
20861
20550
  };
20862
- updateItem = function(array, item, cmp) {
20551
+ updateItem = function(array2, item, cmp) {
20863
20552
  var pos;
20864
20553
  if (cmp == null) {
20865
20554
  cmp = defaultCmp;
20866
20555
  }
20867
- pos = array.indexOf(item);
20556
+ pos = array2.indexOf(item);
20868
20557
  if (pos === -1) {
20869
20558
  return;
20870
20559
  }
20871
- _siftdown(array, 0, pos, cmp);
20872
- return _siftup(array, pos, cmp);
20560
+ _siftdown(array2, 0, pos, cmp);
20561
+ return _siftup(array2, pos, cmp);
20873
20562
  };
20874
- nlargest = function(array, n, cmp) {
20563
+ nlargest = function(array2, n, cmp) {
20875
20564
  var elem, result, _i, _len, _ref;
20876
20565
  if (cmp == null) {
20877
20566
  cmp = defaultCmp;
20878
20567
  }
20879
- result = array.slice(0, n);
20568
+ result = array2.slice(0, n);
20880
20569
  if (!result.length) {
20881
20570
  return result;
20882
20571
  }
20883
20572
  heapify(result, cmp);
20884
- _ref = array.slice(n);
20573
+ _ref = array2.slice(n);
20885
20574
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
20886
20575
  elem = _ref[_i];
20887
20576
  heappushpop(result, elem, cmp);
20888
20577
  }
20889
20578
  return result.sort(cmp).reverse();
20890
20579
  };
20891
- nsmallest = function(array, n, cmp) {
20580
+ nsmallest = function(array2, n, cmp) {
20892
20581
  var elem, i2, los, result, _i, _j, _len, _ref, _ref1, _results;
20893
20582
  if (cmp == null) {
20894
20583
  cmp = defaultCmp;
20895
20584
  }
20896
- if (n * 10 <= array.length) {
20897
- result = array.slice(0, n).sort(cmp);
20585
+ if (n * 10 <= array2.length) {
20586
+ result = array2.slice(0, n).sort(cmp);
20898
20587
  if (!result.length) {
20899
20588
  return result;
20900
20589
  }
20901
20590
  los = result[result.length - 1];
20902
- _ref = array.slice(n);
20591
+ _ref = array2.slice(n);
20903
20592
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
20904
20593
  elem = _ref[_i];
20905
20594
  if (cmp(elem, los) < 0) {
@@ -20910,51 +20599,51 @@ var require_heap = __commonJS({
20910
20599
  }
20911
20600
  return result;
20912
20601
  }
20913
- heapify(array, cmp);
20602
+ heapify(array2, cmp);
20914
20603
  _results = [];
20915
- for (i2 = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 0 <= _ref1 ? ++_j : --_j) {
20916
- _results.push(heappop(array, cmp));
20604
+ for (i2 = _j = 0, _ref1 = min(n, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 0 <= _ref1 ? ++_j : --_j) {
20605
+ _results.push(heappop(array2, cmp));
20917
20606
  }
20918
20607
  return _results;
20919
20608
  };
20920
- _siftdown = function(array, startpos, pos, cmp) {
20609
+ _siftdown = function(array2, startpos, pos, cmp) {
20921
20610
  var newitem, parent, parentpos;
20922
20611
  if (cmp == null) {
20923
20612
  cmp = defaultCmp;
20924
20613
  }
20925
- newitem = array[pos];
20614
+ newitem = array2[pos];
20926
20615
  while (pos > startpos) {
20927
20616
  parentpos = pos - 1 >> 1;
20928
- parent = array[parentpos];
20617
+ parent = array2[parentpos];
20929
20618
  if (cmp(newitem, parent) < 0) {
20930
- array[pos] = parent;
20619
+ array2[pos] = parent;
20931
20620
  pos = parentpos;
20932
20621
  continue;
20933
20622
  }
20934
20623
  break;
20935
20624
  }
20936
- return array[pos] = newitem;
20625
+ return array2[pos] = newitem;
20937
20626
  };
20938
- _siftup = function(array, pos, cmp) {
20627
+ _siftup = function(array2, pos, cmp) {
20939
20628
  var childpos, endpos, newitem, rightpos, startpos;
20940
20629
  if (cmp == null) {
20941
20630
  cmp = defaultCmp;
20942
20631
  }
20943
- endpos = array.length;
20632
+ endpos = array2.length;
20944
20633
  startpos = pos;
20945
- newitem = array[pos];
20634
+ newitem = array2[pos];
20946
20635
  childpos = 2 * pos + 1;
20947
20636
  while (childpos < endpos) {
20948
20637
  rightpos = childpos + 1;
20949
- if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
20638
+ if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
20950
20639
  childpos = rightpos;
20951
20640
  }
20952
- array[pos] = array[childpos];
20641
+ array2[pos] = array2[childpos];
20953
20642
  pos = childpos;
20954
20643
  childpos = 2 * pos + 1;
20955
20644
  }
20956
- array[pos] = newitem;
20957
- return _siftdown(array, startpos, pos, cmp);
20645
+ array2[pos] = newitem;
20646
+ return _siftdown(array2, startpos, pos, cmp);
20958
20647
  };
20959
20648
  Heap = function() {
20960
20649
  Heap2.push = heappush;
@@ -22867,12 +22556,12 @@ var require_lib = __commonJS({
22867
22556
  }
22868
22557
  return bestMatch;
22869
22558
  }
22870
- scalarize(array, originals, fuzzyOriginals) {
22559
+ scalarize(array2, originals, fuzzyOriginals) {
22871
22560
  const fuzzyMatches = [];
22872
22561
  if (fuzzyOriginals) {
22873
22562
  const keyScores = {};
22874
- for (let index4 = 0; index4 < array.length; index4++) {
22875
- const item = array[index4];
22563
+ for (let index4 = 0; index4 < array2.length; index4++) {
22564
+ const item = array2[index4];
22876
22565
  if (this.isScalar(item)) {
22877
22566
  continue;
22878
22567
  }
@@ -22886,8 +22575,8 @@ var require_lib = __commonJS({
22886
22575
  }
22887
22576
  }
22888
22577
  const result = [];
22889
- for (let index4 = 0; index4 < array.length; index4++) {
22890
- const item = array[index4];
22578
+ for (let index4 = 0; index4 < array2.length; index4++) {
22579
+ const item = array2[index4];
22891
22580
  if (this.isScalar(item)) {
22892
22581
  result.push(item);
22893
22582
  } else {
@@ -23109,6 +22798,37 @@ function diffColumns(left, right) {
23109
22798
  );
23110
22799
  return alteredTables;
23111
22800
  }
22801
+ function diffPolicies(left, right) {
22802
+ left = JSON.parse(JSON.stringify(left));
22803
+ right = JSON.parse(JSON.stringify(right));
22804
+ const result = (0, import_json_diff.diff)(left, right) ?? {};
22805
+ const alteredTables = Object.fromEntries(
22806
+ Object.entries(result).filter((it) => {
22807
+ return !(it[0].includes("__added") || it[0].includes("__deleted"));
22808
+ }).map((tableEntry) => {
22809
+ const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
22810
+ return it[0].endsWith("__deleted");
22811
+ }).map((it) => {
22812
+ return it[1];
22813
+ });
22814
+ const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
22815
+ return it[0].endsWith("__added");
22816
+ }).map((it) => {
22817
+ return it[1];
22818
+ });
22819
+ tableEntry[1].policies = {
22820
+ added: addedPolicies,
22821
+ deleted: deletedPolicies
22822
+ };
22823
+ const table4 = left[tableEntry[0]];
22824
+ return [
22825
+ tableEntry[0],
22826
+ { name: table4.name, schema: table4.schema, ...tableEntry[1] }
22827
+ ];
22828
+ })
22829
+ );
22830
+ return alteredTables;
22831
+ }
23112
22832
  function applyJsonDiff(json1, json2) {
23113
22833
  json1 = JSON.parse(JSON.stringify(json1));
23114
22834
  json2 = JSON.parse(JSON.stringify(json2));
@@ -23118,7 +22838,7 @@ function applyJsonDiff(json1, json2) {
23118
22838
  difference.tables = difference.tables || {};
23119
22839
  difference.enums = difference.enums || {};
23120
22840
  difference.sequences = difference.sequences || {};
23121
- difference.views = difference.views || {};
22841
+ difference.roles = difference.roles || {};
23122
22842
  const schemaKeys = Object.keys(difference.schemas);
23123
22843
  for (let key of schemaKeys) {
23124
22844
  if (key.endsWith("__added") || key.endsWith("__deleted")) {
@@ -23174,71 +22894,10 @@ function applyJsonDiff(json1, json2) {
23174
22894
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
23175
22895
  return json2.sequences[it[0]];
23176
22896
  });
23177
- const viewsEntries = Object.entries(difference.views);
23178
- const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
23179
- ([nameWithSchema, view2]) => {
23180
- const deletedWithOption = view2.with__deleted;
23181
- const addedWithOption = view2.with__added;
23182
- const deletedWith = Object.fromEntries(
23183
- Object.entries(view2.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
23184
- return [key.replace("__deleted", ""), value];
23185
- })
23186
- );
23187
- const addedWith = Object.fromEntries(
23188
- Object.entries(view2.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
23189
- return [key.replace("__added", ""), value];
23190
- })
23191
- );
23192
- const alterWith = Object.fromEntries(
23193
- Object.entries(view2.with || {}).filter(
23194
- (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
23195
- ).map(
23196
- (it) => {
23197
- return [it[0], it[1].__new];
23198
- }
23199
- )
23200
- );
23201
- const alteredSchema = view2.schema;
23202
- const alteredDefinition = view2.definition;
23203
- const alteredExisting = view2.isExisting;
23204
- const addedTablespace = view2.tablespace__added;
23205
- const droppedTablespace = view2.tablespace__deleted;
23206
- const alterTablespaceTo = view2.tablespace;
23207
- let alteredTablespace;
23208
- if (addedTablespace)
23209
- alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
23210
- if (droppedTablespace)
23211
- alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
23212
- if (alterTablespaceTo)
23213
- alteredTablespace = alterTablespaceTo;
23214
- const addedUsing = view2.using__added;
23215
- const droppedUsing = view2.using__deleted;
23216
- const alterUsingTo = view2.using;
23217
- let alteredUsing;
23218
- if (addedUsing)
23219
- alteredUsing = { __new: addedUsing, __old: "heap" };
23220
- if (droppedUsing)
23221
- alteredUsing = { __new: "heap", __old: droppedUsing };
23222
- if (alterUsingTo)
23223
- alteredUsing = alterUsingTo;
23224
- return {
23225
- name: json2.views[nameWithSchema].name,
23226
- schema: json2.views[nameWithSchema].schema,
23227
- deletedWithOption,
23228
- addedWithOption,
23229
- alteredWith: {
23230
- deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
23231
- addedWith: Object.keys(addedWith).length ? addedWith : void 0,
23232
- alterWith: Object.keys(alterWith).length ? alterWith : void 0
23233
- },
23234
- alteredSchema,
23235
- alteredDefinition,
23236
- alteredExisting,
23237
- alteredTablespace,
23238
- alteredUsing
23239
- };
23240
- }
23241
- );
22897
+ const rolesEntries = Object.entries(difference.roles);
22898
+ const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
22899
+ return json2.roles[it[0]];
22900
+ });
23242
22901
  const alteredTablesWithColumns = Object.values(difference.tables).map(
23243
22902
  (table4) => {
23244
22903
  return findAlternationsInTable(table4);
@@ -23248,7 +22907,7 @@ function applyJsonDiff(json1, json2) {
23248
22907
  alteredTablesWithColumns,
23249
22908
  alteredEnums,
23250
22909
  alteredSequences,
23251
- alteredViews
22910
+ alteredRoles
23252
22911
  };
23253
22912
  }
23254
22913
  var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
@@ -23308,6 +22967,21 @@ var init_jsonDiffer = __esm({
23308
22967
  return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
23309
22968
  })
23310
22969
  );
22970
+ const deletedPolicies = Object.fromEntries(
22971
+ Object.entries(table4.policies__deleted || {}).concat(
22972
+ Object.entries(table4.policies || {}).filter((it) => it[0].includes("__deleted"))
22973
+ ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
22974
+ );
22975
+ const addedPolicies = Object.fromEntries(
22976
+ Object.entries(table4.policies__added || {}).concat(
22977
+ Object.entries(table4.policies || {}).filter((it) => it[0].includes("__added"))
22978
+ ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
22979
+ );
22980
+ const alteredPolicies = Object.fromEntries(
22981
+ Object.entries(table4.policies || {}).filter((it) => {
22982
+ return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
22983
+ })
22984
+ );
23311
22985
  const deletedForeignKeys = Object.fromEntries(
23312
22986
  Object.entries(table4.foreignKeys__deleted || {}).concat(
23313
22987
  Object.entries(table4.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
@@ -23369,7 +23043,10 @@ var init_jsonDiffer = __esm({
23369
23043
  alteredCompositePKs,
23370
23044
  addedUniqueConstraints,
23371
23045
  deletedUniqueConstraints,
23372
- alteredUniqueConstraints
23046
+ alteredUniqueConstraints,
23047
+ deletedPolicies,
23048
+ addedPolicies,
23049
+ alteredPolicies
23373
23050
  };
23374
23051
  };
23375
23052
  alternationsInColumn = (column7) => {
@@ -23643,7 +23320,7 @@ function fromJson(statements, dialect7, action, json2) {
23643
23320
  }).filter((it) => it !== "");
23644
23321
  return result;
23645
23322
  }
23646
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, PgDropViewConvertor, PgRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, 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;
23323
+ var pgNativeTypes, isPgNativeType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, 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;
23647
23324
  var init_sqlgenerator = __esm({
23648
23325
  "src/sqlgenerator.ts"() {
23649
23326
  "use strict";
@@ -23700,12 +23377,110 @@ var init_sqlgenerator = __esm({
23700
23377
  };
23701
23378
  Convertor = class {
23702
23379
  };
23380
+ PgCreateRoleConvertor = class extends Convertor {
23381
+ can(statement, dialect7) {
23382
+ return statement.type === "create_role" && dialect7 === "postgresql";
23383
+ }
23384
+ convert(statement) {
23385
+ return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`;
23386
+ }
23387
+ };
23388
+ PgDropRoleConvertor = class extends Convertor {
23389
+ can(statement, dialect7) {
23390
+ return statement.type === "drop_role" && dialect7 === "postgresql";
23391
+ }
23392
+ convert(statement) {
23393
+ return `DROP ROLE "${statement.name}";`;
23394
+ }
23395
+ };
23396
+ PgRenameRoleConvertor = class extends Convertor {
23397
+ can(statement, dialect7) {
23398
+ return statement.type === "rename_role" && dialect7 === "postgresql";
23399
+ }
23400
+ convert(statement) {
23401
+ return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
23402
+ }
23403
+ };
23404
+ PgAlterRoleConvertor = class extends Convertor {
23405
+ can(statement, dialect7) {
23406
+ return statement.type === "alter_role" && dialect7 === "postgresql";
23407
+ }
23408
+ convert(statement) {
23409
+ return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
23410
+ }
23411
+ };
23412
+ PgCreatePolicyConvertor = class extends Convertor {
23413
+ can(statement, dialect7) {
23414
+ return statement.type === "create_policy" && dialect7 === "postgresql";
23415
+ }
23416
+ convert(statement) {
23417
+ var _a, _b, _c;
23418
+ const policy2 = statement.data;
23419
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
23420
+ const usingPart = policy2.using ? ` USING (${policy2.using})` : "";
23421
+ const withCheckPart = policy2.withCheck ? ` WITH CHECK (${policy2.withCheck})` : "";
23422
+ const policyToPart = (_a = policy2.to) == null ? void 0 : _a.map(
23423
+ (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
23424
+ ).join(", ");
23425
+ return `CREATE POLICY "${policy2.name}" ON ${tableNameWithSchema} AS ${(_b = policy2.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy2.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
23426
+ }
23427
+ };
23428
+ PgDropPolicyConvertor = class extends Convertor {
23429
+ can(statement, dialect7) {
23430
+ return statement.type === "drop_policy" && dialect7 === "postgresql";
23431
+ }
23432
+ convert(statement) {
23433
+ const policy2 = statement.data;
23434
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
23435
+ return `DROP POLICY "${policy2.name}" ON ${tableNameWithSchema} CASCADE;`;
23436
+ }
23437
+ };
23438
+ PgRenamePolicyConvertor = class extends Convertor {
23439
+ can(statement, dialect7) {
23440
+ return statement.type === "rename_policy" && dialect7 === "postgresql";
23441
+ }
23442
+ convert(statement) {
23443
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
23444
+ return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
23445
+ }
23446
+ };
23447
+ PgAlterPolicyConvertor = class extends Convertor {
23448
+ can(statement, dialect7) {
23449
+ return statement.type === "alter_policy" && dialect7 === "postgresql";
23450
+ }
23451
+ convert(statement) {
23452
+ const newPolicy = PgSquasher.unsquashPolicy(statement.newData);
23453
+ const oldPolicy = PgSquasher.unsquashPolicy(statement.oldData);
23454
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
23455
+ const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
23456
+ const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : "";
23457
+ return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
23458
+ }
23459
+ };
23460
+ PgEnableRlsConvertor = class extends Convertor {
23461
+ can(statement, dialect7) {
23462
+ return statement.type === "enable_rls" && dialect7 === "postgresql";
23463
+ }
23464
+ convert(statement) {
23465
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
23466
+ return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
23467
+ }
23468
+ };
23469
+ PgDisableRlsConvertor = class extends Convertor {
23470
+ can(statement, dialect7) {
23471
+ return statement.type === "disable_rls" && dialect7 === "postgresql";
23472
+ }
23473
+ convert(statement) {
23474
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
23475
+ return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
23476
+ }
23477
+ };
23703
23478
  PgCreateTableConvertor = class extends Convertor {
23704
23479
  can(statement, dialect7) {
23705
23480
  return statement.type === "create_table" && dialect7 === "postgresql";
23706
23481
  }
23707
23482
  convert(st) {
23708
- const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints } = st;
23483
+ const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints, policies } = st;
23709
23484
  let statement = "";
23710
23485
  const name = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
23711
23486
  statement += `CREATE TABLE IF NOT EXISTS ${name} (
@@ -23742,7 +23517,12 @@ var init_sqlgenerator = __esm({
23742
23517
  );`;
23743
23518
  statement += `
23744
23519
  `;
23745
- return statement;
23520
+ const enableRls = new PgEnableRlsConvertor().convert({
23521
+ type: "enable_rls",
23522
+ tableName,
23523
+ schema: schema5
23524
+ });
23525
+ return [statement, ...policies && policies.length > 0 ? [enableRls] : []];
23746
23526
  }
23747
23527
  };
23748
23528
  MySqlCreateTableConvertor = class extends Convertor {
@@ -23859,118 +23639,6 @@ var init_sqlgenerator = __esm({
23859
23639
  return statement;
23860
23640
  }
23861
23641
  };
23862
- PgCreateViewConvertor = class extends Convertor {
23863
- can(statement, dialect7) {
23864
- return statement.type === "create_view" && dialect7 === "postgresql";
23865
- }
23866
- convert(st) {
23867
- const { definition, name: viewName, schema: schema5, with: withOption, materialized, withNoData, tablespace, using } = st;
23868
- const name = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
23869
- let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`;
23870
- if (using)
23871
- statement += ` USING "${using}"`;
23872
- const options = [];
23873
- if (withOption) {
23874
- statement += ` WITH (`;
23875
- Object.entries(withOption).forEach(([key, value]) => {
23876
- if (typeof value === "undefined")
23877
- return;
23878
- options.push(`${key.snake_case()} = ${value}`);
23879
- });
23880
- statement += options.join(", ");
23881
- statement += `)`;
23882
- }
23883
- if (tablespace)
23884
- statement += ` TABLESPACE ${tablespace}`;
23885
- statement += ` AS (${definition})`;
23886
- if (withNoData)
23887
- statement += ` WITH NO DATA`;
23888
- statement += `;`;
23889
- return statement;
23890
- }
23891
- };
23892
- PgDropViewConvertor = class extends Convertor {
23893
- can(statement, dialect7) {
23894
- return statement.type === "drop_view" && dialect7 === "postgresql";
23895
- }
23896
- convert(st) {
23897
- const { name: viewName, schema: schema5, materialized } = st;
23898
- const name = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
23899
- return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`;
23900
- }
23901
- };
23902
- PgRenameViewConvertor = class extends Convertor {
23903
- can(statement, dialect7) {
23904
- return statement.type === "rename_view" && dialect7 === "postgresql";
23905
- }
23906
- convert(st) {
23907
- const { nameFrom: from, nameTo: to, schema: schema5, materialized } = st;
23908
- const nameFrom = `"${schema5}"."${from}"`;
23909
- return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
23910
- }
23911
- };
23912
- PgAlterViewSchemaConvertor = class extends Convertor {
23913
- can(statement, dialect7) {
23914
- return statement.type === "alter_view_alter_schema" && dialect7 === "postgresql";
23915
- }
23916
- convert(st) {
23917
- const { fromSchema, toSchema, name, materialized } = st;
23918
- const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`;
23919
- return statement;
23920
- }
23921
- };
23922
- PgAlterViewAddWithOptionConvertor = class extends Convertor {
23923
- can(statement, dialect7) {
23924
- return statement.type === "alter_view_add_with_option" && dialect7 === "postgresql";
23925
- }
23926
- convert(st) {
23927
- const { schema: schema5, with: withOption, name, materialized } = st;
23928
- let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name}" SET (`;
23929
- const options = [];
23930
- Object.entries(withOption).forEach(([key, value]) => {
23931
- options.push(`${key.snake_case()} = ${value}`);
23932
- });
23933
- statement += options.join(", ");
23934
- statement += `);`;
23935
- return statement;
23936
- }
23937
- };
23938
- PgAlterViewDropWithOptionConvertor = class extends Convertor {
23939
- can(statement, dialect7) {
23940
- return statement.type === "alter_view_drop_with_option" && dialect7 === "postgresql";
23941
- }
23942
- convert(st) {
23943
- const { schema: schema5, name, materialized, with: withOptions } = st;
23944
- let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name}" RESET (`;
23945
- const options = [];
23946
- Object.entries(withOptions).forEach(([key, value]) => {
23947
- options.push(`${key.snake_case()}`);
23948
- });
23949
- statement += options.join(", ");
23950
- statement += ");";
23951
- return statement;
23952
- }
23953
- };
23954
- PgAlterViewAlterTablespaceConvertor = class extends Convertor {
23955
- can(statement, dialect7) {
23956
- return statement.type === "alter_view_alter_tablespace" && dialect7 === "postgresql";
23957
- }
23958
- convert(st) {
23959
- const { schema: schema5, name, toTablespace } = st;
23960
- const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name}" SET TABLESPACE ${toTablespace};`;
23961
- return statement;
23962
- }
23963
- };
23964
- PgAlterViewAlterUsingConvertor = class extends Convertor {
23965
- can(statement, dialect7) {
23966
- return statement.type === "alter_view_alter_using" && dialect7 === "postgresql";
23967
- }
23968
- convert(st) {
23969
- const { schema: schema5, name, toUsing } = st;
23970
- const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name}" SET ACCESS METHOD "${toUsing}";`;
23971
- return statement;
23972
- }
23973
- };
23974
23642
  PgAlterTableAlterColumnSetGenerated = class extends Convertor {
23975
23643
  can(statement, dialect7) {
23976
23644
  return statement.type === "alter_table_alter_column_set_identity" && dialect7 === "postgresql";
@@ -24171,9 +23839,21 @@ var init_sqlgenerator = __esm({
24171
23839
  return statement.type === "drop_table" && dialect7 === "postgresql";
24172
23840
  }
24173
23841
  convert(statement) {
24174
- const { tableName, schema: schema5 } = statement;
23842
+ const { tableName, schema: schema5, policies } = statement;
24175
23843
  const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
24176
- return `DROP TABLE ${tableNameWithSchema};`;
23844
+ const dropPolicyConvertor = new PgDropPolicyConvertor();
23845
+ const droppedPolicies = (policies == null ? void 0 : policies.map((p2) => {
23846
+ return dropPolicyConvertor.convert({
23847
+ type: "drop_policy",
23848
+ tableName,
23849
+ data: PgSquasher.unsquashPolicy(p2),
23850
+ schema: schema5
23851
+ });
23852
+ })) ?? [];
23853
+ return [
23854
+ ...droppedPolicies,
23855
+ `DROP TABLE ${tableNameWithSchema};`
23856
+ ];
24177
23857
  }
24178
23858
  };
24179
23859
  MySQLDropTableConvertor = class extends Convertor {
@@ -25309,14 +24989,6 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
25309
24989
  convertors.push(new SQLiteCreateTableConvertor());
25310
24990
  convertors.push(new SQLiteRecreateTableConvertor());
25311
24991
  convertors.push(new LibSQLRecreateTableConvertor());
25312
- convertors.push(new PgCreateViewConvertor());
25313
- convertors.push(new PgDropViewConvertor());
25314
- convertors.push(new PgRenameViewConvertor());
25315
- convertors.push(new PgAlterViewSchemaConvertor());
25316
- convertors.push(new PgAlterViewAddWithOptionConvertor());
25317
- convertors.push(new PgAlterViewDropWithOptionConvertor());
25318
- convertors.push(new PgAlterViewAlterTablespaceConvertor());
25319
- convertors.push(new PgAlterViewAlterUsingConvertor());
25320
24992
  convertors.push(new CreateTypeEnumConvertor());
25321
24993
  convertors.push(new CreatePgSequenceConvertor());
25322
24994
  convertors.push(new DropPgSequenceConvertor());
@@ -25356,6 +25028,16 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
25356
25028
  convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
25357
25029
  convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
25358
25030
  convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
25031
+ convertors.push(new PgAlterPolicyConvertor());
25032
+ convertors.push(new PgCreatePolicyConvertor());
25033
+ convertors.push(new PgDropPolicyConvertor());
25034
+ convertors.push(new PgRenamePolicyConvertor());
25035
+ convertors.push(new PgEnableRlsConvertor());
25036
+ convertors.push(new PgDisableRlsConvertor());
25037
+ convertors.push(new PgDropRoleConvertor());
25038
+ convertors.push(new PgAlterRoleConvertor());
25039
+ convertors.push(new PgCreateRoleConvertor());
25040
+ convertors.push(new PgRenameRoleConvertor());
25359
25041
  convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
25360
25042
  convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
25361
25043
  convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
@@ -25651,7 +25333,7 @@ var init_sqlitePushUtils = __esm({
25651
25333
  });
25652
25334
 
25653
25335
  // src/jsonStatements.ts
25654
- 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, preparePgCreateViewJson, preparePgDropViewJson, preparePgRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson;
25336
+ var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareCreatePolicyJsons, prepareDropPolicyJsons, prepareAlterPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql;
25655
25337
  var init_jsonStatements = __esm({
25656
25338
  "src/jsonStatements.ts"() {
25657
25339
  "use strict";
@@ -25662,7 +25344,7 @@ var init_jsonStatements = __esm({
25662
25344
  init_pgSchema();
25663
25345
  init_sqliteSchema();
25664
25346
  preparePgCreateTableJson = (table4, json2) => {
25665
- const { name, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints } = table4;
25347
+ const { name, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints, policies } = table4;
25666
25348
  const tableKey2 = `${schema5 || "public"}.${name}`;
25667
25349
  const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
25668
25350
  return {
@@ -25672,7 +25354,8 @@ var init_jsonStatements = __esm({
25672
25354
  columns: Object.values(columns),
25673
25355
  compositePKs: Object.values(compositePrimaryKeys),
25674
25356
  compositePkName,
25675
- uniqueConstraints: Object.values(uniqueConstraints)
25357
+ uniqueConstraints: Object.values(uniqueConstraints),
25358
+ policies: Object.values(policies)
25676
25359
  };
25677
25360
  };
25678
25361
  prepareMySqlCreateTableJson = (table4, json2, internals) => {
@@ -25710,7 +25393,8 @@ var init_jsonStatements = __esm({
25710
25393
  return {
25711
25394
  type: "drop_table",
25712
25395
  tableName: table4.name,
25713
- schema: table4.schema
25396
+ schema: table4.schema,
25397
+ policies: table4.policies ? Object.values(table4.policies) : []
25714
25398
  };
25715
25399
  };
25716
25400
  prepareRenameTableJson = (tableFrom, tableTo) => {
@@ -25807,6 +25491,41 @@ var init_jsonStatements = __esm({
25807
25491
  schema: schema5
25808
25492
  };
25809
25493
  };
25494
+ prepareCreateRoleJson = (role) => {
25495
+ return {
25496
+ type: "create_role",
25497
+ name: role.name,
25498
+ values: {
25499
+ createDb: role.createDb,
25500
+ createRole: role.createRole,
25501
+ inherit: role.inherit
25502
+ }
25503
+ };
25504
+ };
25505
+ prepareAlterRoleJson = (role) => {
25506
+ return {
25507
+ type: "alter_role",
25508
+ name: role.name,
25509
+ values: {
25510
+ createDb: role.createDb,
25511
+ createRole: role.createRole,
25512
+ inherit: role.inherit
25513
+ }
25514
+ };
25515
+ };
25516
+ prepareDropRoleJson = (name) => {
25517
+ return {
25518
+ type: "drop_role",
25519
+ name
25520
+ };
25521
+ };
25522
+ prepareRenameRoleJson = (nameFrom, nameTo) => {
25523
+ return {
25524
+ type: "rename_role",
25525
+ nameFrom,
25526
+ nameTo
25527
+ };
25528
+ };
25810
25529
  prepareCreateSchemasJson = (values) => {
25811
25530
  return values.map((it) => {
25812
25531
  return {
@@ -26707,6 +26426,46 @@ var init_jsonStatements = __esm({
26707
26426
  }
26708
26427
  return [...dropPkStatements, ...setPkStatements, ...statements];
26709
26428
  };
26429
+ prepareRenamePolicyJsons = (tableName, schema5, renames) => {
26430
+ return renames.map((it) => {
26431
+ return {
26432
+ type: "rename_policy",
26433
+ tableName,
26434
+ oldName: it.from.name,
26435
+ newName: it.to.name,
26436
+ schema: schema5
26437
+ };
26438
+ });
26439
+ };
26440
+ prepareCreatePolicyJsons = (tableName, schema5, policies) => {
26441
+ return policies.map((it) => {
26442
+ return {
26443
+ type: "create_policy",
26444
+ tableName,
26445
+ data: it,
26446
+ schema: schema5
26447
+ };
26448
+ });
26449
+ };
26450
+ prepareDropPolicyJsons = (tableName, schema5, policies) => {
26451
+ return policies.map((it) => {
26452
+ return {
26453
+ type: "drop_policy",
26454
+ tableName,
26455
+ data: it,
26456
+ schema: schema5
26457
+ };
26458
+ });
26459
+ };
26460
+ prepareAlterPolicyJson = (tableName, schema5, oldPolicy, newPolicy) => {
26461
+ return {
26462
+ type: "alter_policy",
26463
+ tableName,
26464
+ oldData: oldPolicy,
26465
+ newData: newPolicy,
26466
+ schema: schema5
26467
+ };
26468
+ };
26710
26469
  preparePgCreateIndexesJson = (tableName, schema5, indexes, fullSchema, action) => {
26711
26470
  if (action === "push") {
26712
26471
  return Object.values(indexes).map((indexData) => {
@@ -26990,81 +26749,6 @@ var init_jsonStatements = __esm({
26990
26749
  };
26991
26750
  });
26992
26751
  };
26993
- preparePgCreateViewJson = (name, schema5, definition, materialized, withNoData = false, withOption, using, tablespace) => {
26994
- return {
26995
- type: "create_view",
26996
- name,
26997
- schema: schema5,
26998
- definition,
26999
- with: withOption,
27000
- materialized,
27001
- withNoData,
27002
- using,
27003
- tablespace
27004
- };
27005
- };
27006
- preparePgDropViewJson = (name, schema5, materialized) => {
27007
- return {
27008
- type: "drop_view",
27009
- name,
27010
- schema: schema5,
27011
- materialized
27012
- };
27013
- };
27014
- preparePgRenameViewJson = (to, from, schema5, materialized) => {
27015
- return {
27016
- type: "rename_view",
27017
- nameTo: to,
27018
- nameFrom: from,
27019
- schema: schema5,
27020
- materialized
27021
- };
27022
- };
27023
- preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => {
27024
- return {
27025
- type: "alter_view_alter_schema",
27026
- fromSchema: from,
27027
- toSchema: to,
27028
- name,
27029
- materialized
27030
- };
27031
- };
27032
- preparePgAlterViewAddWithOptionJson = (name, schema5, materialized, withOption) => {
27033
- return {
27034
- type: "alter_view_add_with_option",
27035
- name,
27036
- schema: schema5,
27037
- materialized,
27038
- with: withOption
27039
- };
27040
- };
27041
- preparePgAlterViewDropWithOptionJson = (name, schema5, materialized, withOption) => {
27042
- return {
27043
- type: "alter_view_drop_with_option",
27044
- name,
27045
- schema: schema5,
27046
- materialized,
27047
- with: withOption
27048
- };
27049
- };
27050
- preparePgAlterViewAlterTablespaceJson = (name, schema5, materialized, to) => {
27051
- return {
27052
- type: "alter_view_alter_tablespace",
27053
- name,
27054
- schema: schema5,
27055
- materialized,
27056
- toTablespace: to
27057
- };
27058
- };
27059
- preparePgAlterViewAlterUsingJson = (name, schema5, materialized, to) => {
27060
- return {
27061
- type: "alter_view_alter_using",
27062
- name,
27063
- schema: schema5,
27064
- materialized,
27065
- toUsing: to
27066
- };
27067
- };
27068
26752
  }
27069
26753
  });
27070
26754
 
@@ -27350,7 +27034,7 @@ var init_statementCombiner = __esm({
27350
27034
  });
27351
27035
 
27352
27036
  // src/snapshotsDiffer.ts
27353
- var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
27037
+ var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
27354
27038
  var init_snapshotsDiffer = __esm({
27355
27039
  "src/snapshotsDiffer.ts"() {
27356
27040
  "use strict";
@@ -27455,7 +27139,8 @@ var init_snapshotsDiffer = __esm({
27455
27139
  indexes: recordType(stringType(), stringType()),
27456
27140
  foreignKeys: recordType(stringType(), stringType()),
27457
27141
  compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
27458
- uniqueConstraints: recordType(stringType(), stringType()).default({})
27142
+ uniqueConstraints: recordType(stringType(), stringType()).default({}),
27143
+ policies: recordType(stringType(), stringType()).default({})
27459
27144
  }).strict();
27460
27145
  alteredTableScheme = objectType({
27461
27146
  name: stringType(),
@@ -27496,44 +27181,22 @@ var init_snapshotsDiffer = __esm({
27496
27181
  __new: stringType(),
27497
27182
  __old: stringType()
27498
27183
  })
27184
+ ),
27185
+ addedPolicies: recordType(stringType(), stringType()),
27186
+ deletedPolicies: recordType(stringType(), stringType()),
27187
+ alteredPolicies: recordType(
27188
+ stringType(),
27189
+ objectType({
27190
+ __new: stringType(),
27191
+ __old: stringType()
27192
+ })
27499
27193
  )
27500
27194
  }).strict();
27501
- alteredViewSchema = objectType({
27502
- name: stringType(),
27503
- schema: stringType(),
27504
- deletedWithOption: mergedViewWithOption.optional(),
27505
- addedWithOption: mergedViewWithOption.optional(),
27506
- alteredWith: objectType({
27507
- addedWith: mergedViewWithOption.optional(),
27508
- deletedWith: mergedViewWithOption.optional(),
27509
- alterWith: mergedViewWithOption.optional()
27510
- }).strict(),
27511
- alteredSchema: objectType({
27512
- __old: stringType(),
27513
- __new: stringType()
27514
- }).strict().optional(),
27515
- alteredDefinition: objectType({
27516
- __old: stringType(),
27517
- __new: stringType()
27518
- }).strict().optional(),
27519
- alteredExisting: objectType({
27520
- __old: booleanType(),
27521
- __new: booleanType()
27522
- }).strict().optional(),
27523
- alteredTablespace: objectType({
27524
- __old: stringType(),
27525
- __new: stringType()
27526
- }).strict().optional(),
27527
- alteredUsing: objectType({
27528
- __old: stringType(),
27529
- __new: stringType()
27530
- }).strict().optional()
27531
- }).strict();
27532
27195
  diffResultScheme = objectType({
27533
27196
  alteredTablesWithColumns: alteredTableScheme.array(),
27534
27197
  alteredEnums: changedEnumSchema.array(),
27535
27198
  alteredSequences: sequenceSquashed.array(),
27536
- alteredViews: alteredViewSchema.array()
27199
+ alteredRoles: roleSchema.array()
27537
27200
  }).strict();
27538
27201
  diffResultSchemeMysql = objectType({
27539
27202
  alteredTablesWithColumns: alteredTableScheme.array(),
@@ -27588,7 +27251,7 @@ var init_snapshotsDiffer = __esm({
27588
27251
  }
27589
27252
  return column7;
27590
27253
  };
27591
- applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
27254
+ applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, roleResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
27592
27255
  const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
27593
27256
  const {
27594
27257
  created: createdSchemas,
@@ -27738,6 +27401,47 @@ var init_snapshotsDiffer = __esm({
27738
27401
  return [tableKey2, tableValue];
27739
27402
  }
27740
27403
  );
27404
+ const rolesDiff = diffSchemasOrTables(
27405
+ schemasPatchedSnap1.roles,
27406
+ json2.roles
27407
+ );
27408
+ const {
27409
+ created: createdRoles,
27410
+ deleted: deletedRoles,
27411
+ renamed: renamedRoles
27412
+ } = await roleResolver2({
27413
+ created: rolesDiff.added,
27414
+ deleted: rolesDiff.deleted
27415
+ });
27416
+ schemasPatchedSnap1.roles = mapEntries(
27417
+ schemasPatchedSnap1.roles,
27418
+ (_2, it) => {
27419
+ const { name } = nameChangeFor(it, renamedRoles);
27420
+ it.name = name;
27421
+ return [name, it];
27422
+ }
27423
+ );
27424
+ const rolesChangeMap = renamedRoles.reduce(
27425
+ (acc, it) => {
27426
+ acc[it.from.name] = {
27427
+ nameFrom: it.from.name,
27428
+ nameTo: it.to.name
27429
+ };
27430
+ return acc;
27431
+ },
27432
+ {}
27433
+ );
27434
+ schemasPatchedSnap1.roles = mapEntries(
27435
+ schemasPatchedSnap1.roles,
27436
+ (roleKey, roleValue) => {
27437
+ const key = roleKey;
27438
+ const change = rolesChangeMap[key];
27439
+ if (change) {
27440
+ roleValue.name = change.nameTo;
27441
+ }
27442
+ return [roleKey, roleValue];
27443
+ }
27444
+ );
27741
27445
  const tablesDiff = diffSchemasOrTables(
27742
27446
  schemasPatchedSnap1.tables,
27743
27447
  json2.tables
@@ -27816,16 +27520,65 @@ var init_snapshotsDiffer = __esm({
27816
27520
  return [tableKey2, tableValue];
27817
27521
  }
27818
27522
  );
27819
- const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
27820
- const {
27821
- created: createdViews,
27822
- deleted: deletedViews,
27823
- renamed: renamedViews,
27824
- moved: movedViews
27825
- } = await viewsResolver2({
27826
- created: viewsDiff.added,
27827
- deleted: viewsDiff.deleted
27828
- });
27523
+ const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
27524
+ const policyRenames = [];
27525
+ const policyCreates = [];
27526
+ const policyDeletes = [];
27527
+ for (let entry of Object.values(policyRes)) {
27528
+ const { renamed, created, deleted } = await policyResolver2({
27529
+ tableName: entry.name,
27530
+ schema: entry.schema,
27531
+ deleted: entry.policies.deleted.map(PgSquasher.unsquashPolicy),
27532
+ created: entry.policies.added.map(PgSquasher.unsquashPolicy)
27533
+ });
27534
+ if (created.length > 0) {
27535
+ policyCreates.push({
27536
+ table: entry.name,
27537
+ schema: entry.schema,
27538
+ columns: created
27539
+ });
27540
+ }
27541
+ if (deleted.length > 0) {
27542
+ policyDeletes.push({
27543
+ table: entry.name,
27544
+ schema: entry.schema,
27545
+ columns: deleted
27546
+ });
27547
+ }
27548
+ if (renamed.length > 0) {
27549
+ policyRenames.push({
27550
+ table: entry.name,
27551
+ schema: entry.schema,
27552
+ renames: renamed
27553
+ });
27554
+ }
27555
+ }
27556
+ const policyRenamesDict = columnRenames.reduce(
27557
+ (acc, it) => {
27558
+ acc[`${it.schema || "public"}.${it.table}`] = it.renames;
27559
+ return acc;
27560
+ },
27561
+ {}
27562
+ );
27563
+ const policyPatchedSnap1 = copy(tablesPatchedSnap1);
27564
+ policyPatchedSnap1.tables = mapEntries(
27565
+ policyPatchedSnap1.tables,
27566
+ (tableKey2, tableValue) => {
27567
+ const patchedPolicies = mapKeys(
27568
+ tableValue.policies,
27569
+ (policyKey, policy2) => {
27570
+ const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
27571
+ const newName = columnChangeFor(policyKey, rens);
27572
+ const unsquashedPolicy = PgSquasher.unsquashPolicy(policy2);
27573
+ unsquashedPolicy.name = newName;
27574
+ policy2 = PgSquasher.squashPolicy(unsquashedPolicy);
27575
+ return newName;
27576
+ }
27577
+ );
27578
+ tableValue.policies = patchedPolicies;
27579
+ return [tableKey2, tableValue];
27580
+ }
27581
+ );
27829
27582
  const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
27830
27583
  const typedResult = diffResultScheme.parse(diffResult);
27831
27584
  const jsonStatements = [];
@@ -27981,7 +27734,99 @@ var init_snapshotsDiffer = __esm({
27981
27734
  it.deletedIndexes || {}
27982
27735
  );
27983
27736
  }).flat();
27737
+ const jsonCreatePoliciesStatements = [];
27738
+ const jsonDropPoliciesStatements = [];
27739
+ const jsonAlterPoliciesStatements = [];
27740
+ const jsonRenamePoliciesStatements = [];
27741
+ const jsonEnableRLSStatements = [];
27742
+ const jsonDisableRLSStatements = [];
27743
+ for (let it of policyRenames) {
27744
+ jsonRenamePoliciesStatements.push(
27745
+ ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
27746
+ );
27747
+ }
27748
+ for (const it of policyCreates) {
27749
+ jsonCreatePoliciesStatements.push(
27750
+ ...prepareCreatePolicyJsons(
27751
+ it.table,
27752
+ it.schema,
27753
+ it.columns
27754
+ )
27755
+ );
27756
+ }
27757
+ for (const it of policyDeletes) {
27758
+ jsonDropPoliciesStatements.push(
27759
+ ...prepareDropPolicyJsons(
27760
+ it.table,
27761
+ it.schema,
27762
+ it.columns
27763
+ )
27764
+ );
27765
+ }
27984
27766
  alteredTables.forEach((it) => {
27767
+ Object.keys(it.alteredPolicies).forEach((policyName) => {
27768
+ const newPolicy = PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
27769
+ const oldPolicy = PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
27770
+ if (newPolicy.as !== oldPolicy.as) {
27771
+ jsonDropPoliciesStatements.push(
27772
+ ...prepareDropPolicyJsons(
27773
+ it.name,
27774
+ it.schema,
27775
+ [oldPolicy]
27776
+ )
27777
+ );
27778
+ jsonCreatePoliciesStatements.push(
27779
+ ...prepareCreatePolicyJsons(
27780
+ it.name,
27781
+ it.schema,
27782
+ [newPolicy]
27783
+ )
27784
+ );
27785
+ return;
27786
+ }
27787
+ if (newPolicy.for !== oldPolicy.for) {
27788
+ jsonDropPoliciesStatements.push(
27789
+ ...prepareDropPolicyJsons(
27790
+ it.name,
27791
+ it.schema,
27792
+ [oldPolicy]
27793
+ )
27794
+ );
27795
+ jsonCreatePoliciesStatements.push(
27796
+ ...prepareCreatePolicyJsons(
27797
+ it.name,
27798
+ it.schema,
27799
+ [newPolicy]
27800
+ )
27801
+ );
27802
+ return;
27803
+ }
27804
+ jsonAlterPoliciesStatements.push(
27805
+ prepareAlterPolicyJson(
27806
+ it.name,
27807
+ it.schema,
27808
+ it.alteredPolicies[policyName].__old,
27809
+ it.alteredPolicies[policyName].__new
27810
+ )
27811
+ );
27812
+ });
27813
+ for (const table4 of Object.values(json2.tables)) {
27814
+ const policiesInCurrentState = Object.keys(table4.policies);
27815
+ const tableInPreviousState = columnsPatchedSnap1.tables[`${table4.schema === "" ? "public" : table4.schema}.${table4.name}`];
27816
+ const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
27817
+ if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0) {
27818
+ jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table4.name, schema: table4.schema });
27819
+ }
27820
+ if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0) {
27821
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
27822
+ }
27823
+ }
27824
+ for (const table4 of Object.values(columnsPatchedSnap1.tables)) {
27825
+ const tableInCurrentState = json2.tables[`${table4.schema === "" ? "public" : table4.schema}.${table4.name}`];
27826
+ if (tableInCurrentState === void 0) {
27827
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
27828
+ }
27829
+ }
27985
27830
  const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
27986
27831
  (current, item) => {
27987
27832
  current[item] = it.alteredIndexes[item].__old;
@@ -28066,6 +27911,18 @@ var init_snapshotsDiffer = __esm({
28066
27911
  const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
28067
27912
  return prepareAlterSequenceJson(it);
28068
27913
  }).flat() ?? [];
27914
+ const createRoles = createdRoles.map((it) => {
27915
+ return prepareCreateRoleJson(it);
27916
+ }) ?? [];
27917
+ const dropRoles = deletedRoles.map((it) => {
27918
+ return prepareDropRoleJson(it.name);
27919
+ });
27920
+ const renameRoles = renamedRoles.map((it) => {
27921
+ return prepareRenameRoleJson(it.from.name, it.to.name);
27922
+ });
27923
+ const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
27924
+ return prepareAlterRoleJson(it);
27925
+ }).flat() ?? [];
28069
27926
  const createSchemas = prepareCreateSchemasJson(
28070
27927
  createdSchemas.map((it) => it.name)
28071
27928
  );
@@ -28078,137 +27935,11 @@ var init_snapshotsDiffer = __esm({
28078
27935
  const createTables = createdTables.map((it) => {
28079
27936
  return preparePgCreateTableJson(it, curFull);
28080
27937
  });
28081
- const createViews = [];
28082
- const dropViews = [];
28083
- const renameViews = [];
28084
- const alterViews = [];
28085
- createViews.push(
28086
- ...createdViews.filter((it) => !it.isExisting).map((it) => {
28087
- return preparePgCreateViewJson(
28088
- it.name,
28089
- it.schema,
28090
- it.definition,
28091
- it.materialized,
28092
- it.withNoData,
28093
- it.with,
28094
- it.using,
28095
- it.tablespace
28096
- );
28097
- })
28098
- );
28099
- dropViews.push(
28100
- ...deletedViews.filter((it) => !it.isExisting).map((it) => {
28101
- return preparePgDropViewJson(it.name, it.schema, it.materialized);
28102
- })
28103
- );
28104
- renameViews.push(
28105
- ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
28106
- return preparePgRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
28107
- })
28108
- );
28109
- alterViews.push(
28110
- ...movedViews.filter((it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting).map((it) => {
28111
- return preparePgAlterViewAlterSchemaJson(
28112
- it.schemaTo,
28113
- it.schemaFrom,
28114
- it.name,
28115
- json2.views[`${it.schemaTo}.${it.name}`].materialized
28116
- );
28117
- })
28118
- );
28119
- const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting);
28120
- for (const alteredView of alteredViews) {
28121
- const viewKey = `${alteredView.schema}.${alteredView.name}`;
28122
- const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey];
28123
- if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
28124
- dropViews.push(preparePgDropViewJson(alteredView.name, alteredView.schema, materialized));
28125
- createViews.push(
28126
- preparePgCreateViewJson(
28127
- alteredView.name,
28128
- alteredView.schema,
28129
- definition,
28130
- materialized,
28131
- withNoData,
28132
- withOption,
28133
- using,
28134
- tablespace
28135
- )
28136
- );
28137
- continue;
28138
- }
28139
- if (alteredView.addedWithOption) {
28140
- alterViews.push(
28141
- preparePgAlterViewAddWithOptionJson(
28142
- alteredView.name,
28143
- alteredView.schema,
28144
- materialized,
28145
- alteredView.addedWithOption
28146
- )
28147
- );
28148
- }
28149
- if (alteredView.deletedWithOption) {
28150
- alterViews.push(
28151
- preparePgAlterViewDropWithOptionJson(
28152
- alteredView.name,
28153
- alteredView.schema,
28154
- materialized,
28155
- alteredView.deletedWithOption
28156
- )
28157
- );
28158
- }
28159
- if (alteredView.alteredWith) {
28160
- if (alteredView.alteredWith.addedWith) {
28161
- alterViews.push(
28162
- preparePgAlterViewAddWithOptionJson(
28163
- alteredView.name,
28164
- alteredView.schema,
28165
- materialized,
28166
- alteredView.alteredWith.addedWith
28167
- )
28168
- );
28169
- }
28170
- if (alteredView.alteredWith.deletedWith) {
28171
- alterViews.push(
28172
- preparePgAlterViewDropWithOptionJson(
28173
- alteredView.name,
28174
- alteredView.schema,
28175
- materialized,
28176
- alteredView.alteredWith.deletedWith
28177
- )
28178
- );
28179
- }
28180
- if (alteredView.alteredWith.alterWith) {
28181
- alterViews.push(
28182
- preparePgAlterViewAddWithOptionJson(
28183
- alteredView.name,
28184
- alteredView.schema,
28185
- materialized,
28186
- alteredView.alteredWith.alterWith
28187
- )
28188
- );
28189
- }
28190
- }
28191
- if (alteredView.alteredTablespace) {
28192
- alterViews.push(
28193
- preparePgAlterViewAlterTablespaceJson(
28194
- alteredView.name,
28195
- alteredView.schema,
28196
- materialized,
28197
- alteredView.alteredTablespace.__new
28198
- )
28199
- );
28200
- }
28201
- if (alteredView.alteredUsing) {
28202
- alterViews.push(
28203
- preparePgAlterViewAlterUsingJson(
28204
- alteredView.name,
28205
- alteredView.schema,
28206
- materialized,
28207
- alteredView.alteredUsing.__new
28208
- )
28209
- );
28210
- }
28211
- }
27938
+ jsonCreatePoliciesStatements.push(...[].concat(
27939
+ ...createdTables.map(
27940
+ (it) => prepareCreatePolicyJsons(it.name, it.schema, Object.values(it.policies).map(PgSquasher.unsquashPolicy))
27941
+ )
27942
+ ));
28212
27943
  jsonStatements.push(...createSchemas);
28213
27944
  jsonStatements.push(...renameSchemas);
28214
27945
  jsonStatements.push(...createEnums);
@@ -28219,10 +27950,13 @@ var init_snapshotsDiffer = __esm({
28219
27950
  jsonStatements.push(...moveSequences);
28220
27951
  jsonStatements.push(...renameSequences);
28221
27952
  jsonStatements.push(...jsonAlterSequences);
27953
+ jsonStatements.push(...renameRoles);
27954
+ jsonStatements.push(...dropRoles);
27955
+ jsonStatements.push(...createRoles);
27956
+ jsonStatements.push(...jsonAlterRoles);
28222
27957
  jsonStatements.push(...createTables);
28223
- jsonStatements.push(...dropViews);
28224
- jsonStatements.push(...renameViews);
28225
- jsonStatements.push(...alterViews);
27958
+ jsonStatements.push(...jsonEnableRLSStatements);
27959
+ jsonStatements.push(...jsonDisableRLSStatements);
28226
27960
  jsonStatements.push(...jsonDropTables);
28227
27961
  jsonStatements.push(...jsonSetTableSchemas);
28228
27962
  jsonStatements.push(...jsonRenameTables);
@@ -28242,7 +27976,10 @@ var init_snapshotsDiffer = __esm({
28242
27976
  jsonStatements.push(...jsonAlteredCompositePKs);
28243
27977
  jsonStatements.push(...jsonAddedUniqueConstraints);
28244
27978
  jsonStatements.push(...jsonAlteredUniqueConstraints);
28245
- jsonStatements.push(...createViews);
27979
+ jsonStatements.push(...jsonRenamePoliciesStatements);
27980
+ jsonStatements.push(...jsonDropPoliciesStatements);
27981
+ jsonStatements.push(...jsonCreatePoliciesStatements);
27982
+ jsonStatements.push(...jsonAlterPoliciesStatements);
28246
27983
  jsonStatements.push(...dropEnums);
28247
27984
  jsonStatements.push(...dropSequences);
28248
27985
  jsonStatements.push(...dropSchemas);
@@ -30506,6 +30243,7 @@ __export(migrate_exports, {
30506
30243
  columnsResolver: () => columnsResolver,
30507
30244
  embeddedMigrations: () => embeddedMigrations,
30508
30245
  enumsResolver: () => enumsResolver,
30246
+ policyResolver: () => policyResolver,
30509
30247
  prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
30510
30248
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
30511
30249
  prepareAndMigratePg: () => prepareAndMigratePg,
@@ -30516,15 +30254,16 @@ __export(migrate_exports, {
30516
30254
  prepareSQLitePush: () => prepareSQLitePush,
30517
30255
  prepareSnapshotFolderName: () => prepareSnapshotFolderName,
30518
30256
  promptColumnsConflicts: () => promptColumnsConflicts,
30257
+ promptNamedConflict: () => promptNamedConflict,
30519
30258
  promptNamedWithSchemasConflict: () => promptNamedWithSchemasConflict,
30520
30259
  promptSchemasConflict: () => promptSchemasConflict,
30260
+ roleResolver: () => roleResolver,
30521
30261
  schemasResolver: () => schemasResolver,
30522
30262
  sequencesResolver: () => sequencesResolver,
30523
30263
  tablesResolver: () => tablesResolver,
30524
- viewsResolver: () => viewsResolver,
30525
30264
  writeResult: () => writeResult
30526
30265
  });
30527
- var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, viewsResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
30266
+ var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, sequencesResolver, roleResolver, policyResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
30528
30267
  var init_migrate = __esm({
30529
30268
  "src/cli/commands/migrate.ts"() {
30530
30269
  "use strict";
@@ -30571,24 +30310,6 @@ var init_migrate = __esm({
30571
30310
  throw e2;
30572
30311
  }
30573
30312
  };
30574
- viewsResolver = async (input) => {
30575
- try {
30576
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
30577
- input.created,
30578
- input.deleted,
30579
- "view"
30580
- );
30581
- return {
30582
- created,
30583
- deleted,
30584
- moved,
30585
- renamed
30586
- };
30587
- } catch (e2) {
30588
- console.error(e2);
30589
- throw e2;
30590
- }
30591
- };
30592
30313
  sequencesResolver = async (input) => {
30593
30314
  try {
30594
30315
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -30607,6 +30328,32 @@ var init_migrate = __esm({
30607
30328
  throw e2;
30608
30329
  }
30609
30330
  };
30331
+ roleResolver = async (input) => {
30332
+ const result = await promptNamedConflict(
30333
+ input.created,
30334
+ input.deleted,
30335
+ "role"
30336
+ );
30337
+ return {
30338
+ created: result.created,
30339
+ deleted: result.deleted,
30340
+ renamed: result.renamed
30341
+ };
30342
+ };
30343
+ policyResolver = async (input) => {
30344
+ const result = await promptColumnsConflicts(
30345
+ input.tableName,
30346
+ input.created,
30347
+ input.deleted
30348
+ );
30349
+ return {
30350
+ tableName: input.tableName,
30351
+ schema: input.schema,
30352
+ created: result.created,
30353
+ deleted: result.deleted,
30354
+ renamed: result.renamed
30355
+ };
30356
+ };
30610
30357
  enumsResolver = async (input) => {
30611
30358
  try {
30612
30359
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -30675,9 +30422,10 @@ var init_migrate = __esm({
30675
30422
  schemasResolver,
30676
30423
  enumsResolver,
30677
30424
  sequencesResolver,
30425
+ policyResolver,
30426
+ roleResolver,
30678
30427
  tablesResolver,
30679
30428
  columnsResolver,
30680
- viewsResolver,
30681
30429
  validatedPrev,
30682
30430
  validatedCur
30683
30431
  );
@@ -30710,9 +30458,10 @@ var init_migrate = __esm({
30710
30458
  schemasResolver,
30711
30459
  enumsResolver,
30712
30460
  sequencesResolver,
30461
+ policyResolver,
30462
+ roleResolver,
30713
30463
  tablesResolver,
30714
30464
  columnsResolver,
30715
- viewsResolver,
30716
30465
  validatedPrev,
30717
30466
  validatedCur,
30718
30467
  "push"
@@ -30991,6 +30740,56 @@ var init_migrate = __esm({
30991
30740
  result.deleted.push(...leftMissing);
30992
30741
  return result;
30993
30742
  };
30743
+ promptNamedConflict = async (newItems, missingItems, entity) => {
30744
+ if (missingItems.length === 0 || newItems.length === 0) {
30745
+ return {
30746
+ created: newItems,
30747
+ renamed: [],
30748
+ deleted: missingItems
30749
+ };
30750
+ }
30751
+ const result = { created: [], renamed: [], deleted: [] };
30752
+ let index4 = 0;
30753
+ let leftMissing = [...missingItems];
30754
+ do {
30755
+ const created = newItems[index4];
30756
+ const renames = leftMissing.map((it) => {
30757
+ return { from: it, to: created };
30758
+ });
30759
+ const promptData = [created, ...renames];
30760
+ const { status, data } = await (0, import_hanji3.render)(
30761
+ new ResolveSelectNamed(created, promptData, entity)
30762
+ );
30763
+ if (status === "aborted") {
30764
+ console.error("ERROR");
30765
+ process.exit(1);
30766
+ }
30767
+ if (isRenamePromptItem(data)) {
30768
+ console.log(
30769
+ `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
30770
+ `${entity} will be renamed/moved`
30771
+ )}`
30772
+ );
30773
+ if (data.from.name !== data.to.name) {
30774
+ result.renamed.push(data);
30775
+ }
30776
+ delete leftMissing[leftMissing.indexOf(data.from)];
30777
+ leftMissing = leftMissing.filter(Boolean);
30778
+ } else {
30779
+ console.log(
30780
+ `${source_default.green("+")} ${data.name} ${source_default.gray(
30781
+ `${entity} will be created`
30782
+ )}`
30783
+ );
30784
+ result.created.push(created);
30785
+ }
30786
+ index4 += 1;
30787
+ } while (index4 < newItems.length);
30788
+ console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
30789
+ `));
30790
+ result.deleted.push(...leftMissing);
30791
+ return result;
30792
+ };
30994
30793
  promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
30995
30794
  if (missingItems.length === 0 || newItems.length === 0) {
30996
30795
  return {
@@ -35534,20 +35333,20 @@ var require_ponyfill_es2018 = __commonJS({
35534
35333
  ;
35535
35334
  ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
35536
35335
  }
35537
- respondWithNewView(view2) {
35336
+ respondWithNewView(view) {
35538
35337
  if (!IsReadableStreamBYOBRequest(this)) {
35539
35338
  throw byobRequestBrandCheckException("respondWithNewView");
35540
35339
  }
35541
- assertRequiredArgument(view2, 1, "respondWithNewView");
35542
- if (!ArrayBuffer.isView(view2)) {
35340
+ assertRequiredArgument(view, 1, "respondWithNewView");
35341
+ if (!ArrayBuffer.isView(view)) {
35543
35342
  throw new TypeError("You can only respond with array buffer views");
35544
35343
  }
35545
35344
  if (this._associatedReadableByteStreamController === void 0) {
35546
35345
  throw new TypeError("This BYOB request has been invalidated");
35547
35346
  }
35548
- if (IsDetachedBuffer(view2.buffer))
35347
+ if (IsDetachedBuffer(view.buffer))
35549
35348
  ;
35550
- ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view2);
35349
+ ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
35551
35350
  }
35552
35351
  }
35553
35352
  Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
@@ -35648,8 +35447,8 @@ var require_ponyfill_es2018 = __commonJS({
35648
35447
  const entry = this._queue.shift();
35649
35448
  this._queueTotalSize -= entry.byteLength;
35650
35449
  ReadableByteStreamControllerHandleQueueDrain(this);
35651
- const view2 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
35652
- readRequest._chunkSteps(view2);
35450
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
35451
+ readRequest._chunkSteps(view);
35653
35452
  return;
35654
35453
  }
35655
35454
  const autoAllocateChunkSize = this._autoAllocateChunkSize;
@@ -35815,19 +35614,19 @@ var require_ponyfill_es2018 = __commonJS({
35815
35614
  }
35816
35615
  }
35817
35616
  }
35818
- function ReadableByteStreamControllerPullInto(controller, view2, readIntoRequest) {
35617
+ function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
35819
35618
  const stream = controller._controlledReadableByteStream;
35820
35619
  let elementSize = 1;
35821
- if (view2.constructor !== DataView) {
35822
- elementSize = view2.constructor.BYTES_PER_ELEMENT;
35620
+ if (view.constructor !== DataView) {
35621
+ elementSize = view.constructor.BYTES_PER_ELEMENT;
35823
35622
  }
35824
- const ctor = view2.constructor;
35825
- const buffer = TransferArrayBuffer(view2.buffer);
35623
+ const ctor = view.constructor;
35624
+ const buffer = TransferArrayBuffer(view.buffer);
35826
35625
  const pullIntoDescriptor = {
35827
35626
  buffer,
35828
35627
  bufferByteLength: buffer.byteLength,
35829
- byteOffset: view2.byteOffset,
35830
- byteLength: view2.byteLength,
35628
+ byteOffset: view.byteOffset,
35629
+ byteLength: view.byteLength,
35831
35630
  bytesFilled: 0,
35832
35631
  elementSize,
35833
35632
  viewConstructor: ctor,
@@ -35995,9 +35794,9 @@ var require_ponyfill_es2018 = __commonJS({
35995
35794
  function ReadableByteStreamControllerGetBYOBRequest(controller) {
35996
35795
  if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
35997
35796
  const firstDescriptor = controller._pendingPullIntos.peek();
35998
- const view2 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
35797
+ const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
35999
35798
  const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
36000
- SetUpReadableStreamBYOBRequest(byobRequest, controller, view2);
35799
+ SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
36001
35800
  controller._byobRequest = byobRequest;
36002
35801
  }
36003
35802
  return controller._byobRequest;
@@ -36030,29 +35829,29 @@ var require_ponyfill_es2018 = __commonJS({
36030
35829
  firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
36031
35830
  ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
36032
35831
  }
36033
- function ReadableByteStreamControllerRespondWithNewView(controller, view2) {
35832
+ function ReadableByteStreamControllerRespondWithNewView(controller, view) {
36034
35833
  const firstDescriptor = controller._pendingPullIntos.peek();
36035
35834
  const state = controller._controlledReadableByteStream._state;
36036
35835
  if (state === "closed") {
36037
- if (view2.byteLength !== 0) {
35836
+ if (view.byteLength !== 0) {
36038
35837
  throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
36039
35838
  }
36040
35839
  } else {
36041
- if (view2.byteLength === 0) {
35840
+ if (view.byteLength === 0) {
36042
35841
  throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
36043
35842
  }
36044
35843
  }
36045
- if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view2.byteOffset) {
35844
+ if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
36046
35845
  throw new RangeError("The region specified by view does not match byobRequest");
36047
35846
  }
36048
- if (firstDescriptor.bufferByteLength !== view2.buffer.byteLength) {
35847
+ if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
36049
35848
  throw new RangeError("The buffer of view has different capacity than byobRequest");
36050
35849
  }
36051
- if (firstDescriptor.bytesFilled + view2.byteLength > firstDescriptor.byteLength) {
35850
+ if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
36052
35851
  throw new RangeError("The region specified by view is larger than byobRequest");
36053
35852
  }
36054
- const viewByteLength = view2.byteLength;
36055
- firstDescriptor.buffer = TransferArrayBuffer(view2.buffer);
35853
+ const viewByteLength = view.byteLength;
35854
+ firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
36056
35855
  ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
36057
35856
  }
36058
35857
  function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
@@ -36098,9 +35897,9 @@ var require_ponyfill_es2018 = __commonJS({
36098
35897
  }
36099
35898
  SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
36100
35899
  }
36101
- function SetUpReadableStreamBYOBRequest(request, controller, view2) {
35900
+ function SetUpReadableStreamBYOBRequest(request, controller, view) {
36102
35901
  request._associatedReadableByteStreamController = controller;
36103
- request._view = view2;
35902
+ request._view = view;
36104
35903
  }
36105
35904
  function byobRequestBrandCheckException(name) {
36106
35905
  return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
@@ -36176,20 +35975,20 @@ var require_ponyfill_es2018 = __commonJS({
36176
35975
  *
36177
35976
  * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
36178
35977
  */
36179
- read(view2) {
35978
+ read(view) {
36180
35979
  if (!IsReadableStreamBYOBReader(this)) {
36181
35980
  return promiseRejectedWith(byobReaderBrandCheckException("read"));
36182
35981
  }
36183
- if (!ArrayBuffer.isView(view2)) {
35982
+ if (!ArrayBuffer.isView(view)) {
36184
35983
  return promiseRejectedWith(new TypeError("view must be an array buffer view"));
36185
35984
  }
36186
- if (view2.byteLength === 0) {
35985
+ if (view.byteLength === 0) {
36187
35986
  return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
36188
35987
  }
36189
- if (view2.buffer.byteLength === 0) {
35988
+ if (view.buffer.byteLength === 0) {
36190
35989
  return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
36191
35990
  }
36192
- if (IsDetachedBuffer(view2.buffer))
35991
+ if (IsDetachedBuffer(view.buffer))
36193
35992
  ;
36194
35993
  if (this._ownerReadableStream === void 0) {
36195
35994
  return promiseRejectedWith(readerLockException("read from"));
@@ -36205,7 +36004,7 @@ var require_ponyfill_es2018 = __commonJS({
36205
36004
  _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
36206
36005
  _errorSteps: (e2) => rejectPromise(e2)
36207
36006
  };
36208
- ReadableStreamBYOBReaderRead(this, view2, readIntoRequest);
36007
+ ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
36209
36008
  return promise;
36210
36009
  }
36211
36010
  /**
@@ -36251,13 +36050,13 @@ var require_ponyfill_es2018 = __commonJS({
36251
36050
  }
36252
36051
  return x2 instanceof ReadableStreamBYOBReader;
36253
36052
  }
36254
- function ReadableStreamBYOBReaderRead(reader, view2, readIntoRequest) {
36053
+ function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
36255
36054
  const stream = reader._ownerReadableStream;
36256
36055
  stream._disturbed = true;
36257
36056
  if (stream._state === "errored") {
36258
36057
  readIntoRequest._errorSteps(stream._storedError);
36259
36058
  } else {
36260
- ReadableByteStreamControllerPullInto(stream._readableStreamController, view2, readIntoRequest);
36059
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
36261
36060
  }
36262
36061
  }
36263
36062
  function byobReaderBrandCheckException(name) {
@@ -37806,7 +37605,7 @@ var require_ponyfill_es2018 = __commonJS({
37806
37605
  };
37807
37606
  ReadableStreamDefaultReaderRead(reader, readRequest);
37808
37607
  }
37809
- function pullWithBYOBReader(view2, forBranch2) {
37608
+ function pullWithBYOBReader(view, forBranch2) {
37810
37609
  if (IsReadableStreamDefaultReader(reader)) {
37811
37610
  ReadableStreamReaderGenericRelease(reader);
37812
37611
  reader = AcquireReadableStreamBYOBReader(stream);
@@ -37872,7 +37671,7 @@ var require_ponyfill_es2018 = __commonJS({
37872
37671
  reading = false;
37873
37672
  }
37874
37673
  };
37875
- ReadableStreamBYOBReaderRead(reader, view2, readIntoRequest);
37674
+ ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
37876
37675
  }
37877
37676
  function pull1Algorithm() {
37878
37677
  if (reading) {
@@ -39819,9 +39618,9 @@ var init_body2 = __esm({
39819
39618
  // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
39820
39619
  function fromRawHeaders(headers = []) {
39821
39620
  return new Headers2(
39822
- headers.reduce((result, value, index4, array) => {
39621
+ headers.reduce((result, value, index4, array2) => {
39823
39622
  if (index4 % 2 === 0) {
39824
- result.push(array.slice(index4, index4 + 2));
39623
+ result.push(array2.slice(index4, index4 + 2));
39825
39624
  }
39826
39625
  return result;
39827
39626
  }, []).filter(([name, value]) => {
@@ -40219,7 +40018,7 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
40219
40018
  if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
40220
40019
  return null;
40221
40020
  }
40222
- const policy = request.referrerPolicy;
40021
+ const policy2 = request.referrerPolicy;
40223
40022
  if (request.referrer === "about:client") {
40224
40023
  return "no-referrer";
40225
40024
  }
@@ -40236,7 +40035,7 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
40236
40035
  referrerOrigin = referrerOriginCallback(referrerOrigin);
40237
40036
  }
40238
40037
  const currentURL = new URL(request.url);
40239
- switch (policy) {
40038
+ switch (policy2) {
40240
40039
  case "no-referrer":
40241
40040
  return "no-referrer";
40242
40041
  case "origin":
@@ -40272,18 +40071,18 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
40272
40071
  }
40273
40072
  return referrerURL;
40274
40073
  default:
40275
- throw new TypeError(`Invalid referrerPolicy: ${policy}`);
40074
+ throw new TypeError(`Invalid referrerPolicy: ${policy2}`);
40276
40075
  }
40277
40076
  }
40278
40077
  function parseReferrerPolicyFromHeader(headers) {
40279
40078
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
40280
- let policy = "";
40079
+ let policy2 = "";
40281
40080
  for (const token of policyTokens) {
40282
40081
  if (token && ReferrerPolicy.has(token)) {
40283
- policy = token;
40082
+ policy2 = token;
40284
40083
  }
40285
40084
  }
40286
- return policy;
40085
+ return policy2;
40287
40086
  }
40288
40087
  var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY;
40289
40088
  var init_referrer = __esm({
@@ -52731,15 +52530,15 @@ var require_dist_cjs36 = __commonJS({
52731
52530
  throw new Error("Int64 buffers must be exactly 8 bytes");
52732
52531
  }
52733
52532
  }
52734
- static fromNumber(number2) {
52735
- if (number2 > 9223372036854776e3 || number2 < -9223372036854776e3) {
52736
- throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`);
52533
+ static fromNumber(number3) {
52534
+ if (number3 > 9223372036854776e3 || number3 < -9223372036854776e3) {
52535
+ throw new Error(`${number3} is too large (or, if negative, too small) to represent as an Int64`);
52737
52536
  }
52738
52537
  const bytes = new Uint8Array(8);
52739
- for (let i2 = 7, remaining = Math.abs(Math.round(number2)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
52538
+ for (let i2 = 7, remaining = Math.abs(Math.round(number3)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
52740
52539
  bytes[i2] = remaining;
52741
52540
  }
52742
- if (number2 < 0) {
52541
+ if (number3 < 0) {
52743
52542
  negate(bytes);
52744
52543
  }
52745
52544
  return new _Int642(bytes);
@@ -60930,7 +60729,7 @@ var require_fromWebToken = __commonJS({
60930
60729
  var fromWebToken2 = (init2) => async () => {
60931
60730
  var _a;
60932
60731
  (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-web-identity", "fromWebToken");
60933
- const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init2;
60732
+ const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy2, durationSeconds } = init2;
60934
60733
  let { roleAssumerWithWebIdentity } = init2;
60935
60734
  if (!roleAssumerWithWebIdentity) {
60936
60735
  const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar2(require_dist_cjs50()));
@@ -60946,7 +60745,7 @@ var require_fromWebToken = __commonJS({
60946
60745
  WebIdentityToken: webIdentityToken,
60947
60746
  ProviderId: providerId,
60948
60747
  PolicyArns: policyArns,
60949
- Policy: policy,
60748
+ Policy: policy2,
60950
60749
  DurationSeconds: durationSeconds
60951
60750
  });
60952
60751
  };
@@ -64170,16 +63969,16 @@ var require_map_stream = __commonJS({
64170
63969
  var writeQueue = {};
64171
63970
  stream.writable = true;
64172
63971
  stream.readable = true;
64173
- function queueData(data, number2) {
63972
+ function queueData(data, number3) {
64174
63973
  var nextToWrite = lastWritten + 1;
64175
- if (number2 === nextToWrite) {
63974
+ if (number3 === nextToWrite) {
64176
63975
  if (data !== void 0) {
64177
63976
  stream.emit.apply(stream, ["data", data]);
64178
63977
  }
64179
63978
  lastWritten++;
64180
63979
  nextToWrite++;
64181
63980
  } else {
64182
- writeQueue[number2] = data;
63981
+ writeQueue[number3] = data;
64183
63982
  }
64184
63983
  if (writeQueue.hasOwnProperty(nextToWrite)) {
64185
63984
  var dataToWrite = writeQueue[nextToWrite];
@@ -64194,21 +63993,21 @@ var require_map_stream = __commonJS({
64194
63993
  end();
64195
63994
  }
64196
63995
  }
64197
- function next(err2, data, number2) {
63996
+ function next(err2, data, number3) {
64198
63997
  if (destroyed)
64199
63998
  return;
64200
63999
  inNext = true;
64201
64000
  if (!err2 || self2.opts.failures) {
64202
- queueData(data, number2);
64001
+ queueData(data, number3);
64203
64002
  }
64204
64003
  if (err2) {
64205
64004
  stream.emit.apply(stream, [errorEventName, err2]);
64206
64005
  }
64207
64006
  inNext = false;
64208
64007
  }
64209
- function wrappedMapper(input, number2, callback) {
64008
+ function wrappedMapper(input, number3, callback) {
64210
64009
  return mapper.call(null, input, function(err2, data) {
64211
- callback(err2, data, number2);
64010
+ callback(err2, data, number3);
64212
64011
  });
64213
64012
  }
64214
64013
  stream.write = function(data) {
@@ -64410,13 +64209,13 @@ var require_event_stream = __commonJS({
64410
64209
  es.writeArray = function(done) {
64411
64210
  if ("function" !== typeof done)
64412
64211
  throw new Error("function writeArray (done): done must be function");
64413
- var a = new Stream3(), array = [], isDone = false;
64212
+ var a = new Stream3(), array2 = [], isDone = false;
64414
64213
  a.write = function(l) {
64415
- array.push(l);
64214
+ array2.push(l);
64416
64215
  };
64417
64216
  a.end = function() {
64418
64217
  isDone = true;
64419
- done(null, array);
64218
+ done(null, array2);
64420
64219
  };
64421
64220
  a.writable = true;
64422
64221
  a.readable = false;
@@ -64424,23 +64223,23 @@ var require_event_stream = __commonJS({
64424
64223
  a.writable = a.readable = false;
64425
64224
  if (isDone)
64426
64225
  return;
64427
- done(new Error("destroyed before end"), array);
64226
+ done(new Error("destroyed before end"), array2);
64428
64227
  };
64429
64228
  return a;
64430
64229
  };
64431
- es.readArray = function(array) {
64230
+ es.readArray = function(array2) {
64432
64231
  var stream = new Stream3(), i2 = 0, paused = false, ended = false;
64433
64232
  stream.readable = true;
64434
64233
  stream.writable = false;
64435
- if (!Array.isArray(array))
64234
+ if (!Array.isArray(array2))
64436
64235
  throw new Error("event-stream.read expects an array");
64437
64236
  stream.resume = function() {
64438
64237
  if (ended)
64439
64238
  return;
64440
64239
  paused = false;
64441
- var l = array.length;
64240
+ var l = array2.length;
64442
64241
  while (i2 < l && !paused && !ended) {
64443
- stream.emit("data", array[i2++]);
64242
+ stream.emit("data", array2[i2++]);
64444
64243
  }
64445
64244
  if (i2 == l && !ended)
64446
64245
  ended = true, stream.readable = false, stream.emit("end");
@@ -68065,8 +67864,8 @@ var require_utils4 = __commonJS({
68065
67864
  "use strict";
68066
67865
  Object.defineProperty(exports2, "__esModule", { value: true });
68067
67866
  exports2.string = exports2.stream = exports2.pattern = exports2.path = exports2.fs = exports2.errno = exports2.array = void 0;
68068
- var array = require_array();
68069
- exports2.array = array;
67867
+ var array2 = require_array();
67868
+ exports2.array = array2;
68070
67869
  var errno = require_errno();
68071
67870
  exports2.errno = errno;
68072
67871
  var fs9 = require_fs2();
@@ -78040,7 +77839,7 @@ var init_selector_ui = __esm({
78040
77839
  });
78041
77840
 
78042
77841
  // src/cli/commands/libSqlPushUtils.ts
78043
- var getOldTableName2, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
77842
+ var getOldTableName3, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
78044
77843
  var init_libSqlPushUtils = __esm({
78045
77844
  "src/cli/commands/libSqlPushUtils.ts"() {
78046
77845
  "use strict";
@@ -78048,7 +77847,7 @@ var init_libSqlPushUtils = __esm({
78048
77847
  init_utils();
78049
77848
  init_sqliteSchema();
78050
77849
  init_sqlgenerator();
78051
- getOldTableName2 = (tableName, meta) => {
77850
+ getOldTableName3 = (tableName, meta) => {
78052
77851
  for (const key of Object.keys(meta.tables)) {
78053
77852
  const value = meta.tables[key];
78054
77853
  if (`"${tableName}"` === value) {
@@ -78203,7 +78002,7 @@ var init_libSqlPushUtils = __esm({
78203
78002
  } else if (statement.type === "recreate_table") {
78204
78003
  const tableName = statement.tableName;
78205
78004
  let dataLoss = false;
78206
- const oldTableName = getOldTableName2(tableName, meta);
78005
+ const oldTableName = getOldTableName3(tableName, meta);
78207
78006
  const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
78208
78007
  const currentColumnNames = Object.keys(json2.tables[tableName].columns);
78209
78008
  const { removedColumns, addedColumns } = findAddedAndRemoved(
@@ -79924,7 +79723,7 @@ var init_pgIntrospect = __esm({
79924
79723
  init_global();
79925
79724
  init_pgSerializer();
79926
79725
  init_views();
79927
- pgPushIntrospect = async (db, filters, schemaFilters) => {
79726
+ pgPushIntrospect = async (db, filters, schemaFilters, entities = { roles: true }) => {
79928
79727
  const matchers = filters.map((it) => {
79929
79728
  return new Minimatch(it);
79930
79729
  });
@@ -79953,7 +79752,7 @@ var init_pgIntrospect = __esm({
79953
79752
  );
79954
79753
  const res = await (0, import_hanji9.renderWithTask)(
79955
79754
  progress,
79956
- fromDatabase2(db, filter2, schemaFilters)
79755
+ fromDatabase2(db, filter2, schemaFilters, entities)
79957
79756
  );
79958
79757
  const schema5 = { id: originUUID, prevId: "", ...res };
79959
79758
  const { internal, ...schemaWithoutInternals } = schema5;
@@ -80488,11 +80287,11 @@ var init_push = __esm({
80488
80287
  console.log(e2);
80489
80288
  }
80490
80289
  };
80491
- pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, force) => {
80290
+ pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, entities, force) => {
80492
80291
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
80493
80292
  const { pgPushIntrospect: pgPushIntrospect2 } = await Promise.resolve().then(() => (init_pgIntrospect(), pgIntrospect_exports));
80494
80293
  const db = await preparePostgresDB2(credentials2);
80495
- const { schema: schema5 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter);
80294
+ const { schema: schema5 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter, entities);
80496
80295
  const { preparePgPush: preparePgPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
80497
80296
  const statements = await preparePgPush2(schemaPath, schema5, schemasFilter);
80498
80297
  try {
@@ -81677,7 +81476,7 @@ function generateIdentityParams(identity) {
81677
81476
  }
81678
81477
  return `.generatedByDefaultAsIdentity(${paramsObj})`;
81679
81478
  }
81680
- var import_drizzle_orm9, import_relations, import_casing3, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, dbColumnName3, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
81479
+ var import_drizzle_orm9, import_relations, import_casing3, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, dbColumnName3, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTablePolicies, createTableUniques3, createTableFKs3;
81681
81480
  var init_introspect_pg = __esm({
81682
81481
  "src/introspect-pg.ts"() {
81683
81482
  "use strict";
@@ -81855,6 +81654,9 @@ var init_introspect_pg = __esm({
81855
81654
  const uniqueImports = Object.values(it.uniqueConstraints).map(
81856
81655
  (it2) => "unique"
81857
81656
  );
81657
+ const policiesImports = Object.values(it.policies).map(
81658
+ (it2) => "pgPolicy"
81659
+ );
81858
81660
  if (it.schema && it.schema !== "public" && it.schema !== "") {
81859
81661
  res.pg.push("pgSchema");
81860
81662
  }
@@ -81862,6 +81664,7 @@ var init_introspect_pg = __esm({
81862
81664
  res.pg.push(...fkImpots);
81863
81665
  res.pg.push(...pkImports);
81864
81666
  res.pg.push(...uniqueImports);
81667
+ res.pg.push(...policiesImports);
81865
81668
  const columnImports = Object.values(it.columns).map((col) => {
81866
81669
  let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
81867
81670
  patched = patched === "double precision" ? "doublePrecision" : patched;
@@ -81881,30 +81684,6 @@ var init_introspect_pg = __esm({
81881
81684
  },
81882
81685
  { pg: [] }
81883
81686
  );
81884
- Object.values(schema5.views).forEach((it) => {
81885
- if (it.schema && it.schema !== "public" && it.schema !== "") {
81886
- imports.pg.push("pgSchema");
81887
- } else if (it.schema === "public") {
81888
- it.materialized ? imports.pg.push("pgMaterializedView") : imports.pg.push("pgView");
81889
- }
81890
- Object.values(it.columns).forEach(() => {
81891
- const columnImports = Object.values(it.columns).map((col) => {
81892
- let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
81893
- patched = patched === "double precision" ? "doublePrecision" : patched;
81894
- patched = patched.startsWith("varchar(") ? "varchar" : patched;
81895
- patched = patched.startsWith("char(") ? "char" : patched;
81896
- patched = patched.startsWith("numeric(") ? "numeric" : patched;
81897
- patched = patched.startsWith("time(") ? "time" : patched;
81898
- patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
81899
- patched = patched.startsWith("vector(") ? "vector" : patched;
81900
- patched = patched.startsWith("geometry(") ? "geometry" : patched;
81901
- return patched;
81902
- }).filter((type) => {
81903
- return pgImportsList.has(type);
81904
- });
81905
- imports.pg.push(...columnImports);
81906
- });
81907
- });
81908
81687
  Object.values(schema5.sequences).forEach((it) => {
81909
81688
  if (it.schema && it.schema !== "public" && it.schema !== "") {
81910
81689
  imports.pg.push("pgSchema");
@@ -81919,6 +81698,9 @@ var init_introspect_pg = __esm({
81919
81698
  imports.pg.push("pgEnum");
81920
81699
  }
81921
81700
  });
81701
+ if (Object.keys(schema5.roles).length > 0) {
81702
+ imports.pg.push("pgRole");
81703
+ }
81922
81704
  const enumStatements = Object.values(schema5.enums).map((it) => {
81923
81705
  const enumSchema3 = schemas[it.schema];
81924
81706
  const paramName = paramNameFor(it.name, enumSchema3);
@@ -81954,9 +81736,16 @@ var init_introspect_pg = __esm({
81954
81736
  }
81955
81737
  return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
81956
81738
  `;
81957
- }).join("").concat("\n");
81739
+ }).join("").concat("");
81958
81740
  const schemaStatements = Object.entries(schemas).map((it) => {
81959
81741
  return `export const ${it[1]} = pgSchema("${it[0]}");
81742
+ `;
81743
+ }).join("");
81744
+ const rolesNameToTsKey = {};
81745
+ const rolesStatements = Object.entries(schema5.roles).map((it) => {
81746
+ const fields = it[1];
81747
+ rolesNameToTsKey[fields.name] = it[0];
81748
+ return `export const ${withCasing2(it[0], casing2)} = pgRole("${fields.name}", ${!fields.createDb && !fields.createRole && fields.inherit ? "" : `${`, { ${fields.createDb ? `createDb: true,` : ""}${fields.createRole ? ` createRole: true,` : ""}${!fields.inherit ? ` inherit: false ` : ""}`.trimChar(",")}}`} );
81960
81749
  `;
81961
81750
  }).join("");
81962
81751
  const tableStatements = Object.values(schema5.tables).map((table4) => {
@@ -81975,8 +81764,8 @@ var init_introspect_pg = __esm({
81975
81764
  schema5.internal
81976
81765
  );
81977
81766
  statement += "}";
81978
- if (Object.keys(table4.indexes).length > 0 || Object.values(table4.foreignKeys).length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
81979
- statement += ",\n";
81767
+ if (Object.keys(table4.indexes).length > 0 || Object.values(table4.foreignKeys).length > 0 || Object.values(table4.policies).length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
81768
+ statement += ", ";
81980
81769
  statement += "(table) => {\n";
81981
81770
  statement += " return {\n";
81982
81771
  statement += createTableIndexes3(
@@ -81993,48 +81782,29 @@ var init_introspect_pg = __esm({
81993
81782
  Object.values(table4.uniqueConstraints),
81994
81783
  casing2
81995
81784
  );
81785
+ statement += createTablePolicies(
81786
+ Object.values(table4.policies),
81787
+ casing2,
81788
+ rolesNameToTsKey
81789
+ );
81996
81790
  statement += " }\n";
81997
81791
  statement += "}";
81998
81792
  }
81999
81793
  statement += ");";
82000
81794
  return statement;
82001
81795
  });
82002
- const viewsStatements = Object.values(schema5.views).map((it) => {
82003
- const viewSchema = schemas[it.schema];
82004
- const paramName = paramNameFor(it.name, viewSchema);
82005
- const func = viewSchema ? it.materialized ? `${viewSchema}.materializedView` : `${viewSchema}.view` : it.materialized ? "pgMaterializedView" : "pgView";
82006
- const withOption = it.with ?? "";
82007
- const as = `sql\`${it.definition}\``;
82008
- const tablespace = it.tablespace ?? "";
82009
- const columns = createTableColumns3(
82010
- "",
82011
- Object.values(it.columns),
82012
- [],
82013
- enumTypes,
82014
- schemas,
82015
- casing2,
82016
- schema5.internal
82017
- );
82018
- let statement = `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", {${columns}})`;
82019
- statement += tablespace ? `.tablespace("${tablespace}")` : "";
82020
- statement += withOption ? `.with(${JSON.stringify(withOption)})` : "";
82021
- statement += `.as(${as});`;
82022
- return statement;
82023
- }).join("\n\n");
82024
81796
  const uniquePgImports = ["pgTable", ...new Set(imports.pg)];
82025
81797
  const importsTs = `import { ${uniquePgImports.join(
82026
81798
  ", "
82027
81799
  )} } from "drizzle-orm/pg-core"
82028
- import { sql } from "drizzle-orm"
81800
+ import { sql } from "drizzle-orm"
82029
81801
 
82030
81802
  `;
82031
81803
  let decalrations = schemaStatements;
81804
+ decalrations += rolesStatements;
82032
81805
  decalrations += enumStatements;
82033
81806
  decalrations += sequencesStatements;
82034
- decalrations += "\n";
82035
- decalrations += tableStatements.join("\n\n");
82036
- decalrations += "\n";
82037
- decalrations += viewsStatements;
81807
+ decalrations += tableStatements.join("\n");
82038
81808
  const file = importsTs + decalrations;
82039
81809
  const schemaEntry = `
82040
81810
  {
@@ -82465,6 +82235,23 @@ var init_introspect_pg = __esm({
82465
82235
  }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
82466
82236
  statement += ")";
82467
82237
  statement += `,
82238
+ `;
82239
+ });
82240
+ return statement;
82241
+ };
82242
+ createTablePolicies = (policies, casing2, rolesNameToTsKey = {}) => {
82243
+ let statement = "";
82244
+ policies.forEach((it) => {
82245
+ var _a, _b, _c;
82246
+ const idxKey = withCasing2(it.name, casing2);
82247
+ const mappedItTo = (_a = it.to) == null ? void 0 : _a.map((v) => {
82248
+ return rolesNameToTsKey[v] ? withCasing2(rolesNameToTsKey[v], casing2) : `"${v}"`;
82249
+ });
82250
+ statement += ` ${idxKey}: `;
82251
+ statement += "pgPolicy(";
82252
+ statement += `"${it.name}", { `;
82253
+ statement += `as: "${(_b = it.as) == null ? void 0 : _b.toLowerCase()}", for: "${(_c = it.for) == null ? void 0 : _c.toLowerCase()}", to: [${mappedItTo == null ? void 0 : mappedItTo.join(", ")}]${it.using ? `, using: sql\`${it.using}\`` : ""}${it.withCheck ? `, withCheck: sql\`${it.withCheck}\` ` : ""}`;
82254
+ statement += ` }),
82468
82255
  `;
82469
82256
  });
82470
82257
  return statement;
@@ -82542,7 +82329,7 @@ var init_introspect = __esm({
82542
82329
  init_utils();
82543
82330
  init_views();
82544
82331
  init_migrate();
82545
- introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2) => {
82332
+ introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
82546
82333
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
82547
82334
  const db = await preparePostgresDB2(credentials2);
82548
82335
  const matchers = tablesFilter.map((it) => {
@@ -82570,9 +82357,15 @@ var init_introspect = __esm({
82570
82357
  const progress = new IntrospectProgress(true);
82571
82358
  const res = await (0, import_hanji12.renderWithTask)(
82572
82359
  progress,
82573
- fromDatabase2(db, filter2, schemasFilter, (stage, count, status) => {
82574
- progress.update(stage, count, status);
82575
- })
82360
+ fromDatabase2(
82361
+ db,
82362
+ filter2,
82363
+ schemasFilter,
82364
+ entities,
82365
+ (stage, count, status) => {
82366
+ progress.update(stage, count, status);
82367
+ }
82368
+ )
82576
82369
  );
82577
82370
  const schema5 = { id: originUUID, prevId: "", ...res };
82578
82371
  const ts = schemaToTypeScript3(schema5, casing2);
@@ -82591,9 +82384,9 @@ var init_introspect = __esm({
82591
82384
  schemasResolver,
82592
82385
  enumsResolver,
82593
82386
  sequencesResolver,
82387
+ policyResolver,
82594
82388
  tablesResolver,
82595
82389
  columnsResolver,
82596
- viewsResolver,
82597
82390
  dryPg,
82598
82391
  schema5
82599
82392
  );
@@ -86105,7 +85898,8 @@ var pull = command({
86105
85898
  breakpoints,
86106
85899
  tablesFilter,
86107
85900
  schemasFilter,
86108
- prefix: prefix2
85901
+ prefix: prefix2,
85902
+ entities
86109
85903
  } = config;
86110
85904
  (0, import_fs13.mkdirSync)(out, { recursive: true });
86111
85905
  console.log(
@@ -86144,7 +85938,8 @@ var pull = command({
86144
85938
  credentials2,
86145
85939
  tablesFilter,
86146
85940
  schemasFilter,
86147
- prefix2
85941
+ prefix2,
85942
+ entities
86148
85943
  );
86149
85944
  } else if (dialect7 === "mysql") {
86150
85945
  const { introspectMysql: introspectMysql2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
@@ -86315,7 +86110,7 @@ init_utils2();
86315
86110
  var version2 = async () => {
86316
86111
  const { npmVersion } = await ormCoreVersions();
86317
86112
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
86318
- const envVersion = "0.25.0-a5a41e0";
86113
+ const envVersion = "0.25.0-b75016b";
86319
86114
  const kitVersion = envVersion ? `v${envVersion}` : "--";
86320
86115
  const versions = `drizzle-kit: ${kitVersion}
86321
86116
  ${ormVersion}`;