gina-sequelize 0.0.16 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,59 +1,305 @@
1
1
  # Gina
2
2
 
3
- Gina is a tool to auto-generate and run migrations based on Sequelize ORM.
3
+ Gina is a migration tool for [Sequelize](https://sequelize.org/) projects, in the spirit of Python's Alembic:
4
4
 
5
- ## How to use it
5
+ - **`generate-migration`** compares your Sequelize models with a live database and writes a migration file with the differences.
6
+ - **`upgrade`** applies every pending migration, in order, and records the current version in the database.
7
+ - **`downgrade`** reverts applied migrations, newest first, running their `down` functions.
6
8
 
7
- ### Install
9
+ Plus some safety nets: migrations form a chain, so a branch merged late can't be skipped silently; `upgrade --dry-run` rehearses pending migrations on a copy of the schema; a migration that fails halfway is recorded and can be finished or undone with `repair`; and `snapshot` lets development databases skip hundreds of migrations.
8
10
 
9
- You can install this using:
11
+ It's a regular CLI. You install it in your project and run it from the project folder, locally while developing and in production as a deploy step. It works with migrations and models written in TypeScript or in plain/compiled JavaScript, on any Node version from 18 up.
12
+
13
+ ## How it works
14
+
15
+ When you run `gina-cli`, it:
16
+
17
+ 1. Reads the `gina` section of the `package.json` in the current folder.
18
+ 2. Connects to the database using the `DB_*` environment variables (and a `.env` file, if there is one).
19
+ 3. Loads every model file in `modelsDir` and calls the `initializeModel(sequelize)` function each one exports.
20
+ 4. Loads the migration files in `migrationsDir` and puts them in order (see [Migration order](#migration-order)).
21
+ 5. Runs the command.
22
+
23
+ **TypeScript files** are transpiled on the fly with your project's own `typescript` package and `tsconfig.json`. Gina only transpiles them, it doesn't type-check, and it doesn't need `ts-node`, `tsx` or any Node loader flags. That's why it behaves the same on every Node version.
24
+
25
+ **JavaScript files** are loaded as they are. In production you can ship only the compiled output (`.js`) and run `gina-cli upgrade` there without TypeScript sources.
26
+
27
+ When the same migration exists as both `.ts` and `.js`, the `.ts` one is used.
28
+
29
+ ### Version control
30
+
31
+ Gina keeps a single row in a `gina_version` table with the name of the last applied migration, e.g. `20240531183010-adding-initial-structure`. `upgrade` runs every migration that comes after it in the [migration order](#migration-order).
32
+
33
+ ### Migration order
34
+
35
+ Each generated migration says which migration it runs after:
36
+
37
+ ```ts
38
+ export const previous = '20240531183010-adding-initial-structure';
39
+ ```
40
+
41
+ So migrations form a chain, and that chain (not the file names) decides the order. Migrations without `previous`, like the ones written before Gina had the chain, come first, sorted by name.
42
+
43
+ `gina/migrations/HEAD` holds the name of the last migration, and `generate-migration` updates it. Its job is to make git complain: when two branches each add a migration, both change `HEAD`, so the second one to merge has a conflict instead of merging silently. Without the chain, the migration with the older timestamp would sort before the version the database is already at and never run.
44
+
45
+ To resolve it, make the migration that was merged last run after the other one: set its `previous` to the other branch's last migration, and set `HEAD` to it. If the conflict is resolved without that, Gina notices: two migrations with the same `previous` (a fork) make `upgrade`, `generate-migration` and `check` fail with a message saying what to fix, and so does a `HEAD` that isn't the last migration of the chain.
46
+
47
+ Run `gina-cli check` in CI to catch this before deploying. It doesn't need a database.
48
+
49
+ ## Installation
50
+
51
+ Install it as a project dependency, so local, CI and production all run the same version:
10
52
 
11
53
  ```bash
12
54
  npm install gina-sequelize
13
55
  ```
14
56
 
15
- You'll need to install it globally so you can you the gina-cli
57
+ Your project also needs `sequelize` (a peer dependency), the driver for your database (e.g. `mysql2`) and, if your models or migrations are TypeScript, `typescript`.
58
+
59
+ Then run it with `npx gina-cli <command>`, or through npm scripts:
60
+
61
+ ```json
62
+ {
63
+ "scripts": {
64
+ "db:upgrade": "gina-cli upgrade",
65
+ "db:migration": "gina-cli generate-migration"
66
+ }
67
+ }
68
+ ```
16
69
 
17
70
  ```bash
18
- npm install -g gina-sequelize
19
- # make sure to install ts-node too:
20
- npm install -g ts-node
71
+ npm run db:upgrade
72
+ npm run db:migration -- "add users table"
21
73
  ```
22
74
 
23
- ### Initialize Gina
75
+ A global install (`npm install -g gina-sequelize`) also works. When the project has its own copy, the global `gina-cli` hands off to it, so models, migrations and gina all use the same `sequelize`.
24
76
 
25
- If this is the first time you are running Gina on your project you'll need to initialize it.
77
+ ## Configuration
26
78
 
27
- ```bash
28
- gina-cli init
79
+ ### `package.json`
80
+
81
+ ```json
82
+ {
83
+ "gina": {
84
+ "modelsDir": "src/database/models",
85
+ "migrationsDir": "gina/migrations",
86
+ "sequelize": {
87
+ "timezone": "-03:00"
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ | Option | Default | Description |
94
+ | --- | --- | --- |
95
+ | `modelsDir` | `gina/models` | Folder with your model files, relative to the project root. |
96
+ | `migrationsDir` | `gina/migrations` | Folder with the migration files, relative to the project root. |
97
+ | `snapshotFile` | `snapshot.sql` next to `migrationsDir` | Schema snapshot written by `gina-cli snapshot`. |
98
+ | `sequelize` | — | Extra options passed to the `Sequelize` constructor. They override the defaults built from the environment variables. |
99
+
100
+ Use paths that are valid in both your source tree and your build output. For example, if `tsc` compiles `src/database/models/*.ts` to `dist/src/database/models/*.js` and production runs from `dist/`, `src/database/models` works in both places. Remember to ship `package.json` with the build.
101
+
102
+ ### Database connection
103
+
104
+ | Variable | Default |
105
+ | --- | --- |
106
+ | `DB_HOST` | — |
107
+ | `DB_PORT` | the dialect's default |
108
+ | `DB_NAME` | — |
109
+ | `DB_USERNAME` | — |
110
+ | `DB_PASSWORD` | — |
111
+ | `DB_DIALECT` | `mysql` |
112
+
113
+ If there's a `.env` file in the project folder, Gina loads it. Variables already set in the environment take precedence, which is what you want in production.
114
+
115
+ ### Models
116
+
117
+ Each file in `modelsDir` must export an `initializeModel(sequelize)` function that initializes the model. It can return a function that sets up associations. Gina calls those only after every model is initialized:
118
+
119
+ ```ts
120
+ import { Model, Sequelize, DataTypes } from 'sequelize';
121
+ import { Post } from './post';
122
+
123
+ export class User extends Model {}
124
+
125
+ export function initializeModel(sequelize: Sequelize) {
126
+ User.init({
127
+ id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
128
+ name: { type: DataTypes.STRING, allowNull: false },
129
+ }, { tableName: 'users', sequelize });
130
+
131
+ return () => {
132
+ User.hasMany(Post, { foreignKey: 'userId', as: 'posts' });
133
+ };
134
+ }
135
+ ```
136
+
137
+ Files that don't export `initializeModel` are skipped with a warning.
138
+
139
+ #### Custom model loading (`gina/initializeModels`)
140
+
141
+ If your project needs to build the Sequelize instance itself, create `gina/initializeModels.ts` (or `.js`) exporting an `initializeModels()` function that returns a Sequelize instance with every model already loaded. When this file exists Gina uses it, and ignores `modelsDir` and the `DB_*` variables.
142
+
143
+ ### Migrations
144
+
145
+ A migration exports `migration` with `up` and `down` functions that receive Sequelize's `QueryInterface`, and `previous`, the migration it runs after:
146
+
147
+ ```ts
148
+ import { QueryInterface, DataTypes } from 'sequelize';
149
+
150
+ export const previous = '20240531183010-adding-initial-structure';
151
+
152
+ export const migration = {
153
+ async up(queryInterface: QueryInterface) {
154
+ await queryInterface.addColumn('users', 'nickname', { type: DataTypes.STRING, allowNull: true });
155
+ },
156
+
157
+ async down(queryInterface: QueryInterface) {
158
+ await queryInterface.removeColumn('users', 'nickname');
159
+ }
160
+ };
29
161
  ```
30
162
 
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*.
163
+ ## Commands
164
+
165
+ ### `gina-cli init`
166
+
167
+ Creates `gina/migrations` with the first migration, which creates the `gina_version` table, and the `HEAD` file. Then set `gina.modelsDir` in your `package.json`.
168
+
169
+ ### `gina-cli upgrade`
34
170
 
35
- ### Upgrade database
171
+ Applies every pending migration in order, updating `gina_version` after each one. Run it on deploy, before the new version of the app starts.
36
172
 
37
- Once you have the `initializeModels` configured you can upgrade your database using:
173
+ #### `--dry-run`
174
+
175
+ Rehearses the pending migrations without changing the database (MySQL/MariaDB): Gina copies the schema, without data, to a temporary database on the same server, applies the pending migrations there and drops it. Run it in the deploy before the real `upgrade` to catch errors like an index or foreign key that can't be created, a column that doesn't exist, or a name that's already taken.
176
+
177
+ Errors that depend on the data can still happen, like duplicates on a new unique index or NULLs on a column that becomes `NOT NULL`. The database user needs permission to create and drop databases.
178
+
179
+ #### `--from-snapshot`
180
+
181
+ On an empty database, creates the schema from the [snapshot](#gina-cli-snapshot) and then applies only the migrations after it. Meant for development, where recreating the database would otherwise run every migration.
182
+
183
+ ### When a migration fails halfway
184
+
185
+ MySQL can't roll back schema changes: every `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` is committed right away, so a transaction around the migration wouldn't help. When a migration fails after changing something, Gina:
186
+
187
+ 1. lists what was applied before the error, e.g. `addColumn users.nickname`;
188
+ 2. records the failure in a `gina_failure` table, and keeps `gina_version` at the previous migration;
189
+ 3. refuses to run `upgrade` or `downgrade` until the failure is repaired, so nothing runs on top of a half-applied migration.
190
+
191
+ If it fails before changing anything, there's nothing to repair: fix it and run `upgrade` again.
192
+
193
+ ### `gina-cli repair --continue | --rollback`
194
+
195
+ Finishes or undoes the migration that failed halfway. Fix the cause first (e.g. remove the duplicates that broke a unique index, or fix the migration), then:
196
+
197
+ - `--continue` runs the migration again and moves the version forward;
198
+ - `--rollback` runs its `down`, undoing what was applied.
199
+
200
+ Either way, each operation is checked before it runs and skipped when the database is already the way it would leave it: a column that already exists isn't added again, an index that was never created isn't removed. Skipped operations are logged, e.g. `skipped: addColumn users.nickname (column users.nickname already exists)`. Any other error still fails.
201
+
202
+ The check is by name, for the `QueryInterface` methods that create, drop, rename, add or remove tables, columns, indexes and constraints; `changeColumn` always runs again, which is harmless. Raw queries (`queryInterface.sequelize.query`) and bulk operations can't be checked and would run again, so `repair` refuses migrations with them unless you review it and pass `--yes`.
203
+
204
+ ### `gina-cli downgrade [steps] [--to <migration>]`
205
+
206
+ Reverts applied migrations, newest first, running each one's `down` and updating `gina_version` after each one.
38
207
 
39
208
  ```bash
40
- gina-cli upgrade
209
+ npx gina-cli downgrade # reverts the last migration
210
+ npx gina-cli downgrade 3 # reverts the last 3 migrations
211
+ npx gina-cli downgrade --to 20240531183010 # reverts every migration after 20240531183010-*
41
212
  ```
42
213
 
43
- ### Generating new migration
214
+ `--to` takes the migration to go back to, which stays applied. It can be the full name or any prefix that matches only one migration, like its timestamp.
215
+
216
+ The first migration (the one `init` creates) is never reverted, because it creates the `gina_version` table. Gina checks the whole request before reverting anything: if you ask for more migrations than can be reverted, or one of them has no `down`, nothing runs.
217
+
218
+ ### `gina-cli check`
219
+
220
+ Checks that the migrations form a single chain and that `HEAD` names the last one. It loads the migration files but doesn't connect to the database, so it fits in CI.
221
+
222
+ ### `gina-cli snapshot`
223
+
224
+ Runs every migration on a temporary database (MySQL/MariaDB) and writes the resulting schema to `snapshot.sql` (see `snapshotFile`), with the version it's at. Then `gina-cli upgrade --from-snapshot` creates a new development database from it in one go, and applies only the migrations added after the snapshot was taken, so it doesn't need to be regenerated with every migration.
225
+
226
+ The migrations stay the source of truth, and everything else keeps using them: production, `downgrade` (a database created from the snapshot can still be downgraded) and `upgrade` without the flag. The snapshot has no data: if a migration inserts or changes rows, `snapshot` lists it so you know that data is missing.
227
+
228
+ ### `gina-cli generate-migration "<name>"`
229
+
230
+ Loads your models, compares them with the database the environment variables point to, and writes `<migrationsDir>/<timestamp>-<name>.ts`. If there are no differences, no file is written.
231
+
232
+ Point it at a database that is up to date (run `upgrade` first; Gina refuses otherwise). Gina writes whatever is different between your models and that database. The new migration runs after the last one (`previous`) and becomes `HEAD`.
44
233
 
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`.
234
+ It detects:
235
+
236
+ - new and removed tables
237
+ - new and removed columns
238
+ - changes to existing columns (MySQL/MariaDB only): type, including length and enum values (e.g. adding a value to an `ENUM`), nullability and default value. These become `changeColumn` calls. `up` uses the model's definition and `down` restores the column as it was in the database.
239
+ - foreign keys of new columns
240
+ - new and removed indexes, including ordered fields like `{ name: 'time', order: 'DESC' }`
241
+
242
+ Column types are written with their parameters, e.g. `DataTypes.ENUM('draft', 'published')`, `DataTypes.STRING(100)` or `DataTypes.DECIMAL(10, 2)`. Enum values are written into the migration instead of importing the enum from your code, so the migration keeps working after the enum changes again.
243
+
244
+ Remember that Sequelize considers a column nullable unless the attribute says `allowNull: false`. That includes attributes created by associations (`foreignKey: 'userId'`) and shorthand timestamps (`createdAt: DataTypes.DATE`). If the database has them as `NOT NULL`, Gina reports the difference. Declare `allowNull: false` in the model (for associations, `foreignKey: { name: 'userId', allowNull: false }`) if that's what you want.
245
+
246
+ The generated `down` undoes the `up`, so `downgrade` brings the schema back to what it was: foreign keys added by the migration are removed first, and dropped columns are added back at their original position (MySQL/MariaDB).
247
+
248
+ **Always review the generated file.** Gina doesn't detect renames (they show up as a drop plus an add), changes to foreign keys, primary keys or auto increment of existing columns. Write those parts by hand.
249
+
250
+ ## Using it in production
251
+
252
+ Install dependencies, build, and run `upgrade` from the folder that has `package.json` and the compiled output. For example, as a Kubernetes job or Helm hook that runs before the new pods start:
253
+
254
+ ```yaml
255
+ command: ["npx", "gina-cli", "upgrade"]
256
+ ```
257
+
258
+ No TypeScript tooling is needed at runtime if the migrations and models are compiled to `.js`.
259
+
260
+ To catch problems before they reach the database, run a rehearsal first; the real `upgrade` only runs if it passes:
48
261
 
49
262
  ```bash
50
- gina-cli generate-migration "Creating user table"
263
+ npx gina-cli upgrade --dry-run && npx gina-cli upgrade
51
264
  ```
52
265
 
266
+ If a migration still fails halfway, see [When a migration fails halfway](#when-a-migration-fails-halfway).
267
+
53
268
  ## Development
54
269
 
55
- If you want to edit the cli and test it you can install it locally:
270
+ ```bash
271
+ npm install
272
+ npm run build
273
+ npm run eslint
274
+ ```
275
+
276
+ ### End-to-end tests
277
+
278
+ `e2e/run.sh` tests Gina the way a user would: it packs Gina, installs the tarball into a separate project (`e2e/fixture`) and, against a new schema with a random name, runs:
279
+
280
+ 1. `init` and `upgrade` on an empty database
281
+ 2. `generate-migration` and `upgrade` with the initial models, then compares the schema with `e2e/expected/v1.json`
282
+ 3. `generate-migration` again, which must not create a file
283
+ 4. a model change (`e2e/changes`), then `generate-migration` and `upgrade`, then compares the schema with `e2e/expected/v2.json`
284
+ 5. `downgrade`, `downgrade 2` and `downgrade --to`, comparing the schema after each one (`v1.json`, and `base.json` for only the version table), and checking that a `downgrade` beyond the first migration is refused without changing anything
285
+ 6. the migration chain: a migration from a branch merged late (`e2e/scenarios/late-branch.ts`) is refused by `check`, `upgrade` and `generate-migration` until it runs after the last one, and then runs even though its name sorts first
286
+ 7. a migration that fails halfway (`e2e/scenarios/fails-halfway.ts`): `upgrade --dry-run` catches it without touching the database, the real `upgrade` records it, `upgrade` and `downgrade` refuse to run, and `repair --rollback` and `repair --continue` each bring the schema to the expected state
287
+ 8. `snapshot` and `upgrade --from-snapshot` on a new database, with a migration added after the snapshot, then `downgrade` from there
288
+ 9. `upgrade` from the compiled `.js` only (production-like) on a new database, then compares the schema with `e2e/expected/v2.json`
289
+
290
+ It needs a MySQL server:
56
291
 
57
292
  ```bash
58
- npm install -g .
293
+ docker run -d --name gina-mysql -e MYSQL_ROOT_PASSWORD=root -p 3306:3306 mysql:8.0
294
+ npm run test:e2e
59
295
  ```
296
+
297
+ Connection settings come from `DB_HOST`, `DB_PORT`, `DB_USERNAME` and `DB_PASSWORD` (defaults: `127.0.0.1`, `3306`, `root`, `root`). After an intended change to the generated schema, run `UPDATE_SNAPSHOTS=1 npm run test:e2e` and review the diff in `e2e/expected/`.
298
+
299
+ ### CI and releases
300
+
301
+ `.github/workflows/e2e.yml` runs lint and the end-to-end suite against MySQL 8.0 on Node 18, 20.10.0, 20, 22 and 24, in parallel, on every push and pull request.
302
+
303
+ Publishing to npm (`.github/workflows/npm-publish.yml`, triggered by creating a GitHub release) runs the same suite first. If it fails on any Node version, the package isn't published.
304
+
305
+ The publish job authenticates with npm through [trusted publishing](https://docs.npmjs.com/trusted-publishers) (OIDC), configured on the package settings at npmjs.com for `digital-divas/gina` and `npm-publish.yml`. No npm token is stored in the repository. To release, bump `version` in `package.json`, merge, and create a GitHub release for that version.
package/bin/index.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable @typescript-eslint/no-var-requires */
3
+
4
+ // Prefer the gina installed in the project being migrated, so models, migrations
5
+ // and gina share the same sequelize copy even when gina-cli was installed globally.
6
+ const path = require('path');
7
+
8
+ let cli = path.join(__dirname, '..', 'dist', 'cli.js');
9
+ try {
10
+ cli = require.resolve('gina-sequelize/dist/cli.js', { paths: [process.cwd()] });
11
+ } catch {
12
+ // not installed on the project (or an old version without dist/cli.js)
13
+ }
14
+
15
+ require(cli);
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};