rake-db 2.2.4 → 2.2.6

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.js CHANGED
@@ -38,7 +38,7 @@ const migrationConfigDefaults = {
38
38
  requireTs: require,
39
39
  log: true,
40
40
  logger: console,
41
- useCodeUpdaterByDefault: true
41
+ useCodeUpdater: true
42
42
  };
43
43
  const getMigrationConfigWithDefaults = (config) => {
44
44
  return __spreadValues$6(__spreadValues$6({}, migrationConfigDefaults), config);
@@ -104,9 +104,9 @@ const setAdminCredentialsToOptions = async (options) => {
104
104
  const createSchemaMigrations = async (db, config) => {
105
105
  try {
106
106
  await db.query(
107
- `CREATE TABLE ${quoteTable(
108
- config.migrationsTable
109
- )} ( version TEXT NOT NULL )`
107
+ `CREATE TABLE ${quoteWithSchema({
108
+ name: config.migrationsTable
109
+ })} ( version TEXT NOT NULL )`
110
110
  );
111
111
  console.log("Created versions table");
112
112
  } catch (err) {
@@ -182,13 +182,15 @@ const joinWords = (...words) => {
182
182
  const joinColumns = (columns) => {
183
183
  return columns.map((column) => `"${column}"`).join(", ");
184
184
  };
185
- const quoteTable = (table) => {
186
- const index = table.indexOf(".");
187
- if (index !== -1) {
188
- return `"${table.slice(0, index)}"."${table.slice(index + 1)}"`;
189
- } else {
190
- return `"${table}"`;
191
- }
185
+ const quoteWithSchema = ({
186
+ schema,
187
+ name
188
+ }) => {
189
+ return schema ? `"${schema}"."${name}"` : `"${name}"`;
190
+ };
191
+ const getSchemaAndTableFromName = (name) => {
192
+ const index = name.indexOf(".");
193
+ return index !== -1 ? [name.slice(0, index), name.slice(index + 1)] : [void 0, name];
192
194
  };
193
195
 
194
196
  let currentMigration;
@@ -239,7 +241,7 @@ const columnToSql = (key, item, values, hasMultiplePrimaryKeys) => {
239
241
  }
240
242
  if (item.isPrimaryKey && !hasMultiplePrimaryKeys) {
241
243
  line.push("PRIMARY KEY");
242
- } else if (!item.isNullable) {
244
+ } else if (!item.data.isNullable) {
243
245
  line.push("NOT NULL");
244
246
  }
245
247
  if (item.data.default !== void 0) {
@@ -251,13 +253,13 @@ const columnToSql = (key, item, values, hasMultiplePrimaryKeys) => {
251
253
  }
252
254
  const { foreignKey } = item.data;
253
255
  if (foreignKey) {
254
- const table = getForeignKeyTable(
256
+ const [schema, table] = getForeignKeyTable(
255
257
  "fn" in foreignKey ? foreignKey.fn : foreignKey.table
256
258
  );
257
259
  if (foreignKey.name) {
258
260
  line.push(`CONSTRAINT "${foreignKey.name}"`);
259
261
  }
260
- line.push(referencesToSql(table, foreignKey.columns, foreignKey));
262
+ line.push(referencesToSql(schema, table, foreignKey.columns, foreignKey));
261
263
  }
262
264
  return line.join(" ");
263
265
  };
@@ -278,25 +280,32 @@ const addColumnComment = (comments, key, item) => {
278
280
  };
279
281
  const getForeignKeyTable = (fnOrTable) => {
280
282
  if (typeof fnOrTable === "string") {
281
- return fnOrTable;
283
+ return getSchemaAndTableFromName(fnOrTable);
282
284
  }
283
- const klass = fnOrTable();
284
- return new klass().table;
285
+ const item = new (fnOrTable())();
286
+ return [item.schema, item.table];
285
287
  };
286
- const constraintToSql = (tableName, up, foreignKey) => {
287
- const constraintName = foreignKey.options.name || `${tableName}_${foreignKey.columns.join("_")}_fkey`;
288
+ const constraintToSql = ({ name }, up, foreignKey) => {
289
+ const constraintName = foreignKey.options.name || `${name}_${foreignKey.columns.join("_")}_fkey`;
288
290
  if (!up) {
289
291
  const { dropMode } = foreignKey.options;
290
292
  return `CONSTRAINT "${constraintName}"${dropMode ? ` ${dropMode}` : ""}`;
291
293
  }
292
- const table = getForeignKeyTable(foreignKey.fnOrTable);
294
+ const [schema, table] = getForeignKeyTable(foreignKey.fnOrTable);
293
295
  return `CONSTRAINT "${constraintName}" FOREIGN KEY (${joinColumns(
294
296
  foreignKey.columns
295
- )}) ${referencesToSql(table, foreignKey.foreignColumns, foreignKey.options)}`;
296
- };
297
- const referencesToSql = (table, columns, foreignKey) => {
297
+ )}) ${referencesToSql(
298
+ schema,
299
+ table,
300
+ foreignKey.foreignColumns,
301
+ foreignKey.options
302
+ )}`;
303
+ };
304
+ const referencesToSql = (schema, table, columns, foreignKey) => {
298
305
  const sql = [
299
- `REFERENCES ${quoteTable(table)}(${joinColumns(columns)})`
306
+ `REFERENCES ${quoteWithSchema({ schema, name: table })}(${joinColumns(
307
+ columns
308
+ )})`
300
309
  ];
301
310
  if (foreignKey.match) {
302
311
  sql.push(`MATCH ${foreignKey.match.toUpperCase()}`);
@@ -309,9 +318,9 @@ const referencesToSql = (table, columns, foreignKey) => {
309
318
  }
310
319
  return sql.join(" ");
311
320
  };
312
- const indexesToQuery = (up, tableName, indexes) => {
321
+ const indexesToQuery = (up, { schema, name }, indexes) => {
313
322
  return indexes.map(({ columns, options }) => {
314
- const indexName = options.name || joinWords(tableName, ...columns.map(({ column }) => column), "index");
323
+ const indexName = options.name || joinWords(name, ...columns.map(({ column }) => column), "index");
315
324
  if (!up) {
316
325
  return {
317
326
  text: `DROP INDEX "${indexName}"${options.dropMode ? ` ${options.dropMode}` : ""}`,
@@ -323,7 +332,7 @@ const indexesToQuery = (up, tableName, indexes) => {
323
332
  if (options.unique) {
324
333
  sql.push("UNIQUE");
325
334
  }
326
- sql.push(`INDEX "${indexName}" ON ${quoteTable(tableName)}`);
335
+ sql.push(`INDEX "${indexName}" ON ${quoteWithSchema({ schema, name })}`);
327
336
  if (options.using) {
328
337
  sql.push(`USING ${options.using}`);
329
338
  }
@@ -363,11 +372,11 @@ const indexesToQuery = (up, tableName, indexes) => {
363
372
  return { text: sql.join(" "), values };
364
373
  });
365
374
  };
366
- const commentsToQuery = (tableName, comments) => {
375
+ const commentsToQuery = (schemaTable, comments) => {
367
376
  return comments.map(({ column, comment }) => ({
368
- text: `COMMENT ON COLUMN ${quoteTable(tableName)}."${column}" IS ${pqb.quote(
369
- comment
370
- )}`,
377
+ text: `COMMENT ON COLUMN ${quoteWithSchema(
378
+ schemaTable
379
+ )}."${column}" IS ${pqb.quote(comment)}`,
371
380
  values: []
372
381
  }));
373
382
  };
@@ -449,10 +458,12 @@ const makeAst$1 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
449
458
  }
450
459
  }
451
460
  const primaryKey = tableData.primaryKey;
461
+ const [schema, table] = getSchemaAndTableFromName(tableName);
452
462
  return __spreadProps$3(__spreadValues$4(__spreadProps$3(__spreadValues$4({
453
463
  type: "table",
454
464
  action: up ? "create" : "drop",
455
- name: tableName,
465
+ schema,
466
+ name: table,
456
467
  shape
457
468
  }, tableData), {
458
469
  primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$3(__spreadValues$4({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
@@ -486,7 +497,7 @@ const astToQueries$1 = (ast) => {
486
497
  if (ast.action === "drop") {
487
498
  return [
488
499
  {
489
- text: `DROP TABLE ${quoteTable(ast.name)}${ast.dropMode ? ` ${ast.dropMode}` : ""}`,
500
+ text: `DROP TABLE ${quoteWithSchema(ast)}${ast.dropMode ? ` ${ast.dropMode}` : ""}`,
490
501
  values: []
491
502
  }
492
503
  ];
@@ -508,21 +519,21 @@ const astToQueries$1 = (ast) => {
508
519
  }
509
520
  ast.foreignKeys.forEach((foreignKey) => {
510
521
  lines.push(`
511
- ${constraintToSql(ast.name, true, foreignKey)}`);
522
+ ${constraintToSql(ast, true, foreignKey)}`);
512
523
  });
513
524
  indexes.push(...ast.indexes);
514
525
  const result = [
515
526
  {
516
- text: `CREATE TABLE ${quoteTable(ast.name)} (${lines.join(",")}
527
+ text: `CREATE TABLE ${quoteWithSchema(ast)} (${lines.join(",")}
517
528
  )`,
518
529
  values
519
530
  },
520
- ...indexesToQuery(true, ast.name, indexes),
521
- ...commentsToQuery(ast.name, comments)
531
+ ...indexesToQuery(true, ast, indexes),
532
+ ...commentsToQuery(ast, comments)
522
533
  ];
523
534
  if (ast.comment) {
524
535
  result.push({
525
- text: `COMMENT ON TABLE ${quoteTable(ast.name)} IS ${pqb.quote(ast.comment)}`,
536
+ text: `COMMENT ON TABLE ${quoteWithSchema(ast)} IS ${pqb.quote(ast.comment)}`,
526
537
  values: []
527
538
  });
528
539
  }
@@ -617,7 +628,7 @@ const columnTypeToColumnChange = (item) => {
617
628
  return __spreadProps$2(__spreadValues$3({
618
629
  column: item,
619
630
  type: item.toSQL(),
620
- nullable: item.isNullable,
631
+ nullable: item.data.isNullable,
621
632
  primaryKey: item.isPrimaryKey
622
633
  }, item.data), {
623
634
  foreignKey
@@ -690,9 +701,11 @@ const makeAst = (up, name, changeData, changeTableData2, options) => {
690
701
  }
691
702
  }
692
703
  }
704
+ const [schema, table] = getSchemaAndTableFromName(name);
693
705
  return __spreadValues$3({
694
706
  type: "changeTable",
695
- name,
707
+ schema,
708
+ name: table,
696
709
  comment: comment ? up ? Array.isArray(comment) ? comment[1] : comment : Array.isArray(comment) ? comment[0] : null : void 0,
697
710
  shape
698
711
  }, up ? changeTableData2 : { add: changeTableData2.drop, drop: changeTableData2.add });
@@ -702,7 +715,7 @@ const astToQueries = (ast) => {
702
715
  const result = [];
703
716
  if (ast.comment !== void 0) {
704
717
  result.push({
705
- text: `COMMENT ON TABLE ${quoteTable(ast.name)} IS ${pqb.quote(ast.comment)}`,
718
+ text: `COMMENT ON TABLE ${quoteWithSchema(ast)} IS ${pqb.quote(ast.comment)}`,
706
719
  values: []
707
720
  });
708
721
  }
@@ -839,7 +852,7 @@ const astToQueries = (ast) => {
839
852
  prependAlterTable.push(
840
853
  ...dropForeignKeys.map(
841
854
  (foreignKey) => `
842
- DROP ${constraintToSql(ast.name, false, foreignKey)}`
855
+ DROP ${constraintToSql(ast, false, foreignKey)}`
843
856
  )
844
857
  );
845
858
  alterTable.unshift(...prependAlterTable);
@@ -849,19 +862,19 @@ const astToQueries = (ast) => {
849
862
  alterTable.push(
850
863
  ...addForeignKeys.map(
851
864
  (foreignKey) => `
852
- ADD ${constraintToSql(ast.name, true, foreignKey)}`
865
+ ADD ${constraintToSql(ast, true, foreignKey)}`
853
866
  )
854
867
  );
855
868
  if (alterTable.length) {
856
869
  result.push({
857
- text: `ALTER TABLE ${quoteTable(ast.name)}
870
+ text: `ALTER TABLE ${quoteWithSchema(ast)}
858
871
  ${alterTable.join(",\n ")}`,
859
872
  values
860
873
  });
861
874
  }
862
- result.push(...indexesToQuery(false, ast.name, dropIndexes));
863
- result.push(...indexesToQuery(true, ast.name, addIndexes));
864
- result.push(...commentsToQuery(ast.name, comments));
875
+ result.push(...indexesToQuery(false, ast, dropIndexes));
876
+ result.push(...indexesToQuery(true, ast, addIndexes));
877
+ result.push(...commentsToQuery(ast, comments));
865
878
  return result;
866
879
  };
867
880
 
@@ -912,21 +925,28 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
912
925
  joinedName: joinWords(pluralize.singular(table), item.name)
913
926
  }))
914
927
  );
928
+ const [schema, name] = getSchemaAndTableFromName(table);
915
929
  if (!primaryKeys.length) {
916
930
  throw new Error(
917
- `Primary key for table ${quoteTable(table)} is not defined`
931
+ `Primary key for table ${quoteWithSchema({
932
+ schema,
933
+ name
934
+ })} is not defined`
918
935
  );
919
936
  }
920
- return [table, primaryKeys];
937
+ return [schema, table, primaryKeys];
921
938
  })
922
939
  );
923
940
  return createTable(migration, up, tableName, options, (t) => {
924
941
  const result = {};
925
- tablesWithPrimaryKeys.forEach(([table, primaryKeys]) => {
942
+ tablesWithPrimaryKeys.forEach(([schema, table, primaryKeys]) => {
926
943
  if (primaryKeys.length === 1) {
927
944
  const [{ type, joinedName, name }] = primaryKeys;
928
945
  const column = new UnknownColumn(type);
929
- result[joinedName] = column.foreignKey(table, name);
946
+ result[joinedName] = column.foreignKey(
947
+ schema ? `${schema}.${table}` : table,
948
+ name
949
+ );
930
950
  return;
931
951
  }
932
952
  primaryKeys.forEach(({ joinedName, type }) => {
@@ -943,7 +963,7 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
943
963
  }
944
964
  t.primaryKey(
945
965
  tablesWithPrimaryKeys.flatMap(
946
- ([, primaryKeys]) => primaryKeys.map((item) => item.joinedName)
966
+ ([, , primaryKeys]) => primaryKeys.map((item) => item.joinedName)
947
967
  )
948
968
  );
949
969
  return result;
@@ -1009,13 +1029,23 @@ class Migration extends pqb.TransactionAdapter {
1009
1029
  return changeTable(this, this.up, tableName, options, fn);
1010
1030
  }
1011
1031
  async renameTable(from, to) {
1032
+ const [fromSchema, f] = getSchemaAndTableFromName(this.up ? from : to);
1033
+ const [toSchema, t] = getSchemaAndTableFromName(this.up ? to : from);
1012
1034
  const ast = {
1013
1035
  type: "renameTable",
1014
- from: this.up ? from : to,
1015
- to: this.up ? to : from
1036
+ fromSchema,
1037
+ from: f,
1038
+ toSchema,
1039
+ to: t
1016
1040
  };
1017
1041
  await this.query(
1018
- `ALTER TABLE ${quoteTable(ast.from)} RENAME TO "${ast.to}"`
1042
+ `ALTER TABLE ${quoteWithSchema({
1043
+ schema: ast.fromSchema,
1044
+ name: ast.from
1045
+ })} RENAME TO ${quoteWithSchema({
1046
+ schema: ast.toSchema,
1047
+ name: ast.to
1048
+ })}`
1019
1049
  );
1020
1050
  await runCodeUpdater(this, ast);
1021
1051
  }
@@ -1239,20 +1269,22 @@ const processMigration = async (db, up, file, config, options, appCodeUpdaterCac
1239
1269
  };
1240
1270
  const saveMigratedVersion = async (db, version, config) => {
1241
1271
  await db.query(
1242
- `INSERT INTO ${quoteTable(config.migrationsTable)} VALUES ('${version}')`
1272
+ `INSERT INTO ${quoteWithSchema({
1273
+ name: config.migrationsTable
1274
+ })} VALUES ('${version}')`
1243
1275
  );
1244
1276
  };
1245
1277
  const removeMigratedVersion = async (db, version, config) => {
1246
1278
  await db.query(
1247
- `DELETE FROM ${quoteTable(
1248
- config.migrationsTable
1249
- )} WHERE version = '${version}'`
1279
+ `DELETE FROM ${quoteWithSchema({
1280
+ name: config.migrationsTable
1281
+ })} WHERE version = '${version}'`
1250
1282
  );
1251
1283
  };
1252
1284
  const getMigratedVersionsMap = async (db, config) => {
1253
1285
  try {
1254
1286
  const result = await db.arrays(
1255
- `SELECT * FROM ${quoteTable(config.migrationsTable)}`
1287
+ `SELECT * FROM ${quoteWithSchema({ name: config.migrationsTable })}`
1256
1288
  );
1257
1289
  return Object.fromEntries(result.rows.map((row) => [row[0], true]));
1258
1290
  } catch (err) {