gina-sequelize 0.0.16 → 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.
- package/README.md +271 -25
- package/bin/index.js +15 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +339 -0
- package/dist/cli.js.map +1 -0
- package/dist/column-types.d.ts +54 -0
- package/dist/column-types.js +188 -0
- package/dist/column-types.js.map +1 -0
- package/dist/gina.d.ts +12 -8
- package/dist/gina.js +230 -120
- package/dist/gina.js.map +1 -1
- package/dist/loader.d.ts +19 -0
- package/dist/loader.js +156 -0
- package/dist/loader.js.map +1 -0
- package/dist/runner.d.ts +73 -0
- package/dist/runner.js +602 -0
- package/dist/runner.js.map +1 -0
- package/package.json +21 -11
- package/.editorconfig +0 -18
- package/.env.example +0 -5
- package/.eslintrc +0 -59
- package/.nvmrc +0 -1
- package/.nycrc +0 -14
- package/.vscode/settings.json +0 -5
- package/bin/index.ts +0 -213
|
@@ -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,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E,cAAc,EAAE,IAAI,EAAE,CAAC;IACvF,CAAC;IACD,IAAI,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAChC,OAAO,EAAE,IAAI,EAAE,YAAY,KAAK,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC;IACpF,CAAC;IACD,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC;QACpF,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,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 {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
declare function createMigration(sequelize: Sequelize, migrationName: string): Promise<
|
|
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,40 +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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
updateAtFieldName = 'updatedAt';
|
|
24
|
-
}
|
|
25
|
-
for (const migrationFile of Object.keys(migrationFiles)) {
|
|
26
|
-
if (migrationFile > version) {
|
|
27
|
-
console.info('applying migration:', migrationFile);
|
|
28
|
-
await migrationFiles[migrationFile].migration.up(sequelize.getQueryInterface());
|
|
29
|
-
if (version) {
|
|
30
|
-
version = migrationFile;
|
|
31
|
-
await sequelize.query(`UPDATE gina_version SET version = '${version}', ${updateAtFieldName} = NOW();`);
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
version = migrationFile;
|
|
35
|
-
await sequelize.query(`INSERT INTO gina_version (${updateAtFieldName}, version) VALUES (NOW(),'${version}');`);
|
|
36
|
-
}
|
|
37
|
-
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}'`);
|
|
38
30
|
}
|
|
39
|
-
|
|
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;
|
|
40
49
|
}
|
|
41
50
|
function tabsToSpace(str) {
|
|
42
51
|
return str.replaceAll('\t', ' ');
|
|
@@ -54,9 +63,11 @@ class Migration {
|
|
|
54
63
|
this.downTables = '';
|
|
55
64
|
this.upFields = '';
|
|
56
65
|
this.downFields = '';
|
|
66
|
+
this.downDroppedFields = '';
|
|
57
67
|
this.upIndexes = '';
|
|
58
68
|
this.downIndexes = '';
|
|
59
69
|
this.upForeignKey = '';
|
|
70
|
+
this.downForeignKey = '';
|
|
60
71
|
/**
|
|
61
72
|
*
|
|
62
73
|
*/
|
|
@@ -88,41 +99,26 @@ class Migration {
|
|
|
88
99
|
return model.primaryKey ?? 'true' ? 'true' : 'false';
|
|
89
100
|
}
|
|
90
101
|
getType(model) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
if (model.type instanceof sequelize_1.DataTypes.STRING) {
|
|
98
|
-
return 'DataTypes.STRING';
|
|
99
|
-
}
|
|
100
|
-
if (model.type instanceof sequelize_1.DataTypes.DATE) {
|
|
101
|
-
return 'DataTypes.DATE';
|
|
102
|
-
}
|
|
103
|
-
if (model.type instanceof sequelize_1.DataTypes.TEXT) {
|
|
104
|
-
return 'DataTypes.TEXT';
|
|
105
|
-
}
|
|
106
|
-
if (model.type instanceof sequelize_1.DataTypes.BOOLEAN) {
|
|
107
|
-
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');
|
|
108
107
|
}
|
|
109
|
-
return '';
|
|
110
108
|
}
|
|
111
109
|
getDefaultValue(model) {
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
this.imports.push('Sequelize');
|
|
116
|
-
}
|
|
117
|
-
return `Sequelize.literal('${val}')`;
|
|
110
|
+
const defaultValue = model.defaultValue;
|
|
111
|
+
if (defaultValue === null) {
|
|
112
|
+
return 'null';
|
|
118
113
|
}
|
|
119
|
-
else if (typeof
|
|
120
|
-
|
|
114
|
+
else if (typeof defaultValue == 'object' && 'val' in defaultValue) {
|
|
115
|
+
this.useSequelize();
|
|
116
|
+
return `Sequelize.literal(${(0, column_types_1.quote)(String(defaultValue.val))})`;
|
|
121
117
|
}
|
|
122
|
-
else if (typeof
|
|
123
|
-
return String(
|
|
118
|
+
else if (typeof defaultValue == 'number' || typeof defaultValue == 'boolean') {
|
|
119
|
+
return String(defaultValue);
|
|
124
120
|
}
|
|
125
|
-
return
|
|
121
|
+
return (0, column_types_1.quote)(String(defaultValue));
|
|
126
122
|
}
|
|
127
123
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
128
124
|
createTable(model) {
|
|
@@ -136,24 +132,13 @@ class Migration {
|
|
|
136
132
|
}
|
|
137
133
|
for (const modelAttrsKey of modelAttrsKeys) {
|
|
138
134
|
const attribute = modelAttrs[modelAttrsKey];
|
|
139
|
-
if (attribute
|
|
135
|
+
if (isVirtual(attribute)) {
|
|
140
136
|
continue;
|
|
141
137
|
}
|
|
142
138
|
if (modelAttrs[modelAttrsKey].references) {
|
|
143
139
|
const references = modelAttrs[modelAttrsKey].references;
|
|
144
140
|
if (typeof references !== 'string') {
|
|
145
|
-
this.
|
|
146
|
-
await queryInterface.addConstraint('${model.getTableName()}', {
|
|
147
|
-
type: 'foreign key',
|
|
148
|
-
fields: ['${modelAttrs[modelAttrsKey].field}'],
|
|
149
|
-
onDelete: '${modelAttrs[modelAttrsKey].onDelete}',
|
|
150
|
-
onUpdate: '${modelAttrs[modelAttrsKey].onUpdate}',
|
|
151
|
-
references: {
|
|
152
|
-
table: '${references?.model}',
|
|
153
|
-
field: '${references?.key}'
|
|
154
|
-
}
|
|
155
|
-
});
|
|
156
|
-
`;
|
|
141
|
+
this.foreignKey(model.getTableName(), modelAttrs[modelAttrsKey].field, references, modelAttrs[modelAttrsKey]);
|
|
157
142
|
}
|
|
158
143
|
}
|
|
159
144
|
this.upTables += tabsToSpace(`\t\t\t${modelAttrsKey}: {${this.attributeProps(modelAttrs[modelAttrsKey], 4)}\n\t\t\t},\n`);
|
|
@@ -162,14 +147,14 @@ class Migration {
|
|
|
162
147
|
if (modelIndexes) {
|
|
163
148
|
for (const modelIndex of modelIndexes) {
|
|
164
149
|
this.upIndexes += `
|
|
165
|
-
await queryInterface.addIndex('${model.getTableName()}',
|
|
150
|
+
await queryInterface.addIndex('${model.getTableName()}', {
|
|
151
|
+
fields: ${formatIndexFields(modelIndex.fields)},
|
|
166
152
|
name: '${modelIndex.name}',
|
|
167
153
|
unique: ${modelIndex.unique},
|
|
168
154
|
});
|
|
169
155
|
`;
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
` + 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
|
|
173
158
|
}
|
|
174
159
|
}
|
|
175
160
|
this.upTables += tabsToSpace(`\t\t});`);
|
|
@@ -191,7 +176,7 @@ class Migration {
|
|
|
191
176
|
if (attribute.primaryKey !== undefined) {
|
|
192
177
|
attrProps += tabsToSpace(`\n${tabs(tabsQty)}primaryKey: ${this.getPrimaryKey(attribute)},`);
|
|
193
178
|
}
|
|
194
|
-
if (attribute.defaultValue !== undefined) {
|
|
179
|
+
if ((0, column_types_1.modelDefaultToSql)(attribute.defaultValue) !== undefined && attribute.defaultValue !== undefined) {
|
|
195
180
|
attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);
|
|
196
181
|
}
|
|
197
182
|
attrProps += tabsToSpace(`\n${tabs(tabsQty)}field: '${attribute.field}'`);
|
|
@@ -203,37 +188,149 @@ class Migration {
|
|
|
203
188
|
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\n\t\t});\n`);
|
|
204
189
|
this.downFields = tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\n`) + this.downFields;
|
|
205
190
|
}
|
|
206
|
-
|
|
191
|
+
/**
|
|
192
|
+
* Props that recreate a column as it currently is in the database.
|
|
193
|
+
*/
|
|
194
|
+
columnAttributeProps(column, tabsQty) {
|
|
207
195
|
if (!this.imports.includes('DataTypes')) {
|
|
208
196
|
this.imports.push('DataTypes');
|
|
209
197
|
}
|
|
210
|
-
let attrProps =
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
dataTypes = dataTypes.replace('VARCHAR(', 'STRING(');
|
|
214
|
-
}
|
|
215
|
-
else if (dataTypes == 'INT') {
|
|
216
|
-
dataTypes = 'INTEGER';
|
|
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,`);
|
|
217
201
|
}
|
|
218
|
-
attrProps += tabsToSpace(`\n${tabs(
|
|
219
|
-
if (
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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},`);
|
|
224
209
|
}
|
|
225
|
-
|
|
226
|
-
|
|
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,`);
|
|
227
221
|
}
|
|
228
|
-
|
|
229
|
-
|
|
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)},`);
|
|
230
225
|
}
|
|
231
226
|
return attrProps;
|
|
232
227
|
}
|
|
233
|
-
|
|
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) {
|
|
234
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
|
+
}
|
|
235
265
|
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${field}');\n`);
|
|
236
|
-
this.
|
|
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;
|
|
237
334
|
}
|
|
238
335
|
async checkDiffs() {
|
|
239
336
|
const models = Object.keys(this.sequelize.models);
|
|
@@ -248,7 +345,7 @@ class Migration {
|
|
|
248
345
|
}
|
|
249
346
|
const modelAttrs = this.sequelize.models[model].getAttributes();
|
|
250
347
|
const queryInterface = this.sequelize.getQueryInterface();
|
|
251
|
-
const attrs = await
|
|
348
|
+
const attrs = await this.describeColumns(modelTable);
|
|
252
349
|
const modelFields = [];
|
|
253
350
|
const modelRefs = [];
|
|
254
351
|
for (const modelAttr of Object.keys(modelAttrs)) {
|
|
@@ -259,40 +356,38 @@ class Migration {
|
|
|
259
356
|
// check each field
|
|
260
357
|
for (const modelAttr of Object.keys(modelAttrs)) {
|
|
261
358
|
modelFields.push(modelAttrs[modelAttr].field || modelAttr);
|
|
262
|
-
|
|
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])) {
|
|
263
367
|
this.newColumn(modelTable, modelAttrs[modelAttr]);
|
|
264
368
|
if (modelAttrs[modelAttr].references) {
|
|
265
369
|
const references = modelAttrs[modelAttr].references;
|
|
266
370
|
if (typeof references !== 'string') {
|
|
267
|
-
this.
|
|
268
|
-
await queryInterface.addConstraint('${modelTable}', {
|
|
269
|
-
type: 'foreign key',
|
|
270
|
-
fields: ['${modelAttrs[modelAttr].field}'],
|
|
271
|
-
onDelete: '${modelAttrs[modelAttr].onDelete}',
|
|
272
|
-
onUpdate: '${modelAttrs[modelAttr].onUpdate}',
|
|
273
|
-
references: {
|
|
274
|
-
table: '${references?.model}',
|
|
275
|
-
field: '${references?.key}'
|
|
276
|
-
}
|
|
277
|
-
});
|
|
278
|
-
`;
|
|
371
|
+
this.foreignKey(modelTable, modelAttrs[modelAttr].field, references, modelAttrs[modelAttr]);
|
|
279
372
|
}
|
|
280
373
|
}
|
|
281
374
|
}
|
|
282
375
|
}
|
|
283
376
|
// drop column
|
|
284
|
-
|
|
377
|
+
const columnNames = Object.keys(attrs);
|
|
378
|
+
columnNames.forEach((attr, index) => {
|
|
285
379
|
if (!modelFields.includes(attr)) {
|
|
286
|
-
this.dropColumn(modelTable, attr, attrs[attr]);
|
|
380
|
+
this.dropColumn(modelTable, attr, attrs[attr], columnNames[index - 1]);
|
|
287
381
|
}
|
|
288
|
-
}
|
|
382
|
+
});
|
|
289
383
|
const indexes = await queryInterface.showIndex(modelTable);
|
|
290
384
|
const modelIndexes = this.sequelize.models[model].options.indexes;
|
|
291
385
|
if (modelIndexes) {
|
|
292
386
|
for (const modelIndex of modelIndexes) {
|
|
293
387
|
if (!indexes.find((index) => index.name == modelIndex.name)) {
|
|
294
388
|
this.upIndexes += `
|
|
295
|
-
await queryInterface.addIndex('${modelTable}',
|
|
389
|
+
await queryInterface.addIndex('${modelTable}', {
|
|
390
|
+
fields: ${formatIndexFields(modelIndex.fields)},
|
|
296
391
|
name: '${modelIndex.name}',
|
|
297
392
|
unique: ${modelIndex.unique},
|
|
298
393
|
});
|
|
@@ -340,9 +435,9 @@ class Migration {
|
|
|
340
435
|
}
|
|
341
436
|
}
|
|
342
437
|
}
|
|
343
|
-
async generateFile(migrationName) {
|
|
438
|
+
async generateFile(migrationName, migrationsDir, previous) {
|
|
344
439
|
const migration = `import { ${this.imports.join(', ')} } from 'sequelize';
|
|
345
|
-
|
|
440
|
+
${previous ? `\n// runs after this migration (see "Migration order" on gina's README)\nexport const previous = ${(0, column_types_1.quote)(previous)};\n` : ''}
|
|
346
441
|
export const migration = {
|
|
347
442
|
async up(queryInterface: QueryInterface) {
|
|
348
443
|
${this.upTables}
|
|
@@ -352,25 +447,40 @@ ${this.upIndexes}
|
|
|
352
447
|
},
|
|
353
448
|
|
|
354
449
|
async down(queryInterface: QueryInterface) {
|
|
450
|
+
${this.downForeignKey}
|
|
355
451
|
${this.downIndexes}
|
|
356
452
|
${this.downFields}
|
|
453
|
+
${this.downDroppedFields}
|
|
357
454
|
${this.downTables}
|
|
358
455
|
}
|
|
359
456
|
};`;
|
|
360
|
-
|
|
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;
|
|
361
461
|
}
|
|
362
462
|
}
|
|
363
|
-
|
|
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) {
|
|
364
470
|
const migration = new Migration(sequelize);
|
|
365
471
|
await migration.loadDatabaseTables();
|
|
366
472
|
await migration.checkDiffs();
|
|
367
473
|
if (!migration.upTables && !migration.upFields && !migration.upIndexes && !migration.upForeignKey) {
|
|
368
474
|
console.info('There\'s no changes between your models and the database.');
|
|
475
|
+
return undefined;
|
|
369
476
|
}
|
|
370
|
-
|
|
477
|
+
return migration.generateFile(migrationName, migrationsDir, previous);
|
|
371
478
|
}
|
|
372
479
|
const gina = {
|
|
373
|
-
runMigrations,
|
|
480
|
+
runMigrations: runner_1.runMigrations,
|
|
481
|
+
revertMigrations: runner_1.revertMigrations,
|
|
482
|
+
repairMigration: runner_1.repairMigration,
|
|
483
|
+
dryRunMigrations: runner_1.dryRunMigrations,
|
|
374
484
|
createMigration,
|
|
375
485
|
};
|
|
376
486
|
exports.default = gina;
|