52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
import { defineNuxtModule } from '@nuxt/kit'
|
|
import { Database } from "bun:sqlite";
|
|
|
|
interface Schema
|
|
{
|
|
type: string;
|
|
name: string;
|
|
tbl_name: string;
|
|
sql: string;
|
|
}
|
|
interface Structure
|
|
{
|
|
cid: number;
|
|
name: string;
|
|
type: string;
|
|
[key: string]: number | string | null;
|
|
}
|
|
|
|
export default defineNuxtModule({
|
|
setup (options, nuxt) {
|
|
nuxt.hook('build:done', () => {
|
|
console.log("Building database");
|
|
|
|
const template = new Database(nuxt.options.runtimeConfig.templateFile);
|
|
const schema = template.query(`SELECT * FROM sqlite_schema WHERE type = 'table'`).all() as Schema[];
|
|
|
|
const db = new Database(nuxt.options.runtimeConfig.dbFile);
|
|
db.exec(`PRAGMA foreign_keys = 0`);
|
|
const structure = db.query(`SELECT * FROM pragma_table_info(?1)`);
|
|
|
|
(db.transaction((tables: Schema[]) => {
|
|
for(const table of tables)
|
|
{
|
|
if(table.name === 'sqlite_sequence')
|
|
continue;
|
|
|
|
const columns = structure.all(table.name) as Structure[];
|
|
|
|
db.exec(`ALTER TABLE ${table.name} RENAME TO ${table.name}_old`);
|
|
db.exec(table.sql);
|
|
db.exec(`INSERT INTO ${table.name} (${columns.map(e => `"${e.name}"`).join(', ')}) SELECT * FROM ${table.name}_old`);
|
|
db.exec(`DROP TABLE ${table.name}_old`);
|
|
}
|
|
})).immediate(schema);
|
|
|
|
db.exec(`PRAGMA foreign_keys = 1`);
|
|
|
|
db.close();
|
|
template.close();
|
|
});
|
|
}
|
|
}) |