gina-sequelize 0.0.16 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,339 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ const path_1 = __importDefault(require("path"));
8
+ const yargs_1 = __importDefault(require("yargs"));
9
+ const helpers_1 = require("yargs/helpers");
10
+ const moment_1 = __importDefault(require("moment"));
11
+ const gina_1 = __importDefault(require("./gina"));
12
+ const runner_1 = require("./runner");
13
+ const loader_1 = require("./loader");
14
+ const LEGACY_INITIALIZE_MODELS = ['initializeModels.ts', 'initializeModels.js'];
15
+ async function exists(filePath) {
16
+ try {
17
+ await fs_1.default.promises.access(filePath);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ async function readConfig(cwd) {
25
+ const packageJsonPath = path_1.default.join(cwd, 'package.json');
26
+ const packageJson = await exists(packageJsonPath) ? JSON.parse(await fs_1.default.promises.readFile(packageJsonPath, 'utf8')) : {};
27
+ const config = packageJson.gina ?? {};
28
+ const migrationsDir = path_1.default.resolve(cwd, config.migrationsDir ?? 'gina/migrations');
29
+ return {
30
+ modelsDir: path_1.default.resolve(cwd, config.modelsDir ?? 'gina/models'),
31
+ migrationsDir,
32
+ snapshotFile: config.snapshotFile ? path_1.default.resolve(cwd, config.snapshotFile) : path_1.default.join(path_1.default.dirname(migrationsDir), 'snapshot.sql'),
33
+ sequelize: config.sequelize,
34
+ };
35
+ }
36
+ function createSequelize(cwd, config) {
37
+ (0, loader_1.requireFromProject)(cwd, 'dotenv').config({ path: path_1.default.join(cwd, '.env') });
38
+ const { Sequelize } = (0, loader_1.requireFromProject)(cwd, 'sequelize');
39
+ return new Sequelize({
40
+ host: process.env.DB_HOST,
41
+ port: process.env.DB_PORT ? Number(process.env.DB_PORT) : undefined,
42
+ database: process.env.DB_NAME,
43
+ username: process.env.DB_USERNAME,
44
+ password: process.env.DB_PASSWORD,
45
+ dialect: (process.env.DB_DIALECT ?? 'mysql'),
46
+ logging: false,
47
+ ...config.sequelize,
48
+ });
49
+ }
50
+ /**
51
+ * Builds a Sequelize instance with every model of the project loaded.
52
+ * Projects that still have a `gina/initializeModels` file keep using it.
53
+ */
54
+ async function initializeModels(cwd, config) {
55
+ let legacyFile;
56
+ for (const file of LEGACY_INITIALIZE_MODELS) {
57
+ if (await exists(path_1.default.join(cwd, 'gina', file))) {
58
+ legacyFile = path_1.default.join(cwd, 'gina', file);
59
+ break;
60
+ }
61
+ }
62
+ if (legacyFile) {
63
+ console.info(`loading models using ${path_1.default.relative(cwd, legacyFile)}...`);
64
+ const initFile = await (0, loader_1.loadModule)(legacyFile, cwd);
65
+ return (initFile.initializeModels ?? initFile.default.initializeModels)();
66
+ }
67
+ console.info(`loading models from ${path_1.default.relative(cwd, config.modelsDir)}...`);
68
+ if (!await exists(config.modelsDir)) {
69
+ throw new Error(`Models folder not found: ${config.modelsDir}. Set "gina.modelsDir" on your package.json.`);
70
+ }
71
+ const sequelize = createSequelize(cwd, config);
72
+ const associations = [];
73
+ for (const { filePath } of await (0, loader_1.listScripts)(config.modelsDir)) {
74
+ const model = await (0, loader_1.loadModule)(filePath, cwd);
75
+ const initializeModel = model.initializeModel ?? model.default?.initializeModel;
76
+ if (typeof initializeModel !== 'function') {
77
+ console.warn(`skipping ${path_1.default.relative(cwd, filePath)}: it doesn't export an initializeModel function.`);
78
+ continue;
79
+ }
80
+ const association = await initializeModel(sequelize);
81
+ if (typeof association === 'function') {
82
+ associations.push(association);
83
+ }
84
+ }
85
+ for (const association of associations) {
86
+ await association();
87
+ }
88
+ return sequelize;
89
+ }
90
+ async function loadMigrations(cwd, config) {
91
+ const migrations = {};
92
+ for (const { name, filePath } of await (0, loader_1.listScripts)(config.migrationsDir)) {
93
+ const file = await (0, loader_1.loadModule)(filePath, cwd);
94
+ const migration = file.migration ?? file.default?.migration ?? file.default;
95
+ if (typeof migration?.up !== 'function') {
96
+ throw new Error(`${path_1.default.relative(cwd, filePath)} doesn't export a migration with an up function.`);
97
+ }
98
+ const previous = file.previous ?? file.default?.previous ?? migration.previous;
99
+ migrations[name] = { migration, previous, filePath };
100
+ }
101
+ return migrations;
102
+ }
103
+ /**
104
+ * `HEAD` holds the name of the last migration. Every new migration changes it, so two branches
105
+ * that add migrations at the same time conflict on it instead of merging silently.
106
+ */
107
+ function headFile(config) {
108
+ return path_1.default.join(config.migrationsDir, 'HEAD');
109
+ }
110
+ async function readHead(config) {
111
+ return await exists(headFile(config)) ? (await fs_1.default.promises.readFile(headFile(config), 'utf8')).trim() : undefined;
112
+ }
113
+ async function writeHead(config, name) {
114
+ await fs_1.default.promises.writeFile(headFile(config), `${name}\n`);
115
+ }
116
+ /**
117
+ * The last migration of the chain. Fails when HEAD names another one, which usually means a
118
+ * merge conflict on HEAD was resolved without fixing the chain.
119
+ */
120
+ async function chainHead(config, migrations) {
121
+ const { order } = (0, runner_1.resolveOrder)(migrations);
122
+ const last = order[order.length - 1];
123
+ const head = await readHead(config);
124
+ if (head !== undefined && head !== last) {
125
+ throw new Error(`${path_1.default.relative(process.cwd(), headFile(config))} says the last migration is ${head}, but it's ${last}. `
126
+ + 'If you just merged a branch with migrations, make the newer migration run after the other one '
127
+ + '(`export const previous`), then set HEAD to the last migration.');
128
+ }
129
+ return { last, head };
130
+ }
131
+ async function init(cwd) {
132
+ const ginaDir = path_1.default.join(cwd, 'gina');
133
+ if (await exists(ginaDir)) {
134
+ console.info('There\'s already a folder/file named gina on your folder indicating that gina is already initialized.');
135
+ return;
136
+ }
137
+ const firstMigration = `${(0, moment_1.default)().format('YYYYMMDDHHmmss')}-add-version-control-table`;
138
+ await fs_1.default.promises.mkdir(path_1.default.join(ginaDir, 'migrations'), { recursive: true });
139
+ await fs_1.default.promises.writeFile(path_1.default.join(ginaDir, 'migrations', 'HEAD'), `${firstMigration}\n`);
140
+ await fs_1.default.promises.writeFile(path_1.default.join(ginaDir, 'migrations', `${firstMigration}.ts`), `import { QueryInterface, DataTypes } from 'sequelize';
141
+
142
+ export const migration = {
143
+ async up(queryInterface: QueryInterface) {
144
+
145
+ await queryInterface.createTable('gina_version', {
146
+ id: {
147
+ type: DataTypes.INTEGER,
148
+ autoIncrement: true,
149
+ primaryKey: true,
150
+ field: 'id'
151
+ },
152
+ version: {
153
+ type: DataTypes.STRING,
154
+ allowNull: false,
155
+ field: 'version'
156
+ },
157
+ createdAt: {
158
+ type: DataTypes.DATE,
159
+ field: 'createdAt'
160
+ },
161
+ updatedAt: {
162
+ type: DataTypes.DATE,
163
+ field: 'updatedAt'
164
+ },
165
+ });
166
+
167
+ },
168
+
169
+ async down(queryInterface: QueryInterface) {
170
+
171
+ await queryInterface.dropTable('gina_version');
172
+
173
+ }
174
+ };
175
+ `);
176
+ console.info('gina initialized. Point "gina.modelsDir" on your package.json to your models folder, e.g.:');
177
+ console.info(JSON.stringify({ gina: { modelsDir: 'src/database/models' } }, null, 2));
178
+ }
179
+ async function generateMigration(cwd, migrationName) {
180
+ const config = await readConfig(cwd);
181
+ const migrations = await loadMigrations(cwd, config);
182
+ const { last } = await chainHead(config, migrations);
183
+ const sequelize = await initializeModels(cwd, config);
184
+ try {
185
+ const version = await (0, runner_1.readVersion)(sequelize);
186
+ if (last && version !== last) {
187
+ throw new Error(`The database is at ${version || 'no version'}, but the last migration is ${last}. `
188
+ + 'Run upgrade first, so the new migration only has the changes that are not in a migration yet.');
189
+ }
190
+ const fileName = await gina_1.default.createMigration(sequelize, migrationName, config.migrationsDir, last);
191
+ if (fileName) {
192
+ await writeHead(config, path_1.default.parse(fileName).name);
193
+ }
194
+ }
195
+ finally {
196
+ await sequelize.close();
197
+ }
198
+ }
199
+ async function upgrade(cwd, options) {
200
+ const config = await readConfig(cwd);
201
+ const sequelize = await initializeModels(cwd, config);
202
+ try {
203
+ console.info('loading migrations...');
204
+ const migrations = await loadMigrations(cwd, config);
205
+ if (options.dryRun) {
206
+ await gina_1.default.dryRunMigrations(sequelize, migrations);
207
+ }
208
+ else if (options.fromSnapshot) {
209
+ await (0, runner_1.upgradeFromSnapshot)(sequelize, migrations, config.snapshotFile);
210
+ }
211
+ else {
212
+ await gina_1.default.runMigrations(sequelize, migrations, undefined);
213
+ }
214
+ }
215
+ finally {
216
+ await sequelize.close();
217
+ }
218
+ }
219
+ async function repair(cwd, mode, yes) {
220
+ const config = await readConfig(cwd);
221
+ const sequelize = await initializeModels(cwd, config);
222
+ try {
223
+ const migrations = await loadMigrations(cwd, config);
224
+ await gina_1.default.repairMigration(sequelize, migrations, mode, { yes });
225
+ }
226
+ finally {
227
+ await sequelize.close();
228
+ }
229
+ }
230
+ async function check(cwd) {
231
+ const config = await readConfig(cwd);
232
+ const migrations = await loadMigrations(cwd, config);
233
+ const { last, head } = await chainHead(config, migrations);
234
+ if (head === undefined) {
235
+ throw new Error(`${path_1.default.relative(cwd, headFile(config))} not found. Create it with the last migration: echo ${last} > ${path_1.default.relative(cwd, headFile(config))}`);
236
+ }
237
+ console.info(`migrations OK: ${Object.keys(migrations).length} migration(s), the last one is ${last}.`);
238
+ }
239
+ async function snapshot(cwd) {
240
+ const config = await readConfig(cwd);
241
+ const sequelize = await initializeModels(cwd, config);
242
+ try {
243
+ const migrations = await loadMigrations(cwd, config);
244
+ await chainHead(config, migrations);
245
+ await (0, runner_1.createSnapshot)(sequelize, migrations, config.snapshotFile);
246
+ }
247
+ finally {
248
+ await sequelize.close();
249
+ }
250
+ }
251
+ async function downgrade(cwd, target) {
252
+ const config = await readConfig(cwd);
253
+ const sequelize = await initializeModels(cwd, config);
254
+ try {
255
+ console.info('loading migrations...');
256
+ const migrations = await loadMigrations(cwd, config);
257
+ await gina_1.default.revertMigrations(sequelize, migrations, target);
258
+ }
259
+ finally {
260
+ await sequelize.close();
261
+ }
262
+ }
263
+ async function run(command) {
264
+ try {
265
+ await command(process.cwd());
266
+ process.exit(0);
267
+ }
268
+ catch (err) {
269
+ console.error(err);
270
+ process.exit(1);
271
+ }
272
+ }
273
+ (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
274
+ .scriptName('gina-cli')
275
+ .command('init', 'creates initial folder and files for gina', () => undefined, () => run(init))
276
+ .command('generate-migration <migration-name>', 'Generates a new migration file to add the differences between models and database', (yargs) => {
277
+ return yargs
278
+ .positional('migration-name', {
279
+ describe: 'Name of the migration to be added',
280
+ type: 'string',
281
+ demandOption: true,
282
+ });
283
+ }, (argv) => run(cwd => generateMigration(cwd, argv['migration-name'])))
284
+ .command('upgrade', 'upgrade database to its last revision', (yargs) => {
285
+ return yargs
286
+ .option('dry-run', {
287
+ describe: 'Apply the pending migrations to a copy of the schema (no data) in a temporary database instead (MySQL/MariaDB)',
288
+ type: 'boolean',
289
+ })
290
+ .option('from-snapshot', {
291
+ describe: 'On an empty database, create the schema from the snapshot and apply only the migrations after it (MySQL/MariaDB)',
292
+ type: 'boolean',
293
+ })
294
+ .conflicts('dry-run', 'from-snapshot');
295
+ }, (argv) => run(cwd => upgrade(cwd, { dryRun: argv['dry-run'], fromSnapshot: argv['from-snapshot'] })))
296
+ .command('downgrade [steps]', 'reverts the last migration, the last N migrations or every migration after --to', (yargs) => {
297
+ return yargs
298
+ .positional('steps', {
299
+ describe: 'How many migrations to revert',
300
+ type: 'number',
301
+ })
302
+ .option('to', {
303
+ describe: 'Migration to go back to, which stays applied (full name or a unique prefix, like its timestamp)',
304
+ type: 'string',
305
+ })
306
+ .conflicts('steps', 'to')
307
+ .example('$0 downgrade', 'reverts the last migration')
308
+ .example('$0 downgrade 3', 'reverts the last 3 migrations')
309
+ .example('$0 downgrade --to 20240531183010', 'reverts every migration after 20240531183010-*');
310
+ }, (argv) => run(cwd => downgrade(cwd, { steps: argv.steps, to: argv.to })))
311
+ .command('repair', 'finishes or undoes a migration that failed halfway', (yargs) => {
312
+ return yargs
313
+ .option('continue', {
314
+ describe: 'Run the failed migration again, skipping what was already applied',
315
+ type: 'boolean',
316
+ })
317
+ .option('rollback', {
318
+ describe: 'Undo what the failed migration applied, skipping what it didn\'t get to',
319
+ type: 'boolean',
320
+ })
321
+ .option('yes', {
322
+ describe: 'Run even if the migration has raw queries or bulk operations, which repair can\'t check and would run again',
323
+ type: 'boolean',
324
+ })
325
+ .conflicts('continue', 'rollback')
326
+ .check(argv => {
327
+ if (!argv.continue && !argv.rollback) {
328
+ throw new Error('Pass --continue or --rollback.');
329
+ }
330
+ return true;
331
+ });
332
+ }, (argv) => run(cwd => repair(cwd, argv.continue ? 'continue' : 'rollback', Boolean(argv.yes))))
333
+ .command('check', 'checks that the migrations form a single chain and match the HEAD file (for CI)', () => undefined, () => run(check))
334
+ .command('snapshot', 'runs every migration on a temporary database and saves the resulting schema for upgrade --from-snapshot (MySQL/MariaDB)', () => undefined, () => run(snapshot))
335
+ .demandCommand(1)
336
+ .strict()
337
+ .help()
338
+ .parse();
339
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"/","sources":["cli.ts"],"names":[],"mappings":";;;;;AAAA,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,2CAAwC;AACxC,oDAA4B;AAE5B,kDAA+D;AAC/D,qCAA0F;AAC1F,qCAAuE;AAavE,MAAM,wBAAwB,GAAG,CAAC,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;AAEhF,KAAK,UAAU,MAAM,CAAC,QAAgB;IAClC,IAAI,CAAC;QACD,MAAM,YAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACnC,OAAO,IAAI,CAAC;IAChB,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,GAAW;IACjC,MAAM,eAAe,GAAG,cAAI,CAAC,IAAI,CAAC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QAAQ,CAAC,CAAC;KACpL,aAAa,CAAC,CAAC,CAAC;KAChB,MAAM,EAAE;KACR,IAAI,EAAE;KACN,KAAK,EAAE,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport moment from 'moment';\nimport type { Options, Sequelize } from 'sequelize';\nimport gina, { DowngradeTarget, MigrationFiles } from './gina';\nimport { resolveOrder, readVersion, createSnapshot, upgradeFromSnapshot } from './runner';\nimport { listScripts, loadModule, requireFromProject } from './loader';\n\ninterface GinaConfig {\n /** folder with the model files, each one exporting `initializeModel(sequelize)` */\n modelsDir: string;\n /** folder with the migration files */\n migrationsDir: string;\n /** schema snapshot used by `upgrade --from-snapshot` */\n snapshotFile: string;\n /** extra options passed to the Sequelize constructor */\n sequelize?: Options;\n}\n\nconst LEGACY_INITIALIZE_MODELS = ['initializeModels.ts', 'initializeModels.js'];\n\nasync function exists(filePath: string) {\n try {\n await fs.promises.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readConfig(cwd: string): Promise<GinaConfig> {\n const packageJsonPath = path.join(cwd, 'package.json');\n const packageJson = await exists(packageJsonPath) ? JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf8')) : {};\n const config = packageJson.gina ?? {};\n\n const migrationsDir = path.resolve(cwd, config.migrationsDir ?? 'gina/migrations');\n return {\n modelsDir: path.resolve(cwd, config.modelsDir ?? 'gina/models'),\n migrationsDir,\n snapshotFile: config.snapshotFile ? path.resolve(cwd, config.snapshotFile) : path.join(path.dirname(migrationsDir), 'snapshot.sql'),\n sequelize: config.sequelize,\n };\n}\n\nfunction createSequelize(cwd: string, config: GinaConfig): Sequelize {\n requireFromProject<typeof import('dotenv')>(cwd, 'dotenv').config({ path: path.join(cwd, '.env') });\n\n const { Sequelize } = requireFromProject<typeof import('sequelize')>(cwd, 'sequelize');\n\n return new Sequelize({\n host: process.env.DB_HOST,\n port: process.env.DB_PORT ? Number(process.env.DB_PORT) : undefined,\n database: process.env.DB_NAME,\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n dialect: (process.env.DB_DIALECT ?? 'mysql') as Options['dialect'],\n logging: false,\n ...config.sequelize,\n });\n}\n\n/**\n * Builds a Sequelize instance with every model of the project loaded.\n * Projects that still have a `gina/initializeModels` file keep using it.\n */\nasync function initializeModels(cwd: string, config: GinaConfig): Promise<Sequelize> {\n let legacyFile: string | undefined;\n for (const file of LEGACY_INITIALIZE_MODELS) {\n if (await exists(path.join(cwd, 'gina', file))) {\n legacyFile = path.join(cwd, 'gina', file);\n break;\n }\n }\n\n if (legacyFile) {\n console.info(`loading models using ${path.relative(cwd, legacyFile)}...`);\n const initFile = await loadModule(legacyFile, cwd);\n return (initFile.initializeModels ?? initFile.default.initializeModels)();\n }\n\n console.info(`loading models from ${path.relative(cwd, config.modelsDir)}...`);\n if (!await exists(config.modelsDir)) {\n throw new Error(`Models folder not found: ${config.modelsDir}. Set \"gina.modelsDir\" on your package.json.`);\n }\n\n const sequelize = createSequelize(cwd, config);\n const associations: (() => unknown)[] = [];\n\n for (const { filePath } of await listScripts(config.modelsDir)) {\n const model = await loadModule(filePath, cwd);\n const initializeModel = model.initializeModel ?? model.default?.initializeModel;\n if (typeof initializeModel !== 'function') {\n console.warn(`skipping ${path.relative(cwd, filePath)}: it doesn't export an initializeModel function.`);\n continue;\n }\n\n const association = await initializeModel(sequelize);\n if (typeof association === 'function') {\n associations.push(association);\n }\n }\n\n for (const association of associations) {\n await association();\n }\n\n return sequelize;\n}\n\nasync function loadMigrations(cwd: string, config: GinaConfig) {\n const migrations: MigrationFiles = {};\n\n for (const { name, filePath } of await listScripts(config.migrationsDir)) {\n const file = await loadModule(filePath, cwd);\n const migration = file.migration ?? file.default?.migration ?? file.default;\n if (typeof migration?.up !== 'function') {\n throw new Error(`${path.relative(cwd, filePath)} doesn't export a migration with an up function.`);\n }\n const previous: string | null | undefined = file.previous ?? file.default?.previous ?? migration.previous;\n migrations[name] = { migration, previous, filePath };\n }\n\n return migrations;\n}\n\n/**\n * `HEAD` holds the name of the last migration. Every new migration changes it, so two branches\n * that add migrations at the same time conflict on it instead of merging silently.\n */\nfunction headFile(config: GinaConfig) {\n return path.join(config.migrationsDir, 'HEAD');\n}\n\nasync function readHead(config: GinaConfig) {\n return await exists(headFile(config)) ? (await fs.promises.readFile(headFile(config), 'utf8')).trim() : undefined;\n}\n\nasync function writeHead(config: GinaConfig, name: string) {\n await fs.promises.writeFile(headFile(config), `${name}\\n`);\n}\n\n/**\n * The last migration of the chain. Fails when HEAD names another one, which usually means a\n * merge conflict on HEAD was resolved without fixing the chain.\n */\nasync function chainHead(config: GinaConfig, migrations: MigrationFiles) {\n const { order } = resolveOrder(migrations);\n const last = order[order.length - 1];\n const head = await readHead(config);\n if (head !== undefined && head !== last) {\n throw new Error(`${path.relative(process.cwd(), headFile(config))} says the last migration is ${head}, but it's ${last}. `\n + 'If you just merged a branch with migrations, make the newer migration run after the other one '\n + '(`export const previous`), then set HEAD to the last migration.');\n }\n return { last, head };\n}\n\nasync function init(cwd: string) {\n const ginaDir = path.join(cwd, 'gina');\n if (await exists(ginaDir)) {\n console.info('There\\'s already a folder/file named gina on your folder indicating that gina is already initialized.');\n return;\n }\n\n const firstMigration = `${moment().format('YYYYMMDDHHmmss')}-add-version-control-table`;\n await fs.promises.mkdir(path.join(ginaDir, 'migrations'), { recursive: true });\n await fs.promises.writeFile(path.join(ginaDir, 'migrations', 'HEAD'), `${firstMigration}\\n`);\n await fs.promises.writeFile(path.join(ginaDir, 'migrations', `${firstMigration}.ts`), `import { QueryInterface, DataTypes } from 'sequelize';\n\nexport const migration = {\n async up(queryInterface: QueryInterface) {\n\n await queryInterface.createTable('gina_version', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true,\n field: 'id'\n },\n version: {\n type: DataTypes.STRING,\n allowNull: false,\n field: 'version'\n },\n createdAt: {\n type: DataTypes.DATE,\n field: 'createdAt'\n },\n updatedAt: {\n type: DataTypes.DATE,\n field: 'updatedAt'\n },\n });\n\n },\n\n async down(queryInterface: QueryInterface) {\n\n await queryInterface.dropTable('gina_version');\n\n }\n};\n`);\n\n console.info('gina initialized. Point \"gina.modelsDir\" on your package.json to your models folder, e.g.:');\n console.info(JSON.stringify({ gina: { modelsDir: 'src/database/models' } }, null, 2));\n}\n\nasync function generateMigration(cwd: string, migrationName: string) {\n const config = await readConfig(cwd);\n const migrations = await loadMigrations(cwd, config);\n const { last } = await chainHead(config, migrations);\n\n const sequelize = await initializeModels(cwd, config);\n try {\n const version = await readVersion(sequelize);\n if (last && version !== last) {\n throw new Error(`The database is at ${version || 'no version'}, but the last migration is ${last}. `\n + 'Run upgrade first, so the new migration only has the changes that are not in a migration yet.');\n }\n const fileName = await gina.createMigration(sequelize, migrationName, config.migrationsDir, last);\n if (fileName) {\n await writeHead(config, path.parse(fileName).name);\n }\n } finally {\n await sequelize.close();\n }\n}\n\nasync function upgrade(cwd: string, options: { dryRun?: boolean; fromSnapshot?: boolean; }) {\n const config = await readConfig(cwd);\n const sequelize = await initializeModels(cwd, config);\n try {\n console.info('loading migrations...');\n const migrations = await loadMigrations(cwd, config);\n if (options.dryRun) {\n await gina.dryRunMigrations(sequelize, migrations);\n } else if (options.fromSnapshot) {\n await upgradeFromSnapshot(sequelize, migrations, config.snapshotFile);\n } else {\n await gina.runMigrations(sequelize, migrations, undefined);\n }\n } finally {\n await sequelize.close();\n }\n}\n\nasync function repair(cwd: string, mode: 'continue' | 'rollback', yes: boolean) {\n const config = await readConfig(cwd);\n const sequelize = await initializeModels(cwd, config);\n try {\n const migrations = await loadMigrations(cwd, config);\n await gina.repairMigration(sequelize, migrations, mode, { yes });\n } finally {\n await sequelize.close();\n }\n}\n\nasync function check(cwd: string) {\n const config = await readConfig(cwd);\n const migrations = await loadMigrations(cwd, config);\n const { last, head } = await chainHead(config, migrations);\n if (head === undefined) {\n throw new Error(`${path.relative(cwd, headFile(config))} not found. Create it with the last migration: echo ${last} > ${path.relative(cwd, headFile(config))}`);\n }\n console.info(`migrations OK: ${Object.keys(migrations).length} migration(s), the last one is ${last}.`);\n}\n\nasync function snapshot(cwd: string) {\n const config = await readConfig(cwd);\n const sequelize = await initializeModels(cwd, config);\n try {\n const migrations = await loadMigrations(cwd, config);\n await chainHead(config, migrations);\n await createSnapshot(sequelize, migrations, config.snapshotFile);\n } finally {\n await sequelize.close();\n }\n}\n\nasync function downgrade(cwd: string, target: DowngradeTarget) {\n const config = await readConfig(cwd);\n const sequelize = await initializeModels(cwd, config);\n try {\n console.info('loading migrations...');\n const migrations = await loadMigrations(cwd, config);\n await gina.revertMigrations(sequelize, migrations, target);\n } finally {\n await sequelize.close();\n }\n}\n\nasync function run(command: (cwd: string) => Promise<void>) {\n try {\n await command(process.cwd());\n process.exit(0);\n } catch (err) {\n console.error(err);\n process.exit(1);\n }\n}\n\nyargs(hideBin(process.argv))\n .scriptName('gina-cli')\n .command('init', 'creates initial folder and files for gina', () => undefined, () => run(init))\n .command('generate-migration <migration-name>', 'Generates a new migration file to add the differences between models and database', (yargs) => {\n return yargs\n .positional('migration-name', {\n describe: 'Name of the migration to be added',\n type: 'string',\n demandOption: true,\n });\n }, (argv) => run(cwd => generateMigration(cwd, argv['migration-name'])))\n .command('upgrade', 'upgrade database to its last revision', (yargs) => {\n return yargs\n .option('dry-run', {\n describe: 'Apply the pending migrations to a copy of the schema (no data) in a temporary database instead (MySQL/MariaDB)',\n type: 'boolean',\n })\n .option('from-snapshot', {\n describe: 'On an empty database, create the schema from the snapshot and apply only the migrations after it (MySQL/MariaDB)',\n type: 'boolean',\n })\n .conflicts('dry-run', 'from-snapshot');\n }, (argv) => run(cwd => upgrade(cwd, { dryRun: argv['dry-run'], fromSnapshot: argv['from-snapshot'] })))\n .command('downgrade [steps]', 'reverts the last migration, the last N migrations or every migration after --to', (yargs) => {\n return yargs\n .positional('steps', {\n describe: 'How many migrations to revert',\n type: 'number',\n })\n .option('to', {\n describe: 'Migration to go back to, which stays applied (full name or a unique prefix, like its timestamp)',\n type: 'string',\n })\n .conflicts('steps', 'to')\n .example('$0 downgrade', 'reverts the last migration')\n .example('$0 downgrade 3', 'reverts the last 3 migrations')\n .example('$0 downgrade --to 20240531183010', 'reverts every migration after 20240531183010-*');\n }, (argv) => run(cwd => downgrade(cwd, { steps: argv.steps, to: argv.to })))\n .command('repair', 'finishes or undoes a migration that failed halfway', (yargs) => {\n return yargs\n .option('continue', {\n describe: 'Run the failed migration again, skipping what was already applied',\n type: 'boolean',\n })\n .option('rollback', {\n describe: 'Undo what the failed migration applied, skipping what it didn\\'t get to',\n type: 'boolean',\n })\n .option('yes', {\n describe: 'Run even if the migration has raw queries or bulk operations, which repair can\\'t check and would run again',\n type: 'boolean',\n })\n .conflicts('continue', 'rollback')\n .check(argv => {\n if (!argv.continue && !argv.rollback) {\n throw new Error('Pass --continue or --rollback.');\n }\n return true;\n });\n }, (argv) => run(cwd => repair(cwd, argv.continue ? 'continue' : 'rollback', Boolean(argv.yes))))\n .command('check', 'checks that the migrations form a single chain and match the HEAD file (for CI)', () => undefined, () => run(check))\n .command('snapshot', 'runs every migration on a temporary database and saves the resulting schema for upgrade --from-snapshot (MySQL/MariaDB)', () => undefined, () => run(snapshot))\n .demandCommand(1)\n .strict()\n .help()\n .parse();\n"]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Conversions between Sequelize data types, MySQL column definitions and the code
3
+ * written into generated migrations.
4
+ */
5
+ /** A column as it currently is in the database. */
6
+ interface DatabaseColumn {
7
+ /** e.g. `varchar(100)`, `int unsigned`, `enum('deny_list','clone')` (enum values keep their case) */
8
+ type: string;
9
+ allowNull: boolean;
10
+ /** raw default as stored by the database, `null` when there's none */
11
+ defaultValue: string | null;
12
+ autoIncrement: boolean;
13
+ primaryKey: boolean;
14
+ }
15
+ interface ModelDataType {
16
+ key: string;
17
+ options?: {
18
+ [option: string]: unknown;
19
+ };
20
+ values?: string[];
21
+ toSql(options?: {
22
+ escape(value: unknown): string;
23
+ }): string;
24
+ }
25
+ declare function quote(value: string): string;
26
+ /**
27
+ * Code that recreates a model's data type, e.g. `DataTypes.ENUM('a', 'b')` or `DataTypes.STRING(100)`.
28
+ */
29
+ declare function modelTypeToCode(type: ModelDataType): string;
30
+ /**
31
+ * Normalizes a column definition so the model's SQL and the database's can be compared:
32
+ * `INTEGER(11) UNSIGNED` and `int unsigned` are the same thing. Quoted enum values are kept as they are.
33
+ */
34
+ declare function normalizeColumnType(sql: string): string;
35
+ /**
36
+ * The default value as the database stores it, `null` for no default and
37
+ * `undefined` when it can't be compared (e.g. `DataTypes.NOW` or `sequelize.fn`, which never reach the database).
38
+ */
39
+ declare function modelDefaultToSql(defaultValue: unknown): string | null | undefined;
40
+ declare function sameDefault(modelDefault: string | null, databaseDefault: string | null): boolean;
41
+ /**
42
+ * Code that recreates a column as it is in the database, e.g. `enum('a','b')` becomes `DataTypes.ENUM('a', 'b')`.
43
+ * Types without a DataTypes equivalent are written as raw SQL strings, which Sequelize also accepts.
44
+ */
45
+ declare function databaseTypeToCode(columnType: string): string;
46
+ /**
47
+ * Code for a database default value, typed after the column (numbers, booleans, literals or strings).
48
+ * Returns `needsSequelize` when it uses `Sequelize.literal`.
49
+ */
50
+ declare function databaseDefaultToCode(defaultValue: string, columnType: string): {
51
+ code: string;
52
+ needsSequelize: boolean;
53
+ };
54
+ export { DatabaseColumn, ModelDataType, quote, modelTypeToCode, normalizeColumnType, modelDefaultToSql, sameDefault, databaseTypeToCode, databaseDefaultToCode, };
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ /**
3
+ * Conversions between Sequelize data types, MySQL column definitions and the code
4
+ * written into generated migrations.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.quote = quote;
8
+ exports.modelTypeToCode = modelTypeToCode;
9
+ exports.normalizeColumnType = normalizeColumnType;
10
+ exports.modelDefaultToSql = modelDefaultToSql;
11
+ exports.sameDefault = sameDefault;
12
+ exports.databaseTypeToCode = databaseTypeToCode;
13
+ exports.databaseDefaultToCode = databaseDefaultToCode;
14
+ const INTEGER_KEYS = ['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INTEGER', 'BIGINT'];
15
+ const NUMERIC_TYPES = ['tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'decimal', 'float', 'double'];
16
+ function quote(value) {
17
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, '\\\'')}'`;
18
+ }
19
+ function args(...values) {
20
+ const defined = values.filter(value => value !== undefined && value !== null);
21
+ return defined.length ? `(${defined.join(', ')})` : '';
22
+ }
23
+ function numericModifiers(options) {
24
+ return `${options.unsigned ? '.UNSIGNED' : ''}${options.zerofill ? '.ZEROFILL' : ''}`;
25
+ }
26
+ /**
27
+ * Code that recreates a model's data type, e.g. `DataTypes.ENUM('a', 'b')` or `DataTypes.STRING(100)`.
28
+ */
29
+ function modelTypeToCode(type) {
30
+ const options = type.options ?? {};
31
+ switch (type.key) {
32
+ case 'ENUM':
33
+ return `DataTypes.ENUM(${(type.values ?? []).map(quote).join(', ')})`;
34
+ case 'STRING':
35
+ return `DataTypes.STRING${options.length === 255 ? '' : args(options.length)}${options.binary ? '.BINARY' : ''}`;
36
+ case 'CHAR':
37
+ return `DataTypes.CHAR${args(options.length)}${options.binary ? '.BINARY' : ''}`;
38
+ case 'TEXT':
39
+ return `DataTypes.TEXT${typeof options.length === 'string' ? `(${quote(options.length)})` : ''}`;
40
+ case 'DECIMAL':
41
+ return `DataTypes.DECIMAL${args(options.precision, options.scale)}${numericModifiers(options)}`;
42
+ case 'FLOAT':
43
+ case 'REAL':
44
+ case 'DOUBLE':
45
+ case 'DOUBLE PRECISION':
46
+ return `DataTypes.${type.key.split(' ')[0]}${args(options.length, options.decimals)}${numericModifiers(options)}`;
47
+ case 'DATE':
48
+ return `DataTypes.DATE${args(options.length)}`;
49
+ }
50
+ if (INTEGER_KEYS.includes(type.key)) {
51
+ return `DataTypes.${type.key}${args(options.length)}${numericModifiers(options)}`;
52
+ }
53
+ return `DataTypes.${type.key}`;
54
+ }
55
+ /**
56
+ * Normalizes a column definition so the model's SQL and the database's can be compared:
57
+ * `INTEGER(11) UNSIGNED` and `int unsigned` are the same thing. Quoted enum values are kept as they are.
58
+ */
59
+ function normalizeColumnType(sql) {
60
+ return sql
61
+ .trim()
62
+ .split(/('(?:[^'\\]|\\.|'')*')/)
63
+ .map((part, index) => {
64
+ if (index % 2) {
65
+ return part.replace(/\\'/g, '\'\'');
66
+ }
67
+ return part
68
+ .toLowerCase()
69
+ .replace(/\s*([(),])\s*/g, '$1')
70
+ .replace(/\s+/g, ' ')
71
+ .replace(/\binteger\b/g, 'int')
72
+ .replace(/\bdouble precision\b/g, 'double')
73
+ .replace(/\b(smallint|mediumint|int|bigint)\(\d+\)/g, '$1')
74
+ .replace(/\btinyint\((?!1\))\d+\)/g, 'tinyint')
75
+ .replace(/^decimal$/, 'decimal(10,0)')
76
+ .replace(/ binary$/, '');
77
+ })
78
+ .join('');
79
+ }
80
+ /**
81
+ * The default value as the database stores it, `null` for no default and
82
+ * `undefined` when it can't be compared (e.g. `DataTypes.NOW` or `sequelize.fn`, which never reach the database).
83
+ */
84
+ function modelDefaultToSql(defaultValue) {
85
+ if (defaultValue === undefined || defaultValue === null) {
86
+ return null;
87
+ }
88
+ if (typeof defaultValue === 'boolean') {
89
+ return defaultValue ? '1' : '0';
90
+ }
91
+ if (typeof defaultValue === 'number' || typeof defaultValue === 'string') {
92
+ return String(defaultValue);
93
+ }
94
+ if (typeof defaultValue === 'object' && 'val' in defaultValue) {
95
+ return String(defaultValue.val);
96
+ }
97
+ return undefined;
98
+ }
99
+ function sameDefault(modelDefault, databaseDefault) {
100
+ if (modelDefault === null || databaseDefault === null) {
101
+ return modelDefault === databaseDefault;
102
+ }
103
+ if (modelDefault.trim() !== '' && !isNaN(Number(modelDefault)) && !isNaN(Number(databaseDefault))) {
104
+ return Number(modelDefault) === Number(databaseDefault);
105
+ }
106
+ return modelDefault.toLowerCase() === databaseDefault.toLowerCase() || modelDefault === databaseDefault;
107
+ }
108
+ function parseEnumValues(columnType) {
109
+ return [...columnType.matchAll(/'((?:[^'\\]|\\.|'')*)'/g)].map(match => match[1].replace(/''/g, '\'').replace(/\\(.)/g, '$1'));
110
+ }
111
+ /**
112
+ * Code that recreates a column as it is in the database, e.g. `enum('a','b')` becomes `DataTypes.ENUM('a', 'b')`.
113
+ * Types without a DataTypes equivalent are written as raw SQL strings, which Sequelize also accepts.
114
+ */
115
+ function databaseTypeToCode(columnType) {
116
+ const match = /^(\w+)(?:\((.*)\))?\s*(.*)$/s.exec(columnType.trim());
117
+ if (!match) {
118
+ return quote(columnType);
119
+ }
120
+ const base = match[1].toLowerCase();
121
+ const params = match[2]?.split(',').map(param => param.trim());
122
+ const rest = match[3].toLowerCase();
123
+ const modifiers = `${rest.includes('unsigned') ? '.UNSIGNED' : ''}${rest.includes('zerofill') ? '.ZEROFILL' : ''}`;
124
+ switch (base) {
125
+ case 'enum':
126
+ return `DataTypes.ENUM(${parseEnumValues(columnType).map(quote).join(', ')})`;
127
+ case 'varchar':
128
+ return `DataTypes.STRING${params && params[0] !== '255' ? `(${params[0]})` : ''}`;
129
+ case 'char':
130
+ return `DataTypes.CHAR${params ? `(${params[0]})` : ''}`;
131
+ case 'tinyint':
132
+ return params?.[0] === '1' && !modifiers ? 'DataTypes.BOOLEAN' : `DataTypes.TINYINT${modifiers}`;
133
+ case 'smallint':
134
+ return `DataTypes.SMALLINT${modifiers}`;
135
+ case 'mediumint':
136
+ return `DataTypes.MEDIUMINT${modifiers}`;
137
+ case 'int':
138
+ case 'integer':
139
+ return `DataTypes.INTEGER${modifiers}`;
140
+ case 'bigint':
141
+ return `DataTypes.BIGINT${modifiers}`;
142
+ case 'decimal':
143
+ return `DataTypes.DECIMAL${params ? `(${params.join(', ')})` : ''}${modifiers}`;
144
+ case 'float':
145
+ return `DataTypes.FLOAT${params ? `(${params.join(', ')})` : ''}${modifiers}`;
146
+ case 'double':
147
+ return `DataTypes.DOUBLE${params ? `(${params.join(', ')})` : ''}${modifiers}`;
148
+ case 'datetime':
149
+ return `DataTypes.DATE${params ? `(${params[0]})` : ''}`;
150
+ case 'date':
151
+ return 'DataTypes.DATEONLY';
152
+ case 'time':
153
+ return 'DataTypes.TIME';
154
+ case 'text':
155
+ return 'DataTypes.TEXT';
156
+ case 'tinytext':
157
+ case 'mediumtext':
158
+ case 'longtext':
159
+ return `DataTypes.TEXT('${base.replace('text', '')}')`;
160
+ case 'json':
161
+ return 'DataTypes.JSON';
162
+ case 'blob':
163
+ return 'DataTypes.BLOB';
164
+ case 'tinyblob':
165
+ case 'mediumblob':
166
+ case 'longblob':
167
+ return `DataTypes.BLOB('${base.replace('blob', '')}')`;
168
+ }
169
+ return quote(columnType);
170
+ }
171
+ /**
172
+ * Code for a database default value, typed after the column (numbers, booleans, literals or strings).
173
+ * Returns `needsSequelize` when it uses `Sequelize.literal`.
174
+ */
175
+ function databaseDefaultToCode(defaultValue, columnType) {
176
+ const base = columnType.trim().toLowerCase();
177
+ if (/^current_timestamp/.test(defaultValue.toLowerCase())) {
178
+ return { code: `Sequelize.literal(${quote(defaultValue)})`, needsSequelize: true };
179
+ }
180
+ if (base.startsWith('tinyint(1)')) {
181
+ return { code: defaultValue === '0' ? 'false' : 'true', needsSequelize: false };
182
+ }
183
+ if (NUMERIC_TYPES.some(type => base.startsWith(type)) && !isNaN(Number(defaultValue))) {
184
+ return { code: String(Number(defaultValue)), needsSequelize: false };
185
+ }
186
+ return { code: quote(defaultValue), needsSequelize: false };
187
+ }
188
+ //# sourceMappingURL=column-types.js.map