@stacksjs/database 0.75.674 → 0.75.683
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/compiled-migrations.d.ts +57 -0
- package/dist/compiled-migrations.js +5 -0
- package/package.json +16 -16
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a migration opens its own transaction: a statement that starts with
|
|
3
|
+
* `BEGIN` once comments are gone. A trigger body's `BEGIN` follows `FOR EACH
|
|
4
|
+
* ROW`, not a statement end, so it does not count.
|
|
5
|
+
*/
|
|
6
|
+
export declare function managesOwnTransaction(sql: string): boolean;
|
|
7
|
+
/** The schema version a set of migrations brings a database to: the highest file number. */
|
|
8
|
+
export declare function schemaVersion(migrations: Record<string, string>): number;
|
|
9
|
+
/**
|
|
10
|
+
* The schema version recorded in a database, or 0 for one that has none.
|
|
11
|
+
*
|
|
12
|
+
* Read from the file header when no write-ahead log is pending, so asking
|
|
13
|
+
* changes nothing on disk: on Linux even a read-only connection to a WAL
|
|
14
|
+
* database creates `-shm` and `-wal` files it cannot remove, and the refusal
|
|
15
|
+
* of a newer database is meant to leave it exactly as it was found.
|
|
16
|
+
*/
|
|
17
|
+
export declare function databaseVersion(databasePath: string): number;
|
|
18
|
+
/** The migrations a build carries that this database has not had, in order. */
|
|
19
|
+
export declare function pendingMigrations(databasePath: string, migrations: Record<string, string>): string[];
|
|
20
|
+
/** Write a consistent copy of a live database to `destination`, readable by its owner only. */
|
|
21
|
+
export declare function backupDatabase(databasePath: string, destination: string): void;
|
|
22
|
+
/**
|
|
23
|
+
* Bring the database at `databasePath` up to the schema `migrations` describe.
|
|
24
|
+
*
|
|
25
|
+
* A missing database is created and given every migration, with no backup.
|
|
26
|
+
* An existing one is first checked against the build: a newer schema throws
|
|
27
|
+
* {@link NewerSchemaError} and nothing changes. When anything is pending, a
|
|
28
|
+
* consistent backup is written, the pending files are applied in order, and a
|
|
29
|
+
* failure puts the backup back and throws {@link MigrationRestoredError}.
|
|
30
|
+
* Older backups beyond `keepBackups` are removed after a success.
|
|
31
|
+
*/
|
|
32
|
+
export declare function migrateCompiledDatabase(options: CompiledMigrationOptions): CompiledMigrationResult;
|
|
33
|
+
export declare interface CompiledMigrationOptions {
|
|
34
|
+
databasePath: string
|
|
35
|
+
migrations: Record<string, string>
|
|
36
|
+
backupDir?: string
|
|
37
|
+
keepBackups?: number
|
|
38
|
+
}
|
|
39
|
+
export declare interface CompiledMigrationResult {
|
|
40
|
+
applied: string[]
|
|
41
|
+
created: boolean
|
|
42
|
+
backup?: string
|
|
43
|
+
version: number
|
|
44
|
+
}
|
|
45
|
+
/** The database was last used by a newer build. Nothing was changed. */
|
|
46
|
+
export declare class NewerSchemaError extends Error {
|
|
47
|
+
public readonly found: number;
|
|
48
|
+
public readonly supported: number;
|
|
49
|
+
constructor(found: number, supported: number);
|
|
50
|
+
}
|
|
51
|
+
/** A migration failed, and the database was put back as it was. */
|
|
52
|
+
export declare class MigrationRestoredError extends Error {
|
|
53
|
+
public readonly migration: string;
|
|
54
|
+
public readonly backup: string;
|
|
55
|
+
public readonly cause: unknown;
|
|
56
|
+
constructor(migration: string, backup: string, cause: unknown);
|
|
57
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{Database}from"bun:sqlite";import{chmodSync,closeSync,copyFileSync,existsSync,mkdirSync,openSync,readdirSync,readSync,rmSync,statSync}from"node:fs";import{basename,dirname,extname,join}from"node:path";export class NewerSchemaError extends Error{found;supported;constructor(found,supported){super(`This data was last used by a newer version of the app (schema ${found}; this version understands ${supported}). Nothing was changed.`);this.found=found;this.supported=supported;this.name="NewerSchemaError"}}export class MigrationRestoredError extends Error{migration;backup;cause;constructor(migration,backup,cause){super(`Migration ${migration} failed, and the data was put back as it was: ${cause instanceof Error?cause.message:String(cause)}. A copy is also at ${backup}.`);this.migration=migration;this.backup=backup;this.cause=cause;this.name="MigrationRestoredError"}}export function managesOwnTransaction(sql){const withoutComments=sql.replace(/--[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");return/(?:^|;)\s*BEGIN\b/i.test(withoutComments)}function migrationNumber(name){return Number(name.match(/^(\d+)/)?.[1]??0)}export function schemaVersion(migrations){return Object.keys(migrations).reduce((highest,name)=>Math.max(highest,migrationNumber(name)),0)}export function databaseVersion(databasePath){const header=headerUserVersion(databasePath);if(header!==undefined)return header;const database=new Database(databasePath,{readonly:true});try{return Number(database.query("PRAGMA user_version").get().user_version)}finally{database.close()}}function headerUserVersion(databasePath){const wal=`${databasePath}-wal`;if(existsSync(wal)&&statSync(wal).size>0)return;const header=Buffer.alloc(100);const fd=openSync(databasePath,"r");try{if(readSync(fd,header,0,100,0)<100)return 0}finally{closeSync(fd)}if(header.toString("latin1",0,16)!=="SQLite format 3\x00")return;return header.readInt32BE(60)}export function pendingMigrations(databasePath,migrations){const names=Object.keys(migrations).sort();if(!existsSync(databasePath))return names;const database=new Database(databasePath,{readonly:true});try{const done=new Set(database.query("SELECT migration FROM migrations").all().map((row)=>row.migration));return names.filter((name)=>!done.has(name))}catch{return names}finally{database.close()}}export function backupDatabase(databasePath,destination){mkdirSync(dirname(destination),{recursive:true});rmSync(destination,{force:true});const database=new Database(databasePath);try{database.exec(`VACUUM INTO '${destination.replace(/'/g,"''")}'`)}finally{database.close()}chmodSync(destination,384)}function restoreDatabase(backup,databasePath){for(const suffix of["","-wal","-shm"])rmSync(`${databasePath}${suffix}`,{force:true});copyFileSync(backup,databasePath);chmodSync(databasePath,384)}function stem(databasePath){const name=basename(databasePath);return extname(name)?name.slice(0,-extname(name).length):name}function pruneBackups(databasePath,backupDir,keep){const prefix=`${stem(databasePath)}.before-`;const backups=readdirSync(backupDir).filter((name)=>name.startsWith(prefix)&&name.endsWith(".sqlite")).sort();for(const name of backups.slice(0,Math.max(0,backups.length-keep)))rmSync(join(backupDir,name),{force:true})}function applyMigrations(databasePath,migrations,pending){const database=new Database(databasePath);const applied=[];try{database.exec("PRAGMA journal_mode = WAL");database.exec(`CREATE TABLE IF NOT EXISTS migrations (
|
|
2
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
4
|
+
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
5
|
+
)`);const record=database.query("INSERT INTO migrations (migration) VALUES (?)");for(const name of pending){const sql=migrations[name];try{if(managesOwnTransaction(sql)){database.exec(sql);record.run(name)}else{database.transaction(()=>{database.exec(sql);record.run(name)})()}}catch(error){if(database.inTransaction)database.exec("ROLLBACK");throw Object.assign(error instanceof Error?error:new Error(String(error)),{migration:name})}finally{database.exec("PRAGMA foreign_keys = ON")}applied.push(name)}}finally{database.close()}return applied}function stampVersion(databasePath,version){const database=new Database(databasePath);try{const current=Number(database.query("PRAGMA user_version").get().user_version);if(version>current)database.exec(`PRAGMA user_version = ${Math.trunc(version)}`);return Math.max(current,version)}finally{database.close()}}export function migrateCompiledDatabase(options){const{databasePath,migrations}=options;const supported=schemaVersion(migrations);const created=!existsSync(databasePath);mkdirSync(dirname(databasePath),{recursive:true});if(!created){const found=databaseVersion(databasePath);if(found>supported)throw new NewerSchemaError(found,supported)}const pending=pendingMigrations(databasePath,migrations);if(pending.length===0)return{applied:[],created,version:stampVersion(databasePath,supported)};if(created){const applied=applyMigrations(databasePath,migrations,pending);chmodSync(databasePath,384);return{applied,created,version:stampVersion(databasePath,supported)}}const backupDir=options.backupDir??dirname(databasePath);const backup=join(backupDir,`${stem(databasePath)}.before-${pending[0].replace(/\.sql$/,"")}.sqlite`);backupDatabase(databasePath,backup);let applied;try{applied=applyMigrations(databasePath,migrations,pending)}catch(error){restoreDatabase(backup,databasePath);throw new MigrationRestoredError(error.migration??pending[0],backup,error)}pruneBackups(databasePath,backupDir,Math.max(1,options.keepBackups??3));return{applied,created,backup,version:stampVersion(databasePath,supported)}}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/database",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.683",
|
|
6
6
|
"description": "The Stacks database integration.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,26 +66,26 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/config": "0.75.
|
|
70
|
-
"@stacksjs/env": "0.75.
|
|
71
|
-
"@stacksjs/error-handling": "0.75.
|
|
72
|
-
"@stacksjs/faker": "0.75.
|
|
73
|
-
"@stacksjs/features": "0.75.
|
|
74
|
-
"@stacksjs/logging": "0.75.
|
|
75
|
-
"@stacksjs/model-meta": "0.75.
|
|
76
|
-
"@stacksjs/path": "0.75.
|
|
77
|
-
"@stacksjs/query-builder": "0.75.
|
|
78
|
-
"@stacksjs/security": "0.75.
|
|
79
|
-
"@stacksjs/storage": "0.75.
|
|
80
|
-
"@stacksjs/strings": "0.75.
|
|
69
|
+
"@stacksjs/config": "0.75.683",
|
|
70
|
+
"@stacksjs/env": "0.75.683",
|
|
71
|
+
"@stacksjs/error-handling": "0.75.683",
|
|
72
|
+
"@stacksjs/faker": "0.75.683",
|
|
73
|
+
"@stacksjs/features": "0.75.683",
|
|
74
|
+
"@stacksjs/logging": "0.75.683",
|
|
75
|
+
"@stacksjs/model-meta": "0.75.683",
|
|
76
|
+
"@stacksjs/path": "0.75.683",
|
|
77
|
+
"@stacksjs/query-builder": "0.75.683",
|
|
78
|
+
"@stacksjs/security": "0.75.683",
|
|
79
|
+
"@stacksjs/storage": "0.75.683",
|
|
80
|
+
"@stacksjs/strings": "0.75.683",
|
|
81
81
|
"@stacksjs/ts-validation": "^0.5.7",
|
|
82
82
|
"bun-query-builder": "^0.6.4",
|
|
83
83
|
"dynamodb-tooling": "^0.3.6"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
|
-
"@stacksjs/cli": "0.75.
|
|
87
|
-
"@stacksjs/router": "0.75.
|
|
88
|
-
"@stacksjs/utils": "0.75.
|
|
86
|
+
"@stacksjs/cli": "0.75.683",
|
|
87
|
+
"@stacksjs/router": "0.75.683",
|
|
88
|
+
"@stacksjs/utils": "0.75.683",
|
|
89
89
|
"better-dx": "^0.2.39"
|
|
90
90
|
}
|
|
91
91
|
}
|