Skip to content

Instantly share code, notes, and snippets.

@misabitencourt
Last active May 20, 2024 15:04
Show Gist options
  • Save misabitencourt/5b10fb9cf07f33bb8902329b8fc43f07 to your computer and use it in GitHub Desktop.
Save misabitencourt/5b10fb9cf07f33bb8902329b8fc43f07 to your computer and use it in GitHub Desktop.
Typescript Bun Knex Sqlite3 Repository Start
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