-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c0aed3e
commit 2dac054
Showing
2 changed files
with
53 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import MIGRATIONS_TABLE from './migrations_table.sql?raw'; | ||
export class MigrationManager { | ||
constructor(database) { | ||
Object.defineProperty(this, "database", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: database | ||
}); | ||
} | ||
async migrate(migrations) { | ||
await this.init(); | ||
try { | ||
await this.database.exec('BEGIN TRANSACTION'); | ||
for (const migration of migrations) { | ||
await this.migrateOne(migration); | ||
} | ||
await this.database.exec('COMMIT'); | ||
} | ||
catch (error) { | ||
await this.database.exec('ROLLBACK'); | ||
throw error; | ||
} | ||
} | ||
async init() { | ||
await this.database.exec(MIGRATIONS_TABLE); | ||
} | ||
async migrateOne(migration) { | ||
const hashValue = await hash(migration.script); | ||
const [row] = await this.database.exec('SELECT hash FROM migrations WHERE name = ?', [ | ||
migration.name | ||
]); | ||
if (row && row.hash !== hashValue) { | ||
throw new Error(`Migration ${migration.name} has been modified`); | ||
} | ||
if (!row) { | ||
await this.database.exec(migration.script); | ||
await this.database.exec('INSERT INTO migrations (name, hash) VALUES (?, ?)', [ | ||
migration.name, | ||
hashValue | ||
]); | ||
} | ||
} | ||
} | ||
async function hash(input) { | ||
const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input)); | ||
const hashArray = Array.from(new Uint8Array(hashBuffer)); | ||
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters