Skip to content

Commit

Permalink
chore: emit ts file
Browse files Browse the repository at this point in the history
  • Loading branch information
yannamsellem committed Jan 6, 2025
1 parent c0aed3e commit 2dac054
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
49 changes: 49 additions & 0 deletions src/migrate.js
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('');
}
7 changes: 4 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./dist",

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,

"types": ["vite/client"]
"types": ["vite/client"],
},
"include": ["src/migrate.ts"]
}

0 comments on commit 2dac054

Please sign in to comment.