Last active
May 20, 2024 15:04
-
-
Save misabitencourt/5b10fb9cf07f33bb8902329b8fc43f07 to your computer and use it in GitHub Desktop.
Typescript Bun Knex Sqlite3 Repository Start
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
import knex from "knex"; | |
import fs from 'fs'; | |
if (!fs.existsSync('./local.db')) { | |
fs.appendFileSync('./local.db', ''); | |
} | |
export const localDb = knex({ | |
client: 'sqlite3', | |
connection: { | |
filename: './local.db', | |
}, | |
}); | |
const migrations = [ | |
{ | |
name: 'create-table-kv', | |
async migrationFn() { | |
await localDb.schema.createTableIfNotExists('kv', (table: any) => { | |
table.string('kv_key'); | |
table.string('kv_val'); | |
table.index('kv_key', 'kv_kv_key_index'); | |
}); | |
} | |
} | |
// More migrations here | |
]; | |
const MIGRATIONS_TABLE = '__migrations'; | |
localDb.schema | |
.createTableIfNotExists(MIGRATIONS_TABLE, (table: any) => { | |
table.increments(); | |
table.string('name'); | |
}).finally(() => { | |
(async () => { | |
const migrated = async (migration: string) => { | |
const exists = await localDb(MIGRATIONS_TABLE).select('name').where('name', migration); | |
return exists.length; | |
} | |
const checkAndRunMigration = async (migration: string, migrationFn: () => Promise<void>) => { | |
const done = await migrated(migration); | |
if (!done) { | |
await migrationFn(); | |
await localDb(MIGRATIONS_TABLE).insert({ name: migration }); | |
} | |
} | |
for (const migration of migrations) { | |
await checkAndRunMigration(migration.name, migration.migrationFn); | |
} | |
})().catch(err => { | |
console.error(err); | |
process.exit(1); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment