rake-db 1.2.13 → 1.3.1

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/README.md CHANGED
@@ -41,6 +41,18 @@ Has an option to generate names of columns, indices and foreign keys in camelCas
41
41
 
42
42
  ## Get started
43
43
 
44
+ Install:
45
+
46
+ ```sh
47
+ npm i rake-db
48
+ ```
49
+
50
+ `rake-db` has peer dependencies on `ts-node` and `typescript`, if you don't have them already in your project need to install:
51
+
52
+ ```sh
53
+ npm i ts-node typescript
54
+ ```
55
+
44
56
  Add a script into `package.json`:
45
57
  ```json
46
58
  {
@@ -1,2 +1,4 @@
1
+ import Migration from './migration';
2
+ export declare const run: (db: Migration, fn: (t: Migration, up: boolean) => void | Promise<void>, version: string) => Promise<unknown[]>;
1
3
  export declare const migrate: () => Promise<void>;
2
4
  export declare const rollback: () => Promise<void>;
@@ -22,7 +22,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.rollback = exports.migrate = void 0;
25
+ exports.rollback = exports.migrate = exports.run = void 0;
26
26
  const fs = __importStar(require("fs"));
27
27
  const path = __importStar(require("path"));
28
28
  const utils_1 = require("./utils");
@@ -73,16 +73,37 @@ const getFiles = (migrationsPath, rollback) => new Promise((resolve, reject) =>
73
73
  resolve(files);
74
74
  });
75
75
  });
76
- const run = (db, fn, version) => db.wrapperTransaction(db, async (t) => {
77
- fn(t, !db.reverse);
76
+ const run = async (db, fn, version) => await db.wrapperTransaction(db, async (t) => {
77
+ if (fn.toString().startsWith('async')) {
78
+ await fn(t, !db.reverse);
79
+ }
80
+ else {
81
+ if (!db.reverse) {
82
+ fn(t, true);
83
+ }
84
+ else {
85
+ const originalExec = t.exec;
86
+ const argsList = []; // eslint-disable-line
87
+ t.exec = (...args) => {
88
+ argsList.push(args);
89
+ return Promise.resolve(undefined);
90
+ };
91
+ await fn(t, false);
92
+ t.exec = originalExec;
93
+ for (const args of argsList.reverse()) {
94
+ await t.exec(...args);
95
+ }
96
+ }
97
+ }
78
98
  await t.sync();
79
99
  if (t.failed)
80
100
  return;
81
101
  const sql = db.reverse
82
102
  ? `DELETE FROM "schemaMigrations" WHERE "version" = '${version}'`
83
103
  : `INSERT INTO "schemaMigrations" VALUES ('${version}')`;
84
- t.exec(sql).catch(utils_1.noop);
104
+ await t.exec(sql).catch(utils_1.noop);
85
105
  });
106
+ exports.run = run;
86
107
  const migrateFile = async (db, migrationsPath, version, file) => {
87
108
  const filePath = path.resolve(migrationsPath, file);
88
109
  const migration = require(filePath);
@@ -92,7 +113,7 @@ const migrateFile = async (db, migrationsPath, version, file) => {
92
113
  throw new Error(`Migration ${file} does not contain down or change exports`);
93
114
  for (const key in migration)
94
115
  if (key === (db.reverse ? 'down' : 'up') || key === 'change')
95
- await run(db, migration[key], version);
116
+ await exports.run(db, migration[key], version);
96
117
  console.info(`${filePath} ${db.reverse ? 'rolled back' : 'migrated'}`);
97
118
  };
98
119
  const migrateDb = async (db, migrationsPath, files) => {
@@ -13,6 +13,8 @@ export default class Migration extends Adapter {
13
13
  addColumn(table: string, name: string, type: string, options?: ColumnOptions): void;
14
14
  addForeignKey(table: string, params: ForeignKeyOptions): void;
15
15
  dropForeignKey(table: string, params: ForeignKeyOptions): void;
16
+ addPrimaryKey(table: string, columns: string[], name?: string): void;
17
+ dropPrimaryKey(table: string, columns: string[], name?: string): void;
16
18
  addIndex(table: string, name: string, options?: IndexOptions): void;
17
19
  dropIndex(table: string, name: string, options?: IndexOptions): void;
18
20
  addTimestamps(table: string, options?: ColumnOptions): void;
@@ -83,6 +83,12 @@ class Migration extends pg_adapter_1.Adapter {
83
83
  dropForeignKey(table, params) {
84
84
  this.changeTable(table, (t) => t.dropForeignKey(params));
85
85
  }
86
+ addPrimaryKey(table, columns, name) {
87
+ this.changeTable(table, (t) => t.primaryKey(columns, name));
88
+ }
89
+ dropPrimaryKey(table, columns, name) {
90
+ this.changeTable(table, (t) => t.dropPrimaryKey(columns, name));
91
+ }
86
92
  addIndex(table, name, options) {
87
93
  this.changeTable(table, (t) => t.index(name, options));
88
94
  }
@@ -1,6 +1,7 @@
1
1
  import Table from './table';
2
2
  import { Column } from './column';
3
3
  import { Migration, ColumnOptions, IndexOptions, ForeignKeyFunction, ColumnFunction } from '../../types';
4
+ import { PrimaryKey } from './primaryKey';
4
5
  export declare type ChangeTableCallback = (t: ChangeTable) => void;
5
6
  export declare class ChangeTable extends Table {
6
7
  constraint: (name: string, sql?: string | undefined) => void;
@@ -16,5 +17,7 @@ export declare class ChangeTable extends Table {
16
17
  dropIndex: (name: string | string[], options?: true | IndexOptions) => number;
17
18
  foreignKey: ForeignKeyFunction;
18
19
  dropForeignKey: ForeignKeyFunction;
20
+ primaryKey: (columns: string[], name?: string | undefined) => PrimaryKey;
21
+ dropPrimaryKey: (columns: string[], name?: string | undefined) => PrimaryKey;
19
22
  __commit: (db: Migration, fn?: ChangeTableCallback | undefined) => void;
20
23
  }
@@ -9,6 +9,7 @@ const column_1 = require("./column");
9
9
  const index_1 = require("./index");
10
10
  const utils_1 = require("../utils");
11
11
  const foreignKey_1 = require("./foreignKey");
12
+ const primaryKey_1 = require("./primaryKey");
12
13
  const addConstraint = (name, sql) => `ADD CONSTRAINT ${sql ? `"${name}" ${sql}` : name}`;
13
14
  const removeConstraint = (name) => `DROP CONSTRAINT "${name}"`;
14
15
  class ChangeTable extends table_1.default {
@@ -69,6 +70,16 @@ class ChangeTable extends table_1.default {
69
70
  this.lines.push(fkey);
70
71
  return fkey;
71
72
  };
73
+ this.primaryKey = (columns, name) => {
74
+ const pkey = new primaryKey_1.PrimaryKey('add', columns, name);
75
+ this.lines.push(pkey);
76
+ return pkey;
77
+ };
78
+ this.dropPrimaryKey = (columns, name) => {
79
+ const pkey = new primaryKey_1.PrimaryKey('drop', columns, name);
80
+ this.lines.push(pkey);
81
+ return pkey;
82
+ };
72
83
  this.__commit = (db, fn) => {
73
84
  this.reverse = db.reverse;
74
85
  if (fn)
@@ -11,6 +11,7 @@ export declare class Column {
11
11
  type(type: string): this;
12
12
  default(value: any): this;
13
13
  required(): this;
14
+ optional(): this;
14
15
  index(options?: boolean | IndexOptions): this;
15
16
  comment(comment: string): this;
16
17
  mode(mode: string): this;
@@ -9,85 +9,101 @@ class Column {
9
9
  this._type = _type;
10
10
  }
11
11
  primaryKey() {
12
- this.options.primaryKey = true;
12
+ this.options = { ...this.options, primaryKey: true };
13
13
  return this;
14
14
  }
15
15
  type(type) {
16
- this.options.type = type;
16
+ this.options = { ...this.options, type };
17
17
  return this;
18
18
  }
19
19
  default(value) {
20
- this.options.default = value;
20
+ this.options = { ...this.options, default: value };
21
21
  return this;
22
22
  }
23
23
  required() {
24
- this.options.null = false;
24
+ this.options = { ...this.options, null: false };
25
+ return this;
26
+ }
27
+ optional() {
28
+ this.options = { ...this.options, null: true };
25
29
  return this;
26
30
  }
27
31
  index(options) {
28
- this.options.index = options;
32
+ this.options = { ...this.options, index: options !== null && options !== void 0 ? options : true };
29
33
  return this;
30
34
  }
31
35
  comment(comment) {
32
- this.options.comment = comment;
36
+ this.options = { ...this.options, comment };
33
37
  return this;
34
38
  }
35
39
  mode(mode) {
36
- this.options.mode = mode;
40
+ this.options = { ...this.options, mode };
37
41
  return this;
38
42
  }
39
43
  unique() {
40
- if (typeof this.options.index !== 'object') {
41
- this.options.index = { unique: true };
44
+ if (typeof this.options.index === 'object') {
45
+ this.options = {
46
+ ...this.options,
47
+ index: { ...this.options.index, unique: true },
48
+ };
42
49
  }
43
50
  else {
44
- this.options.index.unique = true;
51
+ this.options = { ...this.options, index: { unique: true } };
45
52
  }
46
53
  return this;
47
54
  }
48
55
  length(length) {
49
- this.options.length = length;
56
+ this.options = { ...this.options, length };
50
57
  return this;
51
58
  }
52
59
  precision(precision) {
53
- this.options.precision = precision;
60
+ this.options = { ...this.options, precision };
54
61
  return this;
55
62
  }
56
63
  scale(scale) {
57
- this.options.scale = scale;
64
+ this.options = { ...this.options, scale };
58
65
  return this;
59
66
  }
60
67
  collate(collate) {
61
- this.options.collate = collate;
68
+ this.options = { ...this.options, collate };
62
69
  return this;
63
70
  }
64
71
  using(using) {
65
- this.options.using = using;
72
+ this.options = { ...this.options, using };
66
73
  return this;
67
74
  }
68
75
  references(table, column) {
69
- this.options.references = { table, column };
76
+ this.options = { ...this.options, references: { table, column } };
70
77
  return this;
71
78
  }
72
79
  column(column) {
73
80
  if (!this.options.references) {
74
81
  throw new Error('Please specify table for references');
75
82
  }
76
- this.options.references.column = column;
83
+ this.options = {
84
+ ...this.options,
85
+ references: { ...this.options.references, column },
86
+ };
77
87
  return this;
78
88
  }
79
89
  onUpdate(action) {
80
90
  if (!this.options.references) {
81
91
  throw new Error('Please specify table for references');
82
92
  }
83
- this.options.references.onUpdate = action;
93
+ this.options = {
94
+ ...this.options,
95
+ references: { ...this.options.references, onUpdate: action },
96
+ };
84
97
  return this;
85
98
  }
86
99
  onDelete(action) {
87
100
  if (!this.options.references) {
88
101
  throw new Error('Please specify table for references');
89
102
  }
90
- this.options.references.onDelete = action;
103
+ this.options = {
104
+ ...this.options,
105
+ references: { ...this.options.references, onDelete: action },
106
+ };
91
107
  return this;
92
108
  }
93
109
  toSql(table) {
@@ -1,8 +1,10 @@
1
1
  import Table from './table';
2
2
  import { ForeignKeyFunction, Migration, TableCallback, TableOptions } from '../../types';
3
+ import { PrimaryKey } from './primaryKey';
3
4
  export declare class CreateTable extends Table {
4
5
  constructor(tableName: string, reverse: boolean, options?: TableOptions);
5
6
  foreignKey: ForeignKeyFunction;
6
7
  constraint: (name: string, sql?: string | undefined) => void;
8
+ primaryKey: (columns: string[], name?: string | undefined) => PrimaryKey;
7
9
  __commit: (db: Migration, fn?: TableCallback | undefined) => void;
8
10
  }
@@ -8,6 +8,7 @@ const table_1 = __importDefault(require("./table"));
8
8
  const index_1 = require("./index");
9
9
  const utils_1 = require("../utils");
10
10
  const foreignKey_1 = require("./foreignKey");
11
+ const primaryKey_1 = require("./primaryKey");
11
12
  class CreateTable extends table_1.default {
12
13
  constructor(tableName, reverse, options = {}) {
13
14
  super(tableName, reverse, options);
@@ -17,6 +18,11 @@ class CreateTable extends table_1.default {
17
18
  return fkey;
18
19
  };
19
20
  this.constraint = (name, sql) => this.execute(`CONSTRAINT ${sql ? `"${name}" ${sql}` : name}`);
21
+ this.primaryKey = (columns, name) => {
22
+ const pkey = new primaryKey_1.PrimaryKey('create', columns, name);
23
+ this.lines.push(pkey);
24
+ return pkey;
25
+ };
20
26
  this.__commit = (db, fn) => {
21
27
  if (fn)
22
28
  fn(this);
@@ -0,0 +1,9 @@
1
+ import { CreateTable } from './createTable';
2
+ import { ChangeTable } from './changeTable';
3
+ export declare class PrimaryKey {
4
+ action: 'create' | 'add' | 'drop';
5
+ columns: string[];
6
+ name?: string | undefined;
7
+ constructor(action: 'create' | 'add' | 'drop', columns: string[], name?: string | undefined);
8
+ toSql(table: CreateTable | ChangeTable): string;
9
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PrimaryKey = void 0;
4
+ class PrimaryKey {
5
+ constructor(action, columns, name) {
6
+ this.action = action;
7
+ this.columns = columns;
8
+ this.name = name;
9
+ }
10
+ toSql(table) {
11
+ const { action, name } = this;
12
+ const drop = (!table.reverse && action === 'drop') ||
13
+ (table.reverse && action === 'add');
14
+ if (drop) {
15
+ return `DROP CONSTRAINT "${name || `${table.tableName}_pkey`}"`;
16
+ }
17
+ const columns = `(${this.columns
18
+ .map((column) => `"${column}"`)
19
+ .join(', ')})`;
20
+ const constraint = name ? `CONSTRAINT "${name}" ` : '';
21
+ return `${action === 'create' ? '' : 'ADD '}${constraint}PRIMARY KEY ${columns}`;
22
+ }
23
+ }
24
+ exports.PrimaryKey = PrimaryKey;
@@ -1,6 +1,7 @@
1
1
  import { Column } from './column';
2
2
  import { Migration, ColumnFunction, ColumnOptions, IndexOptions, TableOptions, ColumnTypes } from '../../types';
3
3
  import { ForeignKey } from './foreignKey';
4
+ import { PrimaryKey } from './primaryKey';
4
5
  declare type ColumnMethods = {
5
6
  [key in keyof typeof ColumnTypes]: (name: string, options?: ColumnOptions) => Column;
6
7
  };
@@ -8,7 +9,7 @@ export default class Table implements ColumnMethods {
8
9
  tableName: string;
9
10
  reverse: boolean;
10
11
  options: TableOptions;
11
- lines: (string | Column | ForeignKey)[];
12
+ lines: (string | Column | ForeignKey | PrimaryKey)[];
12
13
  indices: [boolean, string | string[], undefined | true | IndexOptions][];
13
14
  comments: [string, string][];
14
15
  constraint: (name: string, sql?: string) => void;
@@ -29,6 +30,7 @@ export default class Table implements ColumnMethods {
29
30
  text(name: string, options?: ColumnOptions): Column;
30
31
  smallint(name: string, options?: ColumnOptions): Column;
31
32
  smallserial(name: string, options?: ColumnOptions): Column;
33
+ varchar(name: string, options?: ColumnOptions): Column;
32
34
  string(name: string, options?: ColumnOptions): Column;
33
35
  time(name: string, options?: ColumnOptions): Column;
34
36
  timestamp(name: string, options?: ColumnOptions): Column;
@@ -79,6 +79,9 @@ class Table {
79
79
  smallserial(name, options) {
80
80
  return this.column(name, 'smallserial', options);
81
81
  }
82
+ varchar(name, options) {
83
+ return this.column(name, 'varchar', options);
84
+ }
82
85
  string(name, options) {
83
86
  return this.column(name, 'text', options);
84
87
  }
package/dist/types.d.ts CHANGED
@@ -70,6 +70,7 @@ export declare const ColumnTypes: {
70
70
  readonly decimal: "decimal";
71
71
  readonly float: "float8";
72
72
  readonly integer: "integer";
73
+ readonly varchar: "varchar";
73
74
  readonly text: "text";
74
75
  readonly smallint: "smallint";
75
76
  readonly smallserial: "smallserial";
package/dist/types.js CHANGED
@@ -16,6 +16,7 @@ exports.ColumnTypes = {
16
16
  decimal: 'decimal',
17
17
  float: 'float8',
18
18
  integer: 'integer',
19
+ varchar: 'varchar',
19
20
  text: 'text',
20
21
  smallint: 'smallint',
21
22
  smallserial: 'smallserial',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rake-db",
3
- "version": "1.2.13",
3
+ "version": "1.3.1",
4
4
  "description": "Postgresql migrations like in Ruby on Rails",
5
5
  "bin": {
6
6
  "rake-db": "dist/rake-db.js"
@@ -42,9 +42,12 @@
42
42
  "typescript": "^4.0.3"
43
43
  },
44
44
  "dependencies": {
45
- "dotenv": "8.x",
45
+ "dotenv": "^16.0.1",
46
46
  "enquirer": "^2.3.6",
47
- "pg-adapter": "^1.2.2",
48
- "ts-node": "^9.1.1"
47
+ "pg-adapter": "^1.2.5"
48
+ },
49
+ "peerDependencies": {
50
+ "ts-node": "*",
51
+ "typescript": "*"
49
52
  }
50
53
  }
@@ -1,3 +0,0 @@
1
- import { ColumnChain, ReferencesChain } from 'types';
2
- export declare const columnChain: (sql: string[], addingColumn: boolean) => ColumnChain;
3
- export declare const referencesChain: (sql: string[], addingColumn: boolean) => ReferencesChain;
@@ -1,49 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.referencesChain = exports.columnChain = void 0;
4
- const columnChain = (sql, addingColumn) => {
5
- const chain = {
6
- required() {
7
- if (addingColumn)
8
- sql.push('NOT NULL');
9
- return chain;
10
- },
11
- default(value) {
12
- if (addingColumn)
13
- sql.push(`DEFAULT ${value}`);
14
- return chain;
15
- },
16
- references(table, column) {
17
- const refChain = exports.referencesChain(sql, addingColumn);
18
- if (addingColumn) {
19
- sql.push(`REFERENCES "${table}"`);
20
- if (column)
21
- return refChain.column(column);
22
- }
23
- return refChain;
24
- },
25
- };
26
- return chain;
27
- };
28
- exports.columnChain = columnChain;
29
- const referencesChain = (sql, addingColumn) => {
30
- const chain = {
31
- column(column) {
32
- if (addingColumn)
33
- sql.push(`("${column}")`);
34
- return chain;
35
- },
36
- onUpdate(action) {
37
- if (addingColumn)
38
- sql.push(`ON UPDATE ${action}`);
39
- return chain;
40
- },
41
- onDelete(action) {
42
- if (addingColumn)
43
- sql.push(`ON DELETE ${action}`);
44
- return chain;
45
- },
46
- };
47
- return chain;
48
- };
49
- exports.referencesChain = referencesChain;
@@ -1,3 +0,0 @@
1
- import { ColumnOptions } from '../../types';
2
- declare const _default: (type: string, options?: ColumnOptions) => string;
3
- export default _default;
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = (type, options = {}) => {
4
- const sql = [type];
5
- if (options.length)
6
- sql.push(`(${options.length})`);
7
- else if (options.precision !== undefined && options.scale === undefined)
8
- sql.push(`(${options.precision})`);
9
- else if (options.precision === undefined && options.scale !== undefined)
10
- sql.push(`(${options.scale})`);
11
- else if (options.precision !== undefined && options.scale !== undefined)
12
- sql.push(`(${options.precision}, ${options.scale})`);
13
- if (options.collate)
14
- sql.push('COLLATE', options.collate);
15
- if (options.using)
16
- sql.push('USING', options.using);
17
- return sql.join(' ');
18
- };
@@ -1,5 +0,0 @@
1
- import { DbConfig } from '../types';
2
- import Migration from './migration';
3
- export declare const createSchemaMigrations: (db: Migration) => Promise<unknown>;
4
- export declare const createForConfig: (config: DbConfig) => Promise<void>;
5
- export declare const create: () => Promise<void>;
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.create = exports.createForConfig = exports.createSchemaMigrations = void 0;
4
- const utils_1 = require("./utils");
5
- const schemaMigrationsSQL = 'CREATE TABLE schema_migrations ( version TEXT NOT NULL )';
6
- exports.createSchemaMigrations = (db) => db.exec(schemaMigrationsSQL);
7
- exports.createForConfig = async (config) => {
8
- const db = utils_1.adapter(config);
9
- await db.exec(schemaMigrationsSQL);
10
- db.close();
11
- };
12
- exports.create = async () => {
13
- let config;
14
- try {
15
- config = await utils_1.getConfig();
16
- }
17
- catch (err) {
18
- return;
19
- }
20
- for (const env in config) {
21
- const envConfig = config[env];
22
- exports.createForConfig(envConfig);
23
- }
24
- };