Automates Sqlite DB schema versioning.
Uses wrapper around better-sqlite3 and bun:sqlite to allow cross- runtime/engine usage.
Add your SQL migrations scripts under dedicated project sub-folder, for ex. ./migrations.
See example SQL migrations scripts:
To generate singe migrations bundle file you can use sql-bundle script and run it as part of build process.
For example, in your package.json:
"scripts": {
"sql-bundle": "npx sql-bundle ./migrations"
}Then run it as follows:
npm run sql-bundlebundle.json file will be (re)generated in the same ./migrations folder.
Since it can be easily generated from the input SQL migrations files there is no need to commit this file.
You can exclude it by adding the following line to your
.gitignore file:
migrations/bundle.jsonThe final setup is to actually load and apply migrations on your Sqlite DB during app startup:
import Database from "@farjs/better-sqlite3-wrapper";
import { readBundle, runBundle } from "@farjs/better-sqlite3-migrate";
// connect to your DB
const db = new Database(":memory:");
const bundleUrl = new URL("./migrations/bundle.json", import.meta.url);
// load migrations bundle
const bundle = await readBundle(bundleUrl);
// apply it
await runBundle(db, bundle);This will create (or update existing) schema_versions DB table with the all SQL migrations that were applied.
So, next time it will only apply new SQL migrations, that were not applied before (not exist in schema_versions table yet).