gina-sequelize 0.0.15 → 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"column-types.js","sourceRoot":"/","sources":["column-types.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAuNC,sBAAK;AACL,0CAAe;AACf,kDAAmB;AACnB,8CAAiB;AACjB,kCAAW;AACX,gDAAkB;AAClB,sDAAqB;AAzMzB,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/E,MAAM,aAAa,GAAG,CAAC,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAE1G,SAAS,KAAK,CAAC,KAAa;IACxB,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC;AACrE,CAAC;AAED,SAAS,IAAI,CAAC,GAAG,MAAiB;IAC9B,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,CAAC,CAAC;IAC9E,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AAC3D,CAAC;AAED,SAAS,gBAAgB,CAAC,OAAuC;IAC7D,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AAC1F,CAAC;AAED;;GAE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K,EAAE,CAAC;IACzE,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Conversions between Sequelize data types, MySQL column definitions and the code\n * written into generated migrations.\n */\n\n/** A column as it currently is in the database. */\ninterface DatabaseColumn {\n /** e.g. `varchar(100)`, `int unsigned`, `enum('deny_list','clone')` (enum values keep their case) */\n type: string;\n allowNull: boolean;\n /** raw default as stored by the database, `null` when there's none */\n defaultValue: string | null;\n autoIncrement: boolean;\n primaryKey: boolean;\n}\n\ninterface ModelDataType {\n key: string;\n options?: { [option: string]: unknown; };\n values?: string[];\n toSql(options?: { escape(value: unknown): string; }): string;\n}\n\nconst INTEGER_KEYS = ['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INTEGER', 'BIGINT'];\nconst NUMERIC_TYPES = ['tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'decimal', 'float', 'double'];\n\nfunction quote(value: string) {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, '\\\\\\'')}'`;\n}\n\nfunction args(...values: unknown[]) {\n const defined = values.filter(value => value !== undefined && value !== null);\n return defined.length ? `(${defined.join(', ')})` : '';\n}\n\nfunction numericModifiers(options: { [option: string]: unknown; }) {\n return `${options.unsigned ? '.UNSIGNED' : ''}${options.zerofill ? '.ZEROFILL' : ''}`;\n}\n\n/**\n * Code that recreates a model's data type, e.g. `DataTypes.ENUM('a', 'b')` or `DataTypes.STRING(100)`.\n */\nfunction modelTypeToCode(type: ModelDataType) {\n const options = type.options ?? {};\n\n switch (type.key) {\n case 'ENUM':\n return `DataTypes.ENUM(${(type.values ?? []).map(quote).join(', ')})`;\n case 'STRING':\n return `DataTypes.STRING${options.length === 255 ? '' : args(options.length)}${options.binary ? '.BINARY' : ''}`;\n case 'CHAR':\n return `DataTypes.CHAR${args(options.length)}${options.binary ? '.BINARY' : ''}`;\n case 'TEXT':\n return `DataTypes.TEXT${typeof options.length === 'string' ? `(${quote(options.length)})` : ''}`;\n case 'DECIMAL':\n return `DataTypes.DECIMAL${args(options.precision, options.scale)}${numericModifiers(options)}`;\n case 'FLOAT':\n case 'REAL':\n case 'DOUBLE':\n case 'DOUBLE PRECISION':\n return `DataTypes.${type.key.split(' ')[0]}${args(options.length, options.decimals)}${numericModifiers(options)}`;\n case 'DATE':\n return `DataTypes.DATE${args(options.length)}`;\n }\n\n if (INTEGER_KEYS.includes(type.key)) {\n return `DataTypes.${type.key}${args(options.length)}${numericModifiers(options)}`;\n }\n\n return `DataTypes.${type.key}`;\n}\n\n/**\n * Normalizes a column definition so the model's SQL and the database's can be compared:\n * `INTEGER(11) UNSIGNED` and `int unsigned` are the same thing. Quoted enum values are kept as they are.\n */\nfunction normalizeColumnType(sql: string) {\n return sql\n .trim()\n .split(/('(?:[^'\\\\]|\\\\.|'')*')/)\n .map((part, index) => {\n if (index % 2) {\n return part.replace(/\\\\'/g, '\\'\\'');\n }\n return part\n .toLowerCase()\n .replace(/\\s*([(),])\\s*/g, '$1')\n .replace(/\\s+/g, ' ')\n .replace(/\\binteger\\b/g, 'int')\n .replace(/\\bdouble precision\\b/g, 'double')\n .replace(/\\b(smallint|mediumint|int|bigint)\\(\\d+\\)/g, '$1')\n .replace(/\\btinyint\\((?!1\\))\\d+\\)/g, 'tinyint')\n .replace(/^decimal$/, 'decimal(10,0)')\n .replace(/ binary$/, '');\n })\n .join('');\n}\n\n/**\n * The default value as the database stores it, `null` for no default and\n * `undefined` when it can't be compared (e.g. `DataTypes.NOW` or `sequelize.fn`, which never reach the database).\n */\nfunction modelDefaultToSql(defaultValue: unknown): string | null | undefined {\n if (defaultValue === undefined || defaultValue === null) {\n return null;\n }\n if (typeof defaultValue === 'boolean') {\n return defaultValue ? '1' : '0';\n }\n if (typeof defaultValue === 'number' || typeof defaultValue === 'string') {\n return String(defaultValue);\n }\n if (typeof defaultValue === 'object' && 'val' in defaultValue) {\n return String((defaultValue as { val: unknown; }).val);\n }\n return undefined;\n}\n\nfunction sameDefault(modelDefault: string | null, databaseDefault: string | null) {\n if (modelDefault === null || databaseDefault === null) {\n return modelDefault === databaseDefault;\n }\n if (modelDefault.trim() !== '' && !isNaN(Number(modelDefault)) && !isNaN(Number(databaseDefault))) {\n return Number(modelDefault) === Number(databaseDefault);\n }\n return modelDefault.toLowerCase() === databaseDefault.toLowerCase() || modelDefault === databaseDefault;\n}\n\nfunction parseEnumValues(columnType: string) {\n return [...columnType.matchAll(/'((?:[^'\\\\]|\\\\.|'')*)'/g)].map(match => match[1].replace(/''/g, '\\'').replace(/\\\\(.)/g, '$1'));\n}\n\n/**\n * Code that recreates a column as it is in the database, e.g. `enum('a','b')` becomes `DataTypes.ENUM('a', 'b')`.\n * Types without a DataTypes equivalent are written as raw SQL strings, which Sequelize also accepts.\n */\nfunction databaseTypeToCode(columnType: string) {\n const match = /^(\\w+)(?:\\((.*)\\))?\\s*(.*)$/s.exec(columnType.trim());\n if (!match) {\n return quote(columnType);\n }\n\n const base = match[1].toLowerCase();\n const params = match[2]?.split(',').map(param => param.trim());\n const rest = match[3].toLowerCase();\n const modifiers = `${rest.includes('unsigned') ? '.UNSIGNED' : ''}${rest.includes('zerofill') ? '.ZEROFILL' : ''}`;\n\n switch (base) {\n case 'enum':\n return `DataTypes.ENUM(${parseEnumValues(columnType).map(quote).join(', ')})`;\n case 'varchar':\n return `DataTypes.STRING${params && params[0] !== '255' ? `(${params[0]})` : ''}`;\n case 'char':\n return `DataTypes.CHAR${params ? `(${params[0]})` : ''}`;\n case 'tinyint':\n return params?.[0] === '1' && !modifiers ? 'DataTypes.BOOLEAN' : `DataTypes.TINYINT${modifiers}`;\n case 'smallint':\n return `DataTypes.SMALLINT${modifiers}`;\n case 'mediumint':\n return `DataTypes.MEDIUMINT${modifiers}`;\n case 'int':\n case 'integer':\n return `DataTypes.INTEGER${modifiers}`;\n case 'bigint':\n return `DataTypes.BIGINT${modifiers}`;\n case 'decimal':\n return `DataTypes.DECIMAL${params ? `(${params.join(', ')})` : ''}${modifiers}`;\n case 'float':\n return `DataTypes.FLOAT${params ? `(${params.join(', ')})` : ''}${modifiers}`;\n case 'double':\n return `DataTypes.DOUBLE${params ? `(${params.join(', ')})` : ''}${modifiers}`;\n case 'datetime':\n return `DataTypes.DATE${params ? `(${params[0]})` : ''}`;\n case 'date':\n return 'DataTypes.DATEONLY';\n case 'time':\n return 'DataTypes.TIME';\n case 'text':\n return 'DataTypes.TEXT';\n case 'tinytext':\n case 'mediumtext':\n case 'longtext':\n return `DataTypes.TEXT('${base.replace('text', '')}')`;\n case 'json':\n return 'DataTypes.JSON';\n case 'blob':\n return 'DataTypes.BLOB';\n case 'tinyblob':\n case 'mediumblob':\n case 'longblob':\n return `DataTypes.BLOB('${base.replace('blob', '')}')`;\n }\n\n return quote(columnType);\n}\n\n/**\n * Code for a database default value, typed after the column (numbers, booleans, literals or strings).\n * Returns `needsSequelize` when it uses `Sequelize.literal`.\n */\nfunction databaseDefaultToCode(defaultValue: string, columnType: string) {\n const base = columnType.trim().toLowerCase();\n\n if (/^current_timestamp/.test(defaultValue.toLowerCase())) {\n return { code: `Sequelize.literal(${quote(defaultValue)})`, needsSequelize: true };\n }\n if (base.startsWith('tinyint(1)')) {\n return { code: defaultValue === '0' ? 'false' : 'true', needsSequelize: false };\n }\n if (NUMERIC_TYPES.some(type => base.startsWith(type)) && !isNaN(Number(defaultValue))) {\n return { code: String(Number(defaultValue)), needsSequelize: false };\n }\n return { code: quote(defaultValue), needsSequelize: false };\n}\n\nexport {\n DatabaseColumn,\n ModelDataType,\n quote,\n modelTypeToCode,\n normalizeColumnType,\n modelDefaultToSql,\n sameDefault,\n databaseTypeToCode,\n databaseDefaultToCode,\n};\n"]}
package/dist/gina.d.ts CHANGED
@@ -1,14 +1,18 @@
1
1
  import { Sequelize } from 'sequelize';
2
- import { MigrationFile } from './typings/migration';
3
- interface MigrationFiles {
4
- [version: string]: {
5
- migration: MigrationFile;
6
- };
7
- }
8
- declare function runMigrations(sequelize: Sequelize, migrationFiles: MigrationFiles): Promise<void>;
9
- declare function createMigration(sequelize: Sequelize, migrationName: string): Promise<void>;
2
+ import { runMigrations, revertMigrations, repairMigration, dryRunMigrations, DowngradeTarget, MigrationFiles } from './runner';
3
+ /**
4
+ * Writes a migration with the differences between the models and the database.
5
+ * Returns its file name, or `undefined` when there are no differences.
6
+ *
7
+ * @param previous the last migration, which the new one runs after
8
+ */
9
+ declare function createMigration(sequelize: Sequelize, migrationName: string, migrationsDir?: string, previous?: string): Promise<string | undefined>;
10
10
  declare const gina: {
11
11
  runMigrations: typeof runMigrations;
12
+ revertMigrations: typeof revertMigrations;
13
+ repairMigration: typeof repairMigration;
14
+ dryRunMigrations: typeof dryRunMigrations;
12
15
  createMigration: typeof createMigration;
13
16
  };
17
+ export { runMigrations, revertMigrations, repairMigration, dryRunMigrations, createMigration, DowngradeTarget, MigrationFiles };
14
18
  export default gina;
package/dist/gina.js CHANGED
@@ -3,37 +3,49 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.dryRunMigrations = exports.repairMigration = exports.revertMigrations = exports.runMigrations = void 0;
7
+ exports.createMigration = createMigration;
6
8
  const sequelize_1 = require("sequelize");
9
+ const runner_1 = require("./runner");
10
+ Object.defineProperty(exports, "runMigrations", { enumerable: true, get: function () { return runner_1.runMigrations; } });
11
+ Object.defineProperty(exports, "revertMigrations", { enumerable: true, get: function () { return runner_1.revertMigrations; } });
12
+ Object.defineProperty(exports, "repairMigration", { enumerable: true, get: function () { return runner_1.repairMigration; } });
13
+ Object.defineProperty(exports, "dryRunMigrations", { enumerable: true, get: function () { return runner_1.dryRunMigrations; } });
7
14
  const promises_1 = __importDefault(require("fs/promises"));
15
+ const path_1 = __importDefault(require("path"));
8
16
  const moment_1 = __importDefault(require("moment"));
9
- async function runMigrations(sequelize, migrationFiles) {
10
- const tables = await sequelize.getQueryInterface().showAllTables();
11
- let version = '';
12
- if (tables.includes('gina_version')) {
13
- const versions = await sequelize.query('SELECT version FROM gina_version;', {
14
- type: sequelize_1.QueryTypes.SELECT,
15
- });
16
- if (versions.length > 1) {
17
- throw new Error('There must be only one version on `gina_version` table.');
17
+ const column_types_1 = require("./column-types");
18
+ /**
19
+ * Index fields can be plain column names or objects like `{ name: 'time', order: 'DESC' }`.
20
+ */
21
+ function formatIndexFields(fields) {
22
+ const formatted = (fields ?? []).map((field) => {
23
+ if (typeof field === 'string') {
24
+ return `'${field}'`;
18
25
  }
19
- version = versions.length == 1 ? versions[0].version : '';
20
- }
21
- console.info('current version:', version);
22
- for (const migrationFile of Object.keys(migrationFiles)) {
23
- if (migrationFile > version) {
24
- console.info('applying migration:', migrationFile);
25
- await migrationFiles[migrationFile].migration.up(sequelize.getQueryInterface());
26
- if (version) {
27
- version = migrationFile;
28
- await sequelize.query(`UPDATE gina_version SET version = '${version}', updatedAt = NOW();`);
29
- }
30
- else {
31
- version = migrationFile;
32
- await sequelize.query(`INSERT INTO gina_version (updatedAt, version) VALUES (NOW(),'${version}');`);
33
- }
34
- console.info('applied version:', migrationFile);
26
+ const { name, order, length, collate } = field;
27
+ const props = [`name: '${name}'`];
28
+ if (order) {
29
+ props.push(`order: '${order}'`);
35
30
  }
36
- }
31
+ if (length) {
32
+ props.push(`length: ${length}`);
33
+ }
34
+ if (collate) {
35
+ props.push(`collate: '${collate}'`);
36
+ }
37
+ return `{ ${props.join(', ')} }`;
38
+ });
39
+ return `[${formatted.join(', ')}]`;
40
+ }
41
+ function isVirtual(attribute) {
42
+ return attribute.type?.key === 'VIRTUAL';
43
+ }
44
+ /**
45
+ * Sequelize columns are nullable unless `allowNull: false`, and primary keys never are.
46
+ */
47
+ function isNullable(attribute) {
48
+ return attribute.allowNull !== false && !attribute.primaryKey;
37
49
  }
38
50
  function tabsToSpace(str) {
39
51
  return str.replaceAll('\t', ' ');
@@ -51,9 +63,11 @@ class Migration {
51
63
  this.downTables = '';
52
64
  this.upFields = '';
53
65
  this.downFields = '';
66
+ this.downDroppedFields = '';
54
67
  this.upIndexes = '';
55
68
  this.downIndexes = '';
56
69
  this.upForeignKey = '';
70
+ this.downForeignKey = '';
57
71
  /**
58
72
  *
59
73
  */
@@ -85,41 +99,26 @@ class Migration {
85
99
  return model.primaryKey ?? 'true' ? 'true' : 'false';
86
100
  }
87
101
  getType(model) {
88
- if (model.type instanceof sequelize_1.DataTypes.BIGINT) {
89
- return 'DataTypes.BIGINT';
90
- }
91
- if (model.type instanceof sequelize_1.DataTypes.INTEGER) {
92
- return 'DataTypes.INTEGER';
93
- }
94
- if (model.type instanceof sequelize_1.DataTypes.STRING) {
95
- return 'DataTypes.STRING';
96
- }
97
- if (model.type instanceof sequelize_1.DataTypes.DATE) {
98
- return 'DataTypes.DATE';
99
- }
100
- if (model.type instanceof sequelize_1.DataTypes.TEXT) {
101
- return 'DataTypes.TEXT';
102
- }
103
- if (model.type instanceof sequelize_1.DataTypes.BOOLEAN) {
104
- return 'DataTypes.BOOLEAN';
102
+ return (0, column_types_1.modelTypeToCode)(model.type);
103
+ }
104
+ useSequelize() {
105
+ if (!this.imports.includes('Sequelize')) {
106
+ this.imports.push('Sequelize');
105
107
  }
106
- return '';
107
108
  }
108
109
  getDefaultValue(model) {
109
- const val = model.defaultValue.val;
110
- if (val) {
111
- if (!this.imports.includes('Sequelize')) {
112
- this.imports.push('Sequelize');
113
- }
114
- return `Sequelize.literal('${val}')`;
110
+ const defaultValue = model.defaultValue;
111
+ if (defaultValue === null) {
112
+ return 'null';
115
113
  }
116
- else if (typeof model.defaultValue == 'number') {
117
- return String(model.defaultValue);
114
+ else if (typeof defaultValue == 'object' && 'val' in defaultValue) {
115
+ this.useSequelize();
116
+ return `Sequelize.literal(${(0, column_types_1.quote)(String(defaultValue.val))})`;
118
117
  }
119
- else if (typeof model.defaultValue == 'boolean') {
120
- return String(model.defaultValue);
118
+ else if (typeof defaultValue == 'number' || typeof defaultValue == 'boolean') {
119
+ return String(defaultValue);
121
120
  }
122
- return `'${model.defaultValue}'`;
121
+ return (0, column_types_1.quote)(String(defaultValue));
123
122
  }
124
123
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
125
124
  createTable(model) {
@@ -133,24 +132,13 @@ class Migration {
133
132
  }
134
133
  for (const modelAttrsKey of modelAttrsKeys) {
135
134
  const attribute = modelAttrs[modelAttrsKey];
136
- if (attribute.type instanceof sequelize_1.DataTypes.VIRTUAL) {
135
+ if (isVirtual(attribute)) {
137
136
  continue;
138
137
  }
139
138
  if (modelAttrs[modelAttrsKey].references) {
140
139
  const references = modelAttrs[modelAttrsKey].references;
141
140
  if (typeof references !== 'string') {
142
- this.upForeignKey += `
143
- await queryInterface.addConstraint('${model.getTableName()}', {
144
- type: 'foreign key',
145
- fields: ['${modelAttrs[modelAttrsKey].field}'],
146
- onDelete: '${modelAttrs[modelAttrsKey].onDelete}',
147
- onUpdate: '${modelAttrs[modelAttrsKey].onUpdate}',
148
- references: {
149
- table: '${references?.model}',
150
- field: '${references?.key}'
151
- }
152
- });
153
- `;
141
+ this.foreignKey(model.getTableName(), modelAttrs[modelAttrsKey].field, references, modelAttrs[modelAttrsKey]);
154
142
  }
155
143
  }
156
144
  this.upTables += tabsToSpace(`\t\t\t${modelAttrsKey}: {${this.attributeProps(modelAttrs[modelAttrsKey], 4)}\n\t\t\t},\n`);
@@ -159,14 +147,14 @@ class Migration {
159
147
  if (modelIndexes) {
160
148
  for (const modelIndex of modelIndexes) {
161
149
  this.upIndexes += `
162
- await queryInterface.addIndex('${model.getTableName()}', ['${modelIndex.fields?.join('\', \'')}'], {
150
+ await queryInterface.addIndex('${model.getTableName()}', {
151
+ fields: ${formatIndexFields(modelIndex.fields)},
163
152
  name: '${modelIndex.name}',
164
153
  unique: ${modelIndex.unique},
165
154
  });
166
155
  `;
167
- this.downIndexes = `
168
- await queryInterface.removeIndex('${model.getTableName()}', '${modelIndex.name}');
169
- ` + this.downIndexes;
156
+ // no removeIndex on down: dropTable removes the table's indexes, and MySQL
157
+ // refuses to remove an index a foreign key needs
170
158
  }
171
159
  }
172
160
  this.upTables += tabsToSpace(`\t\t});`);
@@ -188,7 +176,7 @@ class Migration {
188
176
  if (attribute.primaryKey !== undefined) {
189
177
  attrProps += tabsToSpace(`\n${tabs(tabsQty)}primaryKey: ${this.getPrimaryKey(attribute)},`);
190
178
  }
191
- if (attribute.defaultValue !== undefined) {
179
+ if ((0, column_types_1.modelDefaultToSql)(attribute.defaultValue) !== undefined && attribute.defaultValue !== undefined) {
192
180
  attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);
193
181
  }
194
182
  attrProps += tabsToSpace(`\n${tabs(tabsQty)}field: '${attribute.field}'`);
@@ -200,37 +188,149 @@ class Migration {
200
188
  this.upFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\n\t\t});\n`);
201
189
  this.downFields = tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\n`) + this.downFields;
202
190
  }
203
- columnAttributeProps(attribute) {
191
+ /**
192
+ * Props that recreate a column as it currently is in the database.
193
+ */
194
+ columnAttributeProps(column, tabsQty) {
204
195
  if (!this.imports.includes('DataTypes')) {
205
196
  this.imports.push('DataTypes');
206
197
  }
207
- let attrProps = '';
208
- let dataTypes = attribute.type;
209
- if (dataTypes.includes('VARCHAR(')) {
210
- dataTypes = dataTypes.replace('VARCHAR(', 'STRING(');
198
+ let attrProps = tabsToSpace(`\n${tabs(tabsQty)}type: ${(0, column_types_1.databaseTypeToCode)(column.type)},`);
199
+ if (column.autoIncrement) {
200
+ attrProps += tabsToSpace(`\n${tabs(tabsQty)}autoIncrement: true,`);
211
201
  }
212
- else if (dataTypes == 'INT') {
213
- dataTypes = 'INTEGER';
214
- }
215
- attrProps += tabsToSpace(`\n${tabs(3)}type: DataTypes.${dataTypes},`);
216
- if (attribute.autoIncrement !== null) {
217
- attrProps += tabsToSpace(`\n${tabs(3)}autoIncrement: ${this.getAutoIncrement(attribute)},`);
218
- }
219
- if (attribute.allowNull !== null) {
220
- attrProps += tabsToSpace(`\n${tabs(3)}allowNull: ${this.getAllowNull(attribute)},`);
202
+ attrProps += tabsToSpace(`\n${tabs(tabsQty)}allowNull: ${column.allowNull},`);
203
+ if (column.defaultValue !== null) {
204
+ const { code, needsSequelize } = (0, column_types_1.databaseDefaultToCode)(column.defaultValue, column.type);
205
+ if (needsSequelize) {
206
+ this.useSequelize();
207
+ }
208
+ attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${code},`);
221
209
  }
222
- if (attribute.primaryKey !== null) {
223
- attrProps += tabsToSpace(`\n${tabs(3)}primaryKey: ${this.getPrimaryKey(attribute)},`);
210
+ return attrProps;
211
+ }
212
+ /**
213
+ * Props for `changeColumn` with the model's definition. Primary keys and references are left out:
214
+ * MySQL would try to add them again.
215
+ */
216
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
+ changedAttributeProps(attribute, tabsQty) {
218
+ let attrProps = tabsToSpace(`\n${tabs(tabsQty)}type: ${this.getType(attribute)},`);
219
+ if (attribute.autoIncrement) {
220
+ attrProps += tabsToSpace(`\n${tabs(tabsQty)}autoIncrement: true,`);
224
221
  }
225
- if (attribute.defaultValue !== null) {
226
- attrProps += tabsToSpace(`\n${tabs(3)}defaultValue: ${this.getDefaultValue(attribute)},`);
222
+ attrProps += tabsToSpace(`\n${tabs(tabsQty)}allowNull: ${isNullable(attribute)},`);
223
+ if (attribute.defaultValue !== undefined && (0, column_types_1.modelDefaultToSql)(attribute.defaultValue) !== undefined) {
224
+ attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);
227
225
  }
228
226
  return attrProps;
229
227
  }
230
- dropColumn(tableName, field, attribute) {
228
+ /**
229
+ * The constraint gets an explicit name (the one Sequelize would pick) so down can remove it.
230
+ */
231
+ foreignKey(tableName, field, references, attribute) {
232
+ const name = `${tableName}_${field}_${references.model}_fk`;
233
+ this.upForeignKey += `
234
+ await queryInterface.addConstraint('${tableName}', {
235
+ type: 'foreign key',
236
+ name: '${name}',
237
+ fields: ['${field}'],
238
+ onDelete: '${attribute.onDelete}',
239
+ onUpdate: '${attribute.onUpdate}',
240
+ references: {
241
+ table: '${references.model}',
242
+ field: '${references.key}'
243
+ }
244
+ });
245
+ `;
246
+ this.downForeignKey = `
247
+ await queryInterface.removeConstraint('${tableName}', '${name}');
248
+ ` + this.downForeignKey;
249
+ }
250
+ /**
251
+ * @param after the column before it in the table, so down adds it back at the same position (MySQL/MariaDB)
252
+ */
253
+ dropColumn(tableName, field, column, after) {
231
254
  console.debug(`drop column ${tableName} ${field} `);
255
+ let position = '';
256
+ let cast = '';
257
+ if (this.supportsColumnChanges) {
258
+ // after/first work on MySQL but are missing from Sequelize's types
259
+ position = tabsToSpace(after ? `\n\t\t\tafter: ${(0, column_types_1.quote)(after)},` : '\n\t\t\tfirst: true,');
260
+ cast = ' as ModelAttributeColumnOptions';
261
+ if (!this.imports.includes('ModelAttributeColumnOptions')) {
262
+ this.imports.push('ModelAttributeColumnOptions');
263
+ }
264
+ }
232
265
  this.upFields += tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${field}');\n`);
233
- this.downFields = tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${field}', {${this.columnAttributeProps(attribute)}\n\t\t});`) + this.downFields;
266
+ this.downDroppedFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${field}', {${this.columnAttributeProps(column, 3)}${position}\n\t\t}${cast});\n`);
267
+ }
268
+ /**
269
+ * Compares a model attribute with its column and returns what changed (type, nullability, default).
270
+ */
271
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
272
+ columnChanges(attribute, column) {
273
+ const changes = [];
274
+ const modelType = (0, column_types_1.normalizeColumnType)(attribute.type.toSql({ escape: (value) => this.sequelize.escape(value) }));
275
+ const databaseType = (0, column_types_1.normalizeColumnType)(column.type);
276
+ if (modelType !== databaseType) {
277
+ changes.push(`type ${databaseType} -> ${modelType}`);
278
+ }
279
+ if (isNullable(attribute) !== column.allowNull) {
280
+ changes.push(`allowNull ${column.allowNull} -> ${isNullable(attribute)}`);
281
+ }
282
+ const modelDefault = (0, column_types_1.modelDefaultToSql)(attribute.defaultValue);
283
+ if (modelDefault !== undefined && !(0, column_types_1.sameDefault)(modelDefault, column.defaultValue)) {
284
+ changes.push(`default ${column.defaultValue} -> ${modelDefault}`);
285
+ }
286
+ return changes;
287
+ }
288
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
289
+ changeColumn(tableName, attribute, column, changes) {
290
+ console.debug(`change column ${tableName} ${attribute.field}: ${changes.join(', ')}`);
291
+ this.upFields += tabsToSpace(`\n\t\tawait queryInterface.changeColumn('${tableName}', '${attribute.field}', {${this.changedAttributeProps(attribute, 3)}\n\t\t});\n`);
292
+ this.downFields = tabsToSpace(`\n\t\tawait queryInterface.changeColumn('${tableName}', '${attribute.field}', {${this.columnAttributeProps(column, 3)}\n\t\t});\n`) + this.downFields;
293
+ }
294
+ get supportsColumnChanges() {
295
+ return ['mysql', 'mariadb'].includes(this.sequelize.getDialect());
296
+ }
297
+ /**
298
+ * Reads the table's columns. On MySQL/MariaDB it uses information_schema, which keeps
299
+ * the full column type (e.g. enum values with their original case); other dialects use describeTable.
300
+ */
301
+ async describeColumns(tableName) {
302
+ const columns = {};
303
+ if (this.supportsColumnChanges) {
304
+ const rows = await this.sequelize.query(`
305
+ SELECT COLUMN_NAME AS name, COLUMN_TYPE AS type, IS_NULLABLE AS nullable, COLUMN_DEFAULT AS defaultValue, EXTRA AS extra, COLUMN_KEY AS columnKey
306
+ FROM information_schema.COLUMNS
307
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName
308
+ ORDER BY ORDINAL_POSITION`, {
309
+ type: sequelize_1.QueryTypes.SELECT,
310
+ replacements: { tableName },
311
+ });
312
+ for (const row of rows) {
313
+ columns[row.name] = {
314
+ type: row.type,
315
+ allowNull: row.nullable === 'YES',
316
+ defaultValue: row.defaultValue,
317
+ autoIncrement: row.extra.includes('auto_increment'),
318
+ primaryKey: row.columnKey === 'PRI',
319
+ };
320
+ }
321
+ return columns;
322
+ }
323
+ const description = await this.sequelize.getQueryInterface().describeTable(tableName);
324
+ for (const [name, column] of Object.entries(description)) {
325
+ columns[name] = {
326
+ type: column.type,
327
+ allowNull: column.allowNull,
328
+ defaultValue: column.defaultValue,
329
+ autoIncrement: Boolean(column.autoIncrement),
330
+ primaryKey: column.primaryKey,
331
+ };
332
+ }
333
+ return columns;
234
334
  }
235
335
  async checkDiffs() {
236
336
  const models = Object.keys(this.sequelize.models);
@@ -245,7 +345,7 @@ class Migration {
245
345
  }
246
346
  const modelAttrs = this.sequelize.models[model].getAttributes();
247
347
  const queryInterface = this.sequelize.getQueryInterface();
248
- const attrs = await queryInterface.describeTable(modelTable);
348
+ const attrs = await this.describeColumns(modelTable);
249
349
  const modelFields = [];
250
350
  const modelRefs = [];
251
351
  for (const modelAttr of Object.keys(modelAttrs)) {
@@ -256,40 +356,38 @@ class Migration {
256
356
  // check each field
257
357
  for (const modelAttr of Object.keys(modelAttrs)) {
258
358
  modelFields.push(modelAttrs[modelAttr].field || modelAttr);
259
- if (!Object.keys(attrs).includes(modelAttrs[modelAttr].field || modelAttr) && !(modelAttrs[modelAttr].type instanceof sequelize_1.DataTypes.VIRTUAL)) {
359
+ const column = attrs[modelAttrs[modelAttr].field || modelAttr];
360
+ if (column && !isVirtual(modelAttrs[modelAttr]) && this.supportsColumnChanges) {
361
+ const changes = this.columnChanges(modelAttrs[modelAttr], column);
362
+ if (changes.length) {
363
+ this.changeColumn(modelTable, modelAttrs[modelAttr], column, changes);
364
+ }
365
+ }
366
+ if (!column && !isVirtual(modelAttrs[modelAttr])) {
260
367
  this.newColumn(modelTable, modelAttrs[modelAttr]);
261
368
  if (modelAttrs[modelAttr].references) {
262
369
  const references = modelAttrs[modelAttr].references;
263
370
  if (typeof references !== 'string') {
264
- this.upForeignKey += `
265
- await queryInterface.addConstraint('${modelTable}', {
266
- type: 'foreign key',
267
- fields: ['${modelAttrs[modelAttr].field}'],
268
- onDelete: '${modelAttrs[modelAttr].onDelete}',
269
- onUpdate: '${modelAttrs[modelAttr].onUpdate}',
270
- references: {
271
- table: '${references?.model}',
272
- field: '${references?.key}'
273
- }
274
- });
275
- `;
371
+ this.foreignKey(modelTable, modelAttrs[modelAttr].field, references, modelAttrs[modelAttr]);
276
372
  }
277
373
  }
278
374
  }
279
375
  }
280
376
  // drop column
281
- for (const attr of Object.keys(attrs)) {
377
+ const columnNames = Object.keys(attrs);
378
+ columnNames.forEach((attr, index) => {
282
379
  if (!modelFields.includes(attr)) {
283
- this.dropColumn(modelTable, attr, attrs[attr]);
380
+ this.dropColumn(modelTable, attr, attrs[attr], columnNames[index - 1]);
284
381
  }
285
- }
382
+ });
286
383
  const indexes = await queryInterface.showIndex(modelTable);
287
384
  const modelIndexes = this.sequelize.models[model].options.indexes;
288
385
  if (modelIndexes) {
289
386
  for (const modelIndex of modelIndexes) {
290
387
  if (!indexes.find((index) => index.name == modelIndex.name)) {
291
388
  this.upIndexes += `
292
- await queryInterface.addIndex('${modelTable}', ['${modelIndex.fields?.join('\', \'')}'], {
389
+ await queryInterface.addIndex('${modelTable}', {
390
+ fields: ${formatIndexFields(modelIndex.fields)},
293
391
  name: '${modelIndex.name}',
294
392
  unique: ${modelIndex.unique},
295
393
  });
@@ -337,9 +435,9 @@ class Migration {
337
435
  }
338
436
  }
339
437
  }
340
- async generateFile(migrationName) {
438
+ async generateFile(migrationName, migrationsDir, previous) {
341
439
  const migration = `import { ${this.imports.join(', ')} } from 'sequelize';
342
-
440
+ ${previous ? `\n// runs after this migration (see "Migration order" on gina's README)\nexport const previous = ${(0, column_types_1.quote)(previous)};\n` : ''}
343
441
  export const migration = {
344
442
  async up(queryInterface: QueryInterface) {
345
443
  ${this.upTables}
@@ -349,25 +447,40 @@ ${this.upIndexes}
349
447
  },
350
448
 
351
449
  async down(queryInterface: QueryInterface) {
450
+ ${this.downForeignKey}
352
451
  ${this.downIndexes}
353
452
  ${this.downFields}
453
+ ${this.downDroppedFields}
354
454
  ${this.downTables}
355
455
  }
356
456
  };`;
357
- await promises_1.default.writeFile(`./gina/migrations/${(0, moment_1.default)().format('YYYYMMDDHHmmss')}-${migrationName.toLowerCase().replaceAll(' ', '-')}.ts`, migration);
457
+ const fileName = `${(0, moment_1.default)().format('YYYYMMDDHHmmss')}-${migrationName.toLowerCase().replaceAll(' ', '-')}.ts`;
458
+ await promises_1.default.writeFile(path_1.default.join(migrationsDir, fileName), migration);
459
+ console.info('migration created:', path_1.default.join(migrationsDir, fileName));
460
+ return fileName;
358
461
  }
359
462
  }
360
- async function createMigration(sequelize, migrationName) {
463
+ /**
464
+ * Writes a migration with the differences between the models and the database.
465
+ * Returns its file name, or `undefined` when there are no differences.
466
+ *
467
+ * @param previous the last migration, which the new one runs after
468
+ */
469
+ async function createMigration(sequelize, migrationName, migrationsDir = './gina/migrations', previous) {
361
470
  const migration = new Migration(sequelize);
362
471
  await migration.loadDatabaseTables();
363
472
  await migration.checkDiffs();
364
473
  if (!migration.upTables && !migration.upFields && !migration.upIndexes && !migration.upForeignKey) {
365
474
  console.info('There\'s no changes between your models and the database.');
475
+ return undefined;
366
476
  }
367
- await migration.generateFile(migrationName);
477
+ return migration.generateFile(migrationName, migrationsDir, previous);
368
478
  }
369
479
  const gina = {
370
- runMigrations,
480
+ runMigrations: runner_1.runMigrations,
481
+ revertMigrations: runner_1.revertMigrations,
482
+ repairMigration: runner_1.repairMigration,
483
+ dryRunMigrations: runner_1.dryRunMigrations,
371
484
  createMigration,
372
485
  };
373
486
  exports.default = gina;