drizzle-kit 0.24.2-218cddb → 0.24.2-277e6de

Sign up to get free protection for your applications and to get access to all the features.
package/bin.cjs CHANGED
@@ -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, 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,6 +5954,14 @@ var init_pgSchema = __esm({
5901
5954
  columns: stringType().array(),
5902
5955
  nullsNotDistinct: booleanType()
5903
5956
  }).strict();
5957
+ policy = objectType({
5958
+ name: stringType(),
5959
+ as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
5960
+ for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
5961
+ to: stringType().array().optional(),
5962
+ using: stringType().optional(),
5963
+ withCheck: stringType().optional()
5964
+ }).strict();
5904
5965
  tableV42 = objectType({
5905
5966
  name: stringType(),
5906
5967
  schema: stringType(),
@@ -5942,7 +6003,8 @@ var init_pgSchema = __esm({
5942
6003
  indexes: recordType(stringType(), index2),
5943
6004
  foreignKeys: recordType(stringType(), fk2),
5944
6005
  compositePrimaryKeys: recordType(stringType(), compositePK2),
5945
- uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
6006
+ uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
6007
+ policies: recordType(stringType(), policy).default({})
5946
6008
  }).strict();
5947
6009
  schemaHash2 = objectType({
5948
6010
  id: stringType(),
@@ -6036,6 +6098,7 @@ var init_pgSchema = __esm({
6036
6098
  enums: recordType(stringType(), enumSchema),
6037
6099
  schemas: recordType(stringType(), stringType()),
6038
6100
  sequences: recordType(stringType(), sequenceSchema).default({}),
6101
+ roles: recordType(stringType(), roleSchema).default({}),
6039
6102
  _meta: objectType({
6040
6103
  schemas: recordType(stringType(), stringType()),
6041
6104
  tables: recordType(stringType(), stringType()),
@@ -6050,7 +6113,8 @@ var init_pgSchema = __esm({
6050
6113
  indexes: recordType(stringType(), stringType()),
6051
6114
  foreignKeys: recordType(stringType(), stringType()),
6052
6115
  compositePrimaryKeys: recordType(stringType(), stringType()),
6053
- uniqueConstraints: recordType(stringType(), stringType())
6116
+ uniqueConstraints: recordType(stringType(), stringType()),
6117
+ policies: recordType(stringType(), stringType())
6054
6118
  }).strict();
6055
6119
  tableSquashedV42 = objectType({
6056
6120
  name: stringType(),
@@ -6079,7 +6143,8 @@ var init_pgSchema = __esm({
6079
6143
  tables: recordType(stringType(), tableSquashed2),
6080
6144
  enums: recordType(stringType(), enumSchema),
6081
6145
  schemas: recordType(stringType(), stringType()),
6082
- sequences: recordType(stringType(), sequenceSquashed)
6146
+ sequences: recordType(stringType(), sequenceSquashed),
6147
+ roles: recordType(stringType(), roleSchema).default({})
6083
6148
  }).strict();
6084
6149
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
6085
6150
  pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
@@ -6162,6 +6227,25 @@ var init_pgSchema = __esm({
6162
6227
  squashFK: (fk4) => {
6163
6228
  return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""};${fk4.schemaTo || "public"}`;
6164
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
+ },
6165
6249
  squashPK: (pk) => {
6166
6250
  return `${pk.columns.join(",")};${pk.name}`;
6167
6251
  },
@@ -6264,6 +6348,9 @@ var init_pgSchema = __esm({
6264
6348
  return PgSquasher.squashUnique(unq);
6265
6349
  }
6266
6350
  );
6351
+ const squashedPolicies = mapValues(it[1].policies, (policy2) => {
6352
+ return action === "push" ? PgSquasher.squashPolicyPush(policy2) : PgSquasher.squashPolicy(policy2);
6353
+ });
6267
6354
  return [
6268
6355
  it[0],
6269
6356
  {
@@ -6273,7 +6360,8 @@ var init_pgSchema = __esm({
6273
6360
  indexes: squashedIndexes,
6274
6361
  foreignKeys: squashedFKs,
6275
6362
  compositePrimaryKeys: squashedPKs,
6276
- uniqueConstraints: squashedUniqueConstraints
6363
+ uniqueConstraints: squashedUniqueConstraints,
6364
+ policies: squashedPolicies
6277
6365
  }
6278
6366
  ];
6279
6367
  })
@@ -6296,7 +6384,8 @@ var init_pgSchema = __esm({
6296
6384
  tables: mappedTables,
6297
6385
  enums: json.enums,
6298
6386
  schemas: json.schemas,
6299
- sequences: mappedSequences
6387
+ sequences: mappedSequences,
6388
+ roles: json.roles
6300
6389
  };
6301
6390
  };
6302
6391
  dryPg = pgSchema.parse({
@@ -10590,10 +10679,10 @@ var require_inflight = __commonJS({
10590
10679
  }
10591
10680
  function slice(args) {
10592
10681
  var length = args.length;
10593
- var array = [];
10682
+ var array2 = [];
10594
10683
  for (var i2 = 0; i2 < length; i2++)
10595
- array[i2] = args[i2];
10596
- return array;
10684
+ array2[i2] = args[i2];
10685
+ return array2;
10597
10686
  }
10598
10687
  }
10599
10688
  });
@@ -11412,6 +11501,13 @@ var init_cli = __esm({
11412
11501
  breakpoints: booleanType().optional().default(true),
11413
11502
  migrations: objectType({
11414
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)
11415
11511
  }).optional()
11416
11512
  }).passthrough();
11417
11513
  configCheck = objectType({
@@ -17594,7 +17690,8 @@ var init_utils4 = __esm({
17594
17690
  credentials: parsed2.data,
17595
17691
  tablesFilter,
17596
17692
  schemasFilter,
17597
- 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
17598
17695
  };
17599
17696
  }
17600
17697
  if (dialect7 === "mysql") {
@@ -17611,7 +17708,8 @@ var init_utils4 = __esm({
17611
17708
  credentials: parsed2.data,
17612
17709
  tablesFilter,
17613
17710
  schemasFilter,
17614
- 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
17615
17713
  };
17616
17714
  }
17617
17715
  if (dialect7 === "sqlite") {
@@ -17628,7 +17726,8 @@ var init_utils4 = __esm({
17628
17726
  credentials: parsed2.data,
17629
17727
  tablesFilter,
17630
17728
  schemasFilter,
17631
- 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
17632
17731
  };
17633
17732
  }
17634
17733
  if (dialect7 === "turso") {
@@ -18464,6 +18563,7 @@ var init_pgImports = __esm({
18464
18563
  const enums = [];
18465
18564
  const schemas = [];
18466
18565
  const sequences = [];
18566
+ const roles = [];
18467
18567
  const i0values = Object.values(exports2);
18468
18568
  i0values.forEach((t2) => {
18469
18569
  if ((0, import_pg_core.isPgEnum)(t2)) {
@@ -18479,14 +18579,18 @@ var init_pgImports = __esm({
18479
18579
  if ((0, import_pg_core.isPgSequence)(t2)) {
18480
18580
  sequences.push(t2);
18481
18581
  }
18582
+ if ((0, import_drizzle_orm4.is)(t2, import_pg_core.PgRole)) {
18583
+ roles.push(t2);
18584
+ }
18482
18585
  });
18483
- return { tables, enums, schemas, sequences };
18586
+ return { tables, enums, schemas, sequences, roles };
18484
18587
  };
18485
18588
  prepareFromPgImports = async (imports) => {
18486
18589
  let tables = [];
18487
18590
  let enums = [];
18488
18591
  let schemas = [];
18489
18592
  let sequences = [];
18593
+ let roles = [];
18490
18594
  const { unregister } = await safeRegister();
18491
18595
  for (let i2 = 0; i2 < imports.length; i2++) {
18492
18596
  const it = imports[i2];
@@ -18496,9 +18600,10 @@ var init_pgImports = __esm({
18496
18600
  enums.push(...prepared.enums);
18497
18601
  schemas.push(...prepared.schemas);
18498
18602
  sequences.push(...prepared.sequences);
18603
+ roles.push(...prepared.roles);
18499
18604
  }
18500
18605
  unregister();
18501
- return { tables: Array.from(new Set(tables)), enums, schemas, sequences };
18606
+ return { tables: Array.from(new Set(tables)), enums, schemas, sequences, roles };
18502
18607
  };
18503
18608
  }
18504
18609
  });
@@ -18506,9 +18611,11 @@ var init_pgImports = __esm({
18506
18611
  // src/serializer/pgSerializer.ts
18507
18612
  var pgSerializer_exports = {};
18508
18613
  __export(pgSerializer_exports, {
18614
+ buildArrayString: () => buildArrayString,
18509
18615
  fromDatabase: () => fromDatabase2,
18510
18616
  generatePgSnapshot: () => generatePgSnapshot,
18511
- indexName: () => indexName2
18617
+ indexName: () => indexName2,
18618
+ minRangeForIdentityBasedOn: () => minRangeForIdentityBasedOn
18512
18619
  });
18513
18620
  function stringFromIdentityProperty(field) {
18514
18621
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
@@ -18522,9 +18629,9 @@ function minRangeForIdentityBasedOn(columnType) {
18522
18629
  function stringFromDatabaseIdentityProperty(field) {
18523
18630
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
18524
18631
  }
18525
- function buildArrayString(array, sqlType) {
18632
+ function buildArrayString(array2, sqlType) {
18526
18633
  sqlType = sqlType.split("[")[0];
18527
- const values = array.map((value) => {
18634
+ const values = array2.map((value) => {
18528
18635
  if (typeof value === "number" || typeof value === "bigint") {
18529
18636
  return value.toString();
18530
18637
  } else if (typeof value === "boolean") {
@@ -18546,6 +18653,40 @@ function buildArrayString(array, sqlType) {
18546
18653
  }).join(",");
18547
18654
  return `{${values}}`;
18548
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
+ }
18549
18690
  var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn;
18550
18691
  var init_pgSerializer = __esm({
18551
18692
  "src/serializer/pgSerializer.ts"() {
@@ -18562,10 +18703,11 @@ var init_pgSerializer = __esm({
18562
18703
  indexName2 = (tableName, columns) => {
18563
18704
  return `${tableName}_${columns.join("_")}_index`;
18564
18705
  };
18565
- generatePgSnapshot = (tables, enums, schemas, sequences, schemaFilter) => {
18706
+ generatePgSnapshot = (tables, enums, schemas, sequences, roles, schemaFilter) => {
18566
18707
  var _a, _b, _c, _d, _e, _f;
18567
18708
  const result = {};
18568
18709
  const sequencesToReturn = {};
18710
+ const rolesToReturn = {};
18569
18711
  const indexesInSchema = {};
18570
18712
  for (const table4 of tables) {
18571
18713
  const {
@@ -18576,7 +18718,8 @@ var init_pgSerializer = __esm({
18576
18718
  checks,
18577
18719
  schema: schema5,
18578
18720
  primaryKeys,
18579
- uniqueConstraints
18721
+ uniqueConstraints,
18722
+ policies
18580
18723
  } = (0, import_pg_core3.getTableConfig)(table4);
18581
18724
  if (schemaFilter && !schemaFilter.includes(schema5 ?? "public")) {
18582
18725
  continue;
@@ -18586,6 +18729,7 @@ var init_pgSerializer = __esm({
18586
18729
  const foreignKeysObject = {};
18587
18730
  const primaryKeysObject = {};
18588
18731
  const uniqueConstraintObject = {};
18732
+ const policiesObject = {};
18589
18733
  columns.forEach((column7) => {
18590
18734
  var _a2, _b2, _c2, _d2, _e2, _f2;
18591
18735
  const notNull = column7.notNull;
@@ -18831,6 +18975,35 @@ ${withStyle.errorWarning(
18831
18975
  with: value.config.with ?? {}
18832
18976
  };
18833
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
+ });
18834
19007
  const tableKey2 = `${schema5 ?? "public"}.${tableName}`;
18835
19008
  result[tableKey2] = {
18836
19009
  name: tableName,
@@ -18839,7 +19012,8 @@ ${withStyle.errorWarning(
18839
19012
  indexes: indexesObject,
18840
19013
  foreignKeys: foreignKeysObject,
18841
19014
  compositePrimaryKeys: primaryKeysObject,
18842
- uniqueConstraints: uniqueConstraintObject
19015
+ uniqueConstraints: uniqueConstraintObject,
19016
+ policies: policiesObject
18843
19017
  };
18844
19018
  }
18845
19019
  for (const sequence of sequences) {
@@ -18863,6 +19037,16 @@ ${withStyle.errorWarning(
18863
19037
  } else {
18864
19038
  }
18865
19039
  }
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
+ };
19048
+ }
19049
+ }
18866
19050
  const enumsToReturn = enums.reduce((map, obj) => {
18867
19051
  const enumSchema3 = obj.schema || "public";
18868
19052
  const key = `${enumSchema3}.${obj.enumName}`;
@@ -18889,6 +19073,7 @@ ${withStyle.errorWarning(
18889
19073
  enums: enumsToReturn,
18890
19074
  schemas: schemasObject,
18891
19075
  sequences: sequencesToReturn,
19076
+ roles: rolesToReturn,
18892
19077
  _meta: {
18893
19078
  schemas: {},
18894
19079
  tables: {},
@@ -18905,7 +19090,7 @@ ${withStyle.errorWarning(
18905
19090
  --end;
18906
19091
  return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
18907
19092
  };
18908
- fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
19093
+ fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback) => {
18909
19094
  const result = {};
18910
19095
  const internals = { tables: {} };
18911
19096
  const where = schemaFilters.map((t2) => `table_schema = '${t2}'`).join(" or ");
@@ -18987,6 +19172,55 @@ ${withStyle.errorWarning(
18987
19172
  if (progressCallback) {
18988
19173
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
18989
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
+ }
18990
19224
  const sequencesInColumns = [];
18991
19225
  const all = allTables.map((row) => {
18992
19226
  return new Promise(async (res, rej) => {
@@ -19383,7 +19617,8 @@ ${withStyle.errorWarning(
19383
19617
  indexes: indexToReturn,
19384
19618
  foreignKeys: foreignKeysToReturn,
19385
19619
  compositePrimaryKeys: primaryKeys,
19386
- uniqueConstraints: uniqueConstrains
19620
+ uniqueConstraints: uniqueConstrains,
19621
+ policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {}
19387
19622
  };
19388
19623
  } catch (e2) {
19389
19624
  rej(e2);
@@ -19410,6 +19645,7 @@ ${withStyle.errorWarning(
19410
19645
  enums: enumsToReturn,
19411
19646
  schemas: schemasObject,
19412
19647
  sequences: sequencesToReturn,
19648
+ roles: rolesToReturn,
19413
19649
  _meta: {
19414
19650
  schemas: {},
19415
19651
  tables: {},
@@ -20052,10 +20288,10 @@ ${filenames.join("\n")}
20052
20288
  const filenames = prepareFilenames(path5);
20053
20289
  const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
20054
20290
  const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
20055
- const { tables, enums, schemas, sequences } = await prepareFromPgImports2(
20291
+ const { tables, enums, schemas, sequences, roles } = await prepareFromPgImports2(
20056
20292
  filenames
20057
20293
  );
20058
- return generatePgSnapshot2(tables, enums, schemas, sequences, schemaFilter);
20294
+ return generatePgSnapshot2(tables, enums, schemas, sequences, roles, schemaFilter);
20059
20295
  };
20060
20296
  serializeSQLite = async (path5) => {
20061
20297
  const filenames = prepareFilenames(path5);
@@ -20250,57 +20486,57 @@ var require_heap = __commonJS({
20250
20486
  }
20251
20487
  return [].splice.apply(a, [lo, lo - lo].concat(x2)), x2;
20252
20488
  };
20253
- heappush = function(array, item, cmp) {
20489
+ heappush = function(array2, item, cmp) {
20254
20490
  if (cmp == null) {
20255
20491
  cmp = defaultCmp;
20256
20492
  }
20257
- array.push(item);
20258
- return _siftdown(array, 0, array.length - 1, cmp);
20493
+ array2.push(item);
20494
+ return _siftdown(array2, 0, array2.length - 1, cmp);
20259
20495
  };
20260
- heappop = function(array, cmp) {
20496
+ heappop = function(array2, cmp) {
20261
20497
  var lastelt, returnitem;
20262
20498
  if (cmp == null) {
20263
20499
  cmp = defaultCmp;
20264
20500
  }
20265
- lastelt = array.pop();
20266
- if (array.length) {
20267
- returnitem = array[0];
20268
- array[0] = lastelt;
20269
- _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);
20270
20506
  } else {
20271
20507
  returnitem = lastelt;
20272
20508
  }
20273
20509
  return returnitem;
20274
20510
  };
20275
- heapreplace = function(array, item, cmp) {
20511
+ heapreplace = function(array2, item, cmp) {
20276
20512
  var returnitem;
20277
20513
  if (cmp == null) {
20278
20514
  cmp = defaultCmp;
20279
20515
  }
20280
- returnitem = array[0];
20281
- array[0] = item;
20282
- _siftup(array, 0, cmp);
20516
+ returnitem = array2[0];
20517
+ array2[0] = item;
20518
+ _siftup(array2, 0, cmp);
20283
20519
  return returnitem;
20284
20520
  };
20285
- heappushpop = function(array, item, cmp) {
20521
+ heappushpop = function(array2, item, cmp) {
20286
20522
  var _ref;
20287
20523
  if (cmp == null) {
20288
20524
  cmp = defaultCmp;
20289
20525
  }
20290
- if (array.length && cmp(array[0], item) < 0) {
20291
- _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
20292
- _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);
20293
20529
  }
20294
20530
  return item;
20295
20531
  };
20296
- heapify = function(array, cmp) {
20532
+ heapify = function(array2, cmp) {
20297
20533
  var i2, _i, _j, _len, _ref, _ref1, _results, _results1;
20298
20534
  if (cmp == null) {
20299
20535
  cmp = defaultCmp;
20300
20536
  }
20301
20537
  _ref1 = function() {
20302
20538
  _results1 = [];
20303
- 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--) {
20304
20540
  _results1.push(_j2);
20305
20541
  }
20306
20542
  return _results1;
@@ -20308,51 +20544,51 @@ var require_heap = __commonJS({
20308
20544
  _results = [];
20309
20545
  for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
20310
20546
  i2 = _ref1[_i];
20311
- _results.push(_siftup(array, i2, cmp));
20547
+ _results.push(_siftup(array2, i2, cmp));
20312
20548
  }
20313
20549
  return _results;
20314
20550
  };
20315
- updateItem = function(array, item, cmp) {
20551
+ updateItem = function(array2, item, cmp) {
20316
20552
  var pos;
20317
20553
  if (cmp == null) {
20318
20554
  cmp = defaultCmp;
20319
20555
  }
20320
- pos = array.indexOf(item);
20556
+ pos = array2.indexOf(item);
20321
20557
  if (pos === -1) {
20322
20558
  return;
20323
20559
  }
20324
- _siftdown(array, 0, pos, cmp);
20325
- return _siftup(array, pos, cmp);
20560
+ _siftdown(array2, 0, pos, cmp);
20561
+ return _siftup(array2, pos, cmp);
20326
20562
  };
20327
- nlargest = function(array, n, cmp) {
20563
+ nlargest = function(array2, n, cmp) {
20328
20564
  var elem, result, _i, _len, _ref;
20329
20565
  if (cmp == null) {
20330
20566
  cmp = defaultCmp;
20331
20567
  }
20332
- result = array.slice(0, n);
20568
+ result = array2.slice(0, n);
20333
20569
  if (!result.length) {
20334
20570
  return result;
20335
20571
  }
20336
20572
  heapify(result, cmp);
20337
- _ref = array.slice(n);
20573
+ _ref = array2.slice(n);
20338
20574
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
20339
20575
  elem = _ref[_i];
20340
20576
  heappushpop(result, elem, cmp);
20341
20577
  }
20342
20578
  return result.sort(cmp).reverse();
20343
20579
  };
20344
- nsmallest = function(array, n, cmp) {
20580
+ nsmallest = function(array2, n, cmp) {
20345
20581
  var elem, i2, los, result, _i, _j, _len, _ref, _ref1, _results;
20346
20582
  if (cmp == null) {
20347
20583
  cmp = defaultCmp;
20348
20584
  }
20349
- if (n * 10 <= array.length) {
20350
- result = array.slice(0, n).sort(cmp);
20585
+ if (n * 10 <= array2.length) {
20586
+ result = array2.slice(0, n).sort(cmp);
20351
20587
  if (!result.length) {
20352
20588
  return result;
20353
20589
  }
20354
20590
  los = result[result.length - 1];
20355
- _ref = array.slice(n);
20591
+ _ref = array2.slice(n);
20356
20592
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
20357
20593
  elem = _ref[_i];
20358
20594
  if (cmp(elem, los) < 0) {
@@ -20363,51 +20599,51 @@ var require_heap = __commonJS({
20363
20599
  }
20364
20600
  return result;
20365
20601
  }
20366
- heapify(array, cmp);
20602
+ heapify(array2, cmp);
20367
20603
  _results = [];
20368
- for (i2 = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 0 <= _ref1 ? ++_j : --_j) {
20369
- _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));
20370
20606
  }
20371
20607
  return _results;
20372
20608
  };
20373
- _siftdown = function(array, startpos, pos, cmp) {
20609
+ _siftdown = function(array2, startpos, pos, cmp) {
20374
20610
  var newitem, parent, parentpos;
20375
20611
  if (cmp == null) {
20376
20612
  cmp = defaultCmp;
20377
20613
  }
20378
- newitem = array[pos];
20614
+ newitem = array2[pos];
20379
20615
  while (pos > startpos) {
20380
20616
  parentpos = pos - 1 >> 1;
20381
- parent = array[parentpos];
20617
+ parent = array2[parentpos];
20382
20618
  if (cmp(newitem, parent) < 0) {
20383
- array[pos] = parent;
20619
+ array2[pos] = parent;
20384
20620
  pos = parentpos;
20385
20621
  continue;
20386
20622
  }
20387
20623
  break;
20388
20624
  }
20389
- return array[pos] = newitem;
20625
+ return array2[pos] = newitem;
20390
20626
  };
20391
- _siftup = function(array, pos, cmp) {
20627
+ _siftup = function(array2, pos, cmp) {
20392
20628
  var childpos, endpos, newitem, rightpos, startpos;
20393
20629
  if (cmp == null) {
20394
20630
  cmp = defaultCmp;
20395
20631
  }
20396
- endpos = array.length;
20632
+ endpos = array2.length;
20397
20633
  startpos = pos;
20398
- newitem = array[pos];
20634
+ newitem = array2[pos];
20399
20635
  childpos = 2 * pos + 1;
20400
20636
  while (childpos < endpos) {
20401
20637
  rightpos = childpos + 1;
20402
- if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
20638
+ if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
20403
20639
  childpos = rightpos;
20404
20640
  }
20405
- array[pos] = array[childpos];
20641
+ array2[pos] = array2[childpos];
20406
20642
  pos = childpos;
20407
20643
  childpos = 2 * pos + 1;
20408
20644
  }
20409
- array[pos] = newitem;
20410
- return _siftdown(array, startpos, pos, cmp);
20645
+ array2[pos] = newitem;
20646
+ return _siftdown(array2, startpos, pos, cmp);
20411
20647
  };
20412
20648
  Heap = function() {
20413
20649
  Heap2.push = heappush;
@@ -22320,12 +22556,12 @@ var require_lib = __commonJS({
22320
22556
  }
22321
22557
  return bestMatch;
22322
22558
  }
22323
- scalarize(array, originals, fuzzyOriginals) {
22559
+ scalarize(array2, originals, fuzzyOriginals) {
22324
22560
  const fuzzyMatches = [];
22325
22561
  if (fuzzyOriginals) {
22326
22562
  const keyScores = {};
22327
- for (let index4 = 0; index4 < array.length; index4++) {
22328
- const item = array[index4];
22563
+ for (let index4 = 0; index4 < array2.length; index4++) {
22564
+ const item = array2[index4];
22329
22565
  if (this.isScalar(item)) {
22330
22566
  continue;
22331
22567
  }
@@ -22339,8 +22575,8 @@ var require_lib = __commonJS({
22339
22575
  }
22340
22576
  }
22341
22577
  const result = [];
22342
- for (let index4 = 0; index4 < array.length; index4++) {
22343
- const item = array[index4];
22578
+ for (let index4 = 0; index4 < array2.length; index4++) {
22579
+ const item = array2[index4];
22344
22580
  if (this.isScalar(item)) {
22345
22581
  result.push(item);
22346
22582
  } else {
@@ -22562,6 +22798,37 @@ function diffColumns(left, right) {
22562
22798
  );
22563
22799
  return alteredTables;
22564
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
+ }
22565
22832
  function applyJsonDiff(json1, json2) {
22566
22833
  json1 = JSON.parse(JSON.stringify(json1));
22567
22834
  json2 = JSON.parse(JSON.stringify(json2));
@@ -22571,6 +22838,7 @@ function applyJsonDiff(json1, json2) {
22571
22838
  difference.tables = difference.tables || {};
22572
22839
  difference.enums = difference.enums || {};
22573
22840
  difference.sequences = difference.sequences || {};
22841
+ difference.roles = difference.roles || {};
22574
22842
  const schemaKeys = Object.keys(difference.schemas);
22575
22843
  for (let key of schemaKeys) {
22576
22844
  if (key.endsWith("__added") || key.endsWith("__deleted")) {
@@ -22626,6 +22894,10 @@ function applyJsonDiff(json1, json2) {
22626
22894
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
22627
22895
  return json2.sequences[it[0]];
22628
22896
  });
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
+ });
22629
22901
  const alteredTablesWithColumns = Object.values(difference.tables).map(
22630
22902
  (table4) => {
22631
22903
  return findAlternationsInTable(table4);
@@ -22634,7 +22906,8 @@ function applyJsonDiff(json1, json2) {
22634
22906
  return {
22635
22907
  alteredTablesWithColumns,
22636
22908
  alteredEnums,
22637
- alteredSequences
22909
+ alteredSequences,
22910
+ alteredRoles
22638
22911
  };
22639
22912
  }
22640
22913
  var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
@@ -22694,6 +22967,21 @@ var init_jsonDiffer = __esm({
22694
22967
  return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
22695
22968
  })
22696
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
+ );
22697
22985
  const deletedForeignKeys = Object.fromEntries(
22698
22986
  Object.entries(table4.foreignKeys__deleted || {}).concat(
22699
22987
  Object.entries(table4.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
@@ -22755,7 +23043,10 @@ var init_jsonDiffer = __esm({
22755
23043
  alteredCompositePKs,
22756
23044
  addedUniqueConstraints,
22757
23045
  deletedUniqueConstraints,
22758
- alteredUniqueConstraints
23046
+ alteredUniqueConstraints,
23047
+ deletedPolicies,
23048
+ addedPolicies,
23049
+ alteredPolicies
22759
23050
  };
22760
23051
  };
22761
23052
  alternationsInColumn = (column7) => {
@@ -23029,7 +23320,7 @@ function fromJson(statements, dialect7, action, json2) {
23029
23320
  }).filter((it) => it !== "");
23030
23321
  return result;
23031
23322
  }
23032
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, AlterTypeAddValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
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;
23033
23324
  var init_sqlgenerator = __esm({
23034
23325
  "src/sqlgenerator.ts"() {
23035
23326
  "use strict";
@@ -23086,12 +23377,110 @@ var init_sqlgenerator = __esm({
23086
23377
  };
23087
23378
  Convertor = class {
23088
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
+ };
23089
23478
  PgCreateTableConvertor = class extends Convertor {
23090
23479
  can(statement, dialect7) {
23091
23480
  return statement.type === "create_table" && dialect7 === "postgresql";
23092
23481
  }
23093
23482
  convert(st) {
23094
- const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints } = st;
23483
+ const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints, policies } = st;
23095
23484
  let statement = "";
23096
23485
  const name = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
23097
23486
  statement += `CREATE TABLE IF NOT EXISTS ${name} (
@@ -23128,7 +23517,21 @@ var init_sqlgenerator = __esm({
23128
23517
  );`;
23129
23518
  statement += `
23130
23519
  `;
23131
- return statement;
23520
+ const createPolicyConvertor = new PgCreatePolicyConvertor();
23521
+ const createPolicies = (policies == null ? void 0 : policies.map((p2) => {
23522
+ return createPolicyConvertor.convert({
23523
+ type: "create_policy",
23524
+ tableName,
23525
+ data: PgSquasher.unsquashPolicy(p2),
23526
+ schema: schema5
23527
+ });
23528
+ })) ?? [];
23529
+ const enableRls = new PgEnableRlsConvertor().convert({
23530
+ type: "enable_rls",
23531
+ tableName,
23532
+ schema: schema5
23533
+ });
23534
+ return [statement, ...createPolicies.length > 0 ? [enableRls] : [], ...createPolicies];
23132
23535
  }
23133
23536
  };
23134
23537
  MySqlCreateTableConvertor = class extends Convertor {
@@ -23445,9 +23848,21 @@ var init_sqlgenerator = __esm({
23445
23848
  return statement.type === "drop_table" && dialect7 === "postgresql";
23446
23849
  }
23447
23850
  convert(statement) {
23448
- const { tableName, schema: schema5 } = statement;
23851
+ const { tableName, schema: schema5, policies } = statement;
23449
23852
  const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
23450
- return `DROP TABLE ${tableNameWithSchema};`;
23853
+ const dropPolicyConvertor = new PgDropPolicyConvertor();
23854
+ const droppedPolicies = (policies == null ? void 0 : policies.map((p2) => {
23855
+ return dropPolicyConvertor.convert({
23856
+ type: "drop_policy",
23857
+ tableName,
23858
+ data: PgSquasher.unsquashPolicy(p2),
23859
+ schema: schema5
23860
+ });
23861
+ })) ?? [];
23862
+ return [
23863
+ ...droppedPolicies,
23864
+ `DROP TABLE ${tableNameWithSchema};`
23865
+ ];
23451
23866
  }
23452
23867
  };
23453
23868
  MySQLDropTableConvertor = class extends Convertor {
@@ -24622,6 +25037,16 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
24622
25037
  convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
24623
25038
  convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
24624
25039
  convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
25040
+ convertors.push(new PgAlterPolicyConvertor());
25041
+ convertors.push(new PgCreatePolicyConvertor());
25042
+ convertors.push(new PgDropPolicyConvertor());
25043
+ convertors.push(new PgRenamePolicyConvertor());
25044
+ convertors.push(new PgEnableRlsConvertor());
25045
+ convertors.push(new PgDisableRlsConvertor());
25046
+ convertors.push(new PgDropRoleConvertor());
25047
+ convertors.push(new PgAlterRoleConvertor());
25048
+ convertors.push(new PgCreateRoleConvertor());
25049
+ convertors.push(new PgRenameRoleConvertor());
24625
25050
  convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
24626
25051
  convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
24627
25052
  convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
@@ -24917,7 +25342,7 @@ var init_sqlitePushUtils = __esm({
24917
25342
  });
24918
25343
 
24919
25344
  // src/jsonStatements.ts
24920
- 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;
25345
+ 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;
24921
25346
  var init_jsonStatements = __esm({
24922
25347
  "src/jsonStatements.ts"() {
24923
25348
  "use strict";
@@ -24928,7 +25353,7 @@ var init_jsonStatements = __esm({
24928
25353
  init_pgSchema();
24929
25354
  init_sqliteSchema();
24930
25355
  preparePgCreateTableJson = (table4, json2) => {
24931
- const { name, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints } = table4;
25356
+ const { name, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints, policies } = table4;
24932
25357
  const tableKey2 = `${schema5 || "public"}.${name}`;
24933
25358
  const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
24934
25359
  return {
@@ -24938,7 +25363,8 @@ var init_jsonStatements = __esm({
24938
25363
  columns: Object.values(columns),
24939
25364
  compositePKs: Object.values(compositePrimaryKeys),
24940
25365
  compositePkName,
24941
- uniqueConstraints: Object.values(uniqueConstraints)
25366
+ uniqueConstraints: Object.values(uniqueConstraints),
25367
+ policies: Object.values(policies)
24942
25368
  };
24943
25369
  };
24944
25370
  prepareMySqlCreateTableJson = (table4, json2, internals) => {
@@ -24976,7 +25402,8 @@ var init_jsonStatements = __esm({
24976
25402
  return {
24977
25403
  type: "drop_table",
24978
25404
  tableName: table4.name,
24979
- schema: table4.schema
25405
+ schema: table4.schema,
25406
+ policies: table4.policies ? Object.values(table4.policies) : []
24980
25407
  };
24981
25408
  };
24982
25409
  prepareRenameTableJson = (tableFrom, tableTo) => {
@@ -25073,6 +25500,41 @@ var init_jsonStatements = __esm({
25073
25500
  schema: schema5
25074
25501
  };
25075
25502
  };
25503
+ prepareCreateRoleJson = (role) => {
25504
+ return {
25505
+ type: "create_role",
25506
+ name: role.name,
25507
+ values: {
25508
+ createDb: role.createDb,
25509
+ createRole: role.createRole,
25510
+ inherit: role.inherit
25511
+ }
25512
+ };
25513
+ };
25514
+ prepareAlterRoleJson = (role) => {
25515
+ return {
25516
+ type: "alter_role",
25517
+ name: role.name,
25518
+ values: {
25519
+ createDb: role.createDb,
25520
+ createRole: role.createRole,
25521
+ inherit: role.inherit
25522
+ }
25523
+ };
25524
+ };
25525
+ prepareDropRoleJson = (name) => {
25526
+ return {
25527
+ type: "drop_role",
25528
+ name
25529
+ };
25530
+ };
25531
+ prepareRenameRoleJson = (nameFrom, nameTo) => {
25532
+ return {
25533
+ type: "rename_role",
25534
+ nameFrom,
25535
+ nameTo
25536
+ };
25537
+ };
25076
25538
  prepareCreateSchemasJson = (values) => {
25077
25539
  return values.map((it) => {
25078
25540
  return {
@@ -25973,6 +26435,46 @@ var init_jsonStatements = __esm({
25973
26435
  }
25974
26436
  return [...dropPkStatements, ...setPkStatements, ...statements];
25975
26437
  };
26438
+ prepareRenamePolicyJsons = (tableName, schema5, renames) => {
26439
+ return renames.map((it) => {
26440
+ return {
26441
+ type: "rename_policy",
26442
+ tableName,
26443
+ oldName: it.from.name,
26444
+ newName: it.to.name,
26445
+ schema: schema5
26446
+ };
26447
+ });
26448
+ };
26449
+ prepareCreatePolicyJsons = (tableName, schema5, policies) => {
26450
+ return policies.map((it) => {
26451
+ return {
26452
+ type: "create_policy",
26453
+ tableName,
26454
+ data: it,
26455
+ schema: schema5
26456
+ };
26457
+ });
26458
+ };
26459
+ prepareDropPolicyJsons = (tableName, schema5, policies) => {
26460
+ return policies.map((it) => {
26461
+ return {
26462
+ type: "drop_policy",
26463
+ tableName,
26464
+ data: it,
26465
+ schema: schema5
26466
+ };
26467
+ });
26468
+ };
26469
+ prepareAlterPolicyJson = (tableName, schema5, oldPolicy, newPolicy) => {
26470
+ return {
26471
+ type: "alter_policy",
26472
+ tableName,
26473
+ oldData: oldPolicy,
26474
+ newData: newPolicy,
26475
+ schema: schema5
26476
+ };
26477
+ };
25976
26478
  preparePgCreateIndexesJson = (tableName, schema5, indexes, fullSchema, action) => {
25977
26479
  if (action === "push") {
25978
26480
  return Object.values(indexes).map((indexData) => {
@@ -26646,7 +27148,8 @@ var init_snapshotsDiffer = __esm({
26646
27148
  indexes: recordType(stringType(), stringType()),
26647
27149
  foreignKeys: recordType(stringType(), stringType()),
26648
27150
  compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
26649
- uniqueConstraints: recordType(stringType(), stringType()).default({})
27151
+ uniqueConstraints: recordType(stringType(), stringType()).default({}),
27152
+ policies: recordType(stringType(), stringType()).default({})
26650
27153
  }).strict();
26651
27154
  alteredTableScheme = objectType({
26652
27155
  name: stringType(),
@@ -26687,12 +27190,22 @@ var init_snapshotsDiffer = __esm({
26687
27190
  __new: stringType(),
26688
27191
  __old: stringType()
26689
27192
  })
27193
+ ),
27194
+ addedPolicies: recordType(stringType(), stringType()),
27195
+ deletedPolicies: recordType(stringType(), stringType()),
27196
+ alteredPolicies: recordType(
27197
+ stringType(),
27198
+ objectType({
27199
+ __new: stringType(),
27200
+ __old: stringType()
27201
+ })
26690
27202
  )
26691
27203
  }).strict();
26692
27204
  diffResultScheme = objectType({
26693
27205
  alteredTablesWithColumns: alteredTableScheme.array(),
26694
27206
  alteredEnums: changedEnumSchema.array(),
26695
- alteredSequences: sequenceSquashed.array()
27207
+ alteredSequences: sequenceSquashed.array(),
27208
+ alteredRoles: roleSchema.array()
26696
27209
  }).strict();
26697
27210
  diffResultSchemeMysql = objectType({
26698
27211
  alteredTablesWithColumns: alteredTableScheme.array(),
@@ -26747,7 +27260,7 @@ var init_snapshotsDiffer = __esm({
26747
27260
  }
26748
27261
  return column7;
26749
27262
  };
26750
- applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
27263
+ applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, roleResolver2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
26751
27264
  const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
26752
27265
  const {
26753
27266
  created: createdSchemas,
@@ -26897,6 +27410,47 @@ var init_snapshotsDiffer = __esm({
26897
27410
  return [tableKey2, tableValue];
26898
27411
  }
26899
27412
  );
27413
+ const rolesDiff = diffSchemasOrTables(
27414
+ schemasPatchedSnap1.roles,
27415
+ json2.roles
27416
+ );
27417
+ const {
27418
+ created: createdRoles,
27419
+ deleted: deletedRoles,
27420
+ renamed: renamedRoles
27421
+ } = await roleResolver2({
27422
+ created: rolesDiff.added,
27423
+ deleted: rolesDiff.deleted
27424
+ });
27425
+ schemasPatchedSnap1.roles = mapEntries(
27426
+ schemasPatchedSnap1.roles,
27427
+ (_2, it) => {
27428
+ const { name } = nameChangeFor(it, renamedRoles);
27429
+ it.name = name;
27430
+ return [name, it];
27431
+ }
27432
+ );
27433
+ const rolesChangeMap = renamedRoles.reduce(
27434
+ (acc, it) => {
27435
+ acc[it.from.name] = {
27436
+ nameFrom: it.from.name,
27437
+ nameTo: it.to.name
27438
+ };
27439
+ return acc;
27440
+ },
27441
+ {}
27442
+ );
27443
+ schemasPatchedSnap1.roles = mapEntries(
27444
+ schemasPatchedSnap1.roles,
27445
+ (roleKey, roleValue) => {
27446
+ const key = roleKey;
27447
+ const change = rolesChangeMap[key];
27448
+ if (change) {
27449
+ roleValue.name = change.nameTo;
27450
+ }
27451
+ return [roleKey, roleValue];
27452
+ }
27453
+ );
26900
27454
  const tablesDiff = diffSchemasOrTables(
26901
27455
  schemasPatchedSnap1.tables,
26902
27456
  json2.tables
@@ -26975,6 +27529,65 @@ var init_snapshotsDiffer = __esm({
26975
27529
  return [tableKey2, tableValue];
26976
27530
  }
26977
27531
  );
27532
+ const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
27533
+ const policyRenames = [];
27534
+ const policyCreates = [];
27535
+ const policyDeletes = [];
27536
+ for (let entry of Object.values(policyRes)) {
27537
+ const { renamed, created, deleted } = await policyResolver2({
27538
+ tableName: entry.name,
27539
+ schema: entry.schema,
27540
+ deleted: entry.policies.deleted.map(PgSquasher.unsquashPolicy),
27541
+ created: entry.policies.added.map(PgSquasher.unsquashPolicy)
27542
+ });
27543
+ if (created.length > 0) {
27544
+ policyCreates.push({
27545
+ table: entry.name,
27546
+ schema: entry.schema,
27547
+ columns: created
27548
+ });
27549
+ }
27550
+ if (deleted.length > 0) {
27551
+ policyDeletes.push({
27552
+ table: entry.name,
27553
+ schema: entry.schema,
27554
+ columns: deleted
27555
+ });
27556
+ }
27557
+ if (renamed.length > 0) {
27558
+ policyRenames.push({
27559
+ table: entry.name,
27560
+ schema: entry.schema,
27561
+ renames: renamed
27562
+ });
27563
+ }
27564
+ }
27565
+ const policyRenamesDict = columnRenames.reduce(
27566
+ (acc, it) => {
27567
+ acc[`${it.schema || "public"}.${it.table}`] = it.renames;
27568
+ return acc;
27569
+ },
27570
+ {}
27571
+ );
27572
+ const policyPatchedSnap1 = copy(tablesPatchedSnap1);
27573
+ policyPatchedSnap1.tables = mapEntries(
27574
+ policyPatchedSnap1.tables,
27575
+ (tableKey2, tableValue) => {
27576
+ const patchedPolicies = mapKeys(
27577
+ tableValue.policies,
27578
+ (policyKey, policy2) => {
27579
+ const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
27580
+ const newName = columnChangeFor(policyKey, rens);
27581
+ const unsquashedPolicy = PgSquasher.unsquashPolicy(policy2);
27582
+ unsquashedPolicy.name = newName;
27583
+ policy2 = PgSquasher.squashPolicy(unsquashedPolicy);
27584
+ return newName;
27585
+ }
27586
+ );
27587
+ tableValue.policies = patchedPolicies;
27588
+ return [tableKey2, tableValue];
27589
+ }
27590
+ );
26978
27591
  const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
26979
27592
  const typedResult = diffResultScheme.parse(diffResult);
26980
27593
  const jsonStatements = [];
@@ -27130,7 +27743,99 @@ var init_snapshotsDiffer = __esm({
27130
27743
  it.deletedIndexes || {}
27131
27744
  );
27132
27745
  }).flat();
27746
+ const jsonCreatePoliciesStatements = [];
27747
+ const jsonDropPoliciesStatements = [];
27748
+ const jsonAlterPoliciesStatements = [];
27749
+ const jsonRenamePoliciesStatements = [];
27750
+ const jsonEnableRLSStatements = [];
27751
+ const jsonDisableRLSStatements = [];
27752
+ for (let it of policyRenames) {
27753
+ jsonRenamePoliciesStatements.push(
27754
+ ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
27755
+ );
27756
+ }
27757
+ for (const it of policyCreates) {
27758
+ jsonCreatePoliciesStatements.push(
27759
+ ...prepareCreatePolicyJsons(
27760
+ it.table,
27761
+ it.schema,
27762
+ it.columns
27763
+ )
27764
+ );
27765
+ }
27766
+ for (const it of policyDeletes) {
27767
+ jsonDropPoliciesStatements.push(
27768
+ ...prepareDropPolicyJsons(
27769
+ it.table,
27770
+ it.schema,
27771
+ it.columns
27772
+ )
27773
+ );
27774
+ }
27133
27775
  alteredTables.forEach((it) => {
27776
+ Object.keys(it.alteredPolicies).forEach((policyName) => {
27777
+ const newPolicy = PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
27778
+ const oldPolicy = PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
27779
+ if (newPolicy.as !== oldPolicy.as) {
27780
+ jsonDropPoliciesStatements.push(
27781
+ ...prepareDropPolicyJsons(
27782
+ it.name,
27783
+ it.schema,
27784
+ [oldPolicy]
27785
+ )
27786
+ );
27787
+ jsonCreatePoliciesStatements.push(
27788
+ ...prepareCreatePolicyJsons(
27789
+ it.name,
27790
+ it.schema,
27791
+ [newPolicy]
27792
+ )
27793
+ );
27794
+ return;
27795
+ }
27796
+ if (newPolicy.for !== oldPolicy.for) {
27797
+ jsonDropPoliciesStatements.push(
27798
+ ...prepareDropPolicyJsons(
27799
+ it.name,
27800
+ it.schema,
27801
+ [oldPolicy]
27802
+ )
27803
+ );
27804
+ jsonCreatePoliciesStatements.push(
27805
+ ...prepareCreatePolicyJsons(
27806
+ it.name,
27807
+ it.schema,
27808
+ [newPolicy]
27809
+ )
27810
+ );
27811
+ return;
27812
+ }
27813
+ jsonAlterPoliciesStatements.push(
27814
+ prepareAlterPolicyJson(
27815
+ it.name,
27816
+ it.schema,
27817
+ it.alteredPolicies[policyName].__old,
27818
+ it.alteredPolicies[policyName].__new
27819
+ )
27820
+ );
27821
+ });
27822
+ for (const table4 of Object.values(json2.tables)) {
27823
+ const policiesInCurrentState = Object.keys(table4.policies);
27824
+ const tableInPreviousState = columnsPatchedSnap1.tables[`${table4.schema === "" ? "public" : table4.schema}.${table4.name}`];
27825
+ const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
27826
+ if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0) {
27827
+ jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table4.name, schema: table4.schema });
27828
+ }
27829
+ if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0) {
27830
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
27831
+ }
27832
+ }
27833
+ for (const table4 of Object.values(columnsPatchedSnap1.tables)) {
27834
+ const tableInCurrentState = json2.tables[`${table4.schema === "" ? "public" : table4.schema}.${table4.name}`];
27835
+ if (tableInCurrentState === void 0) {
27836
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
27837
+ }
27838
+ }
27134
27839
  const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
27135
27840
  (current, item) => {
27136
27841
  current[item] = it.alteredIndexes[item].__old;
@@ -27215,6 +27920,18 @@ var init_snapshotsDiffer = __esm({
27215
27920
  const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
27216
27921
  return prepareAlterSequenceJson(it);
27217
27922
  }).flat() ?? [];
27923
+ const createRoles = createdRoles.map((it) => {
27924
+ return prepareCreateRoleJson(it);
27925
+ }) ?? [];
27926
+ const dropRoles = deletedRoles.map((it) => {
27927
+ return prepareDropRoleJson(it.name);
27928
+ });
27929
+ const renameRoles = renamedRoles.map((it) => {
27930
+ return prepareRenameRoleJson(it.from.name, it.to.name);
27931
+ });
27932
+ const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
27933
+ return prepareAlterRoleJson(it);
27934
+ }).flat() ?? [];
27218
27935
  const createSchemas = prepareCreateSchemasJson(
27219
27936
  createdSchemas.map((it) => it.name)
27220
27937
  );
@@ -27237,7 +27954,13 @@ var init_snapshotsDiffer = __esm({
27237
27954
  jsonStatements.push(...moveSequences);
27238
27955
  jsonStatements.push(...renameSequences);
27239
27956
  jsonStatements.push(...jsonAlterSequences);
27957
+ jsonStatements.push(...renameRoles);
27958
+ jsonStatements.push(...dropRoles);
27959
+ jsonStatements.push(...createRoles);
27960
+ jsonStatements.push(...jsonAlterRoles);
27240
27961
  jsonStatements.push(...createTables);
27962
+ jsonStatements.push(...jsonEnableRLSStatements);
27963
+ jsonStatements.push(...jsonDisableRLSStatements);
27241
27964
  jsonStatements.push(...jsonDropTables);
27242
27965
  jsonStatements.push(...jsonSetTableSchemas);
27243
27966
  jsonStatements.push(...jsonRenameTables);
@@ -27257,6 +27980,10 @@ var init_snapshotsDiffer = __esm({
27257
27980
  jsonStatements.push(...jsonAlteredCompositePKs);
27258
27981
  jsonStatements.push(...jsonAddedUniqueConstraints);
27259
27982
  jsonStatements.push(...jsonAlteredUniqueConstraints);
27983
+ jsonStatements.push(...jsonRenamePoliciesStatements);
27984
+ jsonStatements.push(...jsonDropPoliciesStatements);
27985
+ jsonStatements.push(...jsonCreatePoliciesStatements);
27986
+ jsonStatements.push(...jsonAlterPoliciesStatements);
27260
27987
  jsonStatements.push(...dropEnums);
27261
27988
  jsonStatements.push(...dropSequences);
27262
27989
  jsonStatements.push(...dropSchemas);
@@ -29520,6 +30247,7 @@ __export(migrate_exports, {
29520
30247
  columnsResolver: () => columnsResolver,
29521
30248
  embeddedMigrations: () => embeddedMigrations,
29522
30249
  enumsResolver: () => enumsResolver,
30250
+ policyResolver: () => policyResolver,
29523
30251
  prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
29524
30252
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
29525
30253
  prepareAndMigratePg: () => prepareAndMigratePg,
@@ -29530,14 +30258,16 @@ __export(migrate_exports, {
29530
30258
  prepareSQLitePush: () => prepareSQLitePush,
29531
30259
  prepareSnapshotFolderName: () => prepareSnapshotFolderName,
29532
30260
  promptColumnsConflicts: () => promptColumnsConflicts,
30261
+ promptNamedConflict: () => promptNamedConflict,
29533
30262
  promptNamedWithSchemasConflict: () => promptNamedWithSchemasConflict,
29534
30263
  promptSchemasConflict: () => promptSchemasConflict,
30264
+ roleResolver: () => roleResolver,
29535
30265
  schemasResolver: () => schemasResolver,
29536
30266
  sequencesResolver: () => sequencesResolver,
29537
30267
  tablesResolver: () => tablesResolver,
29538
30268
  writeResult: () => writeResult
29539
30269
  });
29540
- var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
30270
+ 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;
29541
30271
  var init_migrate = __esm({
29542
30272
  "src/cli/commands/migrate.ts"() {
29543
30273
  "use strict";
@@ -29602,6 +30332,32 @@ var init_migrate = __esm({
29602
30332
  throw e2;
29603
30333
  }
29604
30334
  };
30335
+ roleResolver = async (input) => {
30336
+ const result = await promptNamedConflict(
30337
+ input.created,
30338
+ input.deleted,
30339
+ "role"
30340
+ );
30341
+ return {
30342
+ created: result.created,
30343
+ deleted: result.deleted,
30344
+ renamed: result.renamed
30345
+ };
30346
+ };
30347
+ policyResolver = async (input) => {
30348
+ const result = await promptColumnsConflicts(
30349
+ input.tableName,
30350
+ input.created,
30351
+ input.deleted
30352
+ );
30353
+ return {
30354
+ tableName: input.tableName,
30355
+ schema: input.schema,
30356
+ created: result.created,
30357
+ deleted: result.deleted,
30358
+ renamed: result.renamed
30359
+ };
30360
+ };
29605
30361
  enumsResolver = async (input) => {
29606
30362
  try {
29607
30363
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -29670,6 +30426,8 @@ var init_migrate = __esm({
29670
30426
  schemasResolver,
29671
30427
  enumsResolver,
29672
30428
  sequencesResolver,
30429
+ policyResolver,
30430
+ roleResolver,
29673
30431
  tablesResolver,
29674
30432
  columnsResolver,
29675
30433
  validatedPrev,
@@ -29704,6 +30462,8 @@ var init_migrate = __esm({
29704
30462
  schemasResolver,
29705
30463
  enumsResolver,
29706
30464
  sequencesResolver,
30465
+ policyResolver,
30466
+ roleResolver,
29707
30467
  tablesResolver,
29708
30468
  columnsResolver,
29709
30469
  validatedPrev,
@@ -29984,6 +30744,56 @@ var init_migrate = __esm({
29984
30744
  result.deleted.push(...leftMissing);
29985
30745
  return result;
29986
30746
  };
30747
+ promptNamedConflict = async (newItems, missingItems, entity) => {
30748
+ if (missingItems.length === 0 || newItems.length === 0) {
30749
+ return {
30750
+ created: newItems,
30751
+ renamed: [],
30752
+ deleted: missingItems
30753
+ };
30754
+ }
30755
+ const result = { created: [], renamed: [], deleted: [] };
30756
+ let index4 = 0;
30757
+ let leftMissing = [...missingItems];
30758
+ do {
30759
+ const created = newItems[index4];
30760
+ const renames = leftMissing.map((it) => {
30761
+ return { from: it, to: created };
30762
+ });
30763
+ const promptData = [created, ...renames];
30764
+ const { status, data } = await (0, import_hanji3.render)(
30765
+ new ResolveSelectNamed(created, promptData, entity)
30766
+ );
30767
+ if (status === "aborted") {
30768
+ console.error("ERROR");
30769
+ process.exit(1);
30770
+ }
30771
+ if (isRenamePromptItem(data)) {
30772
+ console.log(
30773
+ `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
30774
+ `${entity} will be renamed/moved`
30775
+ )}`
30776
+ );
30777
+ if (data.from.name !== data.to.name) {
30778
+ result.renamed.push(data);
30779
+ }
30780
+ delete leftMissing[leftMissing.indexOf(data.from)];
30781
+ leftMissing = leftMissing.filter(Boolean);
30782
+ } else {
30783
+ console.log(
30784
+ `${source_default.green("+")} ${data.name} ${source_default.gray(
30785
+ `${entity} will be created`
30786
+ )}`
30787
+ );
30788
+ result.created.push(created);
30789
+ }
30790
+ index4 += 1;
30791
+ } while (index4 < newItems.length);
30792
+ console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
30793
+ `));
30794
+ result.deleted.push(...leftMissing);
30795
+ return result;
30796
+ };
29987
30797
  promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
29988
30798
  if (missingItems.length === 0 || newItems.length === 0) {
29989
30799
  return {
@@ -38812,9 +39622,9 @@ var init_body2 = __esm({
38812
39622
  // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
38813
39623
  function fromRawHeaders(headers = []) {
38814
39624
  return new Headers2(
38815
- headers.reduce((result, value, index4, array) => {
39625
+ headers.reduce((result, value, index4, array2) => {
38816
39626
  if (index4 % 2 === 0) {
38817
- result.push(array.slice(index4, index4 + 2));
39627
+ result.push(array2.slice(index4, index4 + 2));
38818
39628
  }
38819
39629
  return result;
38820
39630
  }, []).filter(([name, value]) => {
@@ -39212,7 +40022,7 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
39212
40022
  if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
39213
40023
  return null;
39214
40024
  }
39215
- const policy = request.referrerPolicy;
40025
+ const policy2 = request.referrerPolicy;
39216
40026
  if (request.referrer === "about:client") {
39217
40027
  return "no-referrer";
39218
40028
  }
@@ -39229,7 +40039,7 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
39229
40039
  referrerOrigin = referrerOriginCallback(referrerOrigin);
39230
40040
  }
39231
40041
  const currentURL = new URL(request.url);
39232
- switch (policy) {
40042
+ switch (policy2) {
39233
40043
  case "no-referrer":
39234
40044
  return "no-referrer";
39235
40045
  case "origin":
@@ -39265,18 +40075,18 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
39265
40075
  }
39266
40076
  return referrerURL;
39267
40077
  default:
39268
- throw new TypeError(`Invalid referrerPolicy: ${policy}`);
40078
+ throw new TypeError(`Invalid referrerPolicy: ${policy2}`);
39269
40079
  }
39270
40080
  }
39271
40081
  function parseReferrerPolicyFromHeader(headers) {
39272
40082
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
39273
- let policy = "";
40083
+ let policy2 = "";
39274
40084
  for (const token of policyTokens) {
39275
40085
  if (token && ReferrerPolicy.has(token)) {
39276
- policy = token;
40086
+ policy2 = token;
39277
40087
  }
39278
40088
  }
39279
- return policy;
40089
+ return policy2;
39280
40090
  }
39281
40091
  var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY;
39282
40092
  var init_referrer = __esm({
@@ -59923,7 +60733,7 @@ var require_fromWebToken = __commonJS({
59923
60733
  var fromWebToken2 = (init2) => async () => {
59924
60734
  var _a;
59925
60735
  (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-web-identity", "fromWebToken");
59926
- const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init2;
60736
+ const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy2, durationSeconds } = init2;
59927
60737
  let { roleAssumerWithWebIdentity } = init2;
59928
60738
  if (!roleAssumerWithWebIdentity) {
59929
60739
  const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar2(require_dist_cjs50()));
@@ -59939,7 +60749,7 @@ var require_fromWebToken = __commonJS({
59939
60749
  WebIdentityToken: webIdentityToken,
59940
60750
  ProviderId: providerId,
59941
60751
  PolicyArns: policyArns,
59942
- Policy: policy,
60752
+ Policy: policy2,
59943
60753
  DurationSeconds: durationSeconds
59944
60754
  });
59945
60755
  };
@@ -62210,7 +63020,7 @@ var init_connections = __esm({
62210
63020
  return { ...db, ...proxy, migrate: migrateFn };
62211
63021
  }
62212
63022
  console.log(
62213
- "Please install 'better-sqlite3' for Drizzle Kit to connect to SQLite databases"
63023
+ "Please install either 'better-sqlite3' or '@libsql/client' for Drizzle Kit to connect to SQLite databases"
62214
63024
  );
62215
63025
  process.exit(1);
62216
63026
  };
@@ -63403,13 +64213,13 @@ var require_event_stream = __commonJS({
63403
64213
  es.writeArray = function(done) {
63404
64214
  if ("function" !== typeof done)
63405
64215
  throw new Error("function writeArray (done): done must be function");
63406
- var a = new Stream3(), array = [], isDone = false;
64216
+ var a = new Stream3(), array2 = [], isDone = false;
63407
64217
  a.write = function(l) {
63408
- array.push(l);
64218
+ array2.push(l);
63409
64219
  };
63410
64220
  a.end = function() {
63411
64221
  isDone = true;
63412
- done(null, array);
64222
+ done(null, array2);
63413
64223
  };
63414
64224
  a.writable = true;
63415
64225
  a.readable = false;
@@ -63417,23 +64227,23 @@ var require_event_stream = __commonJS({
63417
64227
  a.writable = a.readable = false;
63418
64228
  if (isDone)
63419
64229
  return;
63420
- done(new Error("destroyed before end"), array);
64230
+ done(new Error("destroyed before end"), array2);
63421
64231
  };
63422
64232
  return a;
63423
64233
  };
63424
- es.readArray = function(array) {
64234
+ es.readArray = function(array2) {
63425
64235
  var stream = new Stream3(), i2 = 0, paused = false, ended = false;
63426
64236
  stream.readable = true;
63427
64237
  stream.writable = false;
63428
- if (!Array.isArray(array))
64238
+ if (!Array.isArray(array2))
63429
64239
  throw new Error("event-stream.read expects an array");
63430
64240
  stream.resume = function() {
63431
64241
  if (ended)
63432
64242
  return;
63433
64243
  paused = false;
63434
- var l = array.length;
64244
+ var l = array2.length;
63435
64245
  while (i2 < l && !paused && !ended) {
63436
- stream.emit("data", array[i2++]);
64246
+ stream.emit("data", array2[i2++]);
63437
64247
  }
63438
64248
  if (i2 == l && !ended)
63439
64249
  ended = true, stream.readable = false, stream.emit("end");
@@ -67058,8 +67868,8 @@ var require_utils4 = __commonJS({
67058
67868
  "use strict";
67059
67869
  Object.defineProperty(exports2, "__esModule", { value: true });
67060
67870
  exports2.string = exports2.stream = exports2.pattern = exports2.path = exports2.fs = exports2.errno = exports2.array = void 0;
67061
- var array = require_array();
67062
- exports2.array = array;
67871
+ var array2 = require_array();
67872
+ exports2.array = array2;
67063
67873
  var errno = require_errno();
67064
67874
  exports2.errno = errno;
67065
67875
  var fs9 = require_fs2();
@@ -78917,7 +79727,7 @@ var init_pgIntrospect = __esm({
78917
79727
  init_global();
78918
79728
  init_pgSerializer();
78919
79729
  init_views();
78920
- pgPushIntrospect = async (db, filters, schemaFilters) => {
79730
+ pgPushIntrospect = async (db, filters, schemaFilters, entities = { roles: true }) => {
78921
79731
  const matchers = filters.map((it) => {
78922
79732
  return new Minimatch(it);
78923
79733
  });
@@ -78946,7 +79756,7 @@ var init_pgIntrospect = __esm({
78946
79756
  );
78947
79757
  const res = await (0, import_hanji9.renderWithTask)(
78948
79758
  progress,
78949
- fromDatabase2(db, filter2, schemaFilters)
79759
+ fromDatabase2(db, filter2, schemaFilters, entities)
78950
79760
  );
78951
79761
  const schema5 = { id: originUUID, prevId: "", ...res };
78952
79762
  const { internal, ...schemaWithoutInternals } = schema5;
@@ -79411,6 +80221,7 @@ var init_push = __esm({
79411
80221
  }
79412
80222
  });
79413
80223
  if (verbose) {
80224
+ console.log();
79414
80225
  console.log(
79415
80226
  withStyle.warning("You are about to execute current statements:")
79416
80227
  );
@@ -79468,11 +80279,11 @@ var init_push = __esm({
79468
80279
  console.log(e2);
79469
80280
  }
79470
80281
  };
79471
- pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, force) => {
80282
+ pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, entities, force) => {
79472
80283
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
79473
80284
  const { pgPushIntrospect: pgPushIntrospect2 } = await Promise.resolve().then(() => (init_pgIntrospect(), pgIntrospect_exports));
79474
80285
  const db = await preparePostgresDB2(credentials2);
79475
- const { schema: schema5 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter);
80286
+ const { schema: schema5 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter, entities);
79476
80287
  const { preparePgPush: preparePgPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
79477
80288
  const statements = await preparePgPush2(schemaPath, schema5, schemasFilter);
79478
80289
  try {
@@ -80642,7 +81453,7 @@ function generateIdentityParams(identity) {
80642
81453
  }
80643
81454
  return `.generatedByDefaultAsIdentity(${paramsObj})`;
80644
81455
  }
80645
- var import_drizzle_orm9, import_relations, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
81456
+ var import_drizzle_orm9, import_relations, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTablePolicies, createTableUniques3, createTableFKs3;
80646
81457
  var init_introspect_pg = __esm({
80647
81458
  "src/introspect-pg.ts"() {
80648
81459
  "use strict";
@@ -80810,6 +81621,9 @@ var init_introspect_pg = __esm({
80810
81621
  const uniqueImports = Object.values(it.uniqueConstraints).map(
80811
81622
  (it2) => "unique"
80812
81623
  );
81624
+ const policiesImports = Object.values(it.policies).map(
81625
+ (it2) => "pgPolicy"
81626
+ );
80813
81627
  if (it.schema && it.schema !== "public" && it.schema !== "") {
80814
81628
  res.pg.push("pgSchema");
80815
81629
  }
@@ -80817,6 +81631,7 @@ var init_introspect_pg = __esm({
80817
81631
  res.pg.push(...fkImpots);
80818
81632
  res.pg.push(...pkImports);
80819
81633
  res.pg.push(...uniqueImports);
81634
+ res.pg.push(...policiesImports);
80820
81635
  const columnImports = Object.values(it.columns).map((col) => {
80821
81636
  let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
80822
81637
  patched = patched === "double precision" ? "doublePrecision" : patched;
@@ -80850,6 +81665,9 @@ var init_introspect_pg = __esm({
80850
81665
  imports.pg.push("pgEnum");
80851
81666
  }
80852
81667
  });
81668
+ if (Object.keys(schema5.roles).length > 0) {
81669
+ imports.pg.push("pgRole");
81670
+ }
80853
81671
  const enumStatements = Object.values(schema5.enums).map((it) => {
80854
81672
  const enumSchema3 = schemas[it.schema];
80855
81673
  const paramName = paramNameFor(it.name, enumSchema3);
@@ -80885,9 +81703,16 @@ var init_introspect_pg = __esm({
80885
81703
  }
80886
81704
  return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
80887
81705
  `;
80888
- }).join("").concat("\n");
81706
+ }).join("").concat("");
80889
81707
  const schemaStatements = Object.entries(schemas).map((it) => {
80890
81708
  return `export const ${it[1]} = pgSchema("${it[0]}");
81709
+ `;
81710
+ }).join("");
81711
+ const rolesNameToTsKey = {};
81712
+ const rolesStatements = Object.entries(schema5.roles).map((it) => {
81713
+ const fields = it[1];
81714
+ rolesNameToTsKey[fields.name] = it[0];
81715
+ 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(",")}}`} );
80891
81716
  `;
80892
81717
  }).join("");
80893
81718
  const tableStatements = Object.values(schema5.tables).map((table4) => {
@@ -80906,8 +81731,8 @@ var init_introspect_pg = __esm({
80906
81731
  schema5.internal
80907
81732
  );
80908
81733
  statement += "}";
80909
- 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) {
80910
- statement += ",\n";
81734
+ 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) {
81735
+ statement += ", ";
80911
81736
  statement += "(table) => {\n";
80912
81737
  statement += " return {\n";
80913
81738
  statement += createTableIndexes3(
@@ -80924,6 +81749,11 @@ var init_introspect_pg = __esm({
80924
81749
  Object.values(table4.uniqueConstraints),
80925
81750
  casing2
80926
81751
  );
81752
+ statement += createTablePolicies(
81753
+ Object.values(table4.policies),
81754
+ casing2,
81755
+ rolesNameToTsKey
81756
+ );
80927
81757
  statement += " }\n";
80928
81758
  statement += "}";
80929
81759
  }
@@ -80934,14 +81764,14 @@ var init_introspect_pg = __esm({
80934
81764
  const importsTs = `import { ${uniquePgImports.join(
80935
81765
  ", "
80936
81766
  )} } from "drizzle-orm/pg-core"
80937
- import { sql } from "drizzle-orm"
81767
+ import { sql } from "drizzle-orm"
80938
81768
 
80939
81769
  `;
80940
81770
  let decalrations = schemaStatements;
81771
+ decalrations += rolesStatements;
80941
81772
  decalrations += enumStatements;
80942
81773
  decalrations += sequencesStatements;
80943
- decalrations += "\n";
80944
- decalrations += tableStatements.join("\n\n");
81774
+ decalrations += tableStatements.join("\n");
80945
81775
  const file = importsTs + decalrations;
80946
81776
  const schemaEntry = `
80947
81777
  {
@@ -81372,6 +82202,23 @@ var init_introspect_pg = __esm({
81372
82202
  }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
81373
82203
  statement += ")";
81374
82204
  statement += `,
82205
+ `;
82206
+ });
82207
+ return statement;
82208
+ };
82209
+ createTablePolicies = (policies, casing2, rolesNameToTsKey = {}) => {
82210
+ let statement = "";
82211
+ policies.forEach((it) => {
82212
+ var _a, _b, _c;
82213
+ const idxKey = withCasing2(it.name, casing2);
82214
+ const mappedItTo = (_a = it.to) == null ? void 0 : _a.map((v) => {
82215
+ return rolesNameToTsKey[v] ? withCasing2(rolesNameToTsKey[v], casing2) : `"${v}"`;
82216
+ });
82217
+ statement += ` ${idxKey}: `;
82218
+ statement += "pgPolicy(";
82219
+ statement += `"${it.name}", { `;
82220
+ 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}\` ` : ""}`;
82221
+ statement += ` }),
81375
82222
  `;
81376
82223
  });
81377
82224
  return statement;
@@ -81449,7 +82296,7 @@ var init_introspect = __esm({
81449
82296
  init_utils();
81450
82297
  init_views();
81451
82298
  init_migrate();
81452
- introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2) => {
82299
+ introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
81453
82300
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
81454
82301
  const db = await preparePostgresDB2(credentials2);
81455
82302
  const matchers = tablesFilter.map((it) => {
@@ -81477,9 +82324,15 @@ var init_introspect = __esm({
81477
82324
  const progress = new IntrospectProgress(true);
81478
82325
  const res = await (0, import_hanji12.renderWithTask)(
81479
82326
  progress,
81480
- fromDatabase2(db, filter2, schemasFilter, (stage, count, status) => {
81481
- progress.update(stage, count, status);
81482
- })
82327
+ fromDatabase2(
82328
+ db,
82329
+ filter2,
82330
+ schemasFilter,
82331
+ entities,
82332
+ (stage, count, status) => {
82333
+ progress.update(stage, count, status);
82334
+ }
82335
+ )
81483
82336
  );
81484
82337
  const schema5 = { id: originUUID, prevId: "", ...res };
81485
82338
  const ts = schemaToTypeScript3(schema5, casing2);
@@ -81498,6 +82351,7 @@ var init_introspect = __esm({
81498
82351
  schemasResolver,
81499
82352
  enumsResolver,
81500
82353
  sequencesResolver,
82354
+ policyResolver,
81501
82355
  tablesResolver,
81502
82356
  columnsResolver,
81503
82357
  dryPg,
@@ -85011,7 +85865,8 @@ var pull = command({
85011
85865
  breakpoints,
85012
85866
  tablesFilter,
85013
85867
  schemasFilter,
85014
- prefix: prefix2
85868
+ prefix: prefix2,
85869
+ entities
85015
85870
  } = config;
85016
85871
  (0, import_fs13.mkdirSync)(out, { recursive: true });
85017
85872
  console.log(
@@ -85050,7 +85905,8 @@ var pull = command({
85050
85905
  credentials2,
85051
85906
  tablesFilter,
85052
85907
  schemasFilter,
85053
- prefix2
85908
+ prefix2,
85909
+ entities
85054
85910
  );
85055
85911
  } else if (dialect7 === "mysql") {
85056
85912
  const { introspectMysql: introspectMysql2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
@@ -85221,7 +86077,7 @@ init_utils2();
85221
86077
  var version2 = async () => {
85222
86078
  const { npmVersion } = await ormCoreVersions();
85223
86079
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
85224
- const envVersion = "0.24.2-218cddb";
86080
+ const envVersion = "0.24.2-277e6de";
85225
86081
  const kitVersion = envVersion ? `v${envVersion}` : "--";
85226
86082
  const versions = `drizzle-kit: ${kitVersion}
85227
86083
  ${ormVersion}`;