This repository has been archived on 2024-05-29. You can view files and clone it, but cannot push or open issues or pull requests.
reset-sender-v2/scripts/migrate.js

68 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-02-23 18:43:00 +01:00
import { Kysely, SqliteDialect, sql } from "kysely";
import Database from "better-sqlite3";
import "dotenv/config";
const path = process.env.DATABASE_PATH;
if (!path) {
throw new Error("DATABASE_PATH environment variable is not defined.");
}
console.log("Database path", path);
const database = new Database(path);
database.exec("PRAGMA journal_mode = WAL;");
const dialect = new SqliteDialect({ database });
const db = new Kysely({ dialect });
const migrations = [
db.schema
.createTable("letters")
.addColumn("id", "integer", (c) => c.primaryKey())
.addColumn("created", "datetime", (c) => c.defaultTo(sql`CURRENT_TIMESTAMP`).notNull())
.addColumn("updated", "datetime", (c) => c.defaultTo(sql`CURRENT_TIMESTAMP`).notNull())
.addColumn("firstName", "text", (c) => c.notNull())
.addColumn("lastName", "text", (c) => c.notNull())
.addColumn("language", "text", (c) => c.notNull())
.addColumn("email", "text", (c) => c.notNull())
.addColumn("phone", "text")
.addColumn("variant", "text", (c) => c.notNull())
.addColumn("gender", "text")
.addColumn("branch", "text", (c) => c.notNull())
.addColumn("isClient", "boolean", (c) => c.notNull())
.addColumn("message", "text", (c) => c.notNull())
.addColumn("subscribed", "boolean", (c) => c.notNull())
.addColumn("confirmationToken", "text", (c) => c.notNull())
.addColumn("confirmed", "boolean", (c) => c.notNull().defaultTo(false)),
];
async function initMigrationsTable() {
await db.schema
.createTable("migrations")
.ifNotExists()
.addColumn("id", "integer", (c) => c.primaryKey())
.addColumn("executedAt", "datetime", (c) => c.defaultTo(sql`CURRENT_TIMESTAMP`).notNull())
.execute();
}
async function runMigrations() {
initMigrationsTable();
for (const [id, migration] of migrations.entries()) {
const migrationRecord = await db
.selectFrom("migrations")
.where("id", "=", id)
.select(["id", "executedAt"])
.executeTakeFirst();
if (migrationRecord) {
console.log(id, "|", "at", migrationRecord.executedAt);
} else {
await migration.execute();
await db.insertInto("migrations").values({ id }).execute();
console.log(id, "|", "now");
}
}
}
runMigrations();