rake-db 2.15.8 → 2.15.9

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.d.ts CHANGED
@@ -102,8 +102,11 @@ type DbMigration<CT extends RakeDbColumnTypes> = DbResult<CT> & Migration<CT> &
102
102
  * @param asts - array of migration ASTs to collect changes into
103
103
  */
104
104
  declare const createMigrationInterface: <SchemaConfig extends ColumnSchemaConfig<orchid_core.ColumnTypeBase<orchid_core.ColumnTypeSchemaArg, unknown, any, orchid_core.BaseOperators, unknown, unknown, any, unknown, any, orchid_core.ColumnDataBase>>, CT extends RakeDbColumnTypes>(tx: TransactionAdapter, up: boolean, config: RakeDbConfig<SchemaConfig, CT>, asts: RakeDbAst[]) => DbMigration<CT>;
105
+ interface MigrationAdapter extends TransactionAdapter {
106
+ schema: string;
107
+ }
105
108
  declare class Migration<CT extends RakeDbColumnTypes> {
106
- adapter: TransactionAdapter;
109
+ adapter: MigrationAdapter;
107
110
  log?: QueryLogObject;
108
111
  up: boolean;
109
112
  options: RakeDbConfig<ColumnSchemaConfig>;
@@ -253,10 +256,36 @@ declare class Migration<CT extends RakeDbColumnTypes> {
253
256
  * });
254
257
  * ```
255
258
  *
259
+ * Prefix table name with a schema to set a different schema:
260
+ *
261
+ * ```ts
262
+ * import { change } from '../dbScript';
263
+ *
264
+ * change(async (db) => {
265
+ * await db.renameTable('fromSchema.oldTable', 'toSchema.newTable');
266
+ * });
267
+ * ```
268
+ *
256
269
  * @param from - rename the table from
257
270
  * @param to - rename the table to
258
271
  */
259
272
  renameTable(from: string, to: string): Promise<void>;
273
+ /**
274
+ * Set a different schema to the table:
275
+ *
276
+ * ```ts
277
+ * import { change } from '../dbScript';
278
+ *
279
+ * change(async (db) => {
280
+ * await db.changeTableSchema('tableName', 'fromSchema', 'toSchema');
281
+ * });
282
+ * ```
283
+ *
284
+ * @param table - table name
285
+ * @param from - current table schema
286
+ * @param to - desired table schema
287
+ */
288
+ changeTableSchema(table: string, from: string, to: string): Promise<void>;
260
289
  /**
261
290
  * Add a column to the table on migrating, and remove it on rollback.
262
291
  *
@@ -1126,9 +1155,7 @@ declare const changeCache: Record<string, ChangeCallback<RakeDbColumnTypes>[] |
1126
1155
  /**
1127
1156
  * Type of {@link rakeDb} function
1128
1157
  */
1129
- type RakeDbFn = (<SchemaConfig extends ColumnSchemaConfig, CT extends RakeDbColumnTypes | undefined = undefined>(options: MaybeArray<AdapterOptions>, partialConfig?: InputRakeDbConfig<SchemaConfig, CT>, args?: string[]) => RakeDbChangeFn<CT extends undefined ? DefaultColumnTypes<DefaultSchemaConfig> : CT> & {
1130
- promise: Promise<void>;
1131
- }) & {
1158
+ type RakeDbFn = (<SchemaConfig extends ColumnSchemaConfig, CT extends RakeDbColumnTypes | undefined = undefined>(options: MaybeArray<AdapterOptions>, partialConfig?: InputRakeDbConfig<SchemaConfig, CT>, args?: string[]) => RakeDbFnReturns<CT>) & {
1132
1159
  /**
1133
1160
  * Unlike the original `rakeDb` that executes immediately,
1134
1161
  * `rakeDb.lazy` returns the `run` function to be later called programmatically.
@@ -1139,6 +1166,9 @@ type RakeDbFn = (<SchemaConfig extends ColumnSchemaConfig, CT extends RakeDbColu
1139
1166
  */
1140
1167
  lazy: RakeDbLazyFn;
1141
1168
  };
1169
+ type RakeDbFnReturns<CT extends RakeDbColumnTypes | undefined> = RakeDbChangeFn<CT extends undefined ? DefaultColumnTypes<DefaultSchemaConfig> : CT> & {
1170
+ promise: Promise<void>;
1171
+ };
1142
1172
  /**
1143
1173
  * Type of {@link rakeDb.lazy} function
1144
1174
  */
@@ -1161,4 +1191,4 @@ type RakeDbChangeFn<CT extends RakeDbColumnTypes> = (fn: ChangeCallback<CT>) =>
1161
1191
  */
1162
1192
  declare const rakeDb: RakeDbFn;
1163
1193
 
1164
- export { AnyRakeDbConfig, AppCodeUpdater, AppCodeUpdaterParams, ChangeTableCallback, ChangeTableOptions, ColumnComment, ColumnsShapeCallback, ConstraintArg, DbMigration, DropMode, InputRakeDbConfig, Migration, MigrationColumnTypes, ModuleExportsRecord, NoMigrationsTableError, RAKE_DB_LOCK_KEY, RakeDbAppliedVersions, RakeDbAst, RakeDbBaseTable, RakeDbColumnTypes, RakeDbConfig, RakeDbMigrationId, SilentQueries, TableOptions, changeCache, createDb, createMigrationInterface, deleteMigratedVersion, dropDb, generate, generateTimeStamp, getDatabaseAndUserFromOptions, getMigratedVersionsMap, makeFileVersion, migrate, migrateOrRollback, migrationConfigDefaults, processRakeDbConfig, rakeDb, redo, resetDb, rollback, saveMigratedVersion, writeMigrationFile };
1194
+ export { AnyRakeDbConfig, AppCodeUpdater, AppCodeUpdaterParams, ChangeTableCallback, ChangeTableOptions, ColumnComment, ColumnsShapeCallback, ConstraintArg, DbMigration, DropMode, InputRakeDbConfig, Migration, MigrationAdapter, MigrationColumnTypes, ModuleExportsRecord, NoMigrationsTableError, RAKE_DB_LOCK_KEY, RakeDbAppliedVersions, RakeDbAst, RakeDbBaseTable, RakeDbChangeFn, RakeDbColumnTypes, RakeDbConfig, RakeDbFn, RakeDbFnReturns, RakeDbLazyFn, RakeDbMigrationId, SilentQueries, TableOptions, changeCache, createDb, createMigrationInterface, deleteMigratedVersion, dropDb, generate, generateTimeStamp, getDatabaseAndUserFromOptions, getMigratedVersionsMap, makeFileVersion, migrate, migrateOrRollback, migrationConfigDefaults, processRakeDbConfig, rakeDb, redo, resetDb, rollback, saveMigratedVersion, writeMigrationFile };
package/dist/index.js CHANGED
@@ -41,16 +41,14 @@ const joinColumns = (columns) => {
41
41
  const quoteWithSchema = ({
42
42
  schema,
43
43
  name
44
- }) => {
45
- return schema ? `"${schema}"."${name}"` : `"${name}"`;
46
- };
44
+ }) => quoteTable(schema, name);
45
+ const quoteTable = (schema, table) => schema ? `"${schema}"."${table}"` : `"${table}"`;
47
46
  const getSchemaAndTableFromName = (name) => {
48
47
  const index = name.indexOf(".");
49
48
  return index !== -1 ? [name.slice(0, index), name.slice(index + 1)] : [void 0, name];
50
49
  };
51
50
  const quoteNameFromString = (string) => {
52
- const [schema, name] = getSchemaAndTableFromName(string);
53
- return quoteWithSchema({ schema, name });
51
+ return quoteTable(...getSchemaAndTableFromName(string));
54
52
  };
55
53
  const quoteSchemaTable = ({
56
54
  schema,
@@ -61,10 +59,7 @@ const quoteSchemaTable = ({
61
59
  const makePopulateEnumQuery = (item) => {
62
60
  const [schema, name] = getSchemaAndTableFromName(item.enumName);
63
61
  return {
64
- text: `SELECT unnest(enum_range(NULL::${quoteWithSchema({
65
- schema,
66
- name
67
- })}))::text`,
62
+ text: `SELECT unnest(enum_range(NULL::${quoteTable(schema, name)}))::text`,
68
63
  then(result) {
69
64
  item.options.push(...result.rows.map(([value]) => value));
70
65
  }
@@ -191,7 +186,7 @@ const sequenceOptionsToSql = (item) => {
191
186
  line.push(`CYCLE`);
192
187
  if (item.ownedBy) {
193
188
  const [schema, table] = getSchemaAndTableFromName(item.ownedBy);
194
- line.push(`OWNED BY ${quoteWithSchema({ schema, name: table })}`);
189
+ line.push(`OWNED BY ${quoteTable(schema, table)}`);
195
190
  }
196
191
  return line.join(" ");
197
192
  };
@@ -251,7 +246,7 @@ const foreignKeyToSql = (item, snakeCase) => {
251
246
  const referencesToSql = (references, snakeCase) => {
252
247
  const [schema, table] = getForeignKeyTable(references.fnOrTable);
253
248
  const sql = [
254
- `REFERENCES ${quoteWithSchema({ schema, name: table })}(${joinColumns(
249
+ `REFERENCES ${quoteTable(schema, table)}(${joinColumns(
255
250
  snakeCase ? references.foreignColumns.map(orchidCore.toSnakeCase) : references.foreignColumns
256
251
  )})`
257
252
  ];
@@ -289,7 +284,7 @@ const indexesToQuery = (up, { schema, name }, indexes, language) => {
289
284
  if (options.unique) {
290
285
  sql.push("UNIQUE");
291
286
  }
292
- sql.push(`INDEX "${indexName}" ON ${quoteWithSchema({ schema, name })}`);
287
+ sql.push(`INDEX "${indexName}" ON ${quoteTable(schema, name)}`);
293
288
  const using = options.using || options.tsVector && "GIN";
294
289
  if (using) {
295
290
  sql.push(`USING ${using}`);
@@ -1152,7 +1147,13 @@ var __spreadValues$7 = (a, b) => {
1152
1147
  };
1153
1148
  var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1154
1149
  const createMigrationInterface = (tx, up, config, asts) => {
1155
- const adapter = new pqb.TransactionAdapter(tx, tx.client, tx.types);
1150
+ var _a;
1151
+ const adapter = new pqb.TransactionAdapter(
1152
+ tx,
1153
+ tx.client,
1154
+ tx.types
1155
+ );
1156
+ adapter.schema = (_a = adapter.adapter.schema) != null ? _a : "public";
1156
1157
  const { query, arrays } = adapter;
1157
1158
  const log = pqb.logParamToLogObject(config.logger || console, config.log);
1158
1159
  adapter.query = (q, types) => {
@@ -1204,10 +1205,21 @@ class Migration {
1204
1205
  * });
1205
1206
  * ```
1206
1207
  *
1208
+ * Prefix table name with a schema to set a different schema:
1209
+ *
1210
+ * ```ts
1211
+ * import { change } from '../dbScript';
1212
+ *
1213
+ * change(async (db) => {
1214
+ * await db.renameTable('fromSchema.oldTable', 'toSchema.newTable');
1215
+ * });
1216
+ * ```
1217
+ *
1207
1218
  * @param from - rename the table from
1208
1219
  * @param to - rename the table to
1209
1220
  */
1210
1221
  async renameTable(from, to) {
1222
+ var _a;
1211
1223
  const [fromSchema, f] = getSchemaAndTableFromName(this.up ? from : to);
1212
1224
  const [toSchema, t] = getSchemaAndTableFromName(this.up ? to : from);
1213
1225
  const ast = {
@@ -1217,17 +1229,36 @@ class Migration {
1217
1229
  toSchema,
1218
1230
  to: t
1219
1231
  };
1220
- await this.adapter.query(
1221
- `ALTER TABLE ${quoteWithSchema({
1222
- schema: ast.fromSchema,
1223
- name: ast.from
1224
- })} RENAME TO ${quoteWithSchema({
1225
- schema: ast.toSchema,
1226
- name: ast.to
1227
- })}`
1228
- );
1232
+ if (ast.from !== ast.to) {
1233
+ await this.adapter.query(
1234
+ `ALTER TABLE ${quoteTable(ast.fromSchema, ast.from)} RENAME TO "${ast.to}"`
1235
+ );
1236
+ }
1237
+ if (ast.fromSchema !== ast.toSchema) {
1238
+ await this.adapter.query(
1239
+ `ALTER TABLE ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${(_a = ast.toSchema) != null ? _a : this.adapter.schema}"`
1240
+ );
1241
+ }
1229
1242
  this.migratedAsts.push(ast);
1230
1243
  }
1244
+ /**
1245
+ * Set a different schema to the table:
1246
+ *
1247
+ * ```ts
1248
+ * import { change } from '../dbScript';
1249
+ *
1250
+ * change(async (db) => {
1251
+ * await db.changeTableSchema('tableName', 'fromSchema', 'toSchema');
1252
+ * });
1253
+ * ```
1254
+ *
1255
+ * @param table - table name
1256
+ * @param from - current table schema
1257
+ * @param to - desired table schema
1258
+ */
1259
+ changeTableSchema(table, from, to) {
1260
+ return this.renameTable(`${from}.${table}`, `${to}.${table}`);
1261
+ }
1231
1262
  /**
1232
1263
  * Add a column to the table on migrating, and remove it on rollback.
1233
1264
  *
@@ -2077,9 +2108,7 @@ const changeIds = async (options, config, [arg]) => {
2077
2108
  };
2078
2109
  const renameMigrationVersionsInDb = async (config, adapter, values) => {
2079
2110
  await adapter.arrays({
2080
- text: `UPDATE ${quoteWithSchema({
2081
- name: config.migrationsTable
2082
- })} AS t SET version = v.version FROM (VALUES ${values.map(
2111
+ text: `UPDATE "${config.migrationsTable}" AS t SET version = v.version FROM (VALUES ${values.map(
2083
2112
  ([oldVersion, , newVersion], i) => `('${oldVersion}', $${i + 1}, '${newVersion}')`
2084
2113
  ).join(
2085
2114
  ", "
@@ -2232,17 +2261,13 @@ function getDigitsPrefix(name) {
2232
2261
 
2233
2262
  const saveMigratedVersion = async (db, version, name, config) => {
2234
2263
  await db.silentArrays({
2235
- text: `INSERT INTO ${quoteWithSchema({
2236
- name: config.migrationsTable
2237
- })}(version, name) VALUES ($1, $2)`,
2264
+ text: `INSERT INTO "${config.migrationsTable}"(version, name) VALUES ($1, $2)`,
2238
2265
  values: [version, name]
2239
2266
  });
2240
2267
  };
2241
2268
  const deleteMigratedVersion = async (db, version, name, config) => {
2242
2269
  const res = await db.silentArrays({
2243
- text: `DELETE FROM ${quoteWithSchema({
2244
- name: config.migrationsTable
2245
- })} WHERE version = $1 AND name = $2`,
2270
+ text: `DELETE FROM "${config.migrationsTable}" WHERE version = $1 AND name = $2`,
2246
2271
  values: [version, name]
2247
2272
  });
2248
2273
  if (res.rowCount === 0) {
@@ -2253,9 +2278,7 @@ class NoMigrationsTableError extends Error {
2253
2278
  }
2254
2279
  const getMigratedVersionsMap = async (ctx, adapter, config, renameTo) => {
2255
2280
  try {
2256
- const table = quoteWithSchema({
2257
- name: config.migrationsTable
2258
- });
2281
+ const table = `"${config.migrationsTable}"`;
2259
2282
  const result = await adapter.arrays(
2260
2283
  `SELECT * FROM ${table} ORDER BY version`
2261
2284
  );
@@ -2359,9 +2382,7 @@ const createMigrationsTable = async (db, config) => {
2359
2382
  }
2360
2383
  try {
2361
2384
  await db.query(
2362
- `CREATE TABLE ${quoteWithSchema({
2363
- name: config.migrationsTable
2364
- })} ( version TEXT NOT NULL, name TEXT NOT NULL )`
2385
+ `CREATE TABLE "${config.migrationsTable}" ( version TEXT NOT NULL, name TEXT NOT NULL )`
2365
2386
  );
2366
2387
  (_b = config.logger) == null ? void 0 : _b.log("Created versions table");
2367
2388
  } catch (err) {