diff --git a/bun.lockb b/bun.lockb index d37f33e..5948c7b 100644 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/db.sqlite b/db.sqlite index d893593..4200a9b 100644 Binary files a/db.sqlite and b/db.sqlite differ diff --git a/modules/database.sync/module.ts b/modules/database.sync/module.ts new file mode 100644 index 0000000..24d6799 --- /dev/null +++ b/modules/database.sync/module.ts @@ -0,0 +1,52 @@ +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(); + }); + } +}) \ No newline at end of file diff --git a/nuxt.config.ts b/nuxt.config.ts index 3423692..e541b41 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -1,4 +1,5 @@ // https://nuxt.com/docs/api/configuration/nuxt-config +import DatabaseSync from './modules/database.sync/module'; export default defineNuxtConfig({ modules: [ @@ -6,9 +7,11 @@ export default defineNuxtConfig({ "nuxt-security", "@nuxtjs/tailwindcss", "@vueuse/nuxt", + DatabaseSync ], runtimeConfig: { dbFile: 'db.sqlite', + templateFile: 'template.sqlite', session: { password: '699c46bd-9aaa-4364-ad01-510ee4fe7013' } diff --git a/template.sqlite b/template.sqlite new file mode 100644 index 0000000..381db22 Binary files /dev/null and b/template.sqlite differ