rake-db 2.29.9 → 2.30.0

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
@@ -183,7 +183,7 @@ const promptText = ({
183
183
  const getMaybeTransactionAdapter = (db) => "$getAdapter" in db ? db.$getAdapter() : db;
184
184
  const ensureTransaction = (db, fn) => {
185
185
  const adapter = getMaybeTransactionAdapter(db);
186
- return adapter.isInTransaction() ? fn(adapter) : adapter.transaction(void 0, fn);
186
+ return adapter.isInTransaction() ? fn(adapter) : adapter.transaction(fn);
187
187
  };
188
188
  const runSqlInSavePoint = async (db, sql, code) => {
189
189
  const adapter = getMaybeTransactionAdapter(db);
@@ -283,19 +283,16 @@ const quoteWithSchema = ({
283
283
  name
284
284
  }) => quoteTable(schema, name);
285
285
  const quoteTable = (schema, table) => schema ? `"${schema}"."${table}"` : `"${table}"`;
286
- const getSchemaAndTableFromName = (config, name) => {
286
+ const getSchemaAndTableFromName = (schema, name) => {
287
287
  const i = name.indexOf(".");
288
- return i !== -1 ? [name.slice(0, i), name.slice(i + 1)] : [
289
- typeof config.schema === "function" ? config.schema() : config.schema,
290
- name
291
- ];
288
+ return i !== -1 ? [name.slice(0, i), name.slice(i + 1)] : [typeof schema === "function" ? schema() : schema, name];
292
289
  };
293
- const quoteNameFromString = (config, string) => {
294
- return quoteTable(...getSchemaAndTableFromName(config, string));
290
+ const quoteNameFromString = (schema, string) => {
291
+ return quoteTable(...getSchemaAndTableFromName(schema, string));
295
292
  };
296
- const quoteCustomType = (config, s) => {
297
- const [schema, type] = getSchemaAndTableFromName(config, s);
298
- return schema ? '"' + schema + '".' + type : type;
293
+ const quoteCustomType = (schema, type) => {
294
+ const [s, t] = getSchemaAndTableFromName(schema, type);
295
+ return s ? '"' + s + '".' + t : t;
299
296
  };
300
297
  const quoteSchemaTable = (arg, excludeCurrentSchema) => {
301
298
  return pqb.singleQuote(concatSchemaAndName(arg, excludeCurrentSchema));
@@ -306,17 +303,23 @@ const concatSchemaAndName = ({
306
303
  }, excludeCurrentSchema) => {
307
304
  return schema && schema !== excludeCurrentSchema ? `${schema}.${name}` : name;
308
305
  };
309
- const makePopulateEnumQuery = (config, item) => {
310
- const [schema, name] = getSchemaAndTableFromName(config, item.enumName);
306
+ const makePopulateEnumQuery = (schema, item) => {
307
+ const [s, name] = getSchemaAndTableFromName(schema, item.enumName);
311
308
  return {
312
- text: `SELECT unnest(enum_range(NULL::${quoteTable(schema, name)}))::text`,
309
+ text: `SELECT unnest(enum_range(NULL::${quoteTable(s, name)}))::text`,
313
310
  then(result) {
314
311
  item.options.push(...result.rows.map(([value]) => value));
315
312
  }
316
313
  };
317
314
  };
318
- const transaction = (adapter, fn) => {
319
- return adapter.transaction(void 0, fn);
315
+ const transaction = (adapter, config, fn) => {
316
+ const searchPath = config.transactionSearchPath;
317
+ return adapter.transaction(
318
+ fn,
319
+ searchPath ? {
320
+ searchPath: typeof searchPath === "function" ? searchPath() : searchPath
321
+ } : void 0
322
+ );
320
323
  };
321
324
  const queryLock = (trx) => trx.query(`SELECT pg_advisory_xact_lock('${RAKE_DB_LOCK_KEY}')`);
322
325
  const getCliParam = (args, name) => {
@@ -344,22 +347,22 @@ const getCurrentChanges = () => currentChanges;
344
347
  const pushChange = (change) => currentChanges.push(change);
345
348
 
346
349
  const versionToString = (config, version) => config.migrationId === "timestamp" ? `${version}` : `${version}`.padStart(config.migrationId.serial, "0");
347
- const columnTypeToSql = (config, item) => {
348
- return item.data.isOfCustomType ? item instanceof pqb.DomainColumn ? quoteNameFromString(config, item.dataType) : quoteCustomType(config, item.toSQL()) : item.toSQL();
350
+ const columnTypeToSql = (schema, item) => {
351
+ return item.data.isOfCustomType ? item instanceof pqb.DomainColumn ? quoteNameFromString(schema, item.dataType) : quoteCustomType(schema, item.toSQL()) : item.toSQL();
349
352
  };
350
353
  const getColumnName = (item, key, snakeCase) => {
351
354
  return item.data.name || (snakeCase ? pqb.toSnakeCase(key) : key);
352
355
  };
353
- const columnToSql = (config, name, item, values, hasMultiplePrimaryKeys, snakeCase) => {
354
- const line = [`"${name}" ${columnTypeToSql(config, item)}`];
356
+ const columnToSql = (schema, name, item, values, hasMultiplePrimaryKeys, snakeCase) => {
357
+ const line = [`"${name}" ${columnTypeToSql(schema, item)}`];
355
358
  if (item.data.compression) {
356
359
  line.push(`COMPRESSION ${item.data.compression}`);
357
360
  }
358
361
  if (item.data.collate) {
359
- line.push(`COLLATE ${quoteNameFromString(config, item.data.collate)}`);
362
+ line.push(`COLLATE ${quoteNameFromString(schema, item.data.collate)}`);
360
363
  }
361
364
  if (item.data.identity) {
362
- line.push(identityToSql(config, item.data.identity));
365
+ line.push(identityToSql(schema, item.data.identity));
363
366
  } else if (item.data.generated) {
364
367
  line.push(
365
368
  `GENERATED ALWAYS AS (${item.data.generated.toSQL({
@@ -393,7 +396,7 @@ const columnToSql = (config, name, item, values, hasMultiplePrimaryKeys, snakeCa
393
396
  }
394
397
  line.push(
395
398
  referencesToSql(
396
- config,
399
+ schema,
397
400
  {
398
401
  columns: [name],
399
402
  ...foreignKey
@@ -417,11 +420,11 @@ const encodeColumnDefault = (def, values, column) => {
417
420
  }
418
421
  return null;
419
422
  };
420
- const identityToSql = (config, identity) => {
421
- const options = sequenceOptionsToSql(config, identity);
423
+ const identityToSql = (schema, identity) => {
424
+ const options = sequenceOptionsToSql(schema, identity);
422
425
  return `GENERATED ${identity.always ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY${options ? ` (${options})` : ""}`;
423
426
  };
424
- const sequenceOptionsToSql = (config, item) => {
427
+ const sequenceOptionsToSql = (schema, item) => {
425
428
  const line = [];
426
429
  if (item.dataType) line.push(`AS ${item.dataType}`);
427
430
  if (item.increment !== void 0) line.push(`INCREMENT BY ${item.increment}`);
@@ -431,8 +434,8 @@ const sequenceOptionsToSql = (config, item) => {
431
434
  if (item.cache !== void 0) line.push(`CACHE ${item.cache}`);
432
435
  if (item.cycle) line.push(`CYCLE`);
433
436
  if (item.ownedBy) {
434
- const [schema, table] = getSchemaAndTableFromName(config, item.ownedBy);
435
- line.push(`OWNED BY ${quoteTable(schema, table)}`);
437
+ const [s, table] = getSchemaAndTableFromName(schema, item.ownedBy);
438
+ line.push(`OWNED BY ${quoteTable(s, table)}`);
436
439
  }
437
440
  return line.join(" ");
438
441
  };
@@ -461,9 +464,9 @@ const addColumnComment = (comments, name, item) => {
461
464
  comments.push({ column: name, comment: item.data.comment });
462
465
  }
463
466
  };
464
- const getForeignKeyTable = (config, fnOrTable) => {
467
+ const getForeignKeyTable = (schema, fnOrTable) => {
465
468
  if (typeof fnOrTable === "string") {
466
- return getSchemaAndTableFromName(config, fnOrTable);
469
+ return getSchemaAndTableFromName(schema, fnOrTable);
467
470
  }
468
471
  const item = new (fnOrTable())();
469
472
  return [item.schema, item.table];
@@ -480,7 +483,7 @@ const getConstraintName = (table, constraint, snakeCase) => {
480
483
  if (constraint.identity) return `${table}_identity`;
481
484
  return `${table}_constraint`;
482
485
  };
483
- const constraintToSql = (config, { name }, up, constraint, values, snakeCase) => {
486
+ const constraintToSql = (schema, { name }, up, constraint, values, snakeCase) => {
484
487
  const constraintName = constraint.name || getConstraintName(name, constraint, snakeCase);
485
488
  if (!up) {
486
489
  const { dropMode } = constraint;
@@ -488,7 +491,7 @@ const constraintToSql = (config, { name }, up, constraint, values, snakeCase) =>
488
491
  }
489
492
  const sql = [`CONSTRAINT "${constraintName}"`];
490
493
  if (constraint.references) {
491
- sql.push(foreignKeyToSql(config, constraint.references, snakeCase));
494
+ sql.push(foreignKeyToSql(schema, constraint.references, snakeCase));
492
495
  }
493
496
  if (constraint.check) {
494
497
  sql.push(checkToSql(constraint.check, values));
@@ -498,15 +501,15 @@ const constraintToSql = (config, { name }, up, constraint, values, snakeCase) =>
498
501
  const checkToSql = (check, values) => {
499
502
  return `CHECK (${check.toSQL({ values })})`;
500
503
  };
501
- const foreignKeyToSql = (config, item, snakeCase) => {
504
+ const foreignKeyToSql = (schema, item, snakeCase) => {
502
505
  return `FOREIGN KEY (${joinColumns(
503
506
  snakeCase ? item.columns.map(pqb.toSnakeCase) : item.columns
504
- )}) ${referencesToSql(config, item, snakeCase)}`;
507
+ )}) ${referencesToSql(schema, item, snakeCase)}`;
505
508
  };
506
- const referencesToSql = (config, references, snakeCase) => {
507
- const [schema, table] = getForeignKeyTable(config, references.fnOrTable);
509
+ const referencesToSql = (schema, references, snakeCase) => {
510
+ const [s, table] = getForeignKeyTable(schema, references.fnOrTable);
508
511
  const sql = [
509
- `REFERENCES ${quoteTable(schema, table)}(${joinColumns(
512
+ `REFERENCES ${quoteTable(s, table)}(${joinColumns(
510
513
  snakeCase ? references.foreignColumns.map(pqb.toSnakeCase) : references.foreignColumns
511
514
  )})`
512
515
  ];
@@ -555,7 +558,7 @@ const getIndexOrExcludeName = (table, columns, suffix) => makeConstraintName(
555
558
  );
556
559
  const getIndexName = (table, columns) => getIndexOrExcludeName(table, columns, "idx");
557
560
  const getExcludeName = (table, columns) => getIndexOrExcludeName(table, columns, "exclude");
558
- const indexesToQuery = (config, up, { schema, name: tableName }, indexes, snakeCase, language) => {
561
+ const indexesToQuery = (up, { schema, name: tableName }, indexes, snakeCase, language) => {
559
562
  return indexes.map((index) => {
560
563
  const { options } = index;
561
564
  const { columns, include, name } = getIndexOrExcludeMainOptions(
@@ -584,7 +587,7 @@ const indexesToQuery = (config, up, { schema, name: tableName }, indexes, snakeC
584
587
  const columnsSql = columns.map((column) => {
585
588
  let sql2 = [
586
589
  "expression" in column ? `(${column.expression})` : `"${column.column}"`,
587
- column.collate && `COLLATE ${quoteNameFromString(config, column.collate)}`,
590
+ column.collate && `COLLATE ${quoteNameFromString(schema, column.collate)}`,
588
591
  column.opclass,
589
592
  column.order
590
593
  ].filter((x) => !!x).join(" ");
@@ -628,7 +631,7 @@ const indexesToQuery = (config, up, { schema, name: tableName }, indexes, snakeC
628
631
  return { text: sql.join(" "), values };
629
632
  });
630
633
  };
631
- const excludesToQuery = (config, up, { schema, name: tableName }, excludes, snakeCase) => {
634
+ const excludesToQuery = (up, { schema, name: tableName }, excludes, snakeCase) => {
632
635
  return excludes.map((exclude) => {
633
636
  const { options } = exclude;
634
637
  const { columns, include, name } = getIndexOrExcludeMainOptions(
@@ -648,7 +651,7 @@ const excludesToQuery = (config, up, { schema, name: tableName }, excludes, snak
648
651
  const columnList = columns.map(
649
652
  (column) => [
650
653
  "expression" in column ? `(${column.expression})` : `"${column.column}"`,
651
- column.collate && `COLLATE ${quoteNameFromString(config, column.collate)}`,
654
+ column.collate && `COLLATE ${quoteNameFromString(schema, column.collate)}`,
652
655
  column.opclass,
653
656
  column.order,
654
657
  `WITH ${column.with}`
@@ -715,22 +718,23 @@ const cmpRawSql = (a, b) => {
715
718
  const bValues = JSON.stringify(values);
716
719
  return aSql === bSql && aValues === bValues;
717
720
  };
718
- const getMigrationsSchemaAndTable = (config) => {
721
+ const getMigrationsSchemaAndTable = (adapter, config) => {
722
+ const schema = adapter.getSchema();
719
723
  const [tableSchema, table] = getSchemaAndTableFromName(
720
- config,
724
+ schema,
721
725
  config.migrationsTable
722
726
  );
723
- let schema = tableSchema;
724
- if (!schema) {
725
- schema = typeof config.schema === "function" ? config.schema() : config.schema;
726
- if (schema === "public") {
727
- schema = void 0;
727
+ let s = tableSchema;
728
+ if (!s) {
729
+ s = typeof schema === "function" ? schema() : schema;
730
+ if (s === "public") {
731
+ s = void 0;
728
732
  }
729
733
  }
730
- return { schema, table };
734
+ return { schema: s, table };
731
735
  };
732
- const migrationsSchemaTableSql = (config) => {
733
- const { schema, table } = getMigrationsSchemaAndTable(config);
736
+ const migrationsSchemaTableSql = (adapter, config) => {
737
+ const { schema, table } = getMigrationsSchemaAndTable(adapter, config);
734
738
  return `${schema ? `"${schema}".` : ""}"${table}"`;
735
739
  };
736
740
 
@@ -787,8 +791,9 @@ const createTable = async (migration, up, tableName, first, second, third) => {
787
791
  } else {
788
792
  shape = tableData = pqb.emptyObject;
789
793
  }
794
+ const schema = migration.adapter.getSchema();
790
795
  const ast = makeAst$2(
791
- migration.options,
796
+ schema,
792
797
  up,
793
798
  tableName,
794
799
  shape,
@@ -797,7 +802,7 @@ const createTable = async (migration, up, tableName, first, second, third) => {
797
802
  migration.options.noPrimaryKey
798
803
  );
799
804
  fn && validatePrimaryKey(ast);
800
- const queries = astToQueries$1(migration.options, ast, snakeCase, language);
805
+ const queries = astToQueries$1(schema, ast, snakeCase, language);
801
806
  for (const { then, ...query } of queries) {
802
807
  const result = await migration.adapter.arrays(interpolateSqlValues(query));
803
808
  then?.(result);
@@ -817,7 +822,7 @@ const createTable = async (migration, up, tableName, first, second, third) => {
817
822
  }
818
823
  };
819
824
  };
820
- const makeAst$2 = (config, up, tableName, shape, tableData, options, noPrimaryKey) => {
825
+ const makeAst$2 = (schema, up, tableName, shape, tableData, options, noPrimaryKey) => {
821
826
  const shapePKeys = [];
822
827
  for (const key in shape) {
823
828
  const column = shape[key];
@@ -826,11 +831,11 @@ const makeAst$2 = (config, up, tableName, shape, tableData, options, noPrimaryKe
826
831
  }
827
832
  }
828
833
  const { primaryKey } = tableData;
829
- const [schema, table] = getSchemaAndTableFromName(config, tableName);
834
+ const [s, table] = getSchemaAndTableFromName(schema, tableName);
830
835
  return {
831
836
  type: "table",
832
837
  action: up ? "create" : "drop",
833
- schema,
838
+ schema: s,
834
839
  name: table,
835
840
  shape,
836
841
  ...tableData,
@@ -866,13 +871,13 @@ You can suppress this error by setting { noPrimaryKey: true } after a table name
866
871
  }
867
872
  }
868
873
  };
869
- const astToQueries$1 = (config, ast, snakeCase, language) => {
874
+ const astToQueries$1 = (schema, ast, snakeCase, language) => {
870
875
  const queries = [];
871
876
  const { shape } = ast;
872
877
  for (const key in shape) {
873
878
  const item = shape[key];
874
879
  if (!(item instanceof pqb.EnumColumn)) continue;
875
- queries.push(makePopulateEnumQuery(config, item));
880
+ queries.push(makePopulateEnumQuery(schema, item));
876
881
  }
877
882
  if (ast.action === "drop") {
878
883
  queries.push({
@@ -894,7 +899,7 @@ const astToQueries$1 = (config, ast, snakeCase, language) => {
894
899
  lines.push(
895
900
  `
896
901
  ${columnToSql(
897
- config,
902
+ schema,
898
903
  name,
899
904
  item,
900
905
  values,
@@ -918,7 +923,7 @@ const astToQueries$1 = (config, ast, snakeCase, language) => {
918
923
  lines.push(
919
924
  `
920
925
  ${constraintToSql(
921
- config,
926
+ schema,
922
927
  ast,
923
928
  true,
924
929
  {
@@ -943,8 +948,8 @@ const astToQueries$1 = (config, ast, snakeCase, language) => {
943
948
  )`,
944
949
  values
945
950
  },
946
- ...indexesToQuery(config, true, ast, indexes, snakeCase, language),
947
- ...excludesToQuery(config, true, ast, excludes, snakeCase),
951
+ ...indexesToQuery(true, ast, indexes, snakeCase, language),
952
+ ...excludesToQuery(true, ast, excludes, snakeCase),
948
953
  ...commentsToQuery(ast, comments)
949
954
  );
950
955
  if (ast.comment) {
@@ -1166,21 +1171,22 @@ const changeTable = async (migration, up, tableName, options, fn) => {
1166
1171
  tableChanger[pqb.snakeCaseKey] = snakeCase;
1167
1172
  addOrDropChanges.length = 0;
1168
1173
  const changeData = fn?.(tableChanger) || {};
1174
+ const schema = migration.adapter.getSchema();
1169
1175
  const ast = makeAst$1(
1170
- migration.options,
1176
+ schema,
1171
1177
  up,
1172
1178
  tableName,
1173
1179
  changeData,
1174
1180
  changeTableData,
1175
1181
  options
1176
1182
  );
1177
- const queries = astToQueries(migration.options, ast, snakeCase, language);
1183
+ const queries = astToQueries(schema, ast, snakeCase, language);
1178
1184
  for (const query of queries) {
1179
1185
  const result = await migration.adapter.arrays(interpolateSqlValues(query));
1180
1186
  query.then?.(result);
1181
1187
  }
1182
1188
  };
1183
- const makeAst$1 = (config, up, name, changeData, changeTableData2, options) => {
1189
+ const makeAst$1 = (schema, up, name, changeData, changeTableData2, options) => {
1184
1190
  const { comment } = options;
1185
1191
  const shape = {};
1186
1192
  const consumedChanges = {};
@@ -1225,17 +1231,17 @@ const makeAst$1 = (config, up, name, changeData, changeTableData2, options) => {
1225
1231
  );
1226
1232
  shape[name2] = arr;
1227
1233
  }
1228
- const [schema, table] = getSchemaAndTableFromName(config, name);
1234
+ const [s, table] = getSchemaAndTableFromName(schema, name);
1229
1235
  return {
1230
1236
  type: "changeTable",
1231
- schema,
1237
+ schema: s,
1232
1238
  name: table,
1233
1239
  comment: comment ? up ? Array.isArray(comment) ? comment[1] : comment : Array.isArray(comment) ? comment[0] : null : void 0,
1234
1240
  shape,
1235
1241
  ...up ? changeTableData2 : { add: changeTableData2.drop, drop: changeTableData2.add }
1236
1242
  };
1237
1243
  };
1238
- const astToQueries = (config, ast, snakeCase, language) => {
1244
+ const astToQueries = (schema, ast, snakeCase, language) => {
1239
1245
  const queries = [];
1240
1246
  if (ast.comment !== void 0) {
1241
1247
  queries.push({
@@ -1255,7 +1261,7 @@ const astToQueries = (config, ast, snakeCase, language) => {
1255
1261
  if (Array.isArray(item)) {
1256
1262
  for (const it of item) {
1257
1263
  handlePrerequisitesForTableItem(
1258
- config,
1264
+ schema,
1259
1265
  key,
1260
1266
  it,
1261
1267
  queries,
@@ -1266,7 +1272,7 @@ const astToQueries = (config, ast, snakeCase, language) => {
1266
1272
  }
1267
1273
  } else {
1268
1274
  handlePrerequisitesForTableItem(
1269
- config,
1275
+ schema,
1270
1276
  key,
1271
1277
  item,
1272
1278
  queries,
@@ -1305,7 +1311,7 @@ const astToQueries = (config, ast, snakeCase, language) => {
1305
1311
  if (Array.isArray(item)) {
1306
1312
  for (const it of item) {
1307
1313
  handleTableItemChange(
1308
- config,
1314
+ schema,
1309
1315
  key,
1310
1316
  it,
1311
1317
  ast,
@@ -1325,7 +1331,7 @@ const astToQueries = (config, ast, snakeCase, language) => {
1325
1331
  }
1326
1332
  } else {
1327
1333
  handleTableItemChange(
1328
- config,
1334
+ schema,
1329
1335
  key,
1330
1336
  item,
1331
1337
  ast,
@@ -1359,7 +1365,7 @@ const astToQueries = (config, ast, snakeCase, language) => {
1359
1365
  ...dropConstraints.map(
1360
1366
  (foreignKey) => `
1361
1367
  DROP ${constraintToSql(
1362
- config,
1368
+ schema,
1363
1369
  ast,
1364
1370
  false,
1365
1371
  foreignKey,
@@ -1384,7 +1390,7 @@ const astToQueries = (config, ast, snakeCase, language) => {
1384
1390
  ...addConstraints.map(
1385
1391
  (foreignKey) => `
1386
1392
  ADD ${constraintToSql(
1387
- config,
1393
+ schema,
1388
1394
  ast,
1389
1395
  true,
1390
1396
  foreignKey,
@@ -1406,14 +1412,10 @@ const astToQueries = (config, ast, snakeCase, language) => {
1406
1412
  if (alterTable.length) {
1407
1413
  queries.push(alterTableSql(tableName, alterTable, values));
1408
1414
  }
1409
- queries.push(
1410
- ...indexesToQuery(config, false, ast, dropIndexes, snakeCase, language)
1411
- );
1412
- queries.push(
1413
- ...indexesToQuery(config, true, ast, addIndexes, snakeCase, language)
1414
- );
1415
- queries.push(...excludesToQuery(config, false, ast, dropExcludes, snakeCase));
1416
- queries.push(...excludesToQuery(config, true, ast, addExcludes, snakeCase));
1415
+ queries.push(...indexesToQuery(false, ast, dropIndexes, snakeCase, language));
1416
+ queries.push(...indexesToQuery(true, ast, addIndexes, snakeCase, language));
1417
+ queries.push(...excludesToQuery(false, ast, dropExcludes, snakeCase));
1418
+ queries.push(...excludesToQuery(true, ast, addExcludes, snakeCase));
1417
1419
  queries.push(...commentsToQuery(ast, comments));
1418
1420
  return queries;
1419
1421
  };
@@ -1422,11 +1424,11 @@ const alterTableSql = (tableName, lines, values) => ({
1422
1424
  ${lines.join(",\n ")}`,
1423
1425
  values
1424
1426
  });
1425
- const handlePrerequisitesForTableItem = (config, key, item, queries, addPrimaryKeys, dropPrimaryKeys, snakeCase) => {
1427
+ const handlePrerequisitesForTableItem = (schema, key, item, queries, addPrimaryKeys, dropPrimaryKeys, snakeCase) => {
1426
1428
  if ("item" in item) {
1427
1429
  const { item: column } = item;
1428
1430
  if (column instanceof pqb.EnumColumn) {
1429
- queries.push(makePopulateEnumQuery(config, column));
1431
+ queries.push(makePopulateEnumQuery(schema, column));
1430
1432
  }
1431
1433
  }
1432
1434
  if (item.type === "add") {
@@ -1439,10 +1441,10 @@ const handlePrerequisitesForTableItem = (config, key, item, queries, addPrimaryK
1439
1441
  }
1440
1442
  } else if (item.type === "change") {
1441
1443
  if (item.from.column instanceof pqb.EnumColumn) {
1442
- queries.push(makePopulateEnumQuery(config, item.from.column));
1444
+ queries.push(makePopulateEnumQuery(schema, item.from.column));
1443
1445
  }
1444
1446
  if (item.to.column instanceof pqb.EnumColumn) {
1445
- queries.push(makePopulateEnumQuery(config, item.to.column));
1447
+ queries.push(makePopulateEnumQuery(schema, item.to.column));
1446
1448
  }
1447
1449
  if (item.from.primaryKey) {
1448
1450
  dropPrimaryKeys.columns.push(
@@ -1458,7 +1460,7 @@ const handlePrerequisitesForTableItem = (config, key, item, queries, addPrimaryK
1458
1460
  }
1459
1461
  }
1460
1462
  };
1461
- const handleTableItemChange = (config, key, item, ast, alterTable, renameItems, values, addPrimaryKeys, addIndexes, dropIndexes, addExcludes, dropExcludes, addConstraints, dropConstraints, comments, snakeCase) => {
1463
+ const handleTableItemChange = (schema, key, item, ast, alterTable, renameItems, values, addPrimaryKeys, addIndexes, dropIndexes, addExcludes, dropExcludes, addConstraints, dropConstraints, comments, snakeCase) => {
1462
1464
  if (item.type === "add") {
1463
1465
  const column = item.item;
1464
1466
  const name = getColumnName(column, key, snakeCase);
@@ -1467,7 +1469,7 @@ const handleTableItemChange = (config, key, item, ast, alterTable, renameItems,
1467
1469
  addColumnComment(comments, name, column);
1468
1470
  alterTable.push(
1469
1471
  `ADD COLUMN ${columnToSql(
1470
- config,
1472
+ schema,
1471
1473
  name,
1472
1474
  column,
1473
1475
  values,
@@ -1490,10 +1492,10 @@ const handleTableItemChange = (config, key, item, ast, alterTable, renameItems,
1490
1492
  let changeType = false;
1491
1493
  if (to.type && (from.type !== to.type || from.collate !== to.collate)) {
1492
1494
  changeType = true;
1493
- const type = !to.column || to.column.data.isOfCustomType ? to.column && to.column instanceof pqb.DomainColumn ? quoteNameFromString(config, to.type) : quoteCustomType(config, to.type) : to.type;
1495
+ const type = !to.column || to.column.data.isOfCustomType ? to.column && to.column instanceof pqb.DomainColumn ? quoteNameFromString(schema, to.type) : quoteCustomType(schema, to.type) : to.type;
1494
1496
  const using = item.using?.usingUp ? ` USING ${item.using.usingUp.toSQL({ values })}` : to.column instanceof pqb.EnumColumn ? ` USING "${name}"::text::${type}` : to.column instanceof pqb.ArrayColumn ? ` USING "${name}"::text[]::${type}` : "";
1495
1497
  alterTable.push(
1496
- `ALTER COLUMN "${name}" TYPE ${type}${to.collate ? ` COLLATE ${quoteNameFromString(config, to.collate)}` : ""}${using}`
1498
+ `ALTER COLUMN "${name}" TYPE ${type}${to.collate ? ` COLLATE ${quoteNameFromString(schema, to.collate)}` : ""}${using}`
1497
1499
  );
1498
1500
  }
1499
1501
  if (typeof from.identity !== typeof to.identity || !pqb.deepCompare(from.identity, to.identity)) {
@@ -1502,7 +1504,7 @@ const handleTableItemChange = (config, key, item, ast, alterTable, renameItems,
1502
1504
  }
1503
1505
  if (to.identity) {
1504
1506
  alterTable.push(
1505
- `ALTER COLUMN "${name}" ADD ${identityToSql(config, to.identity)}`
1507
+ `ALTER COLUMN "${name}" ADD ${identityToSql(schema, to.identity)}`
1506
1508
  );
1507
1509
  }
1508
1510
  }
@@ -1635,19 +1637,20 @@ const renameColumnSql = (from, to) => {
1635
1637
  };
1636
1638
 
1637
1639
  const createView = async (migration, up, name, options, sql) => {
1638
- const ast = makeAst(migration.options, up, name, options, sql);
1640
+ const schema = migration.adapter.getSchema();
1641
+ const ast = makeAst(schema, up, name, options, sql);
1639
1642
  const query = astToQuery(ast);
1640
1643
  await migration.adapter.arrays(interpolateSqlValues(query));
1641
1644
  };
1642
- const makeAst = (config, up, fullName, options, sql) => {
1645
+ const makeAst = (schema, up, fullName, options, sql) => {
1643
1646
  if (typeof sql === "string") {
1644
1647
  sql = pqb.raw({ raw: sql });
1645
1648
  }
1646
- const [schema, name] = getSchemaAndTableFromName(config, fullName);
1649
+ const [s, name] = getSchemaAndTableFromName(schema, fullName);
1647
1650
  return {
1648
1651
  type: "view",
1649
1652
  action: up ? "create" : "drop",
1650
- schema,
1653
+ schema: s,
1651
1654
  name,
1652
1655
  shape: {},
1653
1656
  sql,
@@ -2235,7 +2238,10 @@ class Migration {
2235
2238
  * @param values - object where keys are for old names, values are for new names
2236
2239
  */
2237
2240
  async renameEnumValues(enumName, values) {
2238
- const [schema, name] = getSchemaAndTableFromName(this.options, enumName);
2241
+ const [schema, name] = getSchemaAndTableFromName(
2242
+ this.adapter.getSchema(),
2243
+ enumName
2244
+ );
2239
2245
  const ast = {
2240
2246
  type: "renameEnumValues",
2241
2247
  schema,
@@ -2500,7 +2506,10 @@ class Migration {
2500
2506
  */
2501
2507
  async tableExists(tableName) {
2502
2508
  let text = `SELECT 1 FROM "information_schema"."tables" WHERE "table_name" = $1`;
2503
- const [schema, table] = getSchemaAndTableFromName(this.options, tableName);
2509
+ const [schema, table] = getSchemaAndTableFromName(
2510
+ this.adapter.getSchema(),
2511
+ tableName
2512
+ );
2504
2513
  const values = [table];
2505
2514
  if (schema) {
2506
2515
  text += ' AND "table_schema" = $2';
@@ -2531,7 +2540,10 @@ class Migration {
2531
2540
  */
2532
2541
  async columnExists(tableName, columnName) {
2533
2542
  let text = `SELECT 1 FROM "information_schema"."columns" WHERE "table_name" = $1 AND "column_name" = $2`;
2534
- const [schema, table] = getSchemaAndTableFromName(this.options, tableName);
2543
+ const [schema, table] = getSchemaAndTableFromName(
2544
+ this.adapter.getSchema(),
2545
+ tableName
2546
+ );
2535
2547
  const values = [
2536
2548
  table,
2537
2549
  this.options.snakeCase ? pqb.toSnakeCase(columnName) : columnName
@@ -2622,7 +2634,10 @@ const createSchema = async (migration, up, name) => {
2622
2634
  );
2623
2635
  };
2624
2636
  const createExtension = async (migration, up, fullName, options) => {
2625
- const [schema, name] = getSchemaAndTableFromName(migration.options, fullName);
2637
+ const [schema, name] = getSchemaAndTableFromName(
2638
+ migration.adapter.getSchema(),
2639
+ fullName
2640
+ );
2626
2641
  const ast = {
2627
2642
  type: "extension",
2628
2643
  action: up ? "create" : "drop",
@@ -2639,7 +2654,10 @@ const createExtension = async (migration, up, fullName, options) => {
2639
2654
  await migration.adapter.query(query);
2640
2655
  };
2641
2656
  const createEnum = async (migration, up, name, values, options = {}) => {
2642
- const [schema, enumName] = getSchemaAndTableFromName(migration.options, name);
2657
+ const [schema, enumName] = getSchemaAndTableFromName(
2658
+ migration.adapter.getSchema(),
2659
+ name
2660
+ );
2643
2661
  const ast = {
2644
2662
  type: "enum",
2645
2663
  action: up ? "create" : "drop",
@@ -2659,7 +2677,7 @@ const createEnum = async (migration, up, name, values, options = {}) => {
2659
2677
  };
2660
2678
  const createDomain = async (migration, up, name, fn) => {
2661
2679
  const [schema, domainName] = getSchemaAndTableFromName(
2662
- migration.options,
2680
+ migration.adapter.getSchema(),
2663
2681
  name
2664
2682
  );
2665
2683
  const ast = {
@@ -2674,10 +2692,7 @@ const createDomain = async (migration, up, name, fn) => {
2674
2692
  const quotedName = quoteWithSchema(ast);
2675
2693
  if (ast.action === "create") {
2676
2694
  const column = ast.baseType;
2677
- query = `CREATE DOMAIN ${quotedName} AS ${columnTypeToSql(
2678
- migration.options,
2679
- column
2680
- )}${column.data.collate ? `
2695
+ query = `CREATE DOMAIN ${quotedName} AS ${columnTypeToSql(schema, column)}${column.data.collate ? `
2681
2696
  COLLATE "${column.data.collate}"` : ""}${column.data.default !== void 0 ? `
2682
2697
  DEFAULT ${encodeColumnDefault(column.data.default, values)}` : ""}${!column.data.isNullable || column.data.checks ? "\n" : ""}${[
2683
2698
  !column.data.isNullable && "NOT NULL",
@@ -2695,7 +2710,7 @@ DEFAULT ${encodeColumnDefault(column.data.default, values)}` : ""}${!column.data
2695
2710
  };
2696
2711
  const createCollation = async (migration, up, name, options) => {
2697
2712
  const [schema, collationName] = getSchemaAndTableFromName(
2698
- migration.options,
2713
+ migration.adapter.getSchema(),
2699
2714
  name
2700
2715
  );
2701
2716
  const ast = {
@@ -2711,7 +2726,7 @@ const createCollation = async (migration, up, name, options) => {
2711
2726
  query = `CREATE COLLATION${ast.createIfNotExists ? " IF NOT EXISTS" : ""} ${quotedName} `;
2712
2727
  if (ast.fromExisting) {
2713
2728
  query += `FROM ${quoteNameFromString(
2714
- migration.options,
2729
+ migration.adapter.getSchema(),
2715
2730
  ast.fromExisting
2716
2731
  )}`;
2717
2732
  } else {
@@ -2737,11 +2752,11 @@ const queryExists = (db, sql) => {
2737
2752
  };
2738
2753
  const renameType = async (migration, from, to, kind) => {
2739
2754
  const [fromSchema, f] = getSchemaAndTableFromName(
2740
- migration.options,
2755
+ migration.adapter.getSchema(),
2741
2756
  migration.up ? from : to
2742
2757
  );
2743
2758
  const [toSchema, t] = getSchemaAndTableFromName(
2744
- migration.options,
2759
+ migration.adapter.getSchema(),
2745
2760
  migration.up ? to : from
2746
2761
  );
2747
2762
  const ast = {
@@ -2758,14 +2773,15 @@ const renameType = async (migration, from, to, kind) => {
2758
2773
  );
2759
2774
  }
2760
2775
  if (ast.fromSchema !== ast.toSchema) {
2776
+ const schema = migration.adapter.getSchema();
2761
2777
  await migration.adapter.query(
2762
- `ALTER ${ast.kind} ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${ast.toSchema ?? migration.options.schema ?? "public"}"`
2778
+ `ALTER ${ast.kind} ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${ast.toSchema ?? (typeof schema === "function" ? schema() : schema) ?? "public"}"`
2763
2779
  );
2764
2780
  }
2765
2781
  };
2766
2782
  const renameTableItem = async (migration, tableName, from, to, kind) => {
2767
2783
  const [schema, table] = getSchemaAndTableFromName(
2768
- migration.options,
2784
+ migration.adapter.getSchema(),
2769
2785
  tableName
2770
2786
  );
2771
2787
  const [f, t] = migration.up ? [from, to] : [to, from];
@@ -2777,7 +2793,10 @@ const renameTableItem = async (migration, tableName, from, to, kind) => {
2777
2793
  );
2778
2794
  };
2779
2795
  const addOrDropEnumValues = async (migration, up, enumName, values, options) => {
2780
- const [schema, name] = getSchemaAndTableFromName(migration.options, enumName);
2796
+ const [schema, name] = getSchemaAndTableFromName(
2797
+ migration.adapter.getSchema(),
2798
+ enumName
2799
+ );
2781
2800
  const quotedName = quoteTable(schema, name);
2782
2801
  const ast = {
2783
2802
  type: "enumValues",
@@ -2813,7 +2832,10 @@ const addOrDropEnumValues = async (migration, up, enumName, values, options) =>
2813
2832
  );
2814
2833
  };
2815
2834
  const changeEnumValues = async (migration, enumName, fromValues, toValues) => {
2816
- const [schema, name] = getSchemaAndTableFromName(migration.options, enumName);
2835
+ const [schema, name] = getSchemaAndTableFromName(
2836
+ migration.adapter.getSchema(),
2837
+ enumName
2838
+ );
2817
2839
  if (!migration.up) {
2818
2840
  const values = fromValues;
2819
2841
  fromValues = toValues;
@@ -2836,7 +2858,7 @@ const changeEnumValues = async (migration, enumName, fromValues, toValues) => {
2836
2858
  );
2837
2859
  };
2838
2860
  const recreateEnum = async (migration, { schema, name }, values, errorMessage) => {
2839
- const configSchema = migration.options.schema;
2861
+ const configSchema = migration.adapter.getSchema();
2840
2862
  const defaultSchema = (typeof configSchema === "function" ? configSchema() : void 0) ?? "public";
2841
2863
  const quotedName = quoteTable(schema, name);
2842
2864
  const relKinds = ["r", "m"];
@@ -3061,6 +3083,7 @@ ${format === "timestamp" || digits !== 4 ? `Set \`migrationId\`: ${format === "t
3061
3083
  const renameMigrationVersionsInDb = async (config, adapter, values) => {
3062
3084
  await adapter.arrays(
3063
3085
  `UPDATE ${migrationsSchemaTableSql(
3086
+ adapter,
3064
3087
  config
3065
3088
  )} AS t SET version = v.version FROM (VALUES ${values.map(
3066
3089
  ([oldVersion, , newVersion], i) => `('${oldVersion}', $${i + 1}, '${newVersion}')`
@@ -3240,13 +3263,15 @@ function getDigitsPrefix(name) {
3240
3263
  const saveMigratedVersion = async (db, version, name, config) => {
3241
3264
  await db.silentArrays(
3242
3265
  `INSERT INTO ${migrationsSchemaTableSql(
3266
+ db,
3243
3267
  config
3244
3268
  )}(version, name) VALUES ($1, $2)`,
3245
3269
  [version, name]
3246
3270
  );
3247
3271
  };
3248
3272
  const createMigrationsSchemaAndTable = async (db, config) => {
3249
- const { schema, table } = getMigrationsSchemaAndTable(config);
3273
+ const adapter = getMaybeTransactionAdapter(db);
3274
+ const { schema, table } = getMigrationsSchemaAndTable(adapter, config);
3250
3275
  if (schema) {
3251
3276
  const res2 = await createSchema$1(db, schema);
3252
3277
  if (res2 === "done") {
@@ -3266,6 +3291,7 @@ const createMigrationsSchemaAndTable = async (db, config) => {
3266
3291
  const deleteMigratedVersion = async (adapter, version, name, config) => {
3267
3292
  const res = await adapter.silentArrays(
3268
3293
  `DELETE FROM ${migrationsSchemaTableSql(
3294
+ adapter,
3269
3295
  config
3270
3296
  )} WHERE version = $1 AND name = $2`,
3271
3297
  [version, name]
@@ -3278,7 +3304,7 @@ class NoMigrationsTableError extends Error {
3278
3304
  }
3279
3305
  const getMigratedVersionsMap = async (ctx, adapter, config, renameTo) => {
3280
3306
  try {
3281
- const table = migrationsSchemaTableSql(config);
3307
+ const table = migrationsSchemaTableSql(adapter, config);
3282
3308
  const result = await adapter.arrays(
3283
3309
  `SELECT * FROM ${table} ORDER BY version`
3284
3310
  );
@@ -3355,7 +3381,7 @@ async function renameMigrations(config, trx, versions, renameTo) {
3355
3381
  }
3356
3382
 
3357
3383
  const transactionIfSingle = (adapter, config, fn) => {
3358
- return !adapter.isInTransaction() && config.transaction === "single" ? transaction(adapter, fn) : fn(adapter);
3384
+ return !adapter.isInTransaction() && config.transaction === "single" ? transaction(adapter, config, fn) : fn(adapter);
3359
3385
  };
3360
3386
  function makeMigrateFn(up, defaultCount, fn) {
3361
3387
  return async (db, config, params) => {
@@ -3572,8 +3598,12 @@ const getChanges = async (file, config) => {
3572
3598
  }
3573
3599
  return changes;
3574
3600
  };
3575
- const runMigrationInOwnTransaction = (adapter, ...rest) => {
3576
- return transaction(adapter, (trx) => applyMigration(trx, ...rest));
3601
+ const runMigrationInOwnTransaction = (adapter, up, changes, config) => {
3602
+ return transaction(
3603
+ adapter,
3604
+ config,
3605
+ (trx) => applyMigration(trx, up, changes, config)
3606
+ );
3577
3607
  };
3578
3608
  const applyMigration = async (trx, up, changes, config) => {
3579
3609
  const db = createMigrationInterface(trx, up, config);
@@ -3657,9 +3687,10 @@ const createOrDropDatabase = async (action, adapters, config, dontClose) => {
3657
3687
  );
3658
3688
  if (!res) continue;
3659
3689
  if (action === "create") {
3660
- await adapter.transaction(void 0, async (tx) => {
3661
- if (config.schema) {
3662
- const quoted = `"${config.schema}"`;
3690
+ await adapter.transaction(async (tx) => {
3691
+ const schema = tx.getSchema();
3692
+ if (schema) {
3693
+ const quoted = `"${typeof schema === "function" ? schema() : schema}"`;
3663
3694
  const res2 = await createSchema$1(tx, quoted);
3664
3695
  if (res2 === "done") {
3665
3696
  config.logger?.log(`Created schema ${quoted}`);
@@ -3771,7 +3802,7 @@ const astToGenerateItem = (config, ast, currentSchema) => {
3771
3802
  let dep = typeSchemaCache.get(type);
3772
3803
  if (!dep) {
3773
3804
  const [schema = currentSchema, name] = getSchemaAndTableFromName(
3774
- config,
3805
+ currentSchema,
3775
3806
  type
3776
3807
  );
3777
3808
  dep = `${schema}.${name}`;
@@ -3964,7 +3995,7 @@ const analyzeTableColumns = (config, currentSchema, schema, table, deps, resolve
3964
3995
  )
3965
3996
  );
3966
3997
  const [s = currentSchema, t] = getForeignKeyTable(
3967
- config,
3998
+ currentSchema,
3968
3999
  fkey.fnOrTable
3969
4000
  );
3970
4001
  const foreignTable = `${s}.${t}`;
@@ -4011,7 +4042,7 @@ const analyzeTableData = (config, currentSchema, schema, table, keys, deps, data
4011
4042
  );
4012
4043
  if (constraint.references) {
4013
4044
  const [s = currentSchema, t] = getForeignKeyTable(
4014
- config,
4045
+ currentSchema,
4015
4046
  constraint.references.fnOrTable
4016
4047
  );
4017
4048
  deps.push(`${s}.${t}`);
@@ -4148,7 +4179,7 @@ const astEncoders = {
4148
4179
  const isShifted = hasOptions || hasTableData;
4149
4180
  if (isShifted) {
4150
4181
  pqb.addCode(code, `await db.${ast.action}Table(`);
4151
- const inner = [`${quoteSchemaTable(ast)},`];
4182
+ const inner = [`${quoteSchemaTable(ast, currentSchema)},`];
4152
4183
  code.push(inner);
4153
4184
  code = inner;
4154
4185
  if (hasOptions) {
@@ -4162,7 +4193,10 @@ const astEncoders = {
4162
4193
  } else {
4163
4194
  pqb.addCode(
4164
4195
  code,
4165
- `await db.${ast.action}Table(${quoteSchemaTable(ast)}, (t) => ({`
4196
+ `await db.${ast.action}Table(${quoteSchemaTable(
4197
+ ast,
4198
+ currentSchema
4199
+ )}, (t) => ({`
4166
4200
  );
4167
4201
  }
4168
4202
  const timestamps = getHasTimestamps(
@@ -4373,9 +4407,9 @@ const astEncoders = {
4373
4407
  ast.to
4374
4408
  )});`;
4375
4409
  },
4376
- extension(ast) {
4410
+ extension(ast, _, currentSchema) {
4377
4411
  const code = [
4378
- `await db.${ast.action}Extension(${quoteSchemaTable(ast)}`
4412
+ `await db.${ast.action}Extension(${quoteSchemaTable(ast, currentSchema)}`
4379
4413
  ];
4380
4414
  if (ast.version) {
4381
4415
  pqb.addCode(code, ", {");
@@ -4409,13 +4443,14 @@ const astEncoders = {
4409
4443
  },
4410
4444
  domain(ast, _, currentSchema) {
4411
4445
  return `await db.${ast.action}Domain(${quoteSchemaTable(
4412
- ast
4446
+ ast,
4447
+ currentSchema
4413
4448
  )}, (t) => ${ast.baseType.toCode(
4414
4449
  { t: "t", table: ast.name, currentSchema },
4415
4450
  ast.baseType.data.name ?? ""
4416
4451
  )});`;
4417
4452
  },
4418
- collation(ast) {
4453
+ collation(ast, _, currentSchema) {
4419
4454
  const params = [];
4420
4455
  if (ast.locale) params.push(`locale: '${ast.locale}',`);
4421
4456
  if (ast.lcCollate) params.push(`lcCollate: '${ast.lcCollate}',`);
@@ -4424,7 +4459,7 @@ const astEncoders = {
4424
4459
  if (ast.deterministic) params.push(`deterministic: ${ast.deterministic},`);
4425
4460
  if (ast.version) params.push(`version: '${ast.version}',`);
4426
4461
  return [
4427
- `await db.createCollation(${quoteSchemaTable(ast)}, {`,
4462
+ `await db.createCollation(${quoteSchemaTable(ast, currentSchema)}, {`,
4428
4463
  params,
4429
4464
  "});"
4430
4465
  ];
@@ -4454,8 +4489,10 @@ const astEncoders = {
4454
4489
  })}, ${pqb.singleQuote(ast.from)}, ${pqb.singleQuote(ast.to)});`
4455
4490
  ];
4456
4491
  },
4457
- view(ast) {
4458
- const code = [`await db.createView(${quoteSchemaTable(ast)}`];
4492
+ view(ast, _, currentSchema) {
4493
+ const code = [
4494
+ `await db.createView(${quoteSchemaTable(ast, currentSchema)}`
4495
+ ];
4459
4496
  const options = [];
4460
4497
  if (ast.options.recursive) options.push("recursive: true,");
4461
4498
  const w = ast.options.with;
@@ -5046,7 +5083,7 @@ const structureToAst = async (ctx, adapter, config) => {
5046
5083
  });
5047
5084
  }
5048
5085
  const domains = makeDomainsMap(ctx, data);
5049
- const { schema: migrationsSchema = "public", table: migrationsTable } = getMigrationsSchemaAndTable(config);
5086
+ const { schema: migrationsSchema = "public", table: migrationsTable } = getMigrationsSchemaAndTable(adapter, config);
5050
5087
  for (const table of data.tables) {
5051
5088
  if (table.name === migrationsTable && table.schemaName === migrationsSchema)
5052
5089
  continue;