drizzle-kit 0.26.2-57d2372 → 0.26.2-6a162f5

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();
@@ -1316,6 +1363,11 @@ Is ${source_default.bold.blue(
1316
1363
  name: "foreign keys",
1317
1364
  status: "fetching"
1318
1365
  },
1366
+ policies: {
1367
+ count: 0,
1368
+ name: "policies",
1369
+ status: "fetching"
1370
+ },
1319
1371
  checks: {
1320
1372
  count: 0,
1321
1373
  name: "check constraints",
@@ -1362,6 +1414,7 @@ Is ${source_default.bold.blue(
1362
1414
  info2 += this.hasEnums ? this.statusText(spin, this.state.enums) : "";
1363
1415
  info2 += this.statusText(spin, this.state.indexes);
1364
1416
  info2 += this.statusText(spin, this.state.fks);
1417
+ info2 += this.statusText(spin, this.state.policies);
1365
1418
  info2 += this.statusText(spin, this.state.checks);
1366
1419
  info2 += this.statusText(spin, this.state.views);
1367
1420
  return info2;
@@ -1748,8 +1801,8 @@ var init_lib = __esm({
1748
1801
  return void 0;
1749
1802
  };
1750
1803
  util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && isFinite(val2) && Math.floor(val2) === val2;
1751
- function joinValues(array, separator = " | ") {
1752
- return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
1804
+ function joinValues(array2, separator = " | ") {
1805
+ return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
1753
1806
  }
1754
1807
  util2.joinValues = joinValues;
1755
1808
  util2.jsonStringifyReplacer = (_2, value) => {
@@ -5779,7 +5832,7 @@ var init_vector = __esm({
5779
5832
  });
5780
5833
 
5781
5834
  // src/serializer/pgSchema.ts
5782
- var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, viewWithOption, matViewWithOption, mergedViewWithOption, view2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5835
+ var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, roleSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, policy, viewWithOption, matViewWithOption, mergedViewWithOption, view2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5783
5836
  var init_pgSchema = __esm({
5784
5837
  "src/serializer/pgSchema.ts"() {
5785
5838
  "use strict";
@@ -5911,6 +5964,12 @@ var init_pgSchema = __esm({
5911
5964
  cycle: booleanType().optional(),
5912
5965
  schema: stringType()
5913
5966
  }).strict();
5967
+ roleSchema = objectType({
5968
+ name: stringType(),
5969
+ createDb: booleanType().optional(),
5970
+ createRole: booleanType().optional(),
5971
+ inherit: booleanType().optional()
5972
+ }).strict();
5914
5973
  sequenceSquashed = objectType({
5915
5974
  name: stringType(),
5916
5975
  schema: stringType(),
@@ -5978,6 +6037,14 @@ var init_pgSchema = __esm({
5978
6037
  columns: stringType().array(),
5979
6038
  nullsNotDistinct: booleanType()
5980
6039
  }).strict();
6040
+ policy = objectType({
6041
+ name: stringType(),
6042
+ as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
6043
+ for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
6044
+ to: stringType().array().optional(),
6045
+ using: stringType().optional(),
6046
+ withCheck: stringType().optional()
6047
+ }).strict();
5981
6048
  viewWithOption = objectType({
5982
6049
  checkOption: enumType(["local", "cascaded"]).optional(),
5983
6050
  securityBarrier: booleanType().optional(),
@@ -6058,7 +6125,9 @@ var init_pgSchema = __esm({
6058
6125
  foreignKeys: recordType(stringType(), fk2),
6059
6126
  compositePrimaryKeys: recordType(stringType(), compositePK2),
6060
6127
  uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
6061
- checkConstraints: recordType(stringType(), checkConstraint2).default({})
6128
+ policies: recordType(stringType(), policy).default({}),
6129
+ checkConstraints: recordType(stringType(), checkConstraint2).default({}),
6130
+ isRLSEnabled: booleanType().default(false)
6062
6131
  }).strict();
6063
6132
  schemaHash2 = objectType({
6064
6133
  id: stringType(),
@@ -6153,6 +6222,7 @@ var init_pgSchema = __esm({
6153
6222
  schemas: recordType(stringType(), stringType()),
6154
6223
  views: recordType(stringType(), view2).default({}),
6155
6224
  sequences: recordType(stringType(), sequenceSchema).default({}),
6225
+ roles: recordType(stringType(), roleSchema).default({}),
6156
6226
  _meta: objectType({
6157
6227
  schemas: recordType(stringType(), stringType()),
6158
6228
  tables: recordType(stringType(), stringType()),
@@ -6168,7 +6238,9 @@ var init_pgSchema = __esm({
6168
6238
  foreignKeys: recordType(stringType(), stringType()),
6169
6239
  compositePrimaryKeys: recordType(stringType(), stringType()),
6170
6240
  uniqueConstraints: recordType(stringType(), stringType()),
6171
- checkConstraints: recordType(stringType(), stringType())
6241
+ policies: recordType(stringType(), stringType()),
6242
+ checkConstraints: recordType(stringType(), stringType()),
6243
+ isRLSEnabled: booleanType().default(false)
6172
6244
  }).strict();
6173
6245
  tableSquashedV42 = objectType({
6174
6246
  name: stringType(),
@@ -6198,7 +6270,8 @@ var init_pgSchema = __esm({
6198
6270
  enums: recordType(stringType(), enumSchema),
6199
6271
  schemas: recordType(stringType(), stringType()),
6200
6272
  views: recordType(stringType(), view2),
6201
- sequences: recordType(stringType(), sequenceSquashed)
6273
+ sequences: recordType(stringType(), sequenceSquashed),
6274
+ roles: recordType(stringType(), roleSchema).default({})
6202
6275
  }).strict();
6203
6276
  pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
6204
6277
  pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
@@ -6281,6 +6354,25 @@ var init_pgSchema = __esm({
6281
6354
  squashFK: (fk4) => {
6282
6355
  return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""};${fk4.schemaTo || "public"}`;
6283
6356
  },
6357
+ squashPolicy: (policy2) => {
6358
+ var _a;
6359
+ return `${policy2.name}--${policy2.as}--${policy2.for}--${(_a = policy2.to) == null ? void 0 : _a.join(",")}--${policy2.using}--${policy2.withCheck}`;
6360
+ },
6361
+ unsquashPolicy: (policy2) => {
6362
+ const splitted = policy2.split("--");
6363
+ return {
6364
+ name: splitted[0],
6365
+ as: splitted[1],
6366
+ for: splitted[2],
6367
+ to: splitted[3].split(","),
6368
+ using: splitted[4] !== "undefined" ? splitted[4] : void 0,
6369
+ withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0
6370
+ };
6371
+ },
6372
+ squashPolicyPush: (policy2) => {
6373
+ var _a;
6374
+ return `${policy2.name}--${policy2.as}--${policy2.for}--${(_a = policy2.to) == null ? void 0 : _a.join(",")}`;
6375
+ },
6284
6376
  squashPK: (pk) => {
6285
6377
  return `${pk.columns.join(",")};${pk.name}`;
6286
6378
  },
@@ -6393,6 +6485,9 @@ var init_pgSchema = __esm({
6393
6485
  return PgSquasher.squashUnique(unq);
6394
6486
  }
6395
6487
  );
6488
+ const squashedPolicies = mapValues(it[1].policies, (policy2) => {
6489
+ return action === "push" ? PgSquasher.squashPolicyPush(policy2) : PgSquasher.squashPolicy(policy2);
6490
+ });
6396
6491
  const squashedChecksContraints = mapValues(
6397
6492
  it[1].checkConstraints,
6398
6493
  (check2) => {
@@ -6409,7 +6504,9 @@ var init_pgSchema = __esm({
6409
6504
  foreignKeys: squashedFKs,
6410
6505
  compositePrimaryKeys: squashedPKs,
6411
6506
  uniqueConstraints: squashedUniqueConstraints,
6412
- checkConstraints: squashedChecksContraints
6507
+ policies: squashedPolicies,
6508
+ checkConstraints: squashedChecksContraints,
6509
+ isRLSEnabled: it[1].isRLSEnabled ?? false
6413
6510
  }
6414
6511
  ];
6415
6512
  })
@@ -6433,7 +6530,8 @@ var init_pgSchema = __esm({
6433
6530
  enums: json.enums,
6434
6531
  schemas: json.schemas,
6435
6532
  views: json.views,
6436
- sequences: mappedSequences
6533
+ sequences: mappedSequences,
6534
+ roles: json.roles
6437
6535
  };
6438
6536
  };
6439
6537
  dryPg = pgSchema.parse({
@@ -10770,10 +10868,10 @@ var require_inflight = __commonJS({
10770
10868
  }
10771
10869
  function slice(args) {
10772
10870
  var length = args.length;
10773
- var array = [];
10871
+ var array2 = [];
10774
10872
  for (var i2 = 0; i2 < length; i2++)
10775
- array[i2] = args[i2];
10776
- return array;
10873
+ array2[i2] = args[i2];
10874
+ return array2;
10777
10875
  }
10778
10876
  }
10779
10877
  });
@@ -11596,6 +11694,13 @@ var init_cli = __esm({
11596
11694
  breakpoints: booleanType().optional().default(true),
11597
11695
  migrations: objectType({
11598
11696
  prefix: prefix.optional().default("index")
11697
+ }).optional(),
11698
+ entities: objectType({
11699
+ roles: booleanType().or(objectType({
11700
+ provider: stringType().optional(),
11701
+ include: stringType().array().optional(),
11702
+ exclude: stringType().array().optional()
11703
+ })).optional().default(false)
11599
11704
  }).optional()
11600
11705
  }).passthrough();
11601
11706
  configCheck = objectType({
@@ -17783,7 +17888,8 @@ var init_utils4 = __esm({
17783
17888
  credentials: parsed2.data,
17784
17889
  tablesFilter,
17785
17890
  schemasFilter,
17786
- prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index"
17891
+ prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index",
17892
+ entities: config.entities
17787
17893
  };
17788
17894
  }
17789
17895
  if (dialect4 === "mysql") {
@@ -17800,7 +17906,8 @@ var init_utils4 = __esm({
17800
17906
  credentials: parsed2.data,
17801
17907
  tablesFilter,
17802
17908
  schemasFilter,
17803
- prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index"
17909
+ prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index",
17910
+ entities: config.entities
17804
17911
  };
17805
17912
  }
17806
17913
  if (dialect4 === "sqlite") {
@@ -17817,7 +17924,8 @@ var init_utils4 = __esm({
17817
17924
  credentials: parsed2.data,
17818
17925
  tablesFilter,
17819
17926
  schemasFilter,
17820
- prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index"
17927
+ prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index",
17928
+ entities: config.entities
17821
17929
  };
17822
17930
  }
17823
17931
  if (dialect4 === "turso") {
@@ -18861,6 +18969,7 @@ var init_pgImports = __esm({
18861
18969
  const enums = [];
18862
18970
  const schemas = [];
18863
18971
  const sequences = [];
18972
+ const roles = [];
18864
18973
  const views = [];
18865
18974
  const matViews = [];
18866
18975
  const i0values = Object.values(exports2);
@@ -18884,8 +18993,11 @@ var init_pgImports = __esm({
18884
18993
  if ((0, import_pg_core.isPgSequence)(t2)) {
18885
18994
  sequences.push(t2);
18886
18995
  }
18996
+ if ((0, import_drizzle_orm4.is)(t2, import_pg_core.PgRole)) {
18997
+ roles.push(t2);
18998
+ }
18887
18999
  });
18888
- return { tables, enums, schemas, sequences, views, matViews };
19000
+ return { tables, enums, schemas, sequences, views, matViews, roles };
18889
19001
  };
18890
19002
  prepareFromPgImports = async (imports) => {
18891
19003
  const tables = [];
@@ -18893,6 +19005,7 @@ var init_pgImports = __esm({
18893
19005
  const schemas = [];
18894
19006
  const sequences = [];
18895
19007
  const views = [];
19008
+ let roles = [];
18896
19009
  const matViews = [];
18897
19010
  const { unregister } = await safeRegister();
18898
19011
  for (let i2 = 0; i2 < imports.length; i2++) {
@@ -18905,9 +19018,10 @@ var init_pgImports = __esm({
18905
19018
  sequences.push(...prepared.sequences);
18906
19019
  views.push(...prepared.views);
18907
19020
  matViews.push(...prepared.matViews);
19021
+ roles.push(...prepared.roles);
18908
19022
  }
18909
19023
  unregister();
18910
- return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews };
19024
+ return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews, roles };
18911
19025
  };
18912
19026
  }
18913
19027
  });
@@ -18915,6 +19029,7 @@ var init_pgImports = __esm({
18915
19029
  // src/serializer/pgSerializer.ts
18916
19030
  var pgSerializer_exports = {};
18917
19031
  __export(pgSerializer_exports, {
19032
+ buildArrayString: () => buildArrayString,
18918
19033
  fromDatabase: () => fromDatabase2,
18919
19034
  generatePgSnapshot: () => generatePgSnapshot,
18920
19035
  indexName: () => indexName2
@@ -18926,14 +19041,14 @@ function maxRangeForIdentityBasedOn(columnType) {
18926
19041
  return columnType === "integer" ? "2147483647" : columnType === "bigint" ? "9223372036854775807" : "32767";
18927
19042
  }
18928
19043
  function minRangeForIdentityBasedOn(columnType) {
18929
- return columnType === "integer" ? "-2147483648" : columnType === "bitint" ? "-9223372036854775808" : "-32768";
19044
+ return columnType === "integer" ? "-2147483648" : columnType === "bigint" ? "-9223372036854775808" : "-32768";
18930
19045
  }
18931
19046
  function stringFromDatabaseIdentityProperty(field) {
18932
19047
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
18933
19048
  }
18934
- function buildArrayString(array, sqlType) {
19049
+ function buildArrayString(array2, sqlType) {
18935
19050
  sqlType = sqlType.split("[")[0];
18936
- const values = array.map((value) => {
19051
+ const values = array2.map((value) => {
18937
19052
  if (typeof value === "number" || typeof value === "bigint") {
18938
19053
  return value.toString();
18939
19054
  } else if (typeof value === "boolean") {
@@ -18955,6 +19070,40 @@ function buildArrayString(array, sqlType) {
18955
19070
  }).join(",");
18956
19071
  return `{${values}}`;
18957
19072
  }
19073
+ function prepareRoles(entities) {
19074
+ let useRoles = false;
19075
+ const includeRoles = [];
19076
+ const excludeRoles = [];
19077
+ if (entities && entities.roles) {
19078
+ if (typeof entities.roles === "object") {
19079
+ if (entities.roles.provider) {
19080
+ if (entities.roles.provider === "supabase") {
19081
+ excludeRoles.push(...[
19082
+ "anon",
19083
+ "authenticator",
19084
+ "authenticated",
19085
+ "service_role",
19086
+ "supabase_auth_admin",
19087
+ "supabase_storage_admin",
19088
+ "dashboard_user",
19089
+ "supabase_admin"
19090
+ ]);
19091
+ } else if (entities.roles.provider === "neon") {
19092
+ excludeRoles.push(...["authenticated", "anonymous"]);
19093
+ }
19094
+ }
19095
+ if (entities.roles.include) {
19096
+ includeRoles.push(...entities.roles.include);
19097
+ }
19098
+ if (entities.roles.exclude) {
19099
+ excludeRoles.push(...entities.roles.exclude);
19100
+ }
19101
+ } else {
19102
+ useRoles = entities.roles;
19103
+ }
19104
+ }
19105
+ return { useRoles, includeRoles, excludeRoles };
19106
+ }
18958
19107
  var import_drizzle_orm5, import_pg_core2, import_pg_core3, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn, getColumnsInfoQuery;
18959
19108
  var init_pgSerializer = __esm({
18960
19109
  "src/serializer/pgSerializer.ts"() {
@@ -18970,16 +19119,28 @@ var init_pgSerializer = __esm({
18970
19119
  indexName2 = (tableName, columns) => {
18971
19120
  return `${tableName}_${columns.join("_")}_index`;
18972
19121
  };
18973
- generatePgSnapshot = (tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter) => {
19122
+ generatePgSnapshot = (tables, enums, schemas, sequences, roles, views, matViews, casing2, schemaFilter) => {
18974
19123
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
18975
19124
  const dialect4 = new import_pg_core2.PgDialect({ casing: casing2 });
18976
19125
  const result = {};
18977
19126
  const resultViews = {};
18978
19127
  const sequencesToReturn = {};
19128
+ const rolesToReturn = {};
18979
19129
  const indexesInSchema = {};
18980
19130
  for (const table4 of tables) {
18981
19131
  const checksInTable = {};
18982
- const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema5, primaryKeys, uniqueConstraints } = (0, import_pg_core3.getTableConfig)(table4);
19132
+ const {
19133
+ name: tableName,
19134
+ columns,
19135
+ indexes,
19136
+ foreignKeys,
19137
+ checks,
19138
+ schema: schema5,
19139
+ primaryKeys,
19140
+ uniqueConstraints,
19141
+ policies,
19142
+ enableRLS
19143
+ } = (0, import_pg_core3.getTableConfig)(table4);
18983
19144
  if (schemaFilter && !schemaFilter.includes(schema5 ?? "public")) {
18984
19145
  continue;
18985
19146
  }
@@ -18989,6 +19150,7 @@ var init_pgSerializer = __esm({
18989
19150
  const foreignKeysObject = {};
18990
19151
  const primaryKeysObject = {};
18991
19152
  const uniqueConstraintObject = {};
19153
+ const policiesObject = {};
18992
19154
  columns.forEach((column7) => {
18993
19155
  var _a2, _b2, _c2, _d2, _e2, _f2;
18994
19156
  const name = getColumnCasing(column7, casing2);
@@ -19238,6 +19400,35 @@ ${withStyle.errorWarning(
19238
19400
  with: value.config.with ?? {}
19239
19401
  };
19240
19402
  });
19403
+ policies.forEach((policy2) => {
19404
+ var _a2, _b2;
19405
+ const mappedTo = [];
19406
+ if (!policy2.to) {
19407
+ mappedTo.push("public");
19408
+ } else {
19409
+ if (policy2.to && typeof policy2.to === "string") {
19410
+ mappedTo.push(policy2.to);
19411
+ } else if (policy2.to && (0, import_drizzle_orm5.is)(policy2.to, import_pg_core2.PgRole)) {
19412
+ mappedTo.push(policy2.to.name);
19413
+ } else if (policy2.to && Array.isArray(policy2.to)) {
19414
+ policy2.to.forEach((it) => {
19415
+ if (typeof it === "string") {
19416
+ mappedTo.push(it);
19417
+ } else if ((0, import_drizzle_orm5.is)(it, import_pg_core2.PgRole)) {
19418
+ mappedTo.push(it.name);
19419
+ }
19420
+ });
19421
+ }
19422
+ }
19423
+ policiesObject[policy2.name] = {
19424
+ name: policy2.name,
19425
+ as: ((_a2 = policy2.as) == null ? void 0 : _a2.toUpperCase()) ?? "PERMISSIVE",
19426
+ for: ((_b2 = policy2.for) == null ? void 0 : _b2.toUpperCase()) ?? "ALL",
19427
+ to: mappedTo.sort(),
19428
+ using: (0, import_drizzle_orm5.is)(policy2.using, import_drizzle_orm5.SQL) ? dialect4.sqlToQuery(policy2.using).sql : void 0,
19429
+ withCheck: (0, import_drizzle_orm5.is)(policy2.withCheck, import_drizzle_orm5.SQL) ? dialect4.sqlToQuery(policy2.withCheck).sql : void 0
19430
+ };
19431
+ });
19241
19432
  checks.forEach((check2) => {
19242
19433
  const checkName = check2.name;
19243
19434
  if (typeof checksInTable[`"${schema5 ?? "public"}"."${tableName}"`] !== "undefined") {
@@ -19274,7 +19465,9 @@ ${withStyle.errorWarning(
19274
19465
  foreignKeys: foreignKeysObject,
19275
19466
  compositePrimaryKeys: primaryKeysObject,
19276
19467
  uniqueConstraints: uniqueConstraintObject,
19277
- checkConstraints: checksObject
19468
+ policies: policiesObject,
19469
+ checkConstraints: checksObject,
19470
+ isRLSEnabled: enableRLS
19278
19471
  };
19279
19472
  }
19280
19473
  for (const sequence of sequences) {
@@ -19298,6 +19491,16 @@ ${withStyle.errorWarning(
19298
19491
  } else {
19299
19492
  }
19300
19493
  }
19494
+ for (const role of roles) {
19495
+ if (!role._existing) {
19496
+ rolesToReturn[role.name] = {
19497
+ name: role.name,
19498
+ createDb: role.createDb === void 0 ? false : role.createDb,
19499
+ createRole: role.createRole === void 0 ? false : role.createRole,
19500
+ inherit: role.inherit === void 0 ? true : role.inherit
19501
+ };
19502
+ }
19503
+ }
19301
19504
  const combinedViews = [...views, ...matViews];
19302
19505
  for (const view4 of combinedViews) {
19303
19506
  let viewName;
@@ -19454,6 +19657,7 @@ ${withStyle.errorWarning(
19454
19657
  enums: enumsToReturn,
19455
19658
  schemas: schemasObject,
19456
19659
  sequences: sequencesToReturn,
19660
+ roles: rolesToReturn,
19457
19661
  views: resultViews,
19458
19662
  _meta: {
19459
19663
  schemas: {},
@@ -19471,7 +19675,7 @@ ${withStyle.errorWarning(
19471
19675
  --end;
19472
19676
  return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
19473
19677
  };
19474
- fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, progressCallback) => {
19678
+ fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback) => {
19475
19679
  const result = {};
19476
19680
  const views = {};
19477
19681
  const internals = { tables: {} };
@@ -19484,7 +19688,8 @@ ${withStyle.errorWarning(
19484
19688
  WHEN c.relkind = 'r' THEN 'table'
19485
19689
  WHEN c.relkind = 'v' THEN 'view'
19486
19690
  WHEN c.relkind = 'm' THEN 'materialized_view'
19487
- END AS type
19691
+ END AS type,
19692
+ c.relrowsecurity AS rls_enabled
19488
19693
  FROM
19489
19694
  pg_catalog.pg_class c
19490
19695
  JOIN
@@ -19570,6 +19775,64 @@ WHERE
19570
19775
  if (progressCallback) {
19571
19776
  progressCallback("enums", Object.keys(enumsToReturn).length, "done");
19572
19777
  }
19778
+ const allRoles = await db.query(
19779
+ `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
19780
+ );
19781
+ const rolesToReturn = {};
19782
+ const preparedRoles = prepareRoles(entities);
19783
+ if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
19784
+ for (const dbRole of allRoles) {
19785
+ if (preparedRoles.useRoles) {
19786
+ rolesToReturn[dbRole.rolname] = {
19787
+ createDb: dbRole.rolcreatedb,
19788
+ createRole: dbRole.rolcreatedb,
19789
+ inherit: dbRole.rolinherit,
19790
+ name: dbRole.rolname
19791
+ };
19792
+ } else {
19793
+ if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)
19794
+ continue;
19795
+ if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname))
19796
+ continue;
19797
+ if (preparedRoles.excludeRoles.includes(dbRole.rolname))
19798
+ continue;
19799
+ if (!preparedRoles.includeRoles.includes(dbRole.rolname))
19800
+ continue;
19801
+ rolesToReturn[dbRole.rolname] = {
19802
+ createDb: dbRole.rolcreatedb,
19803
+ createRole: dbRole.rolcreaterole,
19804
+ inherit: dbRole.rolinherit,
19805
+ name: dbRole.rolname
19806
+ };
19807
+ }
19808
+ }
19809
+ }
19810
+ const wherePolicies = schemaFilters.map((t2) => `schemaname = '${t2}'`).join(" or ");
19811
+ const policiesByTable = {};
19812
+ 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}`};`);
19813
+ for (const dbPolicy of allPolicies) {
19814
+ const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
19815
+ const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
19816
+ const parsedTo = to;
19817
+ const parsedWithCheck = withCheck === null ? void 0 : withCheck;
19818
+ const parsedUsing = using === null ? void 0 : using;
19819
+ if (tableForPolicy) {
19820
+ tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
19821
+ } else {
19822
+ policiesByTable[`${schemaname}.${tablename}`] = {
19823
+ [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
19824
+ };
19825
+ }
19826
+ }
19827
+ if (progressCallback) {
19828
+ progressCallback(
19829
+ "policies",
19830
+ Object.values(policiesByTable).reduce((total, innerRecord) => {
19831
+ return total + Object.keys(innerRecord).length;
19832
+ }, 0),
19833
+ "done"
19834
+ );
19835
+ }
19573
19836
  const sequencesInColumns = [];
19574
19837
  const all = allTables.filter((it) => it.type === "table").map((row) => {
19575
19838
  return new Promise(async (res, rej) => {
@@ -19934,7 +20197,7 @@ WHERE
19934
20197
  }
19935
20198
  ],
19936
20199
  isUnique: indexIsUnique,
19937
- // should not be a part of diff detecs
20200
+ // should not be a part of diff detects
19938
20201
  concurrently: false,
19939
20202
  method: indexMethod,
19940
20203
  where: indexWhere === null ? void 0 : indexWhere,
@@ -19954,7 +20217,9 @@ WHERE
19954
20217
  foreignKeys: foreignKeysToReturn,
19955
20218
  compositePrimaryKeys: primaryKeys,
19956
20219
  uniqueConstraints: uniqueConstrains,
19957
- checkConstraints
20220
+ checkConstraints,
20221
+ policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {},
20222
+ isRLSEnabled: row.rls_enabled
19958
20223
  };
19959
20224
  } catch (e2) {
19960
20225
  rej(e2);
@@ -20154,6 +20419,7 @@ WHERE
20154
20419
  enums: enumsToReturn,
20155
20420
  schemas: schemasObject,
20156
20421
  sequences: sequencesToReturn,
20422
+ roles: rolesToReturn,
20157
20423
  views,
20158
20424
  _meta: {
20159
20425
  schemas: {},
@@ -21063,10 +21329,10 @@ ${filenames.join("\n")}
21063
21329
  const filenames = prepareFilenames(path5);
21064
21330
  const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
21065
21331
  const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
21066
- const { tables, enums, schemas, sequences, views, matViews } = await prepareFromPgImports2(
21332
+ const { tables, enums, schemas, sequences, views, matViews, roles } = await prepareFromPgImports2(
21067
21333
  filenames
21068
21334
  );
21069
- return generatePgSnapshot2(tables, enums, schemas, sequences, views, matViews, casing2, schemaFilter);
21335
+ return generatePgSnapshot2(tables, enums, schemas, sequences, roles, views, matViews, casing2, schemaFilter);
21070
21336
  };
21071
21337
  serializeSQLite = async (path5, casing2) => {
21072
21338
  const filenames = prepareFilenames(path5);
@@ -21261,57 +21527,57 @@ var require_heap = __commonJS({
21261
21527
  }
21262
21528
  return [].splice.apply(a, [lo, lo - lo].concat(x2)), x2;
21263
21529
  };
21264
- heappush = function(array, item, cmp) {
21530
+ heappush = function(array2, item, cmp) {
21265
21531
  if (cmp == null) {
21266
21532
  cmp = defaultCmp;
21267
21533
  }
21268
- array.push(item);
21269
- return _siftdown(array, 0, array.length - 1, cmp);
21534
+ array2.push(item);
21535
+ return _siftdown(array2, 0, array2.length - 1, cmp);
21270
21536
  };
21271
- heappop = function(array, cmp) {
21537
+ heappop = function(array2, cmp) {
21272
21538
  var lastelt, returnitem;
21273
21539
  if (cmp == null) {
21274
21540
  cmp = defaultCmp;
21275
21541
  }
21276
- lastelt = array.pop();
21277
- if (array.length) {
21278
- returnitem = array[0];
21279
- array[0] = lastelt;
21280
- _siftup(array, 0, cmp);
21542
+ lastelt = array2.pop();
21543
+ if (array2.length) {
21544
+ returnitem = array2[0];
21545
+ array2[0] = lastelt;
21546
+ _siftup(array2, 0, cmp);
21281
21547
  } else {
21282
21548
  returnitem = lastelt;
21283
21549
  }
21284
21550
  return returnitem;
21285
21551
  };
21286
- heapreplace = function(array, item, cmp) {
21552
+ heapreplace = function(array2, item, cmp) {
21287
21553
  var returnitem;
21288
21554
  if (cmp == null) {
21289
21555
  cmp = defaultCmp;
21290
21556
  }
21291
- returnitem = array[0];
21292
- array[0] = item;
21293
- _siftup(array, 0, cmp);
21557
+ returnitem = array2[0];
21558
+ array2[0] = item;
21559
+ _siftup(array2, 0, cmp);
21294
21560
  return returnitem;
21295
21561
  };
21296
- heappushpop = function(array, item, cmp) {
21562
+ heappushpop = function(array2, item, cmp) {
21297
21563
  var _ref;
21298
21564
  if (cmp == null) {
21299
21565
  cmp = defaultCmp;
21300
21566
  }
21301
- if (array.length && cmp(array[0], item) < 0) {
21302
- _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
21303
- _siftup(array, 0, cmp);
21567
+ if (array2.length && cmp(array2[0], item) < 0) {
21568
+ _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
21569
+ _siftup(array2, 0, cmp);
21304
21570
  }
21305
21571
  return item;
21306
21572
  };
21307
- heapify = function(array, cmp) {
21573
+ heapify = function(array2, cmp) {
21308
21574
  var i2, _i, _j, _len, _ref, _ref1, _results, _results1;
21309
21575
  if (cmp == null) {
21310
21576
  cmp = defaultCmp;
21311
21577
  }
21312
21578
  _ref1 = function() {
21313
21579
  _results1 = [];
21314
- for (var _j2 = 0, _ref2 = floor(array.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
21580
+ for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
21315
21581
  _results1.push(_j2);
21316
21582
  }
21317
21583
  return _results1;
@@ -21319,51 +21585,51 @@ var require_heap = __commonJS({
21319
21585
  _results = [];
21320
21586
  for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
21321
21587
  i2 = _ref1[_i];
21322
- _results.push(_siftup(array, i2, cmp));
21588
+ _results.push(_siftup(array2, i2, cmp));
21323
21589
  }
21324
21590
  return _results;
21325
21591
  };
21326
- updateItem = function(array, item, cmp) {
21592
+ updateItem = function(array2, item, cmp) {
21327
21593
  var pos;
21328
21594
  if (cmp == null) {
21329
21595
  cmp = defaultCmp;
21330
21596
  }
21331
- pos = array.indexOf(item);
21597
+ pos = array2.indexOf(item);
21332
21598
  if (pos === -1) {
21333
21599
  return;
21334
21600
  }
21335
- _siftdown(array, 0, pos, cmp);
21336
- return _siftup(array, pos, cmp);
21601
+ _siftdown(array2, 0, pos, cmp);
21602
+ return _siftup(array2, pos, cmp);
21337
21603
  };
21338
- nlargest = function(array, n, cmp) {
21604
+ nlargest = function(array2, n, cmp) {
21339
21605
  var elem, result, _i, _len, _ref;
21340
21606
  if (cmp == null) {
21341
21607
  cmp = defaultCmp;
21342
21608
  }
21343
- result = array.slice(0, n);
21609
+ result = array2.slice(0, n);
21344
21610
  if (!result.length) {
21345
21611
  return result;
21346
21612
  }
21347
21613
  heapify(result, cmp);
21348
- _ref = array.slice(n);
21614
+ _ref = array2.slice(n);
21349
21615
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
21350
21616
  elem = _ref[_i];
21351
21617
  heappushpop(result, elem, cmp);
21352
21618
  }
21353
21619
  return result.sort(cmp).reverse();
21354
21620
  };
21355
- nsmallest = function(array, n, cmp) {
21621
+ nsmallest = function(array2, n, cmp) {
21356
21622
  var elem, i2, los, result, _i, _j, _len, _ref, _ref1, _results;
21357
21623
  if (cmp == null) {
21358
21624
  cmp = defaultCmp;
21359
21625
  }
21360
- if (n * 10 <= array.length) {
21361
- result = array.slice(0, n).sort(cmp);
21626
+ if (n * 10 <= array2.length) {
21627
+ result = array2.slice(0, n).sort(cmp);
21362
21628
  if (!result.length) {
21363
21629
  return result;
21364
21630
  }
21365
21631
  los = result[result.length - 1];
21366
- _ref = array.slice(n);
21632
+ _ref = array2.slice(n);
21367
21633
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
21368
21634
  elem = _ref[_i];
21369
21635
  if (cmp(elem, los) < 0) {
@@ -21374,51 +21640,51 @@ var require_heap = __commonJS({
21374
21640
  }
21375
21641
  return result;
21376
21642
  }
21377
- heapify(array, cmp);
21643
+ heapify(array2, cmp);
21378
21644
  _results = [];
21379
- for (i2 = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 0 <= _ref1 ? ++_j : --_j) {
21380
- _results.push(heappop(array, cmp));
21645
+ for (i2 = _j = 0, _ref1 = min(n, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 0 <= _ref1 ? ++_j : --_j) {
21646
+ _results.push(heappop(array2, cmp));
21381
21647
  }
21382
21648
  return _results;
21383
21649
  };
21384
- _siftdown = function(array, startpos, pos, cmp) {
21650
+ _siftdown = function(array2, startpos, pos, cmp) {
21385
21651
  var newitem, parent, parentpos;
21386
21652
  if (cmp == null) {
21387
21653
  cmp = defaultCmp;
21388
21654
  }
21389
- newitem = array[pos];
21655
+ newitem = array2[pos];
21390
21656
  while (pos > startpos) {
21391
21657
  parentpos = pos - 1 >> 1;
21392
- parent = array[parentpos];
21658
+ parent = array2[parentpos];
21393
21659
  if (cmp(newitem, parent) < 0) {
21394
- array[pos] = parent;
21660
+ array2[pos] = parent;
21395
21661
  pos = parentpos;
21396
21662
  continue;
21397
21663
  }
21398
21664
  break;
21399
21665
  }
21400
- return array[pos] = newitem;
21666
+ return array2[pos] = newitem;
21401
21667
  };
21402
- _siftup = function(array, pos, cmp) {
21668
+ _siftup = function(array2, pos, cmp) {
21403
21669
  var childpos, endpos, newitem, rightpos, startpos;
21404
21670
  if (cmp == null) {
21405
21671
  cmp = defaultCmp;
21406
21672
  }
21407
- endpos = array.length;
21673
+ endpos = array2.length;
21408
21674
  startpos = pos;
21409
- newitem = array[pos];
21675
+ newitem = array2[pos];
21410
21676
  childpos = 2 * pos + 1;
21411
21677
  while (childpos < endpos) {
21412
21678
  rightpos = childpos + 1;
21413
- if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
21679
+ if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
21414
21680
  childpos = rightpos;
21415
21681
  }
21416
- array[pos] = array[childpos];
21682
+ array2[pos] = array2[childpos];
21417
21683
  pos = childpos;
21418
21684
  childpos = 2 * pos + 1;
21419
21685
  }
21420
- array[pos] = newitem;
21421
- return _siftdown(array, startpos, pos, cmp);
21686
+ array2[pos] = newitem;
21687
+ return _siftdown(array2, startpos, pos, cmp);
21422
21688
  };
21423
21689
  Heap = function() {
21424
21690
  Heap2.push = heappush;
@@ -23331,12 +23597,12 @@ var require_lib = __commonJS({
23331
23597
  }
23332
23598
  return bestMatch;
23333
23599
  }
23334
- scalarize(array, originals, fuzzyOriginals) {
23600
+ scalarize(array2, originals, fuzzyOriginals) {
23335
23601
  const fuzzyMatches = [];
23336
23602
  if (fuzzyOriginals) {
23337
23603
  const keyScores = {};
23338
- for (let index4 = 0; index4 < array.length; index4++) {
23339
- const item = array[index4];
23604
+ for (let index4 = 0; index4 < array2.length; index4++) {
23605
+ const item = array2[index4];
23340
23606
  if (this.isScalar(item)) {
23341
23607
  continue;
23342
23608
  }
@@ -23350,8 +23616,8 @@ var require_lib = __commonJS({
23350
23616
  }
23351
23617
  }
23352
23618
  const result = [];
23353
- for (let index4 = 0; index4 < array.length; index4++) {
23354
- const item = array[index4];
23619
+ for (let index4 = 0; index4 < array2.length; index4++) {
23620
+ const item = array2[index4];
23355
23621
  if (this.isScalar(item)) {
23356
23622
  result.push(item);
23357
23623
  } else {
@@ -23573,6 +23839,37 @@ function diffColumns(left, right) {
23573
23839
  );
23574
23840
  return alteredTables;
23575
23841
  }
23842
+ function diffPolicies(left, right) {
23843
+ left = JSON.parse(JSON.stringify(left));
23844
+ right = JSON.parse(JSON.stringify(right));
23845
+ const result = (0, import_json_diff.diff)(left, right) ?? {};
23846
+ const alteredTables = Object.fromEntries(
23847
+ Object.entries(result).filter((it) => {
23848
+ return !(it[0].includes("__added") || it[0].includes("__deleted"));
23849
+ }).map((tableEntry) => {
23850
+ const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
23851
+ return it[0].endsWith("__deleted");
23852
+ }).map((it) => {
23853
+ return it[1];
23854
+ });
23855
+ const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
23856
+ return it[0].endsWith("__added");
23857
+ }).map((it) => {
23858
+ return it[1];
23859
+ });
23860
+ tableEntry[1].policies = {
23861
+ added: addedPolicies,
23862
+ deleted: deletedPolicies
23863
+ };
23864
+ const table4 = left[tableEntry[0]];
23865
+ return [
23866
+ tableEntry[0],
23867
+ { name: table4.name, schema: table4.schema, ...tableEntry[1] }
23868
+ ];
23869
+ })
23870
+ );
23871
+ return alteredTables;
23872
+ }
23576
23873
  function applyJsonDiff(json1, json2) {
23577
23874
  json1 = JSON.parse(JSON.stringify(json1));
23578
23875
  json2 = JSON.parse(JSON.stringify(json2));
@@ -23582,6 +23879,7 @@ function applyJsonDiff(json1, json2) {
23582
23879
  difference.tables = difference.tables || {};
23583
23880
  difference.enums = difference.enums || {};
23584
23881
  difference.sequences = difference.sequences || {};
23882
+ difference.roles = difference.roles || {};
23585
23883
  difference.views = difference.views || {};
23586
23884
  const schemaKeys = Object.keys(difference.schemas);
23587
23885
  for (let key of schemaKeys) {
@@ -23638,6 +23936,10 @@ function applyJsonDiff(json1, json2) {
23638
23936
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
23639
23937
  return json2.sequences[it[0]];
23640
23938
  });
23939
+ const rolesEntries = Object.entries(difference.roles);
23940
+ const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
23941
+ return json2.roles[it[0]];
23942
+ });
23641
23943
  const viewsEntries = Object.entries(difference.views);
23642
23944
  const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
23643
23945
  ([nameWithSchema, view4]) => {
@@ -23717,6 +24019,7 @@ function applyJsonDiff(json1, json2) {
23717
24019
  alteredTablesWithColumns,
23718
24020
  alteredEnums,
23719
24021
  alteredSequences,
24022
+ alteredRoles,
23720
24023
  alteredViews
23721
24024
  };
23722
24025
  }
@@ -23777,6 +24080,21 @@ var init_jsonDiffer = __esm({
23777
24080
  return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
23778
24081
  })
23779
24082
  );
24083
+ const deletedPolicies = Object.fromEntries(
24084
+ Object.entries(table4.policies__deleted || {}).concat(
24085
+ Object.entries(table4.policies || {}).filter((it) => it[0].includes("__deleted"))
24086
+ ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
24087
+ );
24088
+ const addedPolicies = Object.fromEntries(
24089
+ Object.entries(table4.policies__added || {}).concat(
24090
+ Object.entries(table4.policies || {}).filter((it) => it[0].includes("__added"))
24091
+ ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
24092
+ );
24093
+ const alteredPolicies = Object.fromEntries(
24094
+ Object.entries(table4.policies || {}).filter((it) => {
24095
+ return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
24096
+ })
24097
+ );
23780
24098
  const deletedForeignKeys = Object.fromEntries(
23781
24099
  Object.entries(table4.foreignKeys__deleted || {}).concat(
23782
24100
  Object.entries(table4.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
@@ -23854,6 +24172,9 @@ var init_jsonDiffer = __esm({
23854
24172
  addedUniqueConstraints,
23855
24173
  deletedUniqueConstraints,
23856
24174
  alteredUniqueConstraints,
24175
+ deletedPolicies,
24176
+ addedPolicies,
24177
+ alteredPolicies,
23857
24178
  addedCheckConstraints,
23858
24179
  deletedCheckConstraints,
23859
24180
  alteredCheckConstraints
@@ -24156,7 +24477,7 @@ function fromJson(statements, dialect4, action, json2) {
24156
24477
  }).filter((it) => it !== "");
24157
24478
  return result;
24158
24479
  }
24159
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
24480
+ var pgNativeTypes, isPgNativeType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, convertors;
24160
24481
  var init_sqlgenerator = __esm({
24161
24482
  "src/sqlgenerator.ts"() {
24162
24483
  "use strict";
@@ -24209,16 +24530,114 @@ var init_sqlgenerator = __esm({
24209
24530
  if (pgNativeTypes.has(it))
24210
24531
  return true;
24211
24532
  const toCheck = it.replace(/ /g, "");
24212
- return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("doubleprecision[") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || toCheck.startsWith("geography(") || /^(\w+)(\[\d*])+$/.test(it);
24533
+ return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("doubleprecision[") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
24213
24534
  };
24214
24535
  Convertor = class {
24215
24536
  };
24537
+ PgCreateRoleConvertor = class extends Convertor {
24538
+ can(statement, dialect4) {
24539
+ return statement.type === "create_role" && dialect4 === "postgresql";
24540
+ }
24541
+ convert(statement) {
24542
+ 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"}` : ""};`;
24543
+ }
24544
+ };
24545
+ PgDropRoleConvertor = class extends Convertor {
24546
+ can(statement, dialect4) {
24547
+ return statement.type === "drop_role" && dialect4 === "postgresql";
24548
+ }
24549
+ convert(statement) {
24550
+ return `DROP ROLE "${statement.name}";`;
24551
+ }
24552
+ };
24553
+ PgRenameRoleConvertor = class extends Convertor {
24554
+ can(statement, dialect4) {
24555
+ return statement.type === "rename_role" && dialect4 === "postgresql";
24556
+ }
24557
+ convert(statement) {
24558
+ return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
24559
+ }
24560
+ };
24561
+ PgAlterRoleConvertor = class extends Convertor {
24562
+ can(statement, dialect4) {
24563
+ return statement.type === "alter_role" && dialect4 === "postgresql";
24564
+ }
24565
+ convert(statement) {
24566
+ return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
24567
+ }
24568
+ };
24569
+ PgCreatePolicyConvertor = class extends Convertor {
24570
+ can(statement, dialect4) {
24571
+ return statement.type === "create_policy" && dialect4 === "postgresql";
24572
+ }
24573
+ convert(statement) {
24574
+ var _a, _b, _c;
24575
+ const policy2 = statement.data;
24576
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
24577
+ const usingPart = policy2.using ? ` USING (${policy2.using})` : "";
24578
+ const withCheckPart = policy2.withCheck ? ` WITH CHECK (${policy2.withCheck})` : "";
24579
+ const policyToPart = (_a = policy2.to) == null ? void 0 : _a.map(
24580
+ (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
24581
+ ).join(", ");
24582
+ 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};`;
24583
+ }
24584
+ };
24585
+ PgDropPolicyConvertor = class extends Convertor {
24586
+ can(statement, dialect4) {
24587
+ return statement.type === "drop_policy" && dialect4 === "postgresql";
24588
+ }
24589
+ convert(statement) {
24590
+ const policy2 = statement.data;
24591
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
24592
+ return `DROP POLICY "${policy2.name}" ON ${tableNameWithSchema} CASCADE;`;
24593
+ }
24594
+ };
24595
+ PgRenamePolicyConvertor = class extends Convertor {
24596
+ can(statement, dialect4) {
24597
+ return statement.type === "rename_policy" && dialect4 === "postgresql";
24598
+ }
24599
+ convert(statement) {
24600
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
24601
+ return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
24602
+ }
24603
+ };
24604
+ PgAlterPolicyConvertor = class extends Convertor {
24605
+ can(statement, dialect4) {
24606
+ return statement.type === "alter_policy" && dialect4 === "postgresql";
24607
+ }
24608
+ convert(statement) {
24609
+ const newPolicy = PgSquasher.unsquashPolicy(statement.newData);
24610
+ const oldPolicy = PgSquasher.unsquashPolicy(statement.oldData);
24611
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
24612
+ const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
24613
+ const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : "";
24614
+ return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
24615
+ }
24616
+ };
24617
+ PgEnableRlsConvertor = class extends Convertor {
24618
+ can(statement, dialect4) {
24619
+ return statement.type === "enable_rls" && dialect4 === "postgresql";
24620
+ }
24621
+ convert(statement) {
24622
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
24623
+ return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
24624
+ }
24625
+ };
24626
+ PgDisableRlsConvertor = class extends Convertor {
24627
+ can(statement, dialect4) {
24628
+ return statement.type === "disable_rls" && dialect4 === "postgresql";
24629
+ }
24630
+ convert(statement) {
24631
+ const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
24632
+ return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
24633
+ }
24634
+ };
24216
24635
  PgCreateTableConvertor = class extends Convertor {
24217
24636
  can(statement, dialect4) {
24218
24637
  return statement.type === "create_table" && dialect4 === "postgresql";
24219
24638
  }
24220
24639
  convert(st) {
24221
- const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints, checkConstraints } = st;
24640
+ const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
24222
24641
  let statement = "";
24223
24642
  const name = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
24224
24643
  statement += `CREATE TABLE IF NOT EXISTS ${name} (
@@ -24262,7 +24681,12 @@ var init_sqlgenerator = __esm({
24262
24681
  );`;
24263
24682
  statement += `
24264
24683
  `;
24265
- return statement;
24684
+ const enableRls = new PgEnableRlsConvertor().convert({
24685
+ type: "enable_rls",
24686
+ tableName,
24687
+ schema: schema5
24688
+ });
24689
+ return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
24266
24690
  }
24267
24691
  };
24268
24692
  MySqlCreateTableConvertor = class extends Convertor {
@@ -24867,9 +25291,21 @@ WITH ${withCheckOption} CHECK OPTION` : "";
24867
25291
  return statement.type === "drop_table" && dialect4 === "postgresql";
24868
25292
  }
24869
25293
  convert(statement) {
24870
- const { tableName, schema: schema5 } = statement;
25294
+ const { tableName, schema: schema5, policies } = statement;
24871
25295
  const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
24872
- return `DROP TABLE ${tableNameWithSchema};`;
25296
+ const dropPolicyConvertor = new PgDropPolicyConvertor();
25297
+ const droppedPolicies = (policies == null ? void 0 : policies.map((p2) => {
25298
+ return dropPolicyConvertor.convert({
25299
+ type: "drop_policy",
25300
+ tableName,
25301
+ data: PgSquasher.unsquashPolicy(p2),
25302
+ schema: schema5
25303
+ });
25304
+ })) ?? [];
25305
+ return [
25306
+ ...droppedPolicies,
25307
+ `DROP TABLE ${tableNameWithSchema} CASCADE;`
25308
+ ];
24873
25309
  }
24874
25310
  };
24875
25311
  MySQLDropTableConvertor = class extends Convertor {
@@ -26074,6 +26510,16 @@ ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT ${statement.newCo
26074
26510
  convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
26075
26511
  convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
26076
26512
  convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
26513
+ convertors.push(new PgAlterPolicyConvertor());
26514
+ convertors.push(new PgCreatePolicyConvertor());
26515
+ convertors.push(new PgDropPolicyConvertor());
26516
+ convertors.push(new PgRenamePolicyConvertor());
26517
+ convertors.push(new PgEnableRlsConvertor());
26518
+ convertors.push(new PgDisableRlsConvertor());
26519
+ convertors.push(new PgDropRoleConvertor());
26520
+ convertors.push(new PgAlterRoleConvertor());
26521
+ convertors.push(new PgCreateRoleConvertor());
26522
+ convertors.push(new PgRenameRoleConvertor());
26077
26523
  convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
26078
26524
  convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
26079
26525
  convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
@@ -26374,7 +26820,7 @@ var init_sqlitePushUtils = __esm({
26374
26820
  });
26375
26821
 
26376
26822
  // src/jsonStatements.ts
26377
- var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
26823
+ var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, 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, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
26378
26824
  var init_jsonStatements = __esm({
26379
26825
  "src/jsonStatements.ts"() {
26380
26826
  "use strict";
@@ -26385,7 +26831,7 @@ var init_jsonStatements = __esm({
26385
26831
  init_pgSchema();
26386
26832
  init_sqliteSchema();
26387
26833
  preparePgCreateTableJson = (table4, json2) => {
26388
- const { name, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table4;
26834
+ const { name, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table4;
26389
26835
  const tableKey2 = `${schema5 || "public"}.${name}`;
26390
26836
  const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
26391
26837
  return {
@@ -26396,7 +26842,9 @@ var init_jsonStatements = __esm({
26396
26842
  compositePKs: Object.values(compositePrimaryKeys),
26397
26843
  compositePkName,
26398
26844
  uniqueConstraints: Object.values(uniqueConstraints),
26399
- checkConstraints: Object.values(checkConstraints)
26845
+ policies: Object.values(policies),
26846
+ checkConstraints: Object.values(checkConstraints),
26847
+ isRLSEnabled: isRLSEnabled ?? false
26400
26848
  };
26401
26849
  };
26402
26850
  prepareMySqlCreateTableJson = (table4, json2, internals) => {
@@ -26436,7 +26884,8 @@ var init_jsonStatements = __esm({
26436
26884
  return {
26437
26885
  type: "drop_table",
26438
26886
  tableName: table4.name,
26439
- schema: table4.schema
26887
+ schema: table4.schema,
26888
+ policies: table4.policies ? Object.values(table4.policies) : []
26440
26889
  };
26441
26890
  };
26442
26891
  prepareRenameTableJson = (tableFrom, tableTo) => {
@@ -26555,6 +27004,41 @@ var init_jsonStatements = __esm({
26555
27004
  schema: schema5
26556
27005
  };
26557
27006
  };
27007
+ prepareCreateRoleJson = (role) => {
27008
+ return {
27009
+ type: "create_role",
27010
+ name: role.name,
27011
+ values: {
27012
+ createDb: role.createDb,
27013
+ createRole: role.createRole,
27014
+ inherit: role.inherit
27015
+ }
27016
+ };
27017
+ };
27018
+ prepareAlterRoleJson = (role) => {
27019
+ return {
27020
+ type: "alter_role",
27021
+ name: role.name,
27022
+ values: {
27023
+ createDb: role.createDb,
27024
+ createRole: role.createRole,
27025
+ inherit: role.inherit
27026
+ }
27027
+ };
27028
+ };
27029
+ prepareDropRoleJson = (name) => {
27030
+ return {
27031
+ type: "drop_role",
27032
+ name
27033
+ };
27034
+ };
27035
+ prepareRenameRoleJson = (nameFrom, nameTo) => {
27036
+ return {
27037
+ type: "rename_role",
27038
+ nameFrom,
27039
+ nameTo
27040
+ };
27041
+ };
26558
27042
  prepareCreateSchemasJson = (values) => {
26559
27043
  return values.map((it) => {
26560
27044
  return {
@@ -27455,6 +27939,46 @@ var init_jsonStatements = __esm({
27455
27939
  }
27456
27940
  return [...dropPkStatements, ...setPkStatements, ...statements];
27457
27941
  };
27942
+ prepareRenamePolicyJsons = (tableName, schema5, renames) => {
27943
+ return renames.map((it) => {
27944
+ return {
27945
+ type: "rename_policy",
27946
+ tableName,
27947
+ oldName: it.from.name,
27948
+ newName: it.to.name,
27949
+ schema: schema5
27950
+ };
27951
+ });
27952
+ };
27953
+ prepareCreatePolicyJsons = (tableName, schema5, policies) => {
27954
+ return policies.map((it) => {
27955
+ return {
27956
+ type: "create_policy",
27957
+ tableName,
27958
+ data: it,
27959
+ schema: schema5
27960
+ };
27961
+ });
27962
+ };
27963
+ prepareDropPolicyJsons = (tableName, schema5, policies) => {
27964
+ return policies.map((it) => {
27965
+ return {
27966
+ type: "drop_policy",
27967
+ tableName,
27968
+ data: it,
27969
+ schema: schema5
27970
+ };
27971
+ });
27972
+ };
27973
+ prepareAlterPolicyJson = (tableName, schema5, oldPolicy, newPolicy) => {
27974
+ return {
27975
+ type: "alter_policy",
27976
+ tableName,
27977
+ oldData: oldPolicy,
27978
+ newData: newPolicy,
27979
+ schema: schema5
27980
+ };
27981
+ };
27458
27982
  preparePgCreateIndexesJson = (tableName, schema5, indexes, fullSchema, action) => {
27459
27983
  if (action === "push") {
27460
27984
  return Object.values(indexes).map((indexData) => {
@@ -28253,7 +28777,9 @@ var init_snapshotsDiffer = __esm({
28253
28777
  foreignKeys: recordType(stringType(), stringType()),
28254
28778
  compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
28255
28779
  uniqueConstraints: recordType(stringType(), stringType()).default({}),
28256
- checkConstraints: recordType(stringType(), stringType()).default({})
28780
+ policies: recordType(stringType(), stringType()).default({}),
28781
+ checkConstraints: recordType(stringType(), stringType()).default({}),
28782
+ isRLSEnabled: booleanType().default(false)
28257
28783
  }).strict();
28258
28784
  alteredTableScheme = objectType({
28259
28785
  name: stringType(),
@@ -28295,6 +28821,15 @@ var init_snapshotsDiffer = __esm({
28295
28821
  __old: stringType()
28296
28822
  })
28297
28823
  ),
28824
+ addedPolicies: recordType(stringType(), stringType()),
28825
+ deletedPolicies: recordType(stringType(), stringType()),
28826
+ alteredPolicies: recordType(
28827
+ stringType(),
28828
+ objectType({
28829
+ __new: stringType(),
28830
+ __old: stringType()
28831
+ })
28832
+ ),
28298
28833
  addedCheckConstraints: recordType(
28299
28834
  stringType(),
28300
28835
  stringType()
@@ -28356,6 +28891,7 @@ var init_snapshotsDiffer = __esm({
28356
28891
  alteredTablesWithColumns: alteredTableScheme.array(),
28357
28892
  alteredEnums: changedEnumSchema.array(),
28358
28893
  alteredSequences: sequenceSquashed.array(),
28894
+ alteredRoles: roleSchema.array(),
28359
28895
  alteredViews: alteredPgViewSchema.array()
28360
28896
  }).strict();
28361
28897
  diffResultSchemeMysql = objectType({
@@ -28413,7 +28949,7 @@ var init_snapshotsDiffer = __esm({
28413
28949
  }
28414
28950
  return column7;
28415
28951
  };
28416
- applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
28952
+ applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
28417
28953
  const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
28418
28954
  const {
28419
28955
  created: createdSchemas,
@@ -28563,6 +29099,47 @@ var init_snapshotsDiffer = __esm({
28563
29099
  return [tableKey2, tableValue];
28564
29100
  }
28565
29101
  );
29102
+ const rolesDiff = diffSchemasOrTables(
29103
+ schemasPatchedSnap1.roles,
29104
+ json2.roles
29105
+ );
29106
+ const {
29107
+ created: createdRoles,
29108
+ deleted: deletedRoles,
29109
+ renamed: renamedRoles
29110
+ } = await roleResolver2({
29111
+ created: rolesDiff.added,
29112
+ deleted: rolesDiff.deleted
29113
+ });
29114
+ schemasPatchedSnap1.roles = mapEntries(
29115
+ schemasPatchedSnap1.roles,
29116
+ (_2, it) => {
29117
+ const { name } = nameChangeFor(it, renamedRoles);
29118
+ it.name = name;
29119
+ return [name, it];
29120
+ }
29121
+ );
29122
+ const rolesChangeMap = renamedRoles.reduce(
29123
+ (acc, it) => {
29124
+ acc[it.from.name] = {
29125
+ nameFrom: it.from.name,
29126
+ nameTo: it.to.name
29127
+ };
29128
+ return acc;
29129
+ },
29130
+ {}
29131
+ );
29132
+ schemasPatchedSnap1.roles = mapEntries(
29133
+ schemasPatchedSnap1.roles,
29134
+ (roleKey, roleValue) => {
29135
+ const key = roleKey;
29136
+ const change = rolesChangeMap[key];
29137
+ if (change) {
29138
+ roleValue.name = change.nameTo;
29139
+ }
29140
+ return [roleKey, roleValue];
29141
+ }
29142
+ );
28566
29143
  const tablesDiff = diffSchemasOrTables(
28567
29144
  schemasPatchedSnap1.tables,
28568
29145
  json2.tables
@@ -28641,7 +29218,66 @@ var init_snapshotsDiffer = __esm({
28641
29218
  return [tableKey2, tableValue];
28642
29219
  }
28643
29220
  );
28644
- const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
29221
+ const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
29222
+ const policyRenames = [];
29223
+ const policyCreates = [];
29224
+ const policyDeletes = [];
29225
+ for (let entry of Object.values(policyRes)) {
29226
+ const { renamed, created, deleted } = await policyResolver2({
29227
+ tableName: entry.name,
29228
+ schema: entry.schema,
29229
+ deleted: entry.policies.deleted.map(PgSquasher.unsquashPolicy),
29230
+ created: entry.policies.added.map(PgSquasher.unsquashPolicy)
29231
+ });
29232
+ if (created.length > 0) {
29233
+ policyCreates.push({
29234
+ table: entry.name,
29235
+ schema: entry.schema,
29236
+ columns: created
29237
+ });
29238
+ }
29239
+ if (deleted.length > 0) {
29240
+ policyDeletes.push({
29241
+ table: entry.name,
29242
+ schema: entry.schema,
29243
+ columns: deleted
29244
+ });
29245
+ }
29246
+ if (renamed.length > 0) {
29247
+ policyRenames.push({
29248
+ table: entry.name,
29249
+ schema: entry.schema,
29250
+ renames: renamed
29251
+ });
29252
+ }
29253
+ }
29254
+ const policyRenamesDict = columnRenames.reduce(
29255
+ (acc, it) => {
29256
+ acc[`${it.schema || "public"}.${it.table}`] = it.renames;
29257
+ return acc;
29258
+ },
29259
+ {}
29260
+ );
29261
+ const policyPatchedSnap1 = copy(tablesPatchedSnap1);
29262
+ policyPatchedSnap1.tables = mapEntries(
29263
+ policyPatchedSnap1.tables,
29264
+ (tableKey2, tableValue) => {
29265
+ const patchedPolicies = mapKeys(
29266
+ tableValue.policies,
29267
+ (policyKey, policy2) => {
29268
+ const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
29269
+ const newName = columnChangeFor(policyKey, rens);
29270
+ const unsquashedPolicy = PgSquasher.unsquashPolicy(policy2);
29271
+ unsquashedPolicy.name = newName;
29272
+ policy2 = PgSquasher.squashPolicy(unsquashedPolicy);
29273
+ return newName;
29274
+ }
29275
+ );
29276
+ tableValue.policies = patchedPolicies;
29277
+ return [tableKey2, tableValue];
29278
+ }
29279
+ );
29280
+ const viewsDiff = diffSchemasOrTables(policyPatchedSnap1.views, json2.views);
28645
29281
  const {
28646
29282
  created: createdViews,
28647
29283
  deleted: deletedViews,
@@ -28659,7 +29295,7 @@ var init_snapshotsDiffer = __esm({
28659
29295
  movedViews.forEach((it) => {
28660
29296
  movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
28661
29297
  });
28662
- const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
29298
+ const viewsPatchedSnap1 = copy(policyPatchedSnap1);
28663
29299
  viewsPatchedSnap1.views = mapEntries(
28664
29300
  viewsPatchedSnap1.views,
28665
29301
  (viewKey, viewValue) => {
@@ -28718,13 +29354,15 @@ var init_snapshotsDiffer = __esm({
28718
29354
  const jsonDeletedUniqueConstraints = [];
28719
29355
  const jsonAlteredUniqueConstraints = [];
28720
29356
  const jsonSetTableSchemas = [];
28721
- for (let it of movedTables) {
28722
- jsonSetTableSchemas.push({
28723
- type: "alter_table_set_schema",
28724
- tableName: it.name,
28725
- schemaFrom: it.schemaFrom || "public",
28726
- schemaTo: it.schemaTo || "public"
28727
- });
29357
+ if (movedTables) {
29358
+ for (let it of movedTables) {
29359
+ jsonSetTableSchemas.push({
29360
+ type: "alter_table_set_schema",
29361
+ tableName: it.name,
29362
+ schemaFrom: it.schemaFrom || "public",
29363
+ schemaTo: it.schemaTo || "public"
29364
+ });
29365
+ }
28728
29366
  }
28729
29367
  const jsonDeletedCheckConstraints = [];
28730
29368
  const jsonCreatedCheckConstraints = [];
@@ -28851,7 +29489,106 @@ var init_snapshotsDiffer = __esm({
28851
29489
  it.deletedIndexes || {}
28852
29490
  );
28853
29491
  }).flat();
29492
+ const jsonCreatePoliciesStatements = [];
29493
+ const jsonDropPoliciesStatements = [];
29494
+ const jsonAlterPoliciesStatements = [];
29495
+ const jsonRenamePoliciesStatements = [];
29496
+ const jsonEnableRLSStatements = [];
29497
+ const jsonDisableRLSStatements = [];
29498
+ for (let it of policyRenames) {
29499
+ jsonRenamePoliciesStatements.push(
29500
+ ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
29501
+ );
29502
+ }
29503
+ for (const it of policyCreates) {
29504
+ jsonCreatePoliciesStatements.push(
29505
+ ...prepareCreatePolicyJsons(
29506
+ it.table,
29507
+ it.schema,
29508
+ it.columns
29509
+ )
29510
+ );
29511
+ }
29512
+ for (const it of policyDeletes) {
29513
+ jsonDropPoliciesStatements.push(
29514
+ ...prepareDropPolicyJsons(
29515
+ it.table,
29516
+ it.schema,
29517
+ it.columns
29518
+ )
29519
+ );
29520
+ }
28854
29521
  alteredTables.forEach((it) => {
29522
+ Object.keys(it.alteredPolicies).forEach((policyName) => {
29523
+ const newPolicy = PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
29524
+ const oldPolicy = PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
29525
+ if (newPolicy.as !== oldPolicy.as) {
29526
+ jsonDropPoliciesStatements.push(
29527
+ ...prepareDropPolicyJsons(
29528
+ it.name,
29529
+ it.schema,
29530
+ [oldPolicy]
29531
+ )
29532
+ );
29533
+ jsonCreatePoliciesStatements.push(
29534
+ ...prepareCreatePolicyJsons(
29535
+ it.name,
29536
+ it.schema,
29537
+ [newPolicy]
29538
+ )
29539
+ );
29540
+ return;
29541
+ }
29542
+ if (newPolicy.for !== oldPolicy.for) {
29543
+ jsonDropPoliciesStatements.push(
29544
+ ...prepareDropPolicyJsons(
29545
+ it.name,
29546
+ it.schema,
29547
+ [oldPolicy]
29548
+ )
29549
+ );
29550
+ jsonCreatePoliciesStatements.push(
29551
+ ...prepareCreatePolicyJsons(
29552
+ it.name,
29553
+ it.schema,
29554
+ [newPolicy]
29555
+ )
29556
+ );
29557
+ return;
29558
+ }
29559
+ jsonAlterPoliciesStatements.push(
29560
+ prepareAlterPolicyJson(
29561
+ it.name,
29562
+ it.schema,
29563
+ it.alteredPolicies[policyName].__old,
29564
+ it.alteredPolicies[policyName].__new
29565
+ )
29566
+ );
29567
+ });
29568
+ for (const table4 of Object.values(json2.tables)) {
29569
+ const policiesInCurrentState = Object.keys(table4.policies);
29570
+ const tableInPreviousState = columnsPatchedSnap1.tables[`${table4.schema === "" ? "public" : table4.schema}.${table4.name}`];
29571
+ const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
29572
+ if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table4.isRLSEnabled) {
29573
+ jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table4.name, schema: table4.schema });
29574
+ }
29575
+ if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table4.isRLSEnabled) {
29576
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
29577
+ }
29578
+ if (table4.isRLSEnabled !== tableInPreviousState.isRLSEnabled) {
29579
+ if (table4.isRLSEnabled) {
29580
+ jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table4.name, schema: table4.schema });
29581
+ } else if (!table4.isRLSEnabled && policiesInCurrentState.length === 0) {
29582
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
29583
+ }
29584
+ }
29585
+ }
29586
+ for (const table4 of Object.values(columnsPatchedSnap1.tables)) {
29587
+ const tableInCurrentState = json2.tables[`${table4.schema === "" ? "public" : table4.schema}.${table4.name}`];
29588
+ if (tableInCurrentState === void 0 && !table4.isRLSEnabled) {
29589
+ jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table4.name, schema: table4.schema });
29590
+ }
29591
+ }
28855
29592
  const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
28856
29593
  (current, item) => {
28857
29594
  current[item] = it.alteredIndexes[item].__old;
@@ -28939,6 +29676,18 @@ var init_snapshotsDiffer = __esm({
28939
29676
  const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
28940
29677
  return prepareAlterSequenceJson(it);
28941
29678
  }).flat() ?? [];
29679
+ const createRoles = createdRoles.map((it) => {
29680
+ return prepareCreateRoleJson(it);
29681
+ }) ?? [];
29682
+ const dropRoles = deletedRoles.map((it) => {
29683
+ return prepareDropRoleJson(it.name);
29684
+ });
29685
+ const renameRoles = renamedRoles.map((it) => {
29686
+ return prepareRenameRoleJson(it.from.name, it.to.name);
29687
+ });
29688
+ const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
29689
+ return prepareAlterRoleJson(it);
29690
+ }).flat() ?? [];
28942
29691
  const createSchemas = prepareCreateSchemasJson(
28943
29692
  createdSchemas.map((it) => it.name)
28944
29693
  );
@@ -28951,6 +29700,11 @@ var init_snapshotsDiffer = __esm({
28951
29700
  const createTables = createdTables.map((it) => {
28952
29701
  return preparePgCreateTableJson(it, curFull);
28953
29702
  });
29703
+ jsonCreatePoliciesStatements.push(...[].concat(
29704
+ ...createdTables.map(
29705
+ (it) => prepareCreatePolicyJsons(it.name, it.schema, Object.values(it.policies).map(PgSquasher.unsquashPolicy))
29706
+ )
29707
+ ));
28954
29708
  const createViews = [];
28955
29709
  const dropViews = [];
28956
29710
  const renameViews = [];
@@ -29092,7 +29846,13 @@ var init_snapshotsDiffer = __esm({
29092
29846
  jsonStatements.push(...moveSequences);
29093
29847
  jsonStatements.push(...renameSequences);
29094
29848
  jsonStatements.push(...jsonAlterSequences);
29849
+ jsonStatements.push(...renameRoles);
29850
+ jsonStatements.push(...dropRoles);
29851
+ jsonStatements.push(...createRoles);
29852
+ jsonStatements.push(...jsonAlterRoles);
29095
29853
  jsonStatements.push(...createTables);
29854
+ jsonStatements.push(...jsonEnableRLSStatements);
29855
+ jsonStatements.push(...jsonDisableRLSStatements);
29096
29856
  jsonStatements.push(...dropViews);
29097
29857
  jsonStatements.push(...renameViews);
29098
29858
  jsonStatements.push(...alterViews);
@@ -29118,6 +29878,10 @@ var init_snapshotsDiffer = __esm({
29118
29878
  jsonStatements.push(...jsonCreatedCheckConstraints);
29119
29879
  jsonStatements.push(...jsonAlteredUniqueConstraints);
29120
29880
  jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
29881
+ jsonStatements.push(...jsonRenamePoliciesStatements);
29882
+ jsonStatements.push(...jsonDropPoliciesStatements);
29883
+ jsonStatements.push(...jsonCreatePoliciesStatements);
29884
+ jsonStatements.push(...jsonAlterPoliciesStatements);
29121
29885
  jsonStatements.push(...createViews);
29122
29886
  jsonStatements.push(...dropEnums);
29123
29887
  jsonStatements.push(...dropSequences);
@@ -31703,6 +32467,7 @@ __export(migrate_exports, {
31703
32467
  embeddedMigrations: () => embeddedMigrations,
31704
32468
  enumsResolver: () => enumsResolver,
31705
32469
  mySqlViewsResolver: () => mySqlViewsResolver,
32470
+ policyResolver: () => policyResolver,
31706
32471
  prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
31707
32472
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
31708
32473
  prepareAndMigratePg: () => prepareAndMigratePg,
@@ -31713,8 +32478,10 @@ __export(migrate_exports, {
31713
32478
  prepareSQLitePush: () => prepareSQLitePush,
31714
32479
  prepareSnapshotFolderName: () => prepareSnapshotFolderName,
31715
32480
  promptColumnsConflicts: () => promptColumnsConflicts,
32481
+ promptNamedConflict: () => promptNamedConflict,
31716
32482
  promptNamedWithSchemasConflict: () => promptNamedWithSchemasConflict,
31717
32483
  promptSchemasConflict: () => promptSchemasConflict,
32484
+ roleResolver: () => roleResolver,
31718
32485
  schemasResolver: () => schemasResolver,
31719
32486
  sequencesResolver: () => sequencesResolver,
31720
32487
  sqliteViewsResolver: () => sqliteViewsResolver,
@@ -31722,7 +32489,7 @@ __export(migrate_exports, {
31722
32489
  viewsResolver: () => viewsResolver,
31723
32490
  writeResult: () => writeResult
31724
32491
  });
31725
- var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
32492
+ var import_fs5, import_hanji3, import_path4, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, enumsResolver, columnsResolver, prepareAndMigratePg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareAndMigrateSqlite, prepareAndMigrateLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
31726
32493
  var init_migrate = __esm({
31727
32494
  "src/cli/commands/migrate.ts"() {
31728
32495
  "use strict";
@@ -31841,6 +32608,32 @@ var init_migrate = __esm({
31841
32608
  throw e2;
31842
32609
  }
31843
32610
  };
32611
+ roleResolver = async (input) => {
32612
+ const result = await promptNamedConflict(
32613
+ input.created,
32614
+ input.deleted,
32615
+ "role"
32616
+ );
32617
+ return {
32618
+ created: result.created,
32619
+ deleted: result.deleted,
32620
+ renamed: result.renamed
32621
+ };
32622
+ };
32623
+ policyResolver = async (input) => {
32624
+ const result = await promptColumnsConflicts(
32625
+ input.tableName,
32626
+ input.created,
32627
+ input.deleted
32628
+ );
32629
+ return {
32630
+ tableName: input.tableName,
32631
+ schema: input.schema,
32632
+ created: result.created,
32633
+ deleted: result.deleted,
32634
+ renamed: result.renamed
32635
+ };
32636
+ };
31844
32637
  enumsResolver = async (input) => {
31845
32638
  try {
31846
32639
  const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
@@ -31911,6 +32704,8 @@ var init_migrate = __esm({
31911
32704
  schemasResolver,
31912
32705
  enumsResolver,
31913
32706
  sequencesResolver,
32707
+ policyResolver,
32708
+ roleResolver,
31914
32709
  tablesResolver,
31915
32710
  columnsResolver,
31916
32711
  viewsResolver,
@@ -31947,6 +32742,8 @@ var init_migrate = __esm({
31947
32742
  schemasResolver,
31948
32743
  enumsResolver,
31949
32744
  sequencesResolver,
32745
+ policyResolver,
32746
+ roleResolver,
31950
32747
  tablesResolver,
31951
32748
  columnsResolver,
31952
32749
  viewsResolver,
@@ -32241,6 +33038,56 @@ var init_migrate = __esm({
32241
33038
  result.deleted.push(...leftMissing);
32242
33039
  return result;
32243
33040
  };
33041
+ promptNamedConflict = async (newItems, missingItems, entity) => {
33042
+ if (missingItems.length === 0 || newItems.length === 0) {
33043
+ return {
33044
+ created: newItems,
33045
+ renamed: [],
33046
+ deleted: missingItems
33047
+ };
33048
+ }
33049
+ const result = { created: [], renamed: [], deleted: [] };
33050
+ let index4 = 0;
33051
+ let leftMissing = [...missingItems];
33052
+ do {
33053
+ const created = newItems[index4];
33054
+ const renames = leftMissing.map((it) => {
33055
+ return { from: it, to: created };
33056
+ });
33057
+ const promptData = [created, ...renames];
33058
+ const { status, data } = await (0, import_hanji3.render)(
33059
+ new ResolveSelectNamed(created, promptData, entity)
33060
+ );
33061
+ if (status === "aborted") {
33062
+ console.error("ERROR");
33063
+ process.exit(1);
33064
+ }
33065
+ if (isRenamePromptItem(data)) {
33066
+ console.log(
33067
+ `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
33068
+ `${entity} will be renamed/moved`
33069
+ )}`
33070
+ );
33071
+ if (data.from.name !== data.to.name) {
33072
+ result.renamed.push(data);
33073
+ }
33074
+ delete leftMissing[leftMissing.indexOf(data.from)];
33075
+ leftMissing = leftMissing.filter(Boolean);
33076
+ } else {
33077
+ console.log(
33078
+ `${source_default.green("+")} ${data.name} ${source_default.gray(
33079
+ `${entity} will be created`
33080
+ )}`
33081
+ );
33082
+ result.created.push(created);
33083
+ }
33084
+ index4 += 1;
33085
+ } while (index4 < newItems.length);
33086
+ console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
33087
+ `));
33088
+ result.deleted.push(...leftMissing);
33089
+ return result;
33090
+ };
32244
33091
  promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
32245
33092
  if (missingItems.length === 0 || newItems.length === 0) {
32246
33093
  return {
@@ -41069,9 +41916,9 @@ var init_body2 = __esm({
41069
41916
  // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
41070
41917
  function fromRawHeaders(headers = []) {
41071
41918
  return new Headers2(
41072
- headers.reduce((result, value, index4, array) => {
41919
+ headers.reduce((result, value, index4, array2) => {
41073
41920
  if (index4 % 2 === 0) {
41074
- result.push(array.slice(index4, index4 + 2));
41921
+ result.push(array2.slice(index4, index4 + 2));
41075
41922
  }
41076
41923
  return result;
41077
41924
  }, []).filter(([name, value]) => {
@@ -41469,7 +42316,7 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
41469
42316
  if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
41470
42317
  return null;
41471
42318
  }
41472
- const policy = request.referrerPolicy;
42319
+ const policy2 = request.referrerPolicy;
41473
42320
  if (request.referrer === "about:client") {
41474
42321
  return "no-referrer";
41475
42322
  }
@@ -41486,7 +42333,7 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
41486
42333
  referrerOrigin = referrerOriginCallback(referrerOrigin);
41487
42334
  }
41488
42335
  const currentURL = new URL(request.url);
41489
- switch (policy) {
42336
+ switch (policy2) {
41490
42337
  case "no-referrer":
41491
42338
  return "no-referrer";
41492
42339
  case "origin":
@@ -41522,18 +42369,18 @@ function determineRequestsReferrer(request, { referrerURLCallback, referrerOrigi
41522
42369
  }
41523
42370
  return referrerURL;
41524
42371
  default:
41525
- throw new TypeError(`Invalid referrerPolicy: ${policy}`);
42372
+ throw new TypeError(`Invalid referrerPolicy: ${policy2}`);
41526
42373
  }
41527
42374
  }
41528
42375
  function parseReferrerPolicyFromHeader(headers) {
41529
42376
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
41530
- let policy = "";
42377
+ let policy2 = "";
41531
42378
  for (const token of policyTokens) {
41532
42379
  if (token && ReferrerPolicy.has(token)) {
41533
- policy = token;
42380
+ policy2 = token;
41534
42381
  }
41535
42382
  }
41536
- return policy;
42383
+ return policy2;
41537
42384
  }
41538
42385
  var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY;
41539
42386
  var init_referrer = __esm({
@@ -62180,7 +63027,7 @@ var require_fromWebToken = __commonJS({
62180
63027
  var fromWebToken2 = (init2) => async () => {
62181
63028
  var _a;
62182
63029
  (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-web-identity", "fromWebToken");
62183
- const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init2;
63030
+ const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy2, durationSeconds } = init2;
62184
63031
  let { roleAssumerWithWebIdentity } = init2;
62185
63032
  if (!roleAssumerWithWebIdentity) {
62186
63033
  const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar2(require_dist_cjs50()));
@@ -62196,7 +63043,7 @@ var require_fromWebToken = __commonJS({
62196
63043
  WebIdentityToken: webIdentityToken,
62197
63044
  ProviderId: providerId,
62198
63045
  PolicyArns: policyArns,
62199
- Policy: policy,
63046
+ Policy: policy2,
62200
63047
  DurationSeconds: durationSeconds
62201
63048
  });
62202
63049
  };
@@ -65660,13 +66507,13 @@ var require_event_stream = __commonJS({
65660
66507
  es.writeArray = function(done) {
65661
66508
  if ("function" !== typeof done)
65662
66509
  throw new Error("function writeArray (done): done must be function");
65663
- var a = new Stream3(), array = [], isDone = false;
66510
+ var a = new Stream3(), array2 = [], isDone = false;
65664
66511
  a.write = function(l) {
65665
- array.push(l);
66512
+ array2.push(l);
65666
66513
  };
65667
66514
  a.end = function() {
65668
66515
  isDone = true;
65669
- done(null, array);
66516
+ done(null, array2);
65670
66517
  };
65671
66518
  a.writable = true;
65672
66519
  a.readable = false;
@@ -65674,23 +66521,23 @@ var require_event_stream = __commonJS({
65674
66521
  a.writable = a.readable = false;
65675
66522
  if (isDone)
65676
66523
  return;
65677
- done(new Error("destroyed before end"), array);
66524
+ done(new Error("destroyed before end"), array2);
65678
66525
  };
65679
66526
  return a;
65680
66527
  };
65681
- es.readArray = function(array) {
66528
+ es.readArray = function(array2) {
65682
66529
  var stream = new Stream3(), i2 = 0, paused = false, ended = false;
65683
66530
  stream.readable = true;
65684
66531
  stream.writable = false;
65685
- if (!Array.isArray(array))
66532
+ if (!Array.isArray(array2))
65686
66533
  throw new Error("event-stream.read expects an array");
65687
66534
  stream.resume = function() {
65688
66535
  if (ended)
65689
66536
  return;
65690
66537
  paused = false;
65691
- var l = array.length;
66538
+ var l = array2.length;
65692
66539
  while (i2 < l && !paused && !ended) {
65693
- stream.emit("data", array[i2++]);
66540
+ stream.emit("data", array2[i2++]);
65694
66541
  }
65695
66542
  if (i2 == l && !ended)
65696
66543
  ended = true, stream.readable = false, stream.emit("end");
@@ -69315,8 +70162,8 @@ var require_utils4 = __commonJS({
69315
70162
  "use strict";
69316
70163
  Object.defineProperty(exports2, "__esModule", { value: true });
69317
70164
  exports2.string = exports2.stream = exports2.pattern = exports2.path = exports2.fs = exports2.errno = exports2.array = void 0;
69318
- var array = require_array();
69319
- exports2.array = array;
70165
+ var array2 = require_array();
70166
+ exports2.array = array2;
69320
70167
  var errno = require_errno();
69321
70168
  exports2.errno = errno;
69322
70169
  var fs9 = require_fs2();
@@ -79966,17 +80813,11 @@ var init_pgPushUtils = __esm({
79966
80813
  }
79967
80814
  const stmnt = fromJson([statement], "postgresql");
79968
80815
  if (typeof stmnt !== "undefined") {
79969
- if (statement.type === "drop_table") {
79970
- statementsToExecute.push(
79971
- `DROP TABLE ${concatSchemaAndTableName(statement.schema, statement.tableName)} CASCADE;`
79972
- );
79973
- } else {
79974
- statementsToExecute.push(...stmnt);
79975
- }
80816
+ statementsToExecute.push(...stmnt);
79976
80817
  }
79977
80818
  }
79978
80819
  return {
79979
- statementsToExecute,
80820
+ statementsToExecute: [...new Set(statementsToExecute)],
79980
80821
  shouldAskForApprove,
79981
80822
  infoToPrint,
79982
80823
  matViewsToRemove: [...new Set(matViewsToRemove)],
@@ -81124,7 +81965,7 @@ var init_pgIntrospect = __esm({
81124
81965
  init_global();
81125
81966
  init_pgSerializer();
81126
81967
  init_views();
81127
- pgPushIntrospect = async (db, filters, schemaFilters) => {
81968
+ pgPushIntrospect = async (db, filters, schemaFilters, entities = { roles: true }) => {
81128
81969
  const matchers = filters.map((it) => {
81129
81970
  return new Minimatch(it);
81130
81971
  });
@@ -81153,7 +81994,7 @@ var init_pgIntrospect = __esm({
81153
81994
  );
81154
81995
  const res = await (0, import_hanji9.renderWithTask)(
81155
81996
  progress,
81156
- fromDatabase2(db, filter2, schemaFilters)
81997
+ fromDatabase2(db, filter2, schemaFilters, entities)
81157
81998
  );
81158
81999
  const schema5 = { id: originUUID, prevId: "", ...res };
81159
82000
  const { internal, ...schemaWithoutInternals } = schema5;
@@ -81743,11 +82584,11 @@ var init_push = __esm({
81743
82584
  console.log(e2);
81744
82585
  }
81745
82586
  };
81746
- pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, force, casing2) => {
82587
+ pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, entities, force, casing2) => {
81747
82588
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
81748
82589
  const { pgPushIntrospect: pgPushIntrospect2 } = await Promise.resolve().then(() => (init_pgIntrospect(), pgIntrospect_exports));
81749
82590
  const db = await preparePostgresDB2(credentials2);
81750
- const { schema: schema5 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter);
82591
+ const { schema: schema5 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter, entities);
81751
82592
  const { preparePgPush: preparePgPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
81752
82593
  const statements = await preparePgPush2(schemaPath, schema5, schemasFilter, casing2);
81753
82594
  try {
@@ -83004,7 +83845,7 @@ function generateIdentityParams(identity) {
83004
83845
  }
83005
83846
  return `.generatedByDefaultAsIdentity(${paramsObj})`;
83006
83847
  }
83007
- var import_drizzle_orm9, import_relations, import_casing5, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, dbColumnName3, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableChecks3, createTableFKs3;
83848
+ var import_drizzle_orm9, import_relations, import_casing5, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, dbColumnName3, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTablePolicies, createTableUniques3, createTableChecks3, createTableFKs3;
83008
83849
  var init_introspect_pg = __esm({
83009
83850
  "src/introspect-pg.ts"() {
83010
83851
  "use strict";
@@ -83047,13 +83888,7 @@ var init_introspect_pg = __esm({
83047
83888
  "vector",
83048
83889
  "point",
83049
83890
  "line",
83050
- "geometry",
83051
- "geography",
83052
- "oid",
83053
- "name",
83054
- "compactstateagg",
83055
- "stateagg",
83056
- "heartbeatagg"
83891
+ "geometry"
83057
83892
  ]);
83058
83893
  timeConfig2 = (json) => {
83059
83894
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
@@ -83184,6 +84019,9 @@ var init_introspect_pg = __esm({
83184
84019
  const checkImports = Object.values(it.checkConstraints).map(
83185
84020
  (it2) => "check"
83186
84021
  );
84022
+ const policiesImports = Object.values(it.policies).map(
84023
+ (it2) => "pgPolicy"
84024
+ );
83187
84025
  if (it.schema && it.schema !== "public" && it.schema !== "") {
83188
84026
  res.pg.push("pgSchema");
83189
84027
  }
@@ -83191,6 +84029,7 @@ var init_introspect_pg = __esm({
83191
84029
  res.pg.push(...fkImpots);
83192
84030
  res.pg.push(...pkImports);
83193
84031
  res.pg.push(...uniqueImports);
84032
+ res.pg.push(...policiesImports);
83194
84033
  res.pg.push(...checkImports);
83195
84034
  const columnImports = Object.values(it.columns).map((col) => {
83196
84035
  let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
@@ -83202,7 +84041,6 @@ var init_introspect_pg = __esm({
83202
84041
  patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
83203
84042
  patched = patched.startsWith("vector(") ? "vector" : patched;
83204
84043
  patched = patched.startsWith("geometry(") ? "geometry" : patched;
83205
- patched = patched.startsWith("geography(") ? "geography" : patched;
83206
84044
  return patched;
83207
84045
  }).filter((type) => {
83208
84046
  return pgImportsList.has(type);
@@ -83250,6 +84088,9 @@ var init_introspect_pg = __esm({
83250
84088
  imports.pg.push("pgEnum");
83251
84089
  }
83252
84090
  });
84091
+ if (Object.keys(schema5.roles).length > 0) {
84092
+ imports.pg.push("pgRole");
84093
+ }
83253
84094
  const enumStatements = Object.values(schema5.enums).map((it) => {
83254
84095
  const enumSchema3 = schemas[it.schema];
83255
84096
  const paramName = paramNameFor(it.name, enumSchema3);
@@ -83285,9 +84126,16 @@ var init_introspect_pg = __esm({
83285
84126
  }
83286
84127
  return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
83287
84128
  `;
83288
- }).join("").concat("\n");
84129
+ }).join("").concat("");
83289
84130
  const schemaStatements = Object.entries(schemas).map((it) => {
83290
84131
  return `export const ${it[1]} = pgSchema("${it[0]}");
84132
+ `;
84133
+ }).join("");
84134
+ const rolesNameToTsKey = {};
84135
+ const rolesStatements = Object.entries(schema5.roles).map((it) => {
84136
+ const fields = it[1];
84137
+ rolesNameToTsKey[fields.name] = it[0];
84138
+ 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(",")}}`} );
83291
84139
  `;
83292
84140
  }).join("");
83293
84141
  const tableStatements = Object.values(schema5.tables).map((table4) => {
@@ -83306,8 +84154,8 @@ var init_introspect_pg = __esm({
83306
84154
  schema5.internal
83307
84155
  );
83308
84156
  statement += "}";
83309
- 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 || Object.keys(table4.checkConstraints).length > 0) {
83310
- statement += ",\n";
84157
+ 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 || Object.keys(table4.checkConstraints).length > 0) {
84158
+ statement += ", ";
83311
84159
  statement += "(table) => {\n";
83312
84160
  statement += " return {\n";
83313
84161
  statement += createTableIndexes3(table4.name, Object.values(table4.indexes), casing2);
@@ -83320,6 +84168,11 @@ var init_introspect_pg = __esm({
83320
84168
  Object.values(table4.uniqueConstraints),
83321
84169
  casing2
83322
84170
  );
84171
+ statement += createTablePolicies(
84172
+ Object.values(table4.policies),
84173
+ casing2,
84174
+ rolesNameToTsKey
84175
+ );
83323
84176
  statement += createTableChecks3(
83324
84177
  Object.values(table4.checkConstraints),
83325
84178
  casing2
@@ -83353,11 +84206,14 @@ var init_introspect_pg = __esm({
83353
84206
  return statement;
83354
84207
  }).join("\n\n");
83355
84208
  const uniquePgImports = ["pgTable", ...new Set(imports.pg)];
83356
- const importsTs = `import { ${uniquePgImports.join(", ")} } from "drizzle-orm/pg-core"
83357
- import { sql } from "drizzle-orm"
84209
+ const importsTs = `import { ${uniquePgImports.join(
84210
+ ", "
84211
+ )} } from "drizzle-orm/pg-core"
84212
+ import { sql } from "drizzle-orm"
83358
84213
 
83359
84214
  `;
83360
84215
  let decalrations = schemaStatements;
84216
+ decalrations += rolesStatements;
83361
84217
  decalrations += enumStatements;
83362
84218
  decalrations += sequencesStatements;
83363
84219
  decalrations += "\n";
@@ -83475,9 +84331,6 @@ var init_introspect_pg = __esm({
83475
84331
  if (lowered.startsWith("geometry")) {
83476
84332
  return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
83477
84333
  }
83478
- if (lowered.startsWith("geography")) {
83479
- return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
83480
- }
83481
84334
  if (lowered.startsWith("vector")) {
83482
84335
  return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
83483
84336
  }
@@ -83634,30 +84487,6 @@ var init_introspect_pg = __esm({
83634
84487
  if (isGeoUnknown) {
83635
84488
  let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
83636
84489
  // Introspect is currently supporting only type and srid options
83637
- `;
83638
- unknown2 += ` ${withCasing2(name, casing2)}: unknown("${name}")`;
83639
- return unknown2;
83640
- }
83641
- return out;
83642
- }
83643
- if (lowered.startsWith("geography")) {
83644
- let out = "";
83645
- let isGeoUnknown = false;
83646
- if (lowered.length !== 9) {
83647
- const geographyOptions = lowered.slice(10, -1).split(",");
83648
- if (geographyOptions.length === 1 && geographyOptions[0] !== "") {
83649
- out = `${withCasing2(name, casing2)}: geography("${name}", { type: "${geographyOptions[0]}" })`;
83650
- } else if (geographyOptions.length === 2) {
83651
- out = `${withCasing2(name, casing2)}: geography("${name}", { type: "${geographyOptions[0]}", srid: ${geographyOptions[1]} })`;
83652
- } else {
83653
- isGeoUnknown = true;
83654
- }
83655
- } else {
83656
- out = `${withCasing2(name, casing2)}: geography("${name}")`;
83657
- }
83658
- if (isGeoUnknown) {
83659
- let unknown2 = `// TODO: failed to parse geography type because found more than 2 options inside geography function '${type}'
83660
- // Introspect is currently supporting only type and srid options
83661
84490
  `;
83662
84491
  unknown2 += ` ${withCasing2(name, casing2)}: unknown("${name}")`;
83663
84492
  return unknown2;
@@ -83682,26 +84511,6 @@ var init_introspect_pg = __esm({
83682
84511
  }
83683
84512
  return out;
83684
84513
  }
83685
- if (lowered === "oid") {
83686
- let out = `${withCasing2(name, casing2)}: oid(${dbColumnName3({ name, casing: casing2 })})`;
83687
- return out;
83688
- }
83689
- if (lowered === "name") {
83690
- let out = `${withCasing2(name, casing2)}: name(${dbColumnName3({ name, casing: casing2 })})`;
83691
- return out;
83692
- }
83693
- if (lowered === "heartbeatagg") {
83694
- let out = `${withCasing2(name, casing2)}: heartbeatagg(${dbColumnName3({ name, casing: casing2 })})`;
83695
- return out;
83696
- }
83697
- if (lowered === "stateagg") {
83698
- let out = `${withCasing2(name, casing2)}: stateagg(${dbColumnName3({ name, casing: casing2 })})`;
83699
- return out;
83700
- }
83701
- if (lowered === "compactstateagg") {
83702
- let out = `${withCasing2(name, casing2)}: compactstateagg(${dbColumnName3({ name, casing: casing2 })})`;
83703
- return out;
83704
- }
83705
84514
  let unknown = `// TODO: failed to parse database type '${type}'
83706
84515
  `;
83707
84516
  unknown += ` ${withCasing2(name, casing2)}: unknown("${name}")`;
@@ -83803,6 +84612,23 @@ var init_introspect_pg = __esm({
83803
84612
  }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
83804
84613
  statement += ")";
83805
84614
  statement += `,
84615
+ `;
84616
+ });
84617
+ return statement;
84618
+ };
84619
+ createTablePolicies = (policies, casing2, rolesNameToTsKey = {}) => {
84620
+ let statement = "";
84621
+ policies.forEach((it) => {
84622
+ var _a, _b, _c;
84623
+ const idxKey = withCasing2(it.name, casing2);
84624
+ const mappedItTo = (_a = it.to) == null ? void 0 : _a.map((v) => {
84625
+ return rolesNameToTsKey[v] ? withCasing2(rolesNameToTsKey[v], casing2) : `"${v}"`;
84626
+ });
84627
+ statement += ` ${idxKey}: `;
84628
+ statement += "pgPolicy(";
84629
+ statement += `"${it.name}", { `;
84630
+ 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}\` ` : ""}`;
84631
+ statement += ` }),
83806
84632
  `;
83807
84633
  });
83808
84634
  return statement;
@@ -83893,7 +84719,7 @@ var init_introspect = __esm({
83893
84719
  init_utils();
83894
84720
  init_views();
83895
84721
  init_migrate();
83896
- introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2) => {
84722
+ introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
83897
84723
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
83898
84724
  const db = await preparePostgresDB2(credentials2);
83899
84725
  const matchers = tablesFilter.map((it) => {
@@ -83921,9 +84747,15 @@ var init_introspect = __esm({
83921
84747
  const progress = new IntrospectProgress(true);
83922
84748
  const res = await (0, import_hanji12.renderWithTask)(
83923
84749
  progress,
83924
- fromDatabase2(db, filter2, schemasFilter, (stage, count, status) => {
83925
- progress.update(stage, count, status);
83926
- })
84750
+ fromDatabase2(
84751
+ db,
84752
+ filter2,
84753
+ schemasFilter,
84754
+ entities,
84755
+ (stage, count, status) => {
84756
+ progress.update(stage, count, status);
84757
+ }
84758
+ )
83927
84759
  );
83928
84760
  const schema5 = { id: originUUID, prevId: "", ...res };
83929
84761
  const ts = schemaToTypeScript3(schema5, casing2);
@@ -83942,6 +84774,7 @@ var init_introspect = __esm({
83942
84774
  schemasResolver,
83943
84775
  enumsResolver,
83944
84776
  sequencesResolver,
84777
+ policyResolver,
83945
84778
  tablesResolver,
83946
84779
  columnsResolver,
83947
84780
  viewsResolver,
@@ -87468,7 +88301,8 @@ var pull = command({
87468
88301
  breakpoints,
87469
88302
  tablesFilter,
87470
88303
  schemasFilter,
87471
- prefix: prefix2
88304
+ prefix: prefix2,
88305
+ entities
87472
88306
  } = config;
87473
88307
  (0, import_fs13.mkdirSync)(out, { recursive: true });
87474
88308
  console.log(
@@ -87507,7 +88341,8 @@ var pull = command({
87507
88341
  credentials2,
87508
88342
  tablesFilter,
87509
88343
  schemasFilter,
87510
- prefix2
88344
+ prefix2,
88345
+ entities
87511
88346
  );
87512
88347
  } else if (dialect4 === "mysql") {
87513
88348
  const { introspectMysql: introspectMysql2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
@@ -87678,7 +88513,7 @@ init_utils2();
87678
88513
  var version2 = async () => {
87679
88514
  const { npmVersion } = await ormCoreVersions();
87680
88515
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
87681
- const envVersion = "0.26.2-57d2372";
88516
+ const envVersion = "0.26.2-6a162f5";
87682
88517
  const kitVersion = envVersion ? `v${envVersion}` : "--";
87683
88518
  const versions = `drizzle-kit: ${kitVersion}
87684
88519
  ${ormVersion}`;