migrane 1.0.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.
Potentially problematic release.
This version of migrane might be problematic. Click here for more details.
- package/LICENSE +21 -0
- package/README.md +425 -0
- package/bin/migrane.js +54 -0
- package/dist/bundle.d.ts +25 -0
- package/dist/bundle.js +70 -0
- package/dist/cli.d.ts +6 -0
- package/dist/cli.js +149 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.js +62 -0
- package/dist/connect.d.ts +18 -0
- package/dist/connect.js +49 -0
- package/dist/defaults.d.ts +22 -0
- package/dist/defaults.js +22 -0
- package/dist/discover.d.ts +42 -0
- package/dist/discover.js +160 -0
- package/dist/drivers/pg.d.ts +9 -0
- package/dist/drivers/pg.js +109 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +31 -0
- package/dist/load.d.ts +53 -0
- package/dist/load.js +119 -0
- package/dist/lock.d.ts +30 -0
- package/dist/lock.js +35 -0
- package/dist/reset.d.ts +23 -0
- package/dist/reset.js +16 -0
- package/dist/runner.d.ts +61 -0
- package/dist/runner.js +150 -0
- package/dist/safety.d.ts +7 -0
- package/dist/safety.js +45 -0
- package/dist/seeds.d.ts +60 -0
- package/dist/seeds.js +132 -0
- package/dist/sql.d.ts +43 -0
- package/dist/sql.js +66 -0
- package/dist/storage.d.ts +52 -0
- package/dist/storage.js +65 -0
- package/dist/types.d.ts +198 -0
- package/dist/types.js +6 -0
- package/package.json +94 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 eishexac <hexac@existin.space>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
# migrane
|
|
2
|
+
|
|
3
|
+
A SQL migration runner that knows nothing about your application.
|
|
4
|
+
|
|
5
|
+
It is handed a driver and a list of directories. That is all it knows — no ORM,
|
|
6
|
+
no container, no module registry, no dependency it makes you adopt. The package
|
|
7
|
+
itself has no runtime dependencies. Everything specific to an application lives
|
|
8
|
+
in that application's config file.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pnpm add -D migrane
|
|
12
|
+
pnpm add pg # only if you use the bundled postgres driver
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// database/config.ts
|
|
17
|
+
import { defineConfig } from 'migrane';
|
|
18
|
+
import { pgDriver } from 'migrane/drivers/pg';
|
|
19
|
+
|
|
20
|
+
export default defineConfig({
|
|
21
|
+
dirs: ['./migrations'],
|
|
22
|
+
seeds: './seeders',
|
|
23
|
+
manifest: './manifest.gen.ts', // only if you ship a container
|
|
24
|
+
driver: () => pgDriver(process.env.DATABASE_URL!),
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
migrane up | down | status
|
|
30
|
+
migrane reset | fresh [unit]
|
|
31
|
+
migrane seed <unit> | unseed <unit>
|
|
32
|
+
migrane manifest [--out <path>]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Config is looked for at `database/config.ts`, then `migrate.config.{ts,js,mjs}`,
|
|
36
|
+
or wherever `--config` points. Paths in it resolve against the config file, not
|
|
37
|
+
the working directory, so the commands answer the same from anywhere in a
|
|
38
|
+
repository.
|
|
39
|
+
|
|
40
|
+
## Runtimes
|
|
41
|
+
|
|
42
|
+
The published package is plain ES modules; the interesting question is who runs
|
|
43
|
+
_your_ config and migrations, because both may be TypeScript and the CLI loads
|
|
44
|
+
them with `import()`.
|
|
45
|
+
|
|
46
|
+
The executable answers it without being told. Its shebang names `sh`, and the
|
|
47
|
+
first line `exec`s the first of **node** then **bun** that is on `PATH` — so a
|
|
48
|
+
machine holding only bun runs it, and a machine holding node behaves exactly as
|
|
49
|
+
it always did.
|
|
50
|
+
|
|
51
|
+
- **node ≥ 22.18** strips types natively — `migrane up` just works.
|
|
52
|
+
- **bun** always ran TypeScript, and is taken when node is absent. To take it on
|
|
53
|
+
a machine that has both, name it per command with `migrane --runtime=bun up`,
|
|
54
|
+
or for the shell with `MIGRANE_RUNTIME=bun migrane up`. The flag wins, and
|
|
55
|
+
must come first — it is read by the executable before any of this package
|
|
56
|
+
runs, and never reaches the command surface.
|
|
57
|
+
Node is preferred by default because **bun loads `.env` from the working
|
|
58
|
+
directory and node does not** — and bun reads it from where you _ran_ the
|
|
59
|
+
command, while everything else here resolves against the config file. A
|
|
60
|
+
variable already set in the environment still wins, so in CI or a container
|
|
61
|
+
both runtimes reach the same database; the difference shows up on a laptop,
|
|
62
|
+
where `cd apps/api && migrane up` can pick up a different `.env` than the
|
|
63
|
+
repository root. `bun --no-env-file` turns that off, for a project that wants
|
|
64
|
+
bun without it.
|
|
65
|
+
- **older node** works when the config is `.js` and the migrations are `.sql`.
|
|
66
|
+
- **Windows** gets a `.cmd` shim that calls `sh`, which Git Bash provides.
|
|
67
|
+
- **Any of them, without the executable:** `run()` is exported, and
|
|
68
|
+
`process.exit(await run(process.argv.slice(2)))` in a `scripts/db.ts` of your
|
|
69
|
+
own is the whole CLI under whatever runtime you like.
|
|
70
|
+
|
|
71
|
+
## Writing a migration
|
|
72
|
+
|
|
73
|
+
A migration is `<number>-<slug>.ts`, `<number>-<slug>.sql`, or a directory of
|
|
74
|
+
that name. `001-initial` and `20260826143000-add-products` both work and can be
|
|
75
|
+
mixed, because ordering compares the number itself — `9-` sorts before `10-`
|
|
76
|
+
without anyone zero-padding.
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import type { Part } from 'migrane';
|
|
80
|
+
|
|
81
|
+
export const up: Part['up'] = async ({ sql }) => {
|
|
82
|
+
await sql`CREATE TABLE users (id uuid PRIMARY KEY, email text NOT NULL)`;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export const down: Part['down'] = async ({ sql }) => {
|
|
86
|
+
await sql`DROP TABLE users`;
|
|
87
|
+
};
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`down` is optional. A great many migrations have no honest reverse, and a
|
|
91
|
+
required one only ever gets an empty body that lies about being reversible.
|
|
92
|
+
|
|
93
|
+
### The `sql` tag
|
|
94
|
+
|
|
95
|
+
Interpolations become **bind parameters**:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
await sql`INSERT INTO users (email) VALUES (${email})`; // → $1
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
DDL is mostly things that cannot be parameters, so the escape is explicit and
|
|
102
|
+
visible in a diff:
|
|
103
|
+
|
|
104
|
+
| | |
|
|
105
|
+
| --------------------- | --------------------------------------------------- |
|
|
106
|
+
| `sql.raw(text)` | splice verbatim |
|
|
107
|
+
| `sql.id(name)` | quote an identifier — `sql.id('order')` → `"order"` |
|
|
108
|
+
| `sql.join(fragments)` | a column list, a set of constraints |
|
|
109
|
+
|
|
110
|
+
A template that interpolates **nothing** sends no parameters, and may therefore
|
|
111
|
+
carry several statements separated by `;` — PostgreSQL only restricts a request
|
|
112
|
+
to one statement once a bind parameter is present.
|
|
113
|
+
|
|
114
|
+
### Directory migrations
|
|
115
|
+
|
|
116
|
+
A directory is one migration made of parts. Two ways to order them, and the
|
|
117
|
+
choice is per directory:
|
|
118
|
+
|
|
119
|
+
**An `index.ts` is the migration.** The array it composes is the order, read top
|
|
120
|
+
to bottom in one place, and the files need no prefixes:
|
|
121
|
+
|
|
122
|
+
```
|
|
123
|
+
001-initial/
|
|
124
|
+
├── index.ts compose([extensions, users, devices])
|
|
125
|
+
├── pg/extensions.ts
|
|
126
|
+
└── tables/users.ts, devices.ts
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
export const { up, down } = compose([extensions, users, devices]);
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Order is _data_ here, not import order — which is what makes it survive an IDE
|
|
134
|
+
reordering the imports above it.
|
|
135
|
+
|
|
136
|
+
**Without an index**, every `.ts`/`.sql` file under the directory is composed in
|
|
137
|
+
path order, and the numbers carry the order:
|
|
138
|
+
|
|
139
|
+
```
|
|
140
|
+
001-initial/
|
|
141
|
+
├── 010-pg/010-extensions.ts
|
|
142
|
+
└── 020-tables/010-users.ts
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Either way `up` runs forwards and `down` in reverse, so foreign keys hold in
|
|
146
|
+
both directions — and either way the checksum covers **every file**, including
|
|
147
|
+
parts only an index imports.
|
|
148
|
+
|
|
149
|
+
### `.sql` migrations
|
|
150
|
+
|
|
151
|
+
```sql
|
|
152
|
+
-- migrate:up
|
|
153
|
+
CREATE TABLE users (id uuid PRIMARY KEY);
|
|
154
|
+
|
|
155
|
+
-- migrate:down
|
|
156
|
+
DROP TABLE users;
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Each section is sent as one statement. Splitting on `;` would be wrong the first
|
|
160
|
+
time a function body or a quoted string contained one.
|
|
161
|
+
|
|
162
|
+
## What it guarantees
|
|
163
|
+
|
|
164
|
+
- **Each migration commits in a transaction with the row that records it.** A
|
|
165
|
+
failure can never leave DDL applied and the bookkeeping unwritten. Add
|
|
166
|
+
`export const transaction = false` for `CREATE INDEX CONCURRENTLY` and friends
|
|
167
|
+
— the runner says so on the line when it does.
|
|
168
|
+
- **A session advisory lock spans the run**, taken before the bookkeeping is
|
|
169
|
+
read. Two containers starting at once is the ordinary case, not the exotic
|
|
170
|
+
one, and without this both see the same empty table and both run the same DDL.
|
|
171
|
+
- **Editing an applied migration is refused**, by checksum, before anything
|
|
172
|
+
runs. A recorded migration that is no longer on disk is _not_ an error —
|
|
173
|
+
that is what squashing looks like from the database's side, and `status` says
|
|
174
|
+
`orphan` rather than failing.
|
|
175
|
+
- **`status` never refuses.** An edited migration is the likeliest reason you
|
|
176
|
+
are running it, so it reports `changed` and finishes the report rather than
|
|
177
|
+
failing on the very thing you asked about. `up` and `down` still refuse, which
|
|
178
|
+
is where refusing belongs.
|
|
179
|
+
|
|
180
|
+
## What it refuses to do
|
|
181
|
+
|
|
182
|
+
`down`, `reset`, `fresh`, `seed` and `unseed` all rewrite data somebody may be
|
|
183
|
+
using, so all five go through one guard (`safety.ts`) before they touch
|
|
184
|
+
anything — on the functions themselves, so importing one directly does not walk
|
|
185
|
+
around it.
|
|
186
|
+
|
|
187
|
+
Two rules, and they are the **default policy** rather than the mechanism — a
|
|
188
|
+
project that declares `guard` replaces both, see [Replacing it](#replacing-it):
|
|
189
|
+
|
|
190
|
+
- **Never under `NODE_ENV=production`.** A production database is restored from
|
|
191
|
+
a backup, not from a flag. Nothing in `safety.ts` gets past this one.
|
|
192
|
+
- **Never against a host that is not this machine.** `localhost`, `127.x`, `::1`
|
|
193
|
+
and a unix socket are this machine; a service name like `postgres` is not,
|
|
194
|
+
because on a droplet that is exactly what production is called.
|
|
195
|
+
|
|
196
|
+
```
|
|
197
|
+
reset drops every table, and db.example.com is not this machine.
|
|
198
|
+
If you mean that database, name it: DB_ALLOW_REMOTE=db.example.com <the same command>
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
The override names the host on purpose: an export left over from last week
|
|
202
|
+
cannot answer for a database it was never about. The host comes off the driver
|
|
203
|
+
rather than the environment, so the guard reads the connection that is about to
|
|
204
|
+
be used and not a variable that resembles it.
|
|
205
|
+
|
|
206
|
+
### Replacing it
|
|
207
|
+
|
|
208
|
+
Both rules above are the **default**, not the mechanism. `guard` replaces them:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
// database/config.ts
|
|
212
|
+
import { defineConfig, refuse } from 'migrane';
|
|
213
|
+
|
|
214
|
+
export default defineConfig({
|
|
215
|
+
// …
|
|
216
|
+
guard: async (driver, what) => {
|
|
217
|
+
const [row] = await driver.query<{ on: string | null }>(
|
|
218
|
+
`SELECT current_setting('migrane.disposable', true) AS on`,
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
if (row?.on === 'yes') return; // this database says it is disposable
|
|
222
|
+
|
|
223
|
+
refuse(driver, what); // otherwise, the default rules
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
**Declaring nothing is not the same as declaring no policy.** Omit `guard` and
|
|
229
|
+
`refuse` is what runs, so a project that has never thought about this gets the
|
|
230
|
+
strict default rather than none at all. Declare one and it replaces both rules,
|
|
231
|
+
`NODE_ENV=production` included — which is how a preview environment rebuilds its
|
|
232
|
+
own fixtures from the image it is already running, instead of having a
|
|
233
|
+
developer's database copied onto it.
|
|
234
|
+
|
|
235
|
+
Put the permission on the database rather than in a shell:
|
|
236
|
+
|
|
237
|
+
```sql
|
|
238
|
+
ALTER DATABASE preview SET migrane.disposable = 'yes';
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
That survives a schema drop, needs ownership to set, and cannot be typed onto
|
|
242
|
+
the wrong machine — unlike a host name, which in a compose stack is the same
|
|
243
|
+
word on every machine you own.
|
|
244
|
+
|
|
245
|
+
One policy, not a list. A guard yields a verdict, and combining verdicts needs
|
|
246
|
+
an operator a config field cannot spell — so write the composition you mean, as
|
|
247
|
+
above.
|
|
248
|
+
|
|
249
|
+
## Hooks
|
|
250
|
+
|
|
251
|
+
`before` runs once per `up`, on the pinned connection, ahead of anything
|
|
252
|
+
pending — and **even when nothing is pending**, because whether a hook needs to
|
|
253
|
+
run has nothing to do with whether a new migration was added.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
before: [async ({ sql }) => void (await sql`CREATE EXTENSION IF NOT EXISTS pg_trgm`)],
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
It is the seam for anything you want true _before_ a migration but do not want
|
|
260
|
+
to write as one — types synced from a registry, a search path, an extension. It
|
|
261
|
+
is also the only place the runner will execute code it did not discover.
|
|
262
|
+
`status` and `reset` do not run hooks; neither has business writing DDL.
|
|
263
|
+
|
|
264
|
+
## Seeds
|
|
265
|
+
|
|
266
|
+
Seed units are **alternatives, not increments** — one directory is one dataset
|
|
267
|
+
and you run exactly one against a fresh database. A unit is recorded but never
|
|
268
|
+
refused: editing a fixture set and running it again is how one is used, so the
|
|
269
|
+
row moves rather than the insert failing.
|
|
270
|
+
|
|
271
|
+
`status` reads that row back as `current`, `changed since`, or `unit is gone` —
|
|
272
|
+
which answers _which fixtures is this database holding_, and is the only
|
|
273
|
+
question the table exists for.
|
|
274
|
+
|
|
275
|
+
Make a unit safe to run twice: `ON CONFLICT DO NOTHING`, `IF NOT EXISTS`, or
|
|
276
|
+
truncate first. Nothing above it will stop a second run.
|
|
277
|
+
|
|
278
|
+
## Shipping it in a container
|
|
279
|
+
|
|
280
|
+
Discovery is a directory read and loading is `import(file)` or `readFileSync`;
|
|
281
|
+
no bundler follows any of them, and an image has no directories. So the build
|
|
282
|
+
generates a **manifest** — imports and two arrays, and nothing else:
|
|
283
|
+
|
|
284
|
+
```sh
|
|
285
|
+
migrane manifest # writes where `manifest` in the config points
|
|
286
|
+
migrane manifest --out gen/manifest.ts
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Declare the destination rather than letting this package pick one — `entryFor`
|
|
290
|
+
writes every specifier **relative to where the manifest lands**, so guessing
|
|
291
|
+
where it goes would guess what is in it. With neither `manifest` nor `--out`,
|
|
292
|
+
the command says so instead of inventing a path. It opens no database, which is
|
|
293
|
+
what makes it a build step: nothing to connect to, and nothing it could reach.
|
|
294
|
+
|
|
295
|
+
`entryFor` stays exported for a build that would rather call it directly.
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
// database/manifest.gen.ts — generated, gitignored, regenerated every build
|
|
299
|
+
import * as m1_0 from '../migrations/002-backfill.ts';
|
|
300
|
+
|
|
301
|
+
export const migrations = [
|
|
302
|
+
{
|
|
303
|
+
name: '001-initial',
|
|
304
|
+
sequence: 1,
|
|
305
|
+
checksum: 'ab12…',
|
|
306
|
+
parts: [{ sql: `…` }],
|
|
307
|
+
},
|
|
308
|
+
{ name: '002-backfill', sequence: 2, checksum: '77aa…', parts: [m1_0] },
|
|
309
|
+
];
|
|
310
|
+
|
|
311
|
+
export const seeds = [];
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
A `.ts` part is imported, a `.sql` part is carried as text — the same split
|
|
315
|
+
`load()` makes, because it is the same split. A project written entirely in SQL
|
|
316
|
+
generates a manifest that imports nothing at all, which is to say: data.
|
|
317
|
+
|
|
318
|
+
The lists are `discover()`'s and `unitsIn()`'s own output, so the image applies
|
|
319
|
+
the same units in the same order and records the same hashes as the CLI. That
|
|
320
|
+
agreement is the whole reason this lives in the library rather than in your
|
|
321
|
+
build script.
|
|
322
|
+
|
|
323
|
+
### The entry is yours
|
|
324
|
+
|
|
325
|
+
The manifest calls nothing, so nothing worth reading lives where a linter, a
|
|
326
|
+
checker and a test cannot reach it. What to do with the arrays is ordinary
|
|
327
|
+
source in your repository, and the verbs are the ones you want:
|
|
328
|
+
|
|
329
|
+
```ts
|
|
330
|
+
// database/entry.ts
|
|
331
|
+
import {
|
|
332
|
+
fromManifest,
|
|
333
|
+
planFrom,
|
|
334
|
+
reachable,
|
|
335
|
+
seedPlanFrom,
|
|
336
|
+
seed,
|
|
337
|
+
status,
|
|
338
|
+
up,
|
|
339
|
+
withDriver,
|
|
340
|
+
} from 'migrane';
|
|
341
|
+
import config from './config.ts';
|
|
342
|
+
import { migrations, seeds } from './manifest.gen.ts';
|
|
343
|
+
|
|
344
|
+
const [verb = 'up', unit] = process.argv.slice(2);
|
|
345
|
+
|
|
346
|
+
process.exit(
|
|
347
|
+
await withDriver(config, async (driver) => {
|
|
348
|
+
try {
|
|
349
|
+
await reachable(driver);
|
|
350
|
+
|
|
351
|
+
const plan = planFrom(config, fromManifest(migrations));
|
|
352
|
+
|
|
353
|
+
if (verb === 'up') await up(driver, plan);
|
|
354
|
+
else if (verb === 'status') await status(driver, plan);
|
|
355
|
+
else if (verb === 'seed')
|
|
356
|
+
await seed(driver, seedPlanFrom(config, fromManifest(seeds)), unit!);
|
|
357
|
+
else throw new Error(`unknown command: ${verb}`);
|
|
358
|
+
|
|
359
|
+
return 0;
|
|
360
|
+
} catch (error) {
|
|
361
|
+
console.error(error);
|
|
362
|
+
|
|
363
|
+
return 1;
|
|
364
|
+
}
|
|
365
|
+
}),
|
|
366
|
+
);
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
The exit code is the contract a deploy reads: a one-shot migrate container that
|
|
370
|
+
exits non-zero holds the previous release in place rather than starting a server
|
|
371
|
+
against a schema that never got written.
|
|
372
|
+
|
|
373
|
+
Offering `down` or `reset` there is your call, not this package's — and either
|
|
374
|
+
still goes through the guard above before it touches anything.
|
|
375
|
+
|
|
376
|
+
## Writing a driver
|
|
377
|
+
|
|
378
|
+
Three methods and a host, over a session that can lock and transact.
|
|
379
|
+
`drivers/pg.ts` is the reference, and `pg` is an optional peer dependency —
|
|
380
|
+
importing `migrane` does not reach it, only importing `migrane/drivers/pg`
|
|
381
|
+
does.
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
import type { Driver, Session } from 'migrane';
|
|
385
|
+
|
|
386
|
+
interface Driver {
|
|
387
|
+
readonly host: string; // where these coordinates point; '' for a unix socket
|
|
388
|
+
query(text, values?): Promise<Row[]>;
|
|
389
|
+
session<T>(run: (session: Session) => Promise<T>): Promise<T>;
|
|
390
|
+
close(): Promise<void>;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
interface Session extends Queryable {
|
|
394
|
+
transaction<T>(run: (tx: Queryable) => Promise<T>): Promise<T>;
|
|
395
|
+
lock<T>(key: number, run: () => Promise<T>): Promise<T>;
|
|
396
|
+
}
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
`host` is required rather than optional-with-a-default because the destructive
|
|
400
|
+
commands refuse on it, and a driver that could leave it out would be a driver
|
|
401
|
+
that silently opts out of the refusal. State it even when it is `'localhost'`.
|
|
402
|
+
|
|
403
|
+
`session` pins one connection: a lock and a transaction are only meaningful on a
|
|
404
|
+
connection that stays the same between statements, and a pool hands out
|
|
405
|
+
whichever is free.
|
|
406
|
+
|
|
407
|
+
`lock` is a **method rather than a statement the runner sends**, because taking
|
|
408
|
+
a lock is a database-agnostic idea and `SELECT pg_advisory_lock($1)` is not —
|
|
409
|
+
this package names no database, and that statement was the one place it did. It
|
|
410
|
+
takes and releases around `run`, so no caller can forget to give a lock back,
|
|
411
|
+
and it must block rather than fail: whoever holds it is applying the migrations
|
|
412
|
+
this process wants applied, so waiting is the correct outcome. Where a database
|
|
413
|
+
has nothing like one, a driver that runs one migrator at a time may implement it
|
|
414
|
+
as `run()` and say so.
|
|
415
|
+
|
|
416
|
+
One honest caveat: the core is agnostic by contract, PostgreSQL-first in
|
|
417
|
+
dialect. The `sql` tag emits `$n` placeholders, the bookkeeping tables use
|
|
418
|
+
`TIMESTAMPTZ`/`now()`, and `reset` speaks `DROP SCHEMA … CASCADE`. A driver for
|
|
419
|
+
another database is absolutely writable — its `query` translates what its
|
|
420
|
+
database spells differently — but that translation is the driver's job until a
|
|
421
|
+
second first-party driver moves the seams here.
|
|
422
|
+
|
|
423
|
+
## License
|
|
424
|
+
|
|
425
|
+
[MIT](LICENSE)
|
package/bin/migrane.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env sh
|
|
2
|
+
':' //; f=; case "$1" in --runtime=*) f=${1#--runtime=}; shift;; esac; for r in ${f:-${MIGRANE_RUNTIME:-node bun}}; do command -v "$r" >/dev/null 2>&1 && exec "$r" "$0" "$@"; done; echo 'migrane: needs node or bun on PATH' >&2; exit 1
|
|
3
|
+
|
|
4
|
+
import { run } from '../dist/cli.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The `migrane` executable. Argument handling lives in `src/cli.ts`; this file
|
|
8
|
+
* turns its answer into an exit code.
|
|
9
|
+
*
|
|
10
|
+
* Plain JavaScript rather than part of the build, because `cli.ts` is also a
|
|
11
|
+
* library export: an entrypoint runs on import, and what `index.ts` re-exports
|
|
12
|
+
* must never do that.
|
|
13
|
+
*
|
|
14
|
+
* ## Line 2 is sh and JavaScript at once
|
|
15
|
+
*
|
|
16
|
+
* `#!/usr/bin/env node` makes this package unusable on a bun-only machine — the
|
|
17
|
+
* kernel reads the shebang, so nothing of ours runs and no error of ours can
|
|
18
|
+
* explain why. Naming `sh` instead lets the line below pick a runtime and
|
|
19
|
+
* `exec` it on this same file.
|
|
20
|
+
*
|
|
21
|
+
* sh reads `:` called with the argument `//`, then a loop. JavaScript reads the
|
|
22
|
+
* string `':'` and a `//` comment swallowing the rest — which is why the whole
|
|
23
|
+
* dispatch has to stay on one line. Both runtimes strip a `#!` first line, so
|
|
24
|
+
* what arrives is a valid module.
|
|
25
|
+
*
|
|
26
|
+
* **`.prettierignore` names this file, and that is load-bearing.** Prettier
|
|
27
|
+
* reformats the line to `':'; //;`, which is still valid JavaScript and no
|
|
28
|
+
* longer valid sh: `:` loses its argument, the shell tries to run `//`, and
|
|
29
|
+
* every command prints `//: is a directory` before working.
|
|
30
|
+
*
|
|
31
|
+
* ## Which runtime, and why node first
|
|
32
|
+
*
|
|
33
|
+
* `migrane --runtime=bun up` names it per command, `MIGRANE_RUNTIME=bun` for
|
|
34
|
+
* the shell, and the flag wins. It must come first and use the `=` form: this
|
|
35
|
+
* line reads exactly one argument, because scanning the whole list would take
|
|
36
|
+
* more shell than fits in a JavaScript comment. It never reaches `run()`, which
|
|
37
|
+
* is why the usage `cli.ts` prints does not list it.
|
|
38
|
+
*
|
|
39
|
+
* Node is tried first as a compatibility promise, not a preference — a machine
|
|
40
|
+
* holding both behaved as node before this line existed. The two differ in one
|
|
41
|
+
* way that matters: bun loads `.env` from the *working directory*, while
|
|
42
|
+
* everything else here resolves against the config file, so `cd apps/api &&
|
|
43
|
+
* migrane up` can pick up a different `.env` than the repository root. A
|
|
44
|
+
* variable already set in the environment still wins, so CI and containers are
|
|
45
|
+
* unaffected. See the README for the full trade and `bun --no-env-file`.
|
|
46
|
+
*
|
|
47
|
+
* ## The cost is Windows
|
|
48
|
+
*
|
|
49
|
+
* npm writes the `.cmd` shim from this shebang, so it emits one calling `sh`:
|
|
50
|
+
* present under Git Bash, absent otherwise. `#!/bin/sh` would emit a literal
|
|
51
|
+
* path cmd.exe can never resolve, so the `env` form degrades rather than dies.
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
process.exit(await run(process.argv.slice(2)));
|
package/dist/bundle.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Resolved } from './config.js';
|
|
2
|
+
/**
|
|
3
|
+
* Writing the manifest a bundler can follow.
|
|
4
|
+
*
|
|
5
|
+
* Discovery is a directory read and loading is `import(file)` or
|
|
6
|
+
* `readFileSync`; no bundler follows any of them, and an image has no
|
|
7
|
+
* directories. So a build calls this and bundles what it writes. The lists come
|
|
8
|
+
* from `discover()` and `unitsIn()`, so an image applies the same units in the
|
|
9
|
+
* same order and records the same checksums as the CLI.
|
|
10
|
+
*
|
|
11
|
+
* **Data, not a program**: imports and two arrays, calling nothing. What to do
|
|
12
|
+
* with the arrays is the consumer's entry, which is ordinary source in their
|
|
13
|
+
* repository rather than generated text no linter reaches.
|
|
14
|
+
*/
|
|
15
|
+
export interface EntryOptions {
|
|
16
|
+
/** The resolved config. Read for its directories, never imported. */
|
|
17
|
+
config: Resolved;
|
|
18
|
+
/**
|
|
19
|
+
* Where the manifest will be written. Given one, every specifier is relative
|
|
20
|
+
* to it, so the file resolves the same on any machine; omitted, specifiers
|
|
21
|
+
* are absolute, which only suits a file going to a temporary directory.
|
|
22
|
+
*/
|
|
23
|
+
to?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare const entryFor: ({ config, to }: EntryOptions) => string;
|
package/dist/bundle.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, extname, relative, sep } from 'node:path';
|
|
3
|
+
import { discover } from './discover.js';
|
|
4
|
+
import { unitsIn } from './seeds.js';
|
|
5
|
+
/**
|
|
6
|
+
* POSIX separators unconditionally: `relative` answers with backslashes on
|
|
7
|
+
* Windows, and a backslash in an import specifier is an escape.
|
|
8
|
+
*/
|
|
9
|
+
const specifierFor = (file, to) => {
|
|
10
|
+
if (!to)
|
|
11
|
+
return file;
|
|
12
|
+
const path = relative(dirname(to), file).split(sep).join('/');
|
|
13
|
+
return path.startsWith('.') ? path : `./${path}`;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* SQL carried as text rather than imported, because a `.sql` migration is
|
|
17
|
+
* loaded with `readFileSync` and never `import`. Inlining is what that becomes
|
|
18
|
+
* when there is no file to read, byte-for-byte, so the checksum still describes
|
|
19
|
+
* what the image runs.
|
|
20
|
+
*
|
|
21
|
+
* A template literal so newlines survive; three escapes make it reversible.
|
|
22
|
+
*/
|
|
23
|
+
const inlined = (file) => '`' +
|
|
24
|
+
readFileSync(file, 'utf8')
|
|
25
|
+
.replaceAll('\\', '\\\\')
|
|
26
|
+
.replaceAll('`', '\\`')
|
|
27
|
+
.replaceAll('${', '\\${') +
|
|
28
|
+
'`';
|
|
29
|
+
/**
|
|
30
|
+
* One array's worth of entries: the imports its `.ts` parts need, and a row per
|
|
31
|
+
* unit naming its parts in run order.
|
|
32
|
+
*
|
|
33
|
+
* Parts stay an ordered list of either kind, because a directory without an
|
|
34
|
+
* index may hold both and the order is the dependency order. Composing them is
|
|
35
|
+
* `fromManifest`'s job, which keeps this file importing nothing from the runner.
|
|
36
|
+
*/
|
|
37
|
+
const emit = (found, prefix, to) => {
|
|
38
|
+
const imports = [];
|
|
39
|
+
const rows = [];
|
|
40
|
+
found.forEach((entry, index) => {
|
|
41
|
+
const parts = entry.run.map((file, part) => {
|
|
42
|
+
if (extname(file) === '.sql')
|
|
43
|
+
return `{ sql: ${inlined(file)} }`;
|
|
44
|
+
const binding = `${prefix}${index}_${part}`;
|
|
45
|
+
imports.push(`import * as ${binding} from ${JSON.stringify(specifierFor(file, to))};`);
|
|
46
|
+
return binding;
|
|
47
|
+
});
|
|
48
|
+
rows.push(` { name: ${JSON.stringify(entry.name)}, sequence: ${entry.sequence}, checksum: ${JSON.stringify(entry.checksum)}, parts: [${parts.join(', ')}] },`);
|
|
49
|
+
});
|
|
50
|
+
return { imports, rows };
|
|
51
|
+
};
|
|
52
|
+
const arrayOf = (name, rows) => rows.length
|
|
53
|
+
? [`export const ${name} = [`, ...rows, '];']
|
|
54
|
+
: [`export const ${name} = [];`];
|
|
55
|
+
export const entryFor = ({ config, to }) => {
|
|
56
|
+
const migrations = emit(discover(config.dirs), 'm', to);
|
|
57
|
+
// A consumer with no seeds declares none, and gets an empty array rather than
|
|
58
|
+
// a missing export: an entry that destructures both should not have to know
|
|
59
|
+
// which of them this project happens to have.
|
|
60
|
+
const seeds = emit(config.seeds ? unitsIn(config.seeds) : [], 's', to);
|
|
61
|
+
return [
|
|
62
|
+
...migrations.imports,
|
|
63
|
+
...seeds.imports,
|
|
64
|
+
...(migrations.imports.length || seeds.imports.length ? [''] : []),
|
|
65
|
+
...arrayOf('migrations', migrations.rows),
|
|
66
|
+
'',
|
|
67
|
+
...arrayOf('seeds', seeds.rows),
|
|
68
|
+
'',
|
|
69
|
+
].join('\n');
|
|
70
|
+
};
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The exit code is the contract a deploy reads: a one-shot migrate container
|
|
3
|
+
* that exits non-zero holds the previous release in place rather than starting
|
|
4
|
+
* a server against a schema that never got written.
|
|
5
|
+
*/
|
|
6
|
+
export declare const run: (argv: readonly string[], cwd?: string) => Promise<number>;
|