gina-sequelize 0.0.9 → 0.0.11
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/.vscode/settings.json +5 -0
- package/README.md +50 -0
- package/bin/index.ts +14 -7
- package/dist/gina.js +27 -14
- package/dist/gina.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,55 @@
|
|
|
1
1
|
# Gina
|
|
2
2
|
|
|
3
|
+
Gina is a tool to auto-generate and run migrations based on Sequelize ORM.
|
|
4
|
+
|
|
5
|
+
## How to use it
|
|
6
|
+
|
|
7
|
+
### Install
|
|
8
|
+
|
|
9
|
+
You can install this using:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install gina-sequelize
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
You'll need to install it globally so you can you the gina-cli
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install -g gina-sequelize
|
|
19
|
+
# make sure to install ts-node too:
|
|
20
|
+
npm install -g ts-node
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Initialize Gina
|
|
24
|
+
|
|
25
|
+
If this is the first time you are running Gina on your project you'll need to initialize it.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
gina-cli init
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
This will generate a folder `gina` to your project.
|
|
32
|
+
Inside this folder you will find the file `initializeModels.ts`.
|
|
33
|
+
You will need to modify this file so that the `initializeModels` method inside it return a valid sequelize instance object that *has all your models ALREADY loaded*.
|
|
34
|
+
|
|
35
|
+
### Upgrade database
|
|
36
|
+
|
|
37
|
+
Once you have the `initializeModels` configured you can upgrade your database using:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
gina-cli upgrade
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Generating new migration
|
|
44
|
+
|
|
45
|
+
Once you have the `initializeModels` configured you can generate auto migrations.
|
|
46
|
+
It'll compare your loaded models with the database that you are connected.
|
|
47
|
+
All differences should be listed on a new migration file that will be placed inside the folder `gina/migrations`.
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
gina-cli generate-migration "Creating user table"
|
|
51
|
+
```
|
|
52
|
+
|
|
3
53
|
## Development
|
|
4
54
|
|
|
5
55
|
If you want to edit the cli and test it you can install it locally:
|
package/bin/index.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env ts-node
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
4
|
+
// @ts-nocheck
|
|
5
|
+
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
7
|
+
const yargs = require('yargs/yargs');
|
|
8
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
9
|
+
const { hideBin } = require('yargs/helpers');
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
11
|
+
const { readdir, mkdir, writeFile } = require('fs/promises');
|
|
12
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
13
|
+
const moment = require('moment');
|
|
7
14
|
|
|
8
15
|
async function createInitialFolder() {
|
|
9
16
|
const files = await readdir('.');
|
|
@@ -106,7 +113,7 @@ export { initializeModels };
|
|
|
106
113
|
|
|
107
114
|
}
|
|
108
115
|
|
|
109
|
-
async function generateMigration(migrationName
|
|
116
|
+
async function generateMigration(migrationName) {
|
|
110
117
|
try {
|
|
111
118
|
const pathName = process.cwd();
|
|
112
119
|
const initFile = await import(pathName + '/gina/initializeModels.ts');
|
|
@@ -143,7 +150,7 @@ async function upgrade() {
|
|
|
143
150
|
const files = (await readdir(pathName + '/gina/migrations')).filter(file => !file.includes('.d.ts') && !file.includes('.js.map'));
|
|
144
151
|
|
|
145
152
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
146
|
-
const migrations
|
|
153
|
+
const migrations = {};
|
|
147
154
|
|
|
148
155
|
for (const file of files) {
|
|
149
156
|
const filePath = await import(pathName + '/gina/migrations/' + file);
|
|
@@ -177,7 +184,7 @@ yargs(hideBin(process.argv))
|
|
|
177
184
|
describe: 'Name of the migration to be added'
|
|
178
185
|
});
|
|
179
186
|
}, (argv) => {
|
|
180
|
-
generateMigration(argv['migration-name']
|
|
187
|
+
generateMigration(argv['migration-name']);
|
|
181
188
|
})
|
|
182
189
|
.command('upgrade', 'upgrade database to its last revision', () => {
|
|
183
190
|
upgrade();
|
package/dist/gina.js
CHANGED
|
@@ -162,6 +162,32 @@ class Migration {
|
|
|
162
162
|
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\n\t\t});\n`);
|
|
163
163
|
this.downFields = tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\n`) + this.downFields;
|
|
164
164
|
}
|
|
165
|
+
columnAttributeProps(attribute) {
|
|
166
|
+
if (!this.imports.includes('DataTypes')) {
|
|
167
|
+
this.imports.push('DataTypes');
|
|
168
|
+
}
|
|
169
|
+
let attrProps = '';
|
|
170
|
+
console.log('attribute.defaultValue', attribute.defaultValue);
|
|
171
|
+
attrProps += tabsToSpace(`\n${tabs(3)}type: DataTypes.${attribute.type.replace('VARCHAR(', 'STRING(')},`);
|
|
172
|
+
if (attribute.autoIncrement !== null) {
|
|
173
|
+
attrProps += tabsToSpace(`\n${tabs(3)}autoIncrement: ${this.getAutoIncrement(attribute)},`);
|
|
174
|
+
}
|
|
175
|
+
if (attribute.allowNull !== null) {
|
|
176
|
+
attrProps += tabsToSpace(`\n${tabs(3)}allowNull: ${this.getAllowNull(attribute)},`);
|
|
177
|
+
}
|
|
178
|
+
if (attribute.primaryKey !== null) {
|
|
179
|
+
attrProps += tabsToSpace(`\n${tabs(3)}primaryKey: ${this.getPrimaryKey(attribute)},`);
|
|
180
|
+
}
|
|
181
|
+
if (attribute.defaultValue !== null) {
|
|
182
|
+
attrProps += tabsToSpace(`\n${tabs(3)}defaultValue: ${this.getDefaultValue(attribute)},`);
|
|
183
|
+
}
|
|
184
|
+
return attrProps;
|
|
185
|
+
}
|
|
186
|
+
dropColumn(tableName, field, attribute) {
|
|
187
|
+
console.debug(`drop column ${tableName} ${field} `);
|
|
188
|
+
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${field}');\n`);
|
|
189
|
+
this.downFields = tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${field}', {${this.columnAttributeProps(attribute)}\n\t\t});`) + this.downFields;
|
|
190
|
+
}
|
|
165
191
|
async checkDiffs() {
|
|
166
192
|
const models = Object.keys(this.sequelize.models);
|
|
167
193
|
const modelTableNames = [];
|
|
@@ -186,20 +212,7 @@ class Migration {
|
|
|
186
212
|
}
|
|
187
213
|
for (const attr of Object.keys(attrs)) {
|
|
188
214
|
if (!modelFields.includes(attr)) {
|
|
189
|
-
|
|
190
|
-
this.upFields += `;
|
|
191
|
-
await queryInterface.removeColumn('${modelTable}', '${attr}');
|
|
192
|
-
`;
|
|
193
|
-
if (!this.imports.includes('DataTypes')) {
|
|
194
|
-
this.imports.push('DataTypes');
|
|
195
|
-
}
|
|
196
|
-
this.downFields = `;
|
|
197
|
-
await queryInterface.addColumn('${modelTable}', '${attr}', {
|
|
198
|
-
type: DataTypes.${attrs[attr].type.replace('VARCHAR(', 'STRING(')},
|
|
199
|
-
allowNull: ${this.getAllowNull(attrs[attr])},
|
|
200
|
-
defaultValue: ${attrs[attr].defaultValue},
|
|
201
|
-
});
|
|
202
|
-
` + this.downFields;
|
|
215
|
+
this.dropColumn(modelTable, attr, attrs[attr]);
|
|
203
216
|
}
|
|
204
217
|
}
|
|
205
218
|
// TODO: add index and constraints
|
package/dist/gina.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gina.js","sourceRoot":"/","sources":["gina.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C","sourcesContent":["import { DataTypes, ModelCtor, Model, Sequelize, ModelAttributeColumnOptions, QueryTypes } from 'sequelize';\nimport fs from 'fs/promises';\nimport moment from 'moment';\nimport { MigrationFile } from './typings/migration';\n\ninterface MigrationFiles {\n [version: string]: { migration: MigrationFile; };\n}\n\nasync function runMigrations(sequelize: Sequelize, migrationFiles: MigrationFiles) {\n const tables = await sequelize.getQueryInterface().showAllTables();\n\n let version = '';\n\n if (tables.includes('gina_version')) {\n const versions: { version: string; }[] = await sequelize.query('SELECT version FROM gina_version;', {\n type: QueryTypes.SELECT,\n });\n\n if (versions.length > 1) {\n throw new Error('There must be only one version on `gina_version` table.');\n }\n\n version = versions.length == 1 ? versions[0].version : '';\n }\n\n console.info('current version:', version);\n\n for (const migrationFile of Object.keys(migrationFiles)) {\n if (migrationFile > version) {\n console.info('applying migration:', migrationFile);\n await migrationFiles[migrationFile].migration.up(sequelize.getQueryInterface());\n if (version) {\n version = migrationFile;\n await sequelize.query(`UPDATE gina_version SET version = '${version}', updatedAt = NOW();`);\n } else {\n version = migrationFile;\n await sequelize.query(`INSERT INTO gina_version (updatedAt, version) VALUES (NOW(),'${version}');`);\n }\n console.info('applied version:', migrationFile);\n }\n }\n}\n\nfunction tabsToSpace(str: string) {\n return str.replaceAll('\\t', ' ');\n}\n\nfunction tabs(qty: number) {\n let tabText = '';\n\n for (let i = 0; i < qty; i++) {\n tabText += '\\t';\n }\n\n return tabText;\n}\n\nclass Migration {\n upTables: string;\n downTables: string;\n upFields: string;\n downFields: string;\n upIndexes: string;\n downIndexes: string;\n private sequelize: Sequelize;\n tables: string[];\n imports: string[];\n\n constructor(sequelize: Sequelize) {\n this.upTables = '';\n this.downTables = '';\n this.upFields = '';\n this.downFields = '';\n this.upIndexes = '';\n this.downIndexes = '';\n\n /**\n *\n */\n this.tables = [];\n this.sequelize = sequelize;\n this.imports = ['QueryInterface'];\n }\n\n async loadDatabaseTables() {\n const queryInterface = this.sequelize.getQueryInterface();\n this.tables = await queryInterface.showAllTables();\n }\n\n dropTable(tableName: string) {\n // TODO: create proper logic to delete table\n console.debug(`drop table ${tableName} `);\n\n this.upTables += `\n await queryInterface.dropTable('${tableName}');\n`;\n\n this.downTables = `\n await queryInterface.createTable('${tableName}', {});\n` + this.downTables;\n }\n\n getAllowNull(model: { allowNull?: boolean; }) {\n return model.allowNull ?? 'true' ? 'true' : 'false';\n }\n\n getAutoIncrement(model: { autoIncrement?: boolean; }) {\n return model.autoIncrement ?? 'true' ? 'true' : 'false';\n }\n\n getPrimaryKey(model: { primaryKey?: boolean; }) {\n return model.primaryKey ?? 'true' ? 'true' : 'false';\n }\n\n getType(model: { type?: DataTypes.DataType; }) {\n if (model.type instanceof DataTypes.BIGINT) {\n return 'DataTypes.BIGINT';\n }\n if (model.type instanceof DataTypes.INTEGER) {\n return 'DataTypes.INTEGER';\n }\n if (model.type instanceof DataTypes.STRING) {\n return 'DataTypes.STRING';\n }\n if (model.type instanceof DataTypes.DATE) {\n return 'DataTypes.DATE';\n }\n if (model.type instanceof DataTypes.TEXT) {\n return 'DataTypes.TEXT';\n }\n return '';\n }\n\n getDefaultValue(model: { defaultValue?: unknown; }) {\n\n const val = (model.defaultValue as { val?: string; }).val;\n\n if (val) {\n if (!this.imports.includes('Sequelize')) {\n this.imports.push('Sequelize');\n }\n return `Sequelize.literal('${val}')`;\n } else if (typeof model.defaultValue == 'number') {\n return String(model.defaultValue);\n }\n\n return `'${model.defaultValue}'`;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n createTable(model: ModelCtor<Model<any, any>>) {\n // TODO: create proper logic to create table\n console.debug(`new table ${model.getTableName()}`);\n const modelAttrs = model.getAttributes();\n const modelAttrsKeys = Object.keys(modelAttrs);\n this.upTables += tabsToSpace(`\\n\\t\\tawait queryInterface.createTable('${model.getTableName()}', {\\n`);\n\n if (!this.imports.includes('DataTypes')) {\n this.imports.push('DataTypes');\n }\n\n for (const modelAttrsKey of modelAttrsKeys) {\n\n const attribute = modelAttrs[modelAttrsKey];\n\n if (attribute.type instanceof DataTypes.VIRTUAL) {\n continue;\n }\n\n this.upTables += tabsToSpace(`\\t\\t\\t${modelAttrsKey}: {${this.attributeProps(modelAttrs[modelAttrsKey], 4)}\\n\\t\\t\\t},\\n`);\n }\n\n this.upTables += tabsToSpace(`\\t\\t});`);\n\n this.downTables = tabsToSpace(`\\n\\t\\tawait queryInterface.dropTable('${model.getTableName()}');\\n`) + this.downTables;\n }\n\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attributeProps(attribute: ModelAttributeColumnOptions<Model<any, any>>, tabsQty: number) {\n\n if (!this.imports.includes('DataTypes')) {\n this.imports.push('DataTypes');\n }\n\n let attrProps = '';\n\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}type: ${this.getType(attribute)},`);\n if (attribute.autoIncrement !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}autoIncrement: ${this.getAutoIncrement(attribute)},`);\n }\n if (attribute.allowNull !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}allowNull: ${this.getAllowNull(attribute)},`);\n }\n if (attribute.primaryKey !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}primaryKey: ${this.getPrimaryKey(attribute)},`);\n }\n if (attribute.defaultValue !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);\n }\n\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}field: '${attribute.field}'`);\n\n return attrProps;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newColumn(tableName: string, attribute: ModelAttributeColumnOptions<Model<any, any>>) {\n console.debug(`new column ${tableName} ${attribute.field}`);\n this.upFields += tabsToSpace(`\\n\\t\\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\\n\\t\\t});\\n`);\n this.downFields = tabsToSpace(`\\n\\t\\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\\n`) + this.downFields;\n }\n\n async checkDiffs() {\n const models = Object.keys(this.sequelize.models);\n const modelTableNames: string[] = [];\n for (const model of models) {\n\n const modelTable = this.sequelize.models[model].getTableName() as string;\n modelTableNames.push(modelTable);\n\n // new table\n if (!this.tables.includes(modelTable)) {\n this.createTable(this.sequelize.models[model]);\n continue;\n }\n\n const modelAttrs = this.sequelize.models[model].getAttributes();\n const queryInterface = this.sequelize.getQueryInterface();\n const attrs = await queryInterface.describeTable(modelTable);\n\n const modelFields: string[] = [];\n\n // check each field\n for (const modelAttr of Object.keys(modelAttrs)) {\n modelFields.push(modelAttrs[modelAttr].field || modelAttr);\n if (!Object.keys(attrs).includes(modelAttrs[modelAttr].field || modelAttr) && !(modelAttrs[modelAttr].type instanceof DataTypes.VIRTUAL)) {\n this.newColumn(modelTable, modelAttrs[modelAttr]);\n }\n }\n\n for (const attr of Object.keys(attrs)) {\n if (!modelFields.includes(attr)) {\n console.debug(`drop column ${modelTable} ${attr} `);\n\n this.upFields += `;\n await queryInterface.removeColumn('${modelTable}', '${attr}');\n `;\n\n if (!this.imports.includes('DataTypes')) {\n this.imports.push('DataTypes');\n }\n\n this.downFields = `;\n await queryInterface.addColumn('${modelTable}', '${attr}', {\n type: DataTypes.${attrs[attr].type.replace('VARCHAR(', 'STRING(')},\n allowNull: ${this.getAllowNull(attrs[attr])},\n defaultValue: ${attrs[attr].defaultValue},\n });\n ` + this.downFields;\n }\n }\n\n // TODO: add index and constraints\n // sequelize.models[model].\n // console.debug('sequelize.models.GinaVersion.options.indexes', sequelize.models.GinaVersion.options.indexes);\n // console.log(sequelize.models[model]);\n\n }\n\n for (const table of this.tables) {\n if (!modelTableNames.includes(table) && table != 'gina_version') {\n this.dropTable(table);\n }\n }\n }\n\n async generateFile(migrationName: string) {\n const migration = `import { ${this.imports.join(', ')} } from 'sequelize';\n\nexport const migration = {\n async up(queryInterface: QueryInterface) {\n${this.upTables}\n${this.upFields}\n },\n\n async down(queryInterface: QueryInterface) {\n${this.downFields}\n${this.downTables}\n }\n};`;\n\n await fs.writeFile(`./gina/migrations/${moment().format('YYYYMMDDHHmmss')}-${migrationName.toLowerCase().replaceAll(' ', '-')}.ts`, migration);\n }\n}\n\nasync function createMigration(sequelize: Sequelize, migrationName: string) {\n\n const migration = new Migration(sequelize);\n await migration.loadDatabaseTables();\n\n await migration.checkDiffs();\n\n if (!migration.upTables && !migration.upFields && !migration.upIndexes) {\n console.info('There\\'s no changes between your models and the database.');\n return;\n }\n await migration.generateFile(migrationName);\n\n}\n\nconst gina = {\n runMigrations,\n createMigration,\n};\n\nexport default gina;\n"]}
|
|
1
|
+
{"version":3,"file":"gina.js","sourceRoot":"/","sources":["gina.ts"],"names":[],"mappings":";;;;;AAAA,yCAA+H;AAC/H,2DAA6B;AAC7B,oDAA4B;AAO5B,KAAK,UAAU,aAAa,CAAC,SAAoB,EAAE,cAA8B;IAC7E,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,iBAAiB,EAAE,CAAC,aAAa,EAAE,CAAC;IAEnE,IAAI,OAAO,GAAG,EAAE,CAAC;IAEjB,IAAI,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE;QACjC,MAAM,QAAQ,GAA2B,MAAM,SAAS,CAAC,KAAK,CAAC,mCAAmC,EAAE;YAChG,IAAI,EAAE,sBAAU,CAAC,MAAM;SAC1B,CAAC,CAAC;QAEH,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;SAC9E;QAED,OAAO,GAAG,QAAQ,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;KAC7D;IAED,OAAO,CAAC,IAAI,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAC;IAE1C,KAAK,MAAM,aAAa,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,EA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CAAC,QAAQ,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE;QACpE,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;QAC1E,OAAO;KACV;IACD,MAAM,SAAS,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;AAEhD,CAAC;AAED,MAAM,IAAI,GAAG;IACT,aAAa;IACb,eAAe;CAClB,CAAC;AAEF,kBAAe,IAAI,CAAC","sourcesContent":["import { DataTypes, ModelCtor, Model, Sequelize, ModelAttributeColumnOptions, QueryTypes, ColumnDescription } from 'sequelize';\nimport fs from 'fs/promises';\nimport moment from 'moment';\nimport { MigrationFile } from './typings/migration';\n\ninterface MigrationFiles {\n [version: string]: { migration: MigrationFile; };\n}\n\nasync function runMigrations(sequelize: Sequelize, migrationFiles: MigrationFiles) {\n const tables = await sequelize.getQueryInterface().showAllTables();\n\n let version = '';\n\n if (tables.includes('gina_version')) {\n const versions: { version: string; }[] = await sequelize.query('SELECT version FROM gina_version;', {\n type: QueryTypes.SELECT,\n });\n\n if (versions.length > 1) {\n throw new Error('There must be only one version on `gina_version` table.');\n }\n\n version = versions.length == 1 ? versions[0].version : '';\n }\n\n console.info('current version:', version);\n\n for (const migrationFile of Object.keys(migrationFiles)) {\n if (migrationFile > version) {\n console.info('applying migration:', migrationFile);\n await migrationFiles[migrationFile].migration.up(sequelize.getQueryInterface());\n if (version) {\n version = migrationFile;\n await sequelize.query(`UPDATE gina_version SET version = '${version}', updatedAt = NOW();`);\n } else {\n version = migrationFile;\n await sequelize.query(`INSERT INTO gina_version (updatedAt, version) VALUES (NOW(),'${version}');`);\n }\n console.info('applied version:', migrationFile);\n }\n }\n}\n\nfunction tabsToSpace(str: string) {\n return str.replaceAll('\\t', ' ');\n}\n\nfunction tabs(qty: number) {\n let tabText = '';\n\n for (let i = 0; i < qty; i++) {\n tabText += '\\t';\n }\n\n return tabText;\n}\n\nclass Migration {\n upTables: string;\n downTables: string;\n upFields: string;\n downFields: string;\n upIndexes: string;\n downIndexes: string;\n private sequelize: Sequelize;\n tables: string[];\n imports: string[];\n\n constructor(sequelize: Sequelize) {\n this.upTables = '';\n this.downTables = '';\n this.upFields = '';\n this.downFields = '';\n this.upIndexes = '';\n this.downIndexes = '';\n\n /**\n *\n */\n this.tables = [];\n this.sequelize = sequelize;\n this.imports = ['QueryInterface'];\n }\n\n async loadDatabaseTables() {\n const queryInterface = this.sequelize.getQueryInterface();\n this.tables = await queryInterface.showAllTables();\n }\n\n dropTable(tableName: string) {\n // TODO: create proper logic to delete table\n console.debug(`drop table ${tableName} `);\n\n this.upTables += `\n await queryInterface.dropTable('${tableName}');\n`;\n\n this.downTables = `\n await queryInterface.createTable('${tableName}', {});\n` + this.downTables;\n }\n\n getAllowNull(model: { allowNull?: boolean; }) {\n return model.allowNull ?? 'true' ? 'true' : 'false';\n }\n\n getAutoIncrement(model: { autoIncrement?: boolean; }) {\n return model.autoIncrement ?? 'true' ? 'true' : 'false';\n }\n\n getPrimaryKey(model: { primaryKey?: boolean; }) {\n return model.primaryKey ?? 'true' ? 'true' : 'false';\n }\n\n getType(model: { type?: DataTypes.DataType; }) {\n if (model.type instanceof DataTypes.BIGINT) {\n return 'DataTypes.BIGINT';\n }\n if (model.type instanceof DataTypes.INTEGER) {\n return 'DataTypes.INTEGER';\n }\n if (model.type instanceof DataTypes.STRING) {\n return 'DataTypes.STRING';\n }\n if (model.type instanceof DataTypes.DATE) {\n return 'DataTypes.DATE';\n }\n if (model.type instanceof DataTypes.TEXT) {\n return 'DataTypes.TEXT';\n }\n return '';\n }\n\n getDefaultValue(model: { defaultValue?: unknown; }) {\n\n const val = (model.defaultValue as { val?: string; }).val;\n\n if (val) {\n if (!this.imports.includes('Sequelize')) {\n this.imports.push('Sequelize');\n }\n return `Sequelize.literal('${val}')`;\n } else if (typeof model.defaultValue == 'number') {\n return String(model.defaultValue);\n }\n\n return `'${model.defaultValue}'`;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n createTable(model: ModelCtor<Model<any, any>>) {\n // TODO: create proper logic to create table\n console.debug(`new table ${model.getTableName()}`);\n const modelAttrs = model.getAttributes();\n const modelAttrsKeys = Object.keys(modelAttrs);\n this.upTables += tabsToSpace(`\\n\\t\\tawait queryInterface.createTable('${model.getTableName()}', {\\n`);\n\n if (!this.imports.includes('DataTypes')) {\n this.imports.push('DataTypes');\n }\n\n for (const modelAttrsKey of modelAttrsKeys) {\n\n const attribute = modelAttrs[modelAttrsKey];\n\n if (attribute.type instanceof DataTypes.VIRTUAL) {\n continue;\n }\n\n this.upTables += tabsToSpace(`\\t\\t\\t${modelAttrsKey}: {${this.attributeProps(modelAttrs[modelAttrsKey], 4)}\\n\\t\\t\\t},\\n`);\n }\n\n this.upTables += tabsToSpace(`\\t\\t});`);\n\n this.downTables = tabsToSpace(`\\n\\t\\tawait queryInterface.dropTable('${model.getTableName()}');\\n`) + this.downTables;\n }\n\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attributeProps(attribute: ModelAttributeColumnOptions<Model<any, any>>, tabsQty: number) {\n\n if (!this.imports.includes('DataTypes')) {\n this.imports.push('DataTypes');\n }\n\n let attrProps = '';\n\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}type: ${this.getType(attribute)},`);\n if (attribute.autoIncrement !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}autoIncrement: ${this.getAutoIncrement(attribute)},`);\n }\n if (attribute.allowNull !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}allowNull: ${this.getAllowNull(attribute)},`);\n }\n if (attribute.primaryKey !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}primaryKey: ${this.getPrimaryKey(attribute)},`);\n }\n if (attribute.defaultValue !== undefined) {\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);\n }\n\n attrProps += tabsToSpace(`\\n${tabs(tabsQty)}field: '${attribute.field}'`);\n\n return attrProps;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newColumn(tableName: string, attribute: ModelAttributeColumnOptions<Model<any, any>>) {\n console.debug(`new column ${tableName} ${attribute.field}`);\n this.upFields += tabsToSpace(`\\n\\t\\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\\n\\t\\t});\\n`);\n this.downFields = tabsToSpace(`\\n\\t\\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\\n`) + this.downFields;\n }\n\n columnAttributeProps(attribute: ColumnDescription) {\n if (!this.imports.includes('DataTypes')) {\n this.imports.push('DataTypes');\n }\n\n let attrProps = '';\n\n console.log('attribute.defaultValue', attribute.defaultValue);\n\n attrProps += tabsToSpace(`\\n${tabs(3)}type: DataTypes.${attribute.type.replace('VARCHAR(', 'STRING(')},`);\n if (attribute.autoIncrement !== null) {\n attrProps += tabsToSpace(`\\n${tabs(3)}autoIncrement: ${this.getAutoIncrement(attribute)},`);\n }\n if (attribute.allowNull !== null) {\n attrProps += tabsToSpace(`\\n${tabs(3)}allowNull: ${this.getAllowNull(attribute)},`);\n }\n if (attribute.primaryKey !== null) {\n attrProps += tabsToSpace(`\\n${tabs(3)}primaryKey: ${this.getPrimaryKey(attribute)},`);\n }\n if (attribute.defaultValue !== null) {\n attrProps += tabsToSpace(`\\n${tabs(3)}defaultValue: ${this.getDefaultValue(attribute)},`);\n }\n\n return attrProps;\n }\n\n dropColumn(tableName: string, field: string, attribute: ColumnDescription) {\n console.debug(`drop column ${tableName} ${field} `);\n this.upFields += tabsToSpace(`\\n\\t\\tawait queryInterface.removeColumn('${tableName}', '${field}');\\n`);\n this.downFields = tabsToSpace(`\\n\\t\\tawait queryInterface.addColumn('${tableName}', '${field}', {${this.columnAttributeProps(attribute)}\\n\\t\\t});`) + this.downFields;\n }\n\n async checkDiffs() {\n const models = Object.keys(this.sequelize.models);\n const modelTableNames: string[] = [];\n for (const model of models) {\n\n const modelTable = this.sequelize.models[model].getTableName() as string;\n modelTableNames.push(modelTable);\n\n // new table\n if (!this.tables.includes(modelTable)) {\n this.createTable(this.sequelize.models[model]);\n continue;\n }\n\n const modelAttrs = this.sequelize.models[model].getAttributes();\n const queryInterface = this.sequelize.getQueryInterface();\n const attrs = await queryInterface.describeTable(modelTable);\n\n const modelFields: string[] = [];\n\n // check each field\n for (const modelAttr of Object.keys(modelAttrs)) {\n modelFields.push(modelAttrs[modelAttr].field || modelAttr);\n if (!Object.keys(attrs).includes(modelAttrs[modelAttr].field || modelAttr) && !(modelAttrs[modelAttr].type instanceof DataTypes.VIRTUAL)) {\n this.newColumn(modelTable, modelAttrs[modelAttr]);\n }\n }\n\n for (const attr of Object.keys(attrs)) {\n if (!modelFields.includes(attr)) {\n this.dropColumn(modelTable, attr, attrs[attr]);\n }\n }\n\n // TODO: add index and constraints\n // sequelize.models[model].\n // console.debug('sequelize.models.GinaVersion.options.indexes', sequelize.models.GinaVersion.options.indexes);\n // console.log(sequelize.models[model]);\n\n }\n\n for (const table of this.tables) {\n if (!modelTableNames.includes(table) && table != 'gina_version') {\n this.dropTable(table);\n }\n }\n }\n\n async generateFile(migrationName: string) {\n const migration = `import { ${this.imports.join(', ')} } from 'sequelize';\n\nexport const migration = {\n async up(queryInterface: QueryInterface) {\n${this.upTables}\n${this.upFields}\n },\n\n async down(queryInterface: QueryInterface) {\n${this.downFields}\n${this.downTables}\n }\n};`;\n\n await fs.writeFile(`./gina/migrations/${moment().format('YYYYMMDDHHmmss')}-${migrationName.toLowerCase().replaceAll(' ', '-')}.ts`, migration);\n }\n}\n\nasync function createMigration(sequelize: Sequelize, migrationName: string) {\n\n const migration = new Migration(sequelize);\n await migration.loadDatabaseTables();\n\n await migration.checkDiffs();\n\n if (!migration.upTables && !migration.upFields && !migration.upIndexes) {\n console.info('There\\'s no changes between your models and the database.');\n return;\n }\n await migration.generateFile(migrationName);\n\n}\n\nconst gina = {\n runMigrations,\n createMigration,\n};\n\nexport default gina;\n"]}
|
package/package.json
CHANGED