gina-sequelize 0.0.16 → 0.1.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 +273 -25
- package/bin/index.js +15 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +335 -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 +296 -124
- 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,41 +3,90 @@ 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
|
-
|
|
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}'`;
|
|
25
|
+
}
|
|
26
|
+
const { name, order, length, collate } = field;
|
|
27
|
+
const props = [`name: '${name}'`];
|
|
28
|
+
if (order) {
|
|
29
|
+
props.push(`order: '${order}'`);
|
|
30
|
+
}
|
|
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;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The model's indexes: `options.indexes` plus the unique indexes declared on attributes
|
|
52
|
+
* (`unique: true`, or `unique: 'name'` shared by the attributes of a composite index).
|
|
53
|
+
*/
|
|
54
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
55
|
+
function modelIndexesOf(model, tableName) {
|
|
56
|
+
const indexes = [...(model.options.indexes ?? [])];
|
|
57
|
+
const composite = new Map();
|
|
58
|
+
for (const attribute of Object.values(model.getAttributes())) {
|
|
59
|
+
const unique = attribute.unique;
|
|
60
|
+
const field = attribute.field;
|
|
61
|
+
if (!unique || isVirtual(attribute)) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const name = typeof unique === 'string' ? unique : typeof unique === 'object' ? unique.name : undefined;
|
|
65
|
+
if (name) {
|
|
66
|
+
composite.set(name, [...composite.get(name) ?? [], field]);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
indexes.push({ name: `${tableName}_${field}_unique`, fields: [field], unique: true, fromAttribute: true });
|
|
18
70
|
}
|
|
19
|
-
version = versions.length == 1 ? versions[0].version : '';
|
|
20
71
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
updateAtFieldName = 'updatedAt';
|
|
72
|
+
for (const [name, fields] of composite) {
|
|
73
|
+
indexes.push({ name, fields, unique: true, fromAttribute: true });
|
|
24
74
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
version = migrationFile;
|
|
35
|
-
await sequelize.query(`INSERT INTO gina_version (${updateAtFieldName}, version) VALUES (NOW(),'${version}');`);
|
|
36
|
-
}
|
|
37
|
-
console.info('applied version:', migrationFile);
|
|
38
|
-
}
|
|
75
|
+
return indexes;
|
|
76
|
+
}
|
|
77
|
+
function indexColumns(fields) {
|
|
78
|
+
return (fields ?? []).map(field => (typeof field === 'string' ? field : field.name ?? field.attribute));
|
|
79
|
+
}
|
|
80
|
+
/** Whether a database index is the one the model declares: by name, or by its columns for attribute-level unique indexes. */
|
|
81
|
+
function sameIndex(modelIndex, index) {
|
|
82
|
+
if (modelIndex.name === index.name) {
|
|
83
|
+
return true;
|
|
39
84
|
}
|
|
85
|
+
return Boolean(modelIndex.fromAttribute && index.unique
|
|
86
|
+
&& indexColumns(modelIndex.fields).join(',') === indexColumns(index.fields).join(','));
|
|
40
87
|
}
|
|
88
|
+
/** MySQL can't store a default value for these types (and Sequelize drops the plain TEXT one): the model's default only applies on create. */
|
|
89
|
+
const TYPES_WITHOUT_DEFAULT = ['TEXT', 'BLOB', 'JSON', 'GEOMETRY'];
|
|
41
90
|
function tabsToSpace(str) {
|
|
42
91
|
return str.replaceAll('\t', ' ');
|
|
43
92
|
}
|
|
@@ -54,9 +103,11 @@ class Migration {
|
|
|
54
103
|
this.downTables = '';
|
|
55
104
|
this.upFields = '';
|
|
56
105
|
this.downFields = '';
|
|
106
|
+
this.downDroppedFields = '';
|
|
57
107
|
this.upIndexes = '';
|
|
58
108
|
this.downIndexes = '';
|
|
59
109
|
this.upForeignKey = '';
|
|
110
|
+
this.downForeignKey = '';
|
|
60
111
|
/**
|
|
61
112
|
*
|
|
62
113
|
*/
|
|
@@ -88,41 +139,26 @@ class Migration {
|
|
|
88
139
|
return model.primaryKey ?? 'true' ? 'true' : 'false';
|
|
89
140
|
}
|
|
90
141
|
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';
|
|
142
|
+
return (0, column_types_1.modelTypeToCode)(model.type);
|
|
143
|
+
}
|
|
144
|
+
useSequelize() {
|
|
145
|
+
if (!this.imports.includes('Sequelize')) {
|
|
146
|
+
this.imports.push('Sequelize');
|
|
108
147
|
}
|
|
109
|
-
return '';
|
|
110
148
|
}
|
|
111
149
|
getDefaultValue(model) {
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
this.imports.push('Sequelize');
|
|
116
|
-
}
|
|
117
|
-
return `Sequelize.literal('${val}')`;
|
|
150
|
+
const defaultValue = model.defaultValue;
|
|
151
|
+
if (defaultValue === null) {
|
|
152
|
+
return 'null';
|
|
118
153
|
}
|
|
119
|
-
else if (typeof
|
|
120
|
-
|
|
154
|
+
else if (typeof defaultValue == 'object' && 'val' in defaultValue) {
|
|
155
|
+
this.useSequelize();
|
|
156
|
+
return `Sequelize.literal(${(0, column_types_1.quote)(String(defaultValue.val))})`;
|
|
121
157
|
}
|
|
122
|
-
else if (typeof
|
|
123
|
-
return String(
|
|
158
|
+
else if (typeof defaultValue == 'number' || typeof defaultValue == 'boolean') {
|
|
159
|
+
return String(defaultValue);
|
|
124
160
|
}
|
|
125
|
-
return
|
|
161
|
+
return (0, column_types_1.quote)(String(defaultValue));
|
|
126
162
|
}
|
|
127
163
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
128
164
|
createTable(model) {
|
|
@@ -136,40 +172,29 @@ class Migration {
|
|
|
136
172
|
}
|
|
137
173
|
for (const modelAttrsKey of modelAttrsKeys) {
|
|
138
174
|
const attribute = modelAttrs[modelAttrsKey];
|
|
139
|
-
if (attribute
|
|
175
|
+
if (isVirtual(attribute)) {
|
|
140
176
|
continue;
|
|
141
177
|
}
|
|
142
178
|
if (modelAttrs[modelAttrsKey].references) {
|
|
143
179
|
const references = modelAttrs[modelAttrsKey].references;
|
|
144
180
|
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
|
-
`;
|
|
181
|
+
this.foreignKey(model.getTableName(), modelAttrs[modelAttrsKey].field, references, modelAttrs[modelAttrsKey]);
|
|
157
182
|
}
|
|
158
183
|
}
|
|
159
184
|
this.upTables += tabsToSpace(`\t\t\t${modelAttrsKey}: {${this.attributeProps(modelAttrs[modelAttrsKey], 4)}\n\t\t\t},\n`);
|
|
160
185
|
}
|
|
161
|
-
const modelIndexes = model.
|
|
162
|
-
if (modelIndexes) {
|
|
186
|
+
const modelIndexes = modelIndexesOf(model, model.getTableName());
|
|
187
|
+
if (modelIndexes.length) {
|
|
163
188
|
for (const modelIndex of modelIndexes) {
|
|
164
189
|
this.upIndexes += `
|
|
165
|
-
await queryInterface.addIndex('${model.getTableName()}',
|
|
190
|
+
await queryInterface.addIndex('${model.getTableName()}', {
|
|
191
|
+
fields: ${formatIndexFields(modelIndex.fields)},
|
|
166
192
|
name: '${modelIndex.name}',
|
|
167
193
|
unique: ${modelIndex.unique},
|
|
168
194
|
});
|
|
169
195
|
`;
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
` + this.downIndexes;
|
|
196
|
+
// no removeIndex on down: dropTable removes the table's indexes, and MySQL
|
|
197
|
+
// refuses to remove an index a foreign key needs
|
|
173
198
|
}
|
|
174
199
|
}
|
|
175
200
|
this.upTables += tabsToSpace(`\t\t});`);
|
|
@@ -191,7 +216,7 @@ class Migration {
|
|
|
191
216
|
if (attribute.primaryKey !== undefined) {
|
|
192
217
|
attrProps += tabsToSpace(`\n${tabs(tabsQty)}primaryKey: ${this.getPrimaryKey(attribute)},`);
|
|
193
218
|
}
|
|
194
|
-
if (attribute
|
|
219
|
+
if (this.hasDatabaseDefault(attribute)) {
|
|
195
220
|
attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);
|
|
196
221
|
}
|
|
197
222
|
attrProps += tabsToSpace(`\n${tabs(tabsQty)}field: '${attribute.field}'`);
|
|
@@ -203,37 +228,160 @@ class Migration {
|
|
|
203
228
|
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\n\t\t});\n`);
|
|
204
229
|
this.downFields = tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\n`) + this.downFields;
|
|
205
230
|
}
|
|
206
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Props that recreate a column as it currently is in the database.
|
|
233
|
+
*/
|
|
234
|
+
columnAttributeProps(column, tabsQty) {
|
|
207
235
|
if (!this.imports.includes('DataTypes')) {
|
|
208
236
|
this.imports.push('DataTypes');
|
|
209
237
|
}
|
|
210
|
-
let attrProps =
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
dataTypes = dataTypes.replace('VARCHAR(', 'STRING(');
|
|
214
|
-
}
|
|
215
|
-
else if (dataTypes == 'INT') {
|
|
216
|
-
dataTypes = 'INTEGER';
|
|
238
|
+
let attrProps = tabsToSpace(`\n${tabs(tabsQty)}type: ${(0, column_types_1.databaseTypeToCode)(column.type)},`);
|
|
239
|
+
if (column.autoIncrement) {
|
|
240
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}autoIncrement: true,`);
|
|
217
241
|
}
|
|
218
|
-
attrProps += tabsToSpace(`\n${tabs(
|
|
219
|
-
if (
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
242
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}allowNull: ${column.allowNull},`);
|
|
243
|
+
if (column.defaultValue !== null) {
|
|
244
|
+
const { code, needsSequelize } = (0, column_types_1.databaseDefaultToCode)(column.defaultValue, column.type);
|
|
245
|
+
if (needsSequelize) {
|
|
246
|
+
this.useSequelize();
|
|
247
|
+
}
|
|
248
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${code},`);
|
|
224
249
|
}
|
|
225
|
-
|
|
226
|
-
|
|
250
|
+
return attrProps;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Props for `changeColumn` with the model's definition. Primary keys and references are left out:
|
|
254
|
+
* MySQL would try to add them again.
|
|
255
|
+
*/
|
|
256
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
257
|
+
changedAttributeProps(attribute, tabsQty) {
|
|
258
|
+
let attrProps = tabsToSpace(`\n${tabs(tabsQty)}type: ${this.getType(attribute)},`);
|
|
259
|
+
if (attribute.autoIncrement) {
|
|
260
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}autoIncrement: true,`);
|
|
227
261
|
}
|
|
228
|
-
|
|
229
|
-
|
|
262
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}allowNull: ${isNullable(attribute)},`);
|
|
263
|
+
if (this.hasDatabaseDefault(attribute)) {
|
|
264
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);
|
|
230
265
|
}
|
|
231
266
|
return attrProps;
|
|
232
267
|
}
|
|
233
|
-
|
|
268
|
+
/**
|
|
269
|
+
* The constraint gets an explicit name (the one Sequelize would pick) so down can remove it.
|
|
270
|
+
*/
|
|
271
|
+
foreignKey(tableName, field, references, attribute) {
|
|
272
|
+
const name = `${tableName}_${field}_${references.model}_fk`;
|
|
273
|
+
this.upForeignKey += `
|
|
274
|
+
await queryInterface.addConstraint('${tableName}', {
|
|
275
|
+
type: 'foreign key',
|
|
276
|
+
name: '${name}',
|
|
277
|
+
fields: ['${field}'],
|
|
278
|
+
onDelete: '${attribute.onDelete}',
|
|
279
|
+
onUpdate: '${attribute.onUpdate}',
|
|
280
|
+
references: {
|
|
281
|
+
table: '${references.model}',
|
|
282
|
+
field: '${references.key}'
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
`;
|
|
286
|
+
this.downForeignKey = `
|
|
287
|
+
await queryInterface.removeConstraint('${tableName}', '${name}');
|
|
288
|
+
` + this.downForeignKey;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* @param after the column before it in the table, so down adds it back at the same position (MySQL/MariaDB)
|
|
292
|
+
*/
|
|
293
|
+
dropColumn(tableName, field, column, after) {
|
|
234
294
|
console.debug(`drop column ${tableName} ${field} `);
|
|
295
|
+
let position = '';
|
|
296
|
+
let cast = '';
|
|
297
|
+
if (this.supportsColumnChanges) {
|
|
298
|
+
// after/first work on MySQL but are missing from Sequelize's types
|
|
299
|
+
position = tabsToSpace(after ? `\n\t\t\tafter: ${(0, column_types_1.quote)(after)},` : '\n\t\t\tfirst: true,');
|
|
300
|
+
cast = ' as ModelAttributeColumnOptions';
|
|
301
|
+
if (!this.imports.includes('ModelAttributeColumnOptions')) {
|
|
302
|
+
this.imports.push('ModelAttributeColumnOptions');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
235
305
|
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${field}');\n`);
|
|
236
|
-
this.
|
|
306
|
+
this.downDroppedFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${field}', {${this.columnAttributeProps(column, 3)}${position}\n\t\t}${cast});\n`);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Compares a model attribute with its column and returns what changed (type, nullability, default).
|
|
310
|
+
*/
|
|
311
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
312
|
+
columnChanges(attribute, column) {
|
|
313
|
+
const changes = [];
|
|
314
|
+
const modelType = (0, column_types_1.normalizeColumnType)(attribute.type.toSql({ escape: (value) => this.sequelize.escape(value) }));
|
|
315
|
+
const databaseType = (0, column_types_1.normalizeColumnType)(column.type);
|
|
316
|
+
if (modelType !== databaseType) {
|
|
317
|
+
changes.push(`type ${databaseType} -> ${modelType}`);
|
|
318
|
+
}
|
|
319
|
+
if (isNullable(attribute) !== column.allowNull) {
|
|
320
|
+
changes.push(`allowNull ${column.allowNull} -> ${isNullable(attribute)}`);
|
|
321
|
+
}
|
|
322
|
+
const modelDefault = (0, column_types_1.modelDefaultToSql)(attribute.defaultValue);
|
|
323
|
+
if (this.hasDatabaseDefault(attribute) && modelDefault !== undefined && !(0, column_types_1.sameDefault)(modelDefault, column.defaultValue)) {
|
|
324
|
+
changes.push(`default ${column.defaultValue} -> ${modelDefault}`);
|
|
325
|
+
}
|
|
326
|
+
return changes;
|
|
327
|
+
}
|
|
328
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
329
|
+
changeColumn(tableName, attribute, column, changes) {
|
|
330
|
+
console.debug(`change column ${tableName} ${attribute.field}: ${changes.join(', ')}`);
|
|
331
|
+
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.changeColumn('${tableName}', '${attribute.field}', {${this.changedAttributeProps(attribute, 3)}\n\t\t});\n`);
|
|
332
|
+
this.downFields = tabsToSpace(`\n\t\tawait queryInterface.changeColumn('${tableName}', '${attribute.field}', {${this.columnAttributeProps(column, 3)}\n\t\t});\n`) + this.downFields;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Whether the attribute's default can be stored by the database. Defaults of functions (e.g. NOW)
|
|
336
|
+
* and, on MySQL/MariaDB, of TEXT, BLOB, JSON and GEOMETRY columns only apply when Sequelize creates a row.
|
|
337
|
+
*/
|
|
338
|
+
hasDatabaseDefault(attribute) {
|
|
339
|
+
if (attribute.defaultValue === undefined || (0, column_types_1.modelDefaultToSql)(attribute.defaultValue) === undefined) {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
const key = attribute.type?.key;
|
|
343
|
+
return !(this.supportsColumnChanges && key !== undefined && TYPES_WITHOUT_DEFAULT.includes(key));
|
|
344
|
+
}
|
|
345
|
+
get supportsColumnChanges() {
|
|
346
|
+
return ['mysql', 'mariadb'].includes(this.sequelize.getDialect());
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Reads the table's columns. On MySQL/MariaDB it uses information_schema, which keeps
|
|
350
|
+
* the full column type (e.g. enum values with their original case); other dialects use describeTable.
|
|
351
|
+
*/
|
|
352
|
+
async describeColumns(tableName) {
|
|
353
|
+
const columns = {};
|
|
354
|
+
if (this.supportsColumnChanges) {
|
|
355
|
+
const rows = await this.sequelize.query(`
|
|
356
|
+
SELECT COLUMN_NAME AS name, COLUMN_TYPE AS type, IS_NULLABLE AS nullable, COLUMN_DEFAULT AS defaultValue, EXTRA AS extra, COLUMN_KEY AS columnKey
|
|
357
|
+
FROM information_schema.COLUMNS
|
|
358
|
+
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName
|
|
359
|
+
ORDER BY ORDINAL_POSITION`, {
|
|
360
|
+
type: sequelize_1.QueryTypes.SELECT,
|
|
361
|
+
replacements: { tableName },
|
|
362
|
+
});
|
|
363
|
+
for (const row of rows) {
|
|
364
|
+
columns[row.name] = {
|
|
365
|
+
type: row.type,
|
|
366
|
+
allowNull: row.nullable === 'YES',
|
|
367
|
+
defaultValue: row.defaultValue,
|
|
368
|
+
autoIncrement: row.extra.includes('auto_increment'),
|
|
369
|
+
primaryKey: row.columnKey === 'PRI',
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
return columns;
|
|
373
|
+
}
|
|
374
|
+
const description = await this.sequelize.getQueryInterface().describeTable(tableName);
|
|
375
|
+
for (const [name, column] of Object.entries(description)) {
|
|
376
|
+
columns[name] = {
|
|
377
|
+
type: column.type,
|
|
378
|
+
allowNull: column.allowNull,
|
|
379
|
+
defaultValue: column.defaultValue,
|
|
380
|
+
autoIncrement: Boolean(column.autoIncrement),
|
|
381
|
+
primaryKey: column.primaryKey,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
return columns;
|
|
237
385
|
}
|
|
238
386
|
async checkDiffs() {
|
|
239
387
|
const models = Object.keys(this.sequelize.models);
|
|
@@ -248,7 +396,7 @@ class Migration {
|
|
|
248
396
|
}
|
|
249
397
|
const modelAttrs = this.sequelize.models[model].getAttributes();
|
|
250
398
|
const queryInterface = this.sequelize.getQueryInterface();
|
|
251
|
-
const attrs = await
|
|
399
|
+
const attrs = await this.describeColumns(modelTable);
|
|
252
400
|
const modelFields = [];
|
|
253
401
|
const modelRefs = [];
|
|
254
402
|
for (const modelAttr of Object.keys(modelAttrs)) {
|
|
@@ -259,40 +407,38 @@ class Migration {
|
|
|
259
407
|
// check each field
|
|
260
408
|
for (const modelAttr of Object.keys(modelAttrs)) {
|
|
261
409
|
modelFields.push(modelAttrs[modelAttr].field || modelAttr);
|
|
262
|
-
|
|
410
|
+
const column = attrs[modelAttrs[modelAttr].field || modelAttr];
|
|
411
|
+
if (column && !isVirtual(modelAttrs[modelAttr]) && this.supportsColumnChanges) {
|
|
412
|
+
const changes = this.columnChanges(modelAttrs[modelAttr], column);
|
|
413
|
+
if (changes.length) {
|
|
414
|
+
this.changeColumn(modelTable, modelAttrs[modelAttr], column, changes);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (!column && !isVirtual(modelAttrs[modelAttr])) {
|
|
263
418
|
this.newColumn(modelTable, modelAttrs[modelAttr]);
|
|
264
419
|
if (modelAttrs[modelAttr].references) {
|
|
265
420
|
const references = modelAttrs[modelAttr].references;
|
|
266
421
|
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
|
-
`;
|
|
422
|
+
this.foreignKey(modelTable, modelAttrs[modelAttr].field, references, modelAttrs[modelAttr]);
|
|
279
423
|
}
|
|
280
424
|
}
|
|
281
425
|
}
|
|
282
426
|
}
|
|
283
427
|
// drop column
|
|
284
|
-
|
|
428
|
+
const columnNames = Object.keys(attrs);
|
|
429
|
+
columnNames.forEach((attr, index) => {
|
|
285
430
|
if (!modelFields.includes(attr)) {
|
|
286
|
-
this.dropColumn(modelTable, attr, attrs[attr]);
|
|
431
|
+
this.dropColumn(modelTable, attr, attrs[attr], columnNames[index - 1]);
|
|
287
432
|
}
|
|
288
|
-
}
|
|
433
|
+
});
|
|
289
434
|
const indexes = await queryInterface.showIndex(modelTable);
|
|
290
|
-
const modelIndexes = this.sequelize.models[model]
|
|
291
|
-
if (modelIndexes) {
|
|
435
|
+
const modelIndexes = modelIndexesOf(this.sequelize.models[model], modelTable);
|
|
436
|
+
if (modelIndexes.length) {
|
|
292
437
|
for (const modelIndex of modelIndexes) {
|
|
293
|
-
if (!indexes.find((index) => index
|
|
438
|
+
if (!indexes.find((index) => sameIndex(modelIndex, index))) {
|
|
294
439
|
this.upIndexes += `
|
|
295
|
-
await queryInterface.addIndex('${modelTable}',
|
|
440
|
+
await queryInterface.addIndex('${modelTable}', {
|
|
441
|
+
fields: ${formatIndexFields(modelIndex.fields)},
|
|
296
442
|
name: '${modelIndex.name}',
|
|
297
443
|
unique: ${modelIndex.unique},
|
|
298
444
|
});
|
|
@@ -319,7 +465,7 @@ class Migration {
|
|
|
319
465
|
if (modelRefs.includes(index.name)) {
|
|
320
466
|
continue;
|
|
321
467
|
}
|
|
322
|
-
if (
|
|
468
|
+
if (!modelIndexes.find((modelIndex) => sameIndex(modelIndex, index))) {
|
|
323
469
|
this.upIndexes += `
|
|
324
470
|
await queryInterface.removeIndex('${modelTable}', '${index.name}');
|
|
325
471
|
|
|
@@ -340,9 +486,9 @@ class Migration {
|
|
|
340
486
|
}
|
|
341
487
|
}
|
|
342
488
|
}
|
|
343
|
-
async generateFile(migrationName) {
|
|
489
|
+
async generateFile(migrationName, migrationsDir, previous) {
|
|
344
490
|
const migration = `import { ${this.imports.join(', ')} } from 'sequelize';
|
|
345
|
-
|
|
491
|
+
${previous ? `\n// runs after this migration (see "Migration order" on gina's README)\nexport const previous = ${(0, column_types_1.quote)(previous)};\n` : ''}
|
|
346
492
|
export const migration = {
|
|
347
493
|
async up(queryInterface: QueryInterface) {
|
|
348
494
|
${this.upTables}
|
|
@@ -352,25 +498,51 @@ ${this.upIndexes}
|
|
|
352
498
|
},
|
|
353
499
|
|
|
354
500
|
async down(queryInterface: QueryInterface) {
|
|
501
|
+
${this.downForeignKey}
|
|
355
502
|
${this.downIndexes}
|
|
356
503
|
${this.downFields}
|
|
504
|
+
${this.downDroppedFields}
|
|
357
505
|
${this.downTables}
|
|
358
506
|
}
|
|
359
507
|
};`;
|
|
360
|
-
|
|
508
|
+
const fileName = `${(0, moment_1.default)().format('YYYYMMDDHHmmss')}-${migrationName.toLowerCase().replaceAll(' ', '-')}.ts`;
|
|
509
|
+
await promises_1.default.writeFile(path_1.default.join(migrationsDir, fileName), tidy(migration));
|
|
510
|
+
console.info('migration created:', path_1.default.join(migrationsDir, fileName));
|
|
511
|
+
return fileName;
|
|
361
512
|
}
|
|
362
513
|
}
|
|
363
|
-
|
|
514
|
+
/**
|
|
515
|
+
* The sections of a generated migration are joined with blank lines, and some of them are empty:
|
|
516
|
+
* no blank lines right after `{` or before `}`, at most one in a row, and a newline at the end.
|
|
517
|
+
*/
|
|
518
|
+
function tidy(code) {
|
|
519
|
+
return `${code
|
|
520
|
+
.replace(/\{\n(?:[ \t]*\n)+/g, '{\n')
|
|
521
|
+
.replace(/\n(?:[ \t]*\n)+([ \t]*\})/g, '\n$1')
|
|
522
|
+
.replace(/\n(?:[ \t]*\n){2,}/g, '\n\n')
|
|
523
|
+
.trimEnd()}\n`;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Writes a migration with the differences between the models and the database.
|
|
527
|
+
* Returns its file name, or `undefined` when there are no differences.
|
|
528
|
+
*
|
|
529
|
+
* @param previous the last migration, which the new one runs after
|
|
530
|
+
*/
|
|
531
|
+
async function createMigration(sequelize, migrationName, migrationsDir = './gina/migrations', previous) {
|
|
364
532
|
const migration = new Migration(sequelize);
|
|
365
533
|
await migration.loadDatabaseTables();
|
|
366
534
|
await migration.checkDiffs();
|
|
367
535
|
if (!migration.upTables && !migration.upFields && !migration.upIndexes && !migration.upForeignKey) {
|
|
368
536
|
console.info('There\'s no changes between your models and the database.');
|
|
537
|
+
return undefined;
|
|
369
538
|
}
|
|
370
|
-
|
|
539
|
+
return migration.generateFile(migrationName, migrationsDir, previous);
|
|
371
540
|
}
|
|
372
541
|
const gina = {
|
|
373
|
-
runMigrations,
|
|
542
|
+
runMigrations: runner_1.runMigrations,
|
|
543
|
+
revertMigrations: runner_1.revertMigrations,
|
|
544
|
+
repairMigration: runner_1.repairMigration,
|
|
545
|
+
dryRunMigrations: runner_1.dryRunMigrations,
|
|
374
546
|
createMigration,
|
|
375
547
|
};
|
|
376
548
|
exports.default = gina;
|