rake-db 2.23.19 → 2.23.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -126,8 +126,12 @@ const columnToSql = (name, item, values, hasMultiplePrimaryKeys, snakeCase) => {
126
126
  } else if (!item.data.isNullable) {
127
127
  line.push("NOT NULL");
128
128
  }
129
- if (item.data.check) {
130
- line.push(checkToSql(item.data.check.sql, values));
129
+ if (item.data.checks) {
130
+ line.push(
131
+ item.data.checks.map(
132
+ (check) => (check.name ? `CONSTRAINT "${check.name}" ` : "") + checkToSql(check.sql, values)
133
+ ).join(", ")
134
+ );
131
135
  }
132
136
  const def = encodeColumnDefault(item.data.default, values, item);
133
137
  if (def !== null) line.push(`DEFAULT ${def}`);
@@ -447,6 +451,19 @@ const interpolateSqlValues = ({ text, values }) => {
447
451
  return escapeForMigration(values[i]);
448
452
  }) : text;
449
453
  };
454
+ const nameColumnChecks = (table, column, checks) => checks.map((check, i) => ({
455
+ ...check,
456
+ name: check.name || `${table}_${column}_check${i === 0 ? "" : i}`
457
+ }));
458
+ const cmpRawSql = (a, b) => {
459
+ const values = [];
460
+ const aSql = a.makeSQL({ values });
461
+ const aValues = JSON.stringify(values);
462
+ values.length = 0;
463
+ const bSql = b.makeSQL({ values });
464
+ const bValues = JSON.stringify(values);
465
+ return aSql === bSql && aValues === bValues;
466
+ };
450
467
 
451
468
  const tableMethods = {
452
469
  enum(name) {
@@ -494,6 +511,10 @@ const createTable = async (migration, up, tableName, first, second, third) => {
494
511
  language
495
512
  );
496
513
  tableData = parseTableData(dataFn);
514
+ tableData.constraints?.forEach((x, i) => {
515
+ if (x.name || !x.check) return;
516
+ x.name = `${tableName}_check${i === 0 ? "" : i}`;
517
+ });
497
518
  } else {
498
519
  shape = tableData = emptyObject;
499
520
  }
@@ -743,7 +764,7 @@ const addOrDrop = (type, item, options) => {
743
764
  type: "change",
744
765
  from: {},
745
766
  to: {
746
- check: item.data.check
767
+ checks: item.data.checks
747
768
  }
748
769
  });
749
770
  return {
@@ -1192,20 +1213,23 @@ const handleTableItemChange = (key, item, ast, alterTable, renameItems, values,
1192
1213
  `ALTER COLUMN "${name}" SET COMPRESSION ${to.compression || "DEFAULT"}`
1193
1214
  );
1194
1215
  }
1195
- if (from.check !== to.check) {
1196
- const checkName = `${ast.name}_${name}_check`;
1197
- if (from.check) {
1198
- alterTable.push(`DROP CONSTRAINT "${checkName}"`);
1216
+ const fromChecks = from.checks && nameColumnChecks(ast.name, fromName, from.checks);
1217
+ const toChecks = to.checks && nameColumnChecks(ast.name, name, to.checks);
1218
+ fromChecks?.forEach((fromCheck) => {
1219
+ if (!toChecks?.some((toCheck) => cmpRawSql(fromCheck.sql, toCheck.sql))) {
1220
+ alterTable.push(`DROP CONSTRAINT "${fromCheck.name}"`);
1199
1221
  }
1200
- if (to.check) {
1222
+ });
1223
+ toChecks?.forEach((toCheck) => {
1224
+ if (!fromChecks?.some((fromCheck) => cmpRawSql(fromCheck.sql, toCheck.sql))) {
1201
1225
  alterTable.push(
1202
- `ADD CONSTRAINT "${checkName}"
1203
- CHECK (${to.check.sql.toSQL({
1226
+ `ADD CONSTRAINT "${toCheck.name}"
1227
+ CHECK (${toCheck.sql.toSQL({
1204
1228
  values
1205
1229
  })})`
1206
1230
  );
1207
1231
  }
1208
- }
1232
+ });
1209
1233
  const foreignKeysLen = Math.max(
1210
1234
  from.foreignKeys?.length || 0,
1211
1235
  to.foreignKeys?.length || 0
@@ -2313,9 +2337,9 @@ const createDomain = async (migration, up, name, fn) => {
2313
2337
  const column = ast.baseType;
2314
2338
  query = `CREATE DOMAIN ${quotedName} AS ${columnTypeToSql(column)}${column.data.collate ? `
2315
2339
  COLLATE "${column.data.collate}"` : ""}${column.data.default !== void 0 ? `
2316
- DEFAULT ${encodeColumnDefault(column.data.default, values)}` : ""}${!column.data.isNullable || column.data.check ? "\n" : ""}${[
2340
+ DEFAULT ${encodeColumnDefault(column.data.default, values)}` : ""}${!column.data.isNullable || column.data.checks ? "\n" : ""}${[
2317
2341
  !column.data.isNullable && "NOT NULL",
2318
- column.data.check && `CHECK (${column.data.check.sql.toSQL({ values })})`
2342
+ column.data.checks?.map((check) => `CHECK (${check.sql.toSQL({ values })})`).join(" ")
2319
2343
  ].filter(Boolean).join(" ")}`;
2320
2344
  } else {
2321
2345
  query = `DROP DOMAIN ${quotedName}`;
@@ -3936,7 +3960,11 @@ const domainsSql = `SELECT
3936
3960
  datetime_precision AS "dateTimePrecision",
3937
3961
  collation_name AS "collate",
3938
3962
  domain_default AS "default",
3939
- pg_get_expr(conbin, conrelid) AS "check"
3963
+ (
3964
+ SELECT json_agg(pg_get_expr(conbin, conrelid))
3965
+ FROM pg_catalog.pg_constraint c
3966
+ WHERE c.contypid = d.oid
3967
+ ) AS "checks"
3940
3968
  FROM pg_catalog.pg_type d
3941
3969
  JOIN pg_catalog.pg_namespace n ON n.oid = d.typnamespace
3942
3970
  JOIN information_schema.domains i
@@ -3950,7 +3978,6 @@ JOIN pg_catalog.pg_type t
3950
3978
  END
3951
3979
  ) = d.typbasetype
3952
3980
  JOIN pg_catalog.pg_namespace s ON s.oid = t.typnamespace
3953
- LEFT JOIN pg_catalog.pg_constraint c ON c.contypid = d.oid
3954
3981
  WHERE d.typtype = 'd' AND ${filterSchema("n.nspname")}`;
3955
3982
  const collationsSql = `SELECT
3956
3983
  nspname "schemaName",
@@ -4169,10 +4196,10 @@ const makeDomainsMap = (ctx, data) => {
4169
4196
  default: it.default,
4170
4197
  typmod: -1
4171
4198
  });
4172
- if (it.check) {
4173
- column.data.check = {
4174
- sql: new RawSQL([[it.check]])
4175
- };
4199
+ if (it.checks) {
4200
+ column.data.checks = it.checks.map((check) => ({
4201
+ sql: new RawSQL([[check]])
4202
+ }));
4176
4203
  }
4177
4204
  domains[`${it.schemaName}.${it.name}`] = column;
4178
4205
  }
@@ -4401,8 +4428,9 @@ const makeDbStructureColumnsShape = (ctx, data, domains, table, tableData) => {
4401
4428
  return shape;
4402
4429
  };
4403
4430
  const getDbTableColumnsChecks = (tableData) => tableData.constraints.reduce((acc, item) => {
4431
+ var _a;
4404
4432
  if (isColumnCheck(item)) {
4405
- acc[item.check.columns[0]] = item.check.expression;
4433
+ (acc[_a = item.check.columns[0]] ?? (acc[_a] = [])).push(item.check.expression);
4406
4434
  }
4407
4435
  return acc;
4408
4436
  }, {});
@@ -4437,11 +4465,11 @@ const dbColumnToAst = (ctx, data, domains, tableName, item, table, tableData, ch
4437
4465
  );
4438
4466
  }
4439
4467
  }
4440
- const check = checks?.[item.name];
4441
- if (check) {
4442
- column.data.check = {
4468
+ const columnChecks = checks?.[item.name];
4469
+ if (columnChecks) {
4470
+ column.data.checks = columnChecks.map((check) => ({
4443
4471
  sql: new RawSQL([[check]])
4444
- };
4472
+ }));
4445
4473
  }
4446
4474
  const camelCaseName = toCamelCase(item.name);
4447
4475
  if (ctx.snakeCase) {
@@ -5779,5 +5807,5 @@ const rakeDbCommands = {
5779
5807
  }
5780
5808
  };
5781
5809
 
5782
- export { Migration, NoMigrationsTableError, RAKE_DB_LOCK_KEY, addColumnComment, addColumnExclude, addColumnIndex, addOrDropEnumValues, astToMigration, changeCache, changeEnumValues, clearChanges, colors, columnToSql, columnTypeToSql, commentsToQuery, concatSchemaAndName, constraintToSql, createDb, createMigrationInterface, dbColumnToAst, deleteMigratedVersion, dropDb, encodeColumnDefault, excludesToQuery, exhaustive, generateTimeStamp, getColumnName, getConstraintName, getCurrentChanges, getDatabaseAndUserFromOptions, getDbStructureTableData, getDbTableColumnsChecks, getExcludeName, getFirstWordAndRest, getForeignKeyTable, getIndexName, getMigratedVersionsMap, getSchemaAndTableFromName, getTextAfterFrom, getTextAfterTo, identityToSql, indexesToQuery, instantiateDbColumn, interpolateSqlValues, introspectDbSchema, joinColumns, joinWords, makeDbStructureColumnsShape, makeDomainsMap, makeFileVersion, makePopulateEnumQuery, makeStructureToAstCtx, migrate, migrateOrRollback, migrationConfigDefaults, newMigration, pluralize, primaryKeyToSql, processRakeDbConfig, promptConfirm, promptSelect, promptText, pushChange, queryLock, quoteCustomType, quoteNameFromString, quoteSchemaTable, quoteTable, quoteWithSchema, rakeDb, rakeDbAliases, rakeDbCommands, redo, referencesToSql, renameType, resetDb, rollback, saveMigratedVersion, structureToAst, tableToAst, transaction, versionToString, writeMigrationFile };
5810
+ export { Migration, NoMigrationsTableError, RAKE_DB_LOCK_KEY, addColumnComment, addColumnExclude, addColumnIndex, addOrDropEnumValues, astToMigration, changeCache, changeEnumValues, clearChanges, cmpRawSql, colors, columnToSql, columnTypeToSql, commentsToQuery, concatSchemaAndName, constraintToSql, createDb, createMigrationInterface, dbColumnToAst, deleteMigratedVersion, dropDb, encodeColumnDefault, excludesToQuery, exhaustive, generateTimeStamp, getColumnName, getConstraintName, getCurrentChanges, getDatabaseAndUserFromOptions, getDbStructureTableData, getDbTableColumnsChecks, getExcludeName, getFirstWordAndRest, getForeignKeyTable, getIndexName, getMigratedVersionsMap, getSchemaAndTableFromName, getTextAfterFrom, getTextAfterTo, identityToSql, indexesToQuery, instantiateDbColumn, interpolateSqlValues, introspectDbSchema, joinColumns, joinWords, makeDbStructureColumnsShape, makeDomainsMap, makeFileVersion, makePopulateEnumQuery, makeStructureToAstCtx, migrate, migrateOrRollback, migrationConfigDefaults, nameColumnChecks, newMigration, pluralize, primaryKeyToSql, processRakeDbConfig, promptConfirm, promptSelect, promptText, pushChange, queryLock, quoteCustomType, quoteNameFromString, quoteSchemaTable, quoteTable, quoteWithSchema, rakeDb, rakeDbAliases, rakeDbCommands, redo, referencesToSql, renameType, resetDb, rollback, saveMigratedVersion, structureToAst, tableToAst, transaction, versionToString, writeMigrationFile };
5783
5811
  //# sourceMappingURL=index.mjs.map