gina-sequelize 0.0.8 → 0.0.10
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/.eslintrc +3 -3
- package/README.md +59 -1
- package/bin/index.ts +185 -0
- package/dist/gina.d.ts +8 -2
- package/dist/gina.js +230 -95
- package/dist/gina.js.map +1 -1
- package/package.json +8 -4
- package/main.ts +0 -58
- package/models/gina-version.ts +0 -38
- package/typings/migration.d.ts +0 -4
package/.eslintrc
CHANGED
package/README.md
CHANGED
|
@@ -1 +1,59 @@
|
|
|
1
|
-
# Gina
|
|
1
|
+
# Gina
|
|
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
|
+
|
|
53
|
+
## Development
|
|
54
|
+
|
|
55
|
+
If you want to edit the cli and test it you can install it locally:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npm install -g .
|
|
59
|
+
```
|
package/bin/index.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
#!/usr/bin/env ts-node
|
|
2
|
+
|
|
3
|
+
import yargs from 'yargs/yargs';
|
|
4
|
+
import { hideBin } from 'yargs/helpers';
|
|
5
|
+
import { readdir, mkdir, writeFile } from 'fs/promises';
|
|
6
|
+
import moment from 'moment';
|
|
7
|
+
|
|
8
|
+
async function createInitialFolder() {
|
|
9
|
+
const files = await readdir('.');
|
|
10
|
+
if (files.includes('gina')) {
|
|
11
|
+
console.info('There\'s already a folder/file named gina on your folder indicating that gina is already initialized.');
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
await mkdir('gina');
|
|
16
|
+
await mkdir('gina/migrations');
|
|
17
|
+
await writeFile(`gina/migrations/${moment().format('YYYYMMDDHHmmss') + '-add-version-control-table.ts'}`, `import { QueryInterface, DataTypes } from 'sequelize';
|
|
18
|
+
|
|
19
|
+
export const migration = {
|
|
20
|
+
async up(queryInterface: QueryInterface) {
|
|
21
|
+
|
|
22
|
+
await queryInterface.createTable('gina_version', {
|
|
23
|
+
id: {
|
|
24
|
+
type: DataTypes.INTEGER,
|
|
25
|
+
autoIncrement: true,
|
|
26
|
+
primaryKey: true,
|
|
27
|
+
field: 'id'
|
|
28
|
+
},
|
|
29
|
+
version: {
|
|
30
|
+
type: DataTypes.STRING,
|
|
31
|
+
allowNull: false,
|
|
32
|
+
field: 'version'
|
|
33
|
+
},
|
|
34
|
+
createdAt: {
|
|
35
|
+
type: DataTypes.DATE,
|
|
36
|
+
field: 'createdAt'
|
|
37
|
+
},
|
|
38
|
+
updatedAt: {
|
|
39
|
+
type: DataTypes.DATE,
|
|
40
|
+
field: 'updatedAt'
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
async down(queryInterface: QueryInterface) {
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
await queryInterface.dropTable('gina_version');
|
|
50
|
+
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
`);
|
|
54
|
+
|
|
55
|
+
await writeFile('gina/initializeModels.ts', `import dotenv from 'dotenv';
|
|
56
|
+
dotenv.config();
|
|
57
|
+
|
|
58
|
+
import { Sequelize, Transaction } from 'sequelize';
|
|
59
|
+
import path from 'path';
|
|
60
|
+
import fs from 'fs/promises';
|
|
61
|
+
|
|
62
|
+
const modelsDir = path.join(__dirname + '/models');
|
|
63
|
+
|
|
64
|
+
const POOL_MAX_CONNECTIONS = 50;
|
|
65
|
+
const POOL_IDLE_TIME = 12000;
|
|
66
|
+
const POOL_ACQUIRE_TIME = 30000;
|
|
67
|
+
|
|
68
|
+
const sequelize = new Sequelize({
|
|
69
|
+
host: process.env.DB_HOST,
|
|
70
|
+
database: process.env.DB_NAME,
|
|
71
|
+
username: process.env.DB_USERNAME,
|
|
72
|
+
password: process.env.DB_PASSWORD,
|
|
73
|
+
dialect: 'mysql',
|
|
74
|
+
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED,
|
|
75
|
+
pool: {
|
|
76
|
+
max: POOL_MAX_CONNECTIONS,
|
|
77
|
+
min: 0,
|
|
78
|
+
idle: POOL_IDLE_TIME,
|
|
79
|
+
evict: POOL_IDLE_TIME - 2000,
|
|
80
|
+
acquire: POOL_ACQUIRE_TIME
|
|
81
|
+
},
|
|
82
|
+
logging: console.info
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
async function initializeModels() {
|
|
86
|
+
|
|
87
|
+
const files = (await fs.readdir(modelsDir)).filter(file => !file.includes('.d.ts') && !file.includes('.js.map'));
|
|
88
|
+
const associations: (() => void)[] = [];
|
|
89
|
+
|
|
90
|
+
for (const file of files) {
|
|
91
|
+
const filePath = path.join(modelsDir, file);
|
|
92
|
+
const model = await import(filePath.replace('.js', ''));
|
|
93
|
+
associations.push(model.initializeModel(sequelize));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
for (const association of associations) {
|
|
97
|
+
association();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return sequelize;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
export { initializeModels };
|
|
105
|
+
`);
|
|
106
|
+
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function generateMigration(migrationName: string) {
|
|
110
|
+
try {
|
|
111
|
+
const pathName = process.cwd();
|
|
112
|
+
const initFile = await import(pathName + '/gina/initializeModels.ts');
|
|
113
|
+
|
|
114
|
+
console.log('loading models...');
|
|
115
|
+
const sequelize = await initFile.initializeModels();
|
|
116
|
+
|
|
117
|
+
console.log('loading gina lib...');
|
|
118
|
+
try {
|
|
119
|
+
const ginaLib = await import(pathName + '/node_modules/gina-sequelize/dist/gina.js');
|
|
120
|
+
await ginaLib.default.createMigration(sequelize, migrationName);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
const ginaLib = await import(pathName + '/lib/gina.ts');
|
|
123
|
+
await ginaLib.default.createMigration(sequelize, migrationName);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
process.exit();
|
|
127
|
+
} catch (err) {
|
|
128
|
+
console.error(err);
|
|
129
|
+
process.exit(1);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function upgrade() {
|
|
135
|
+
try {
|
|
136
|
+
const pathName = process.cwd();
|
|
137
|
+
const initFile = await import(pathName + '/gina/initializeModels.ts');
|
|
138
|
+
|
|
139
|
+
console.log('loading models...');
|
|
140
|
+
const sequelize = await initFile.initializeModels();
|
|
141
|
+
|
|
142
|
+
console.log('loading migrations...');
|
|
143
|
+
const files = (await readdir(pathName + '/gina/migrations')).filter(file => !file.includes('.d.ts') && !file.includes('.js.map'));
|
|
144
|
+
|
|
145
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
146
|
+
const migrations: { [file: string]: any; } = {};
|
|
147
|
+
|
|
148
|
+
for (const file of files) {
|
|
149
|
+
const filePath = await import(pathName + '/gina/migrations/' + file);
|
|
150
|
+
migrations[file.replace('.ts', '')] = filePath;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
console.log('loading gina lib...');
|
|
154
|
+
try {
|
|
155
|
+
const ginaLib = await import(pathName + '/node_modules/gina-sequelize/dist/gina.js');
|
|
156
|
+
await ginaLib.default.runMigrations(sequelize, migrations);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
const ginaLib = await import(pathName + '/lib/gina.ts');
|
|
159
|
+
await ginaLib.default.runMigrations(sequelize, migrations);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
process.exit();
|
|
163
|
+
} catch (err) {
|
|
164
|
+
console.error(err);
|
|
165
|
+
process.exit(1);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
yargs(hideBin(process.argv))
|
|
171
|
+
.command('init', 'creates initial folder and files for gina', () => {
|
|
172
|
+
createInitialFolder();
|
|
173
|
+
})
|
|
174
|
+
.command('generate-migration [migration-name]', 'Generates a new migration file to add the differences between models and database', (yargs) => {
|
|
175
|
+
return yargs
|
|
176
|
+
.positional('migration-name', {
|
|
177
|
+
describe: 'Name of the migration to be added'
|
|
178
|
+
});
|
|
179
|
+
}, (argv) => {
|
|
180
|
+
generateMigration(argv['migration-name'] as string);
|
|
181
|
+
})
|
|
182
|
+
.command('upgrade', 'upgrade database to its last revision', () => {
|
|
183
|
+
upgrade();
|
|
184
|
+
})
|
|
185
|
+
.parse();
|
package/dist/gina.d.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { Sequelize } from 'sequelize';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import { MigrationFile } from './typings/migration';
|
|
3
|
+
interface MigrationFiles {
|
|
4
|
+
[version: string]: {
|
|
5
|
+
migration: MigrationFile;
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
declare function runMigrations(sequelize: Sequelize, migrationFiles: MigrationFiles): Promise<void>;
|
|
9
|
+
declare function createMigration(sequelize: Sequelize, migrationName: string): Promise<void>;
|
|
4
10
|
declare const gina: {
|
|
5
11
|
runMigrations: typeof runMigrations;
|
|
6
12
|
createMigration: typeof createMigration;
|
package/dist/gina.js
CHANGED
|
@@ -6,117 +6,252 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
const sequelize_1 = require("sequelize");
|
|
7
7
|
const promises_1 = __importDefault(require("fs/promises"));
|
|
8
8
|
const moment_1 = __importDefault(require("moment"));
|
|
9
|
-
function runMigrations() {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const tables = await queryInterface.showAllTables();
|
|
16
|
-
const modelTables = [];
|
|
17
|
-
let upTables = '';
|
|
18
|
-
let downTables = '';
|
|
19
|
-
let up = '';
|
|
20
|
-
let down = '';
|
|
21
|
-
const imports = ['QueryInterface'];
|
|
22
|
-
for (const model of models) {
|
|
23
|
-
const modelTable = sequelize.models[model].getTableName();
|
|
24
|
-
modelTables.push(modelTable);
|
|
25
|
-
if (!tables.includes(modelTable)) {
|
|
26
|
-
// TODO: create proper logic to create table
|
|
27
|
-
console.debug(`new table ${modelTable}`);
|
|
28
|
-
// console.debug('sequelize.models[model].getAttributes()', sequelize.models[model].getAttributes());
|
|
29
|
-
upTables += `
|
|
30
|
-
await queryInterface.createTable('${modelTable}', {});
|
|
31
|
-
`;
|
|
32
|
-
downTables = `
|
|
33
|
-
await queryInterface.dropTable('${modelTable}');
|
|
34
|
-
` + downTables;
|
|
35
|
-
continue;
|
|
36
|
-
}
|
|
37
|
-
const modelAttrs = sequelize.models[model].getAttributes();
|
|
38
|
-
const attrs = await queryInterface.describeTable(modelTable);
|
|
39
|
-
const modelFields = [];
|
|
40
|
-
for (const modelAttr of Object.keys(modelAttrs)) {
|
|
41
|
-
modelFields.push(modelAttrs[modelAttr].field || modelAttr);
|
|
42
|
-
if (!Object.keys(attrs).includes(modelAttrs[modelAttr].field || modelAttr) && !(modelAttrs[modelAttr].type instanceof sequelize_1.DataTypes.VIRTUAL)) {
|
|
43
|
-
console.debug(`new column ${modelTable} ${modelAttr}`);
|
|
44
|
-
// console.debug(modelAttrs[modelAttr]);
|
|
45
|
-
const val = modelAttrs[modelAttr].defaultValue.val;
|
|
46
|
-
let defaultValue;
|
|
47
|
-
if (val) {
|
|
48
|
-
if (!imports.includes('Sequelize')) {
|
|
49
|
-
imports.push('Sequelize');
|
|
50
|
-
}
|
|
51
|
-
defaultValue = 'Sequelize.literal(\'CURRENT_TIMESTAMP\')';
|
|
52
|
-
}
|
|
53
|
-
else {
|
|
54
|
-
defaultValue = modelAttrs[modelAttr].defaultValue;
|
|
55
|
-
}
|
|
56
|
-
if (!imports.includes('DataTypes')) {
|
|
57
|
-
imports.push('DataTypes');
|
|
58
|
-
}
|
|
59
|
-
up += `
|
|
60
|
-
await queryInterface.addColumn('${modelTable}', '${modelAttrs[modelAttr].field}', {
|
|
61
|
-
type: DataTypes.${modelAttrs[modelAttr].type instanceof sequelize_1.DataTypes.DATE ? 'DATE' : ''},
|
|
62
|
-
allowNull: ${modelAttrs[modelAttr].allowNull},
|
|
63
|
-
defaultValue: ${defaultValue}
|
|
9
|
+
async function runMigrations(sequelize, migrationFiles) {
|
|
10
|
+
const tables = await sequelize.getQueryInterface().showAllTables();
|
|
11
|
+
let version = '';
|
|
12
|
+
if (tables.includes('gina_version')) {
|
|
13
|
+
const versions = await sequelize.query('SELECT version FROM gina_version;', {
|
|
14
|
+
type: sequelize_1.QueryTypes.SELECT,
|
|
64
15
|
});
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
16
|
+
if (versions.length > 1) {
|
|
17
|
+
throw new Error('There must be only one version on `gina_version` table.');
|
|
18
|
+
}
|
|
19
|
+
version = versions.length == 1 ? versions[0].version : '';
|
|
20
|
+
}
|
|
21
|
+
console.info('current version:', version);
|
|
22
|
+
for (const migrationFile of Object.keys(migrationFiles)) {
|
|
23
|
+
if (migrationFile > version) {
|
|
24
|
+
console.info('applying migration:', migrationFile);
|
|
25
|
+
await migrationFiles[migrationFile].migration.up(sequelize.getQueryInterface());
|
|
26
|
+
if (version) {
|
|
27
|
+
version = migrationFile;
|
|
28
|
+
await sequelize.query(`UPDATE gina_version SET version = '${version}', updatedAt = NOW();`);
|
|
69
29
|
}
|
|
30
|
+
else {
|
|
31
|
+
version = migrationFile;
|
|
32
|
+
await sequelize.query(`INSERT INTO gina_version (updatedAt, version) VALUES (NOW(),'${version}');`);
|
|
33
|
+
}
|
|
34
|
+
console.info('applied version:', migrationFile);
|
|
70
35
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function tabsToSpace(str) {
|
|
39
|
+
return str.replaceAll('\t', ' ');
|
|
40
|
+
}
|
|
41
|
+
function tabs(qty) {
|
|
42
|
+
let tabText = '';
|
|
43
|
+
for (let i = 0; i < qty; i++) {
|
|
44
|
+
tabText += '\t';
|
|
45
|
+
}
|
|
46
|
+
return tabText;
|
|
47
|
+
}
|
|
48
|
+
class Migration {
|
|
49
|
+
constructor(sequelize) {
|
|
50
|
+
this.upTables = '';
|
|
51
|
+
this.downTables = '';
|
|
52
|
+
this.upFields = '';
|
|
53
|
+
this.downFields = '';
|
|
54
|
+
this.upIndexes = '';
|
|
55
|
+
this.downIndexes = '';
|
|
56
|
+
/**
|
|
57
|
+
*
|
|
58
|
+
*/
|
|
59
|
+
this.tables = [];
|
|
60
|
+
this.sequelize = sequelize;
|
|
61
|
+
this.imports = ['QueryInterface'];
|
|
62
|
+
}
|
|
63
|
+
async loadDatabaseTables() {
|
|
64
|
+
const queryInterface = this.sequelize.getQueryInterface();
|
|
65
|
+
this.tables = await queryInterface.showAllTables();
|
|
66
|
+
}
|
|
67
|
+
dropTable(tableName) {
|
|
68
|
+
// TODO: create proper logic to delete table
|
|
69
|
+
console.debug(`drop table ${tableName} `);
|
|
70
|
+
this.upTables += `
|
|
71
|
+
await queryInterface.dropTable('${tableName}');
|
|
76
72
|
`;
|
|
77
|
-
|
|
78
|
-
|
|
73
|
+
this.downTables = `
|
|
74
|
+
await queryInterface.createTable('${tableName}', {});
|
|
75
|
+
` + this.downTables;
|
|
76
|
+
}
|
|
77
|
+
getAllowNull(model) {
|
|
78
|
+
return model.allowNull ?? 'true' ? 'true' : 'false';
|
|
79
|
+
}
|
|
80
|
+
getAutoIncrement(model) {
|
|
81
|
+
return model.autoIncrement ?? 'true' ? 'true' : 'false';
|
|
82
|
+
}
|
|
83
|
+
getPrimaryKey(model) {
|
|
84
|
+
return model.primaryKey ?? 'true' ? 'true' : 'false';
|
|
85
|
+
}
|
|
86
|
+
getType(model) {
|
|
87
|
+
if (model.type instanceof sequelize_1.DataTypes.BIGINT) {
|
|
88
|
+
return 'DataTypes.BIGINT';
|
|
89
|
+
}
|
|
90
|
+
if (model.type instanceof sequelize_1.DataTypes.INTEGER) {
|
|
91
|
+
return 'DataTypes.INTEGER';
|
|
92
|
+
}
|
|
93
|
+
if (model.type instanceof sequelize_1.DataTypes.STRING) {
|
|
94
|
+
return 'DataTypes.STRING';
|
|
95
|
+
}
|
|
96
|
+
if (model.type instanceof sequelize_1.DataTypes.DATE) {
|
|
97
|
+
return 'DataTypes.DATE';
|
|
98
|
+
}
|
|
99
|
+
if (model.type instanceof sequelize_1.DataTypes.TEXT) {
|
|
100
|
+
return 'DataTypes.TEXT';
|
|
101
|
+
}
|
|
102
|
+
return '';
|
|
103
|
+
}
|
|
104
|
+
getDefaultValue(model) {
|
|
105
|
+
const val = model.defaultValue.val;
|
|
106
|
+
if (val) {
|
|
107
|
+
if (!this.imports.includes('Sequelize')) {
|
|
108
|
+
this.imports.push('Sequelize');
|
|
109
|
+
}
|
|
110
|
+
return `Sequelize.literal('${val}')`;
|
|
111
|
+
}
|
|
112
|
+
else if (typeof model.defaultValue == 'number') {
|
|
113
|
+
return String(model.defaultValue);
|
|
114
|
+
}
|
|
115
|
+
return `'${model.defaultValue}'`;
|
|
116
|
+
}
|
|
117
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
118
|
+
createTable(model) {
|
|
119
|
+
// TODO: create proper logic to create table
|
|
120
|
+
console.debug(`new table ${model.getTableName()}`);
|
|
121
|
+
const modelAttrs = model.getAttributes();
|
|
122
|
+
const modelAttrsKeys = Object.keys(modelAttrs);
|
|
123
|
+
this.upTables += tabsToSpace(`\n\t\tawait queryInterface.createTable('${model.getTableName()}', {\n`);
|
|
124
|
+
if (!this.imports.includes('DataTypes')) {
|
|
125
|
+
this.imports.push('DataTypes');
|
|
126
|
+
}
|
|
127
|
+
for (const modelAttrsKey of modelAttrsKeys) {
|
|
128
|
+
const attribute = modelAttrs[modelAttrsKey];
|
|
129
|
+
if (attribute.type instanceof sequelize_1.DataTypes.VIRTUAL) {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
this.upTables += tabsToSpace(`\t\t\t${modelAttrsKey}: {${this.attributeProps(modelAttrs[modelAttrsKey], 4)}\n\t\t\t},\n`);
|
|
133
|
+
}
|
|
134
|
+
this.upTables += tabsToSpace(`\t\t});`);
|
|
135
|
+
this.downTables = tabsToSpace(`\n\t\tawait queryInterface.dropTable('${model.getTableName()}');\n`) + this.downTables;
|
|
136
|
+
}
|
|
137
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
138
|
+
attributeProps(attribute, tabsQty) {
|
|
139
|
+
if (!this.imports.includes('DataTypes')) {
|
|
140
|
+
this.imports.push('DataTypes');
|
|
141
|
+
}
|
|
142
|
+
let attrProps = '';
|
|
143
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}type: ${this.getType(attribute)},`);
|
|
144
|
+
if (attribute.autoIncrement !== undefined) {
|
|
145
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}autoIncrement: ${this.getAutoIncrement(attribute)},`);
|
|
146
|
+
}
|
|
147
|
+
if (attribute.allowNull !== undefined) {
|
|
148
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}allowNull: ${this.getAllowNull(attribute)},`);
|
|
149
|
+
}
|
|
150
|
+
if (attribute.primaryKey !== undefined) {
|
|
151
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}primaryKey: ${this.getPrimaryKey(attribute)},`);
|
|
152
|
+
}
|
|
153
|
+
if (attribute.defaultValue !== undefined) {
|
|
154
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}defaultValue: ${this.getDefaultValue(attribute)},`);
|
|
155
|
+
}
|
|
156
|
+
attrProps += tabsToSpace(`\n${tabs(tabsQty)}field: '${attribute.field}'`);
|
|
157
|
+
return attrProps;
|
|
158
|
+
}
|
|
159
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
160
|
+
newColumn(tableName, attribute) {
|
|
161
|
+
console.debug(`new column ${tableName} ${attribute.field}`);
|
|
162
|
+
this.upFields += tabsToSpace(`\n\t\tawait queryInterface.addColumn('${tableName}', '${attribute.field}', {${this.attributeProps(attribute, 3)}\n\t\t});\n`);
|
|
163
|
+
this.downFields = tabsToSpace(`\n\t\tawait queryInterface.removeColumn('${tableName}', '${attribute.field}');\n`) + this.downFields;
|
|
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
|
+
}
|
|
191
|
+
async checkDiffs() {
|
|
192
|
+
const models = Object.keys(this.sequelize.models);
|
|
193
|
+
const modelTableNames = [];
|
|
194
|
+
for (const model of models) {
|
|
195
|
+
const modelTable = this.sequelize.models[model].getTableName();
|
|
196
|
+
modelTableNames.push(modelTable);
|
|
197
|
+
// new table
|
|
198
|
+
if (!this.tables.includes(modelTable)) {
|
|
199
|
+
this.createTable(this.sequelize.models[model]);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const modelAttrs = this.sequelize.models[model].getAttributes();
|
|
203
|
+
const queryInterface = this.sequelize.getQueryInterface();
|
|
204
|
+
const attrs = await queryInterface.describeTable(modelTable);
|
|
205
|
+
const modelFields = [];
|
|
206
|
+
// check each field
|
|
207
|
+
for (const modelAttr of Object.keys(modelAttrs)) {
|
|
208
|
+
modelFields.push(modelAttrs[modelAttr].field || modelAttr);
|
|
209
|
+
if (!Object.keys(attrs).includes(modelAttrs[modelAttr].field || modelAttr) && !(modelAttrs[modelAttr].type instanceof sequelize_1.DataTypes.VIRTUAL)) {
|
|
210
|
+
this.newColumn(modelTable, modelAttrs[modelAttr]);
|
|
79
211
|
}
|
|
80
|
-
down = `
|
|
81
|
-
await queryInterface.addColumn('${modelTable}', '${attr}', {
|
|
82
|
-
type: DataTypes.${attrs[attr].type.replace('VARCHAR(', 'STRING(')},
|
|
83
|
-
allowNull: ${attrs[attr].allowNull ? 'true' : 'false'},
|
|
84
|
-
defaultValue: ${attrs[attr].defaultValue},
|
|
85
|
-
});
|
|
86
|
-
` + down;
|
|
87
212
|
}
|
|
213
|
+
for (const attr of Object.keys(attrs)) {
|
|
214
|
+
if (!modelFields.includes(attr)) {
|
|
215
|
+
this.dropColumn(modelTable, attr, attrs[attr]);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// TODO: add index and constraints
|
|
219
|
+
// sequelize.models[model].
|
|
220
|
+
// console.debug('sequelize.models.GinaVersion.options.indexes', sequelize.models.GinaVersion.options.indexes);
|
|
221
|
+
// console.log(sequelize.models[model]);
|
|
88
222
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
94
|
-
for (const table of tables) {
|
|
95
|
-
if (!modelTables.includes(table)) {
|
|
96
|
-
// TODO: create proper logic to delete table
|
|
97
|
-
console.debug(`drop table ${table} `);
|
|
98
|
-
upTables += `
|
|
99
|
-
await queryInterface.dropTable('${table}');
|
|
100
|
-
`;
|
|
101
|
-
downTables = `
|
|
102
|
-
await queryInterface.createTable('${table}', {});
|
|
103
|
-
` + downTables;
|
|
223
|
+
for (const table of this.tables) {
|
|
224
|
+
if (!modelTableNames.includes(table) && table != 'gina_version') {
|
|
225
|
+
this.dropTable(table);
|
|
226
|
+
}
|
|
104
227
|
}
|
|
105
228
|
}
|
|
106
|
-
|
|
229
|
+
async generateFile(migrationName) {
|
|
230
|
+
const migration = `import { ${this.imports.join(', ')} } from 'sequelize';
|
|
107
231
|
|
|
108
|
-
export const migration
|
|
232
|
+
export const migration = {
|
|
109
233
|
async up(queryInterface: QueryInterface) {
|
|
110
|
-
${upTables}
|
|
111
|
-
${
|
|
234
|
+
${this.upTables}
|
|
235
|
+
${this.upFields}
|
|
112
236
|
},
|
|
113
237
|
|
|
114
238
|
async down(queryInterface: QueryInterface) {
|
|
115
|
-
${
|
|
116
|
-
${downTables}
|
|
239
|
+
${this.downFields}
|
|
240
|
+
${this.downTables}
|
|
117
241
|
}
|
|
118
242
|
};`;
|
|
119
|
-
|
|
243
|
+
await promises_1.default.writeFile(`./gina/migrations/${(0, moment_1.default)().format('YYYYMMDDHHmmss')}-${migrationName.toLowerCase().replaceAll(' ', '-')}.ts`, migration);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async function createMigration(sequelize, migrationName) {
|
|
247
|
+
const migration = new Migration(sequelize);
|
|
248
|
+
await migration.loadDatabaseTables();
|
|
249
|
+
await migration.checkDiffs();
|
|
250
|
+
if (!migration.upTables && !migration.upFields && !migration.upIndexes) {
|
|
251
|
+
console.info('There\'s no changes between your models and the database.');
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
await migration.generateFile(migrationName);
|
|
120
255
|
}
|
|
121
256
|
const gina = {
|
|
122
257
|
runMigrations,
|
package/dist/gina.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gina.js","sourceRoot":"/","sources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E;;;;EAIF,IAAI;EACJ,UAAU;;GAET,CAAC;IAGA,MAAM,kBAAE,CAAC,SAAS,CAAC,oBAAoB,GAAG,IAAA,gBAAM,GAAE,CAAC,MAAM,CAAC,gBAAgB,CAAC,GAAG,KAAK,EAAE,SAAS,CAAC,CAAC;AAGpG,CAAC;AAED,MAAM,IAAI,GAAG;IACT,aAAa;IACb,eAAe;CAClB,CAAC;AAEF,kBAAe,IAAI,CAAC","sourcesContent":["import { DataTypes, Sequelize } from 'sequelize';\nimport fs from 'fs/promises';\nimport moment from 'moment';\n\nfunction runMigrations() {\n return;\n}\n\nasync function createMigration(sequelize: Sequelize) {\n const models = Object.keys(sequelize.models);\n const queryInterface = sequelize.getQueryInterface();\n const tables = await queryInterface.showAllTables();\n\n const modelTables: string[] = [];\n\n let upTables = '';\n let downTables = '';\n let up = '';\n let down = '';\n const imports = ['QueryInterface'];\n\n for (const model of models) {\n const modelTable = sequelize.models[model].getTableName() as string;\n modelTables.push(modelTable);\n if (!tables.includes(modelTable)) {\n // TODO: create proper logic to create table\n console.debug(`new table ${modelTable}`);\n // console.debug('sequelize.models[model].getAttributes()', sequelize.models[model].getAttributes());\n upTables += `\n await queryInterface.createTable('${modelTable}', {});\n`;\n\n downTables = `\n await queryInterface.dropTable('${modelTable}');\n` + downTables;\n continue;\n }\n\n const modelAttrs = sequelize.models[model].getAttributes();\n const attrs = await queryInterface.describeTable(modelTable);\n\n const modelFields: string[] = [];\n\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\n console.debug(`new column ${modelTable} ${modelAttr}`);\n // console.debug(modelAttrs[modelAttr]);\n\n const val = (modelAttrs[modelAttr].defaultValue as { val?: string; }).val;\n let defaultValue: string;\n\n if (val) {\n if (!imports.includes('Sequelize')) {\n imports.push('Sequelize');\n }\n defaultValue = 'Sequelize.literal(\\'CURRENT_TIMESTAMP\\')';\n } else {\n defaultValue = modelAttrs[modelAttr].defaultValue as string;\n }\n\n if (!imports.includes('DataTypes')) {\n imports.push('DataTypes');\n }\n\n up += `\n await queryInterface.addColumn('${modelTable}', '${modelAttrs[modelAttr].field}', {\n type: DataTypes.${modelAttrs[modelAttr].type instanceof DataTypes.DATE ? 'DATE' : ''},\n allowNull: ${modelAttrs[modelAttr].allowNull},\n defaultValue: ${defaultValue}\n });\n`;\n\n down = `\n await queryInterface.removeColumn('${modelTable}', '${modelAttrs[modelAttr].field}');\n` + down;\n\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 up += `\n await queryInterface.removeColumn('${modelTable}', '${attr}');\n`;\n\n if (!imports.includes('DataTypes')) {\n imports.push('DataTypes');\n }\n\n down = `\n await queryInterface.addColumn('${modelTable}', '${attr}', {\n type: DataTypes.${attrs[attr].type.replace('VARCHAR(', 'STRING(')},\n allowNull: ${attrs[attr].allowNull ? 'true' : 'false'},\n defaultValue: ${attrs[attr].defaultValue},\n });\n` + down;\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 tables) {\n if (!modelTables.includes(table)) {\n // TODO: create proper logic to delete table\n console.debug(`drop table ${table} `);\n upTables += `\n await queryInterface.dropTable('${table}');\n`;\n\n downTables = `\n await queryInterface.createTable('${table}', {});\n` + downTables;\n }\n }\n\n const migration = `import { ${imports.join(', ')} } from 'sequelize';\n\nexport const migration: Migration = {\n async up(queryInterface: QueryInterface) {\n${upTables}\n${up}\n },\n\n async down(queryInterface: QueryInterface) {\n${down}\n${downTables}\n }\n};`;\n\n\n await fs.writeFile('./gina/migrations/' + moment().format('YYYYMMDDHHmmss') + '.ts', migration);\n\n\n}\n\nconst g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Description } 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
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gina-sequelize",
|
|
3
3
|
"main": "./dist/gina.js",
|
|
4
|
+
"bin": {
|
|
5
|
+
"gina-cli": "./bin/index.ts"
|
|
6
|
+
},
|
|
4
7
|
"types": "./dist/gina.d.ts",
|
|
5
|
-
"version": "0.0.
|
|
8
|
+
"version": "0.0.10",
|
|
6
9
|
"description": "Gina is a tool to auto-generate and run migrations based on Sequelize ORM.",
|
|
7
10
|
"scripts": {
|
|
8
11
|
"eslint": "eslint .",
|
|
9
12
|
"eslint_fix": "eslint . --fix",
|
|
10
|
-
"build": "tsc"
|
|
11
|
-
"dev": "ts-node main.ts"
|
|
13
|
+
"build": "tsc"
|
|
12
14
|
},
|
|
13
15
|
"repository": {
|
|
14
16
|
"type": "git",
|
|
@@ -20,12 +22,14 @@
|
|
|
20
22
|
"dependencies": {
|
|
21
23
|
"moment": "^2.30.1",
|
|
22
24
|
"mysql2": "^3.6.0",
|
|
23
|
-
"sequelize": "^6.32.1"
|
|
25
|
+
"sequelize": "^6.32.1",
|
|
26
|
+
"yargs": "^17.7.2"
|
|
24
27
|
},
|
|
25
28
|
"devDependencies": {
|
|
26
29
|
"@types/chai": "^4.3.1",
|
|
27
30
|
"@types/mocha": "^9.1.1",
|
|
28
31
|
"@types/node": "^18.0.0",
|
|
32
|
+
"@types/yargs": "^17.0.32",
|
|
29
33
|
"@typescript-eslint/eslint-plugin": "^5.28.0",
|
|
30
34
|
"@typescript-eslint/parser": "^5.28.0",
|
|
31
35
|
"chai": "^4.3.6",
|
package/main.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import dotenv from 'dotenv';
|
|
2
|
-
dotenv.config();
|
|
3
|
-
|
|
4
|
-
import { Sequelize, Transaction } from 'sequelize';
|
|
5
|
-
import path from 'path';
|
|
6
|
-
import fs from 'fs/promises';
|
|
7
|
-
import gina from './lib/gina';
|
|
8
|
-
|
|
9
|
-
const modelsDir = path.join(__dirname + `/models`);
|
|
10
|
-
|
|
11
|
-
const POOL_MAX_CONNECTIONS = 50;
|
|
12
|
-
const POOL_IDLE_TIME = 12000;
|
|
13
|
-
const POOL_ACQUIRE_TIME = 30000;
|
|
14
|
-
|
|
15
|
-
const sequelize = new Sequelize({
|
|
16
|
-
host: process.env.DB_HOST,
|
|
17
|
-
database: process.env.DB_NAME,
|
|
18
|
-
username: process.env.DB_USERNAME,
|
|
19
|
-
password: process.env.DB_PASSWORD,
|
|
20
|
-
dialect: 'mysql',
|
|
21
|
-
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED,
|
|
22
|
-
pool: {
|
|
23
|
-
max: POOL_MAX_CONNECTIONS,
|
|
24
|
-
min: 0,
|
|
25
|
-
idle: POOL_IDLE_TIME,
|
|
26
|
-
evict: POOL_IDLE_TIME - 2000,
|
|
27
|
-
acquire: POOL_ACQUIRE_TIME
|
|
28
|
-
},
|
|
29
|
-
logging: console.info
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
async function initializeDb() {
|
|
33
|
-
|
|
34
|
-
const files = (await fs.readdir(modelsDir)).filter(file => !file.includes('.d.ts') && !file.includes('.js.map'));
|
|
35
|
-
const associations: (() => void)[] = [];
|
|
36
|
-
|
|
37
|
-
for (const file of files) {
|
|
38
|
-
const filePath = path.join(modelsDir, file);
|
|
39
|
-
const model = await import(filePath.replace('.js', ''));
|
|
40
|
-
associations.push(model.initializeModel(sequelize));
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
for (const association of associations) {
|
|
44
|
-
association();
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
(async () => {
|
|
50
|
-
try {
|
|
51
|
-
await initializeDb();
|
|
52
|
-
await gina.createMigration(sequelize);
|
|
53
|
-
process.exit();
|
|
54
|
-
} catch (err) {
|
|
55
|
-
console.error(err);
|
|
56
|
-
process.exit(1);
|
|
57
|
-
}
|
|
58
|
-
})();
|
package/models/gina-version.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { Model, Sequelize, InferAttributes, InferCreationAttributes, CreationOptional, DataTypes } from 'sequelize';
|
|
2
|
-
|
|
3
|
-
class GinaVersion extends Model<InferAttributes<GinaVersion>, InferCreationAttributes<GinaVersion>> {
|
|
4
|
-
// fields
|
|
5
|
-
declare id: CreationOptional<number>;
|
|
6
|
-
declare version: string;
|
|
7
|
-
|
|
8
|
-
// auto-generated fields
|
|
9
|
-
declare createdAt: CreationOptional<Date>;
|
|
10
|
-
declare updatedAt: CreationOptional<Date>;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
function initializeModel(sequelize: Sequelize) {
|
|
14
|
-
GinaVersion.init({
|
|
15
|
-
id: {
|
|
16
|
-
type: DataTypes.INTEGER,
|
|
17
|
-
primaryKey: true,
|
|
18
|
-
autoIncrement: true,
|
|
19
|
-
},
|
|
20
|
-
version: {
|
|
21
|
-
type: DataTypes.STRING,
|
|
22
|
-
allowNull: false,
|
|
23
|
-
field: 'version'
|
|
24
|
-
},
|
|
25
|
-
createdAt: DataTypes.DATE,
|
|
26
|
-
updatedAt: DataTypes.DATE,
|
|
27
|
-
}, {
|
|
28
|
-
tableName: 'gina_version',
|
|
29
|
-
sequelize
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
return () => {
|
|
33
|
-
return;
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export { GinaVersion, initializeModel };
|
package/typings/migration.d.ts
DELETED