Add new database structure synchronisation at build time
This commit is contained in:
parent
f2261c3f35
commit
fa1a13d411
|
|
@ -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();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
// https://nuxt.com/docs/api/configuration/nuxt-config
|
||||||
|
import DatabaseSync from './modules/database.sync/module';
|
||||||
|
|
||||||
export default defineNuxtConfig({
|
export default defineNuxtConfig({
|
||||||
modules: [
|
modules: [
|
||||||
|
|
@ -6,9 +7,11 @@ export default defineNuxtConfig({
|
||||||
"nuxt-security",
|
"nuxt-security",
|
||||||
"@nuxtjs/tailwindcss",
|
"@nuxtjs/tailwindcss",
|
||||||
"@vueuse/nuxt",
|
"@vueuse/nuxt",
|
||||||
|
DatabaseSync
|
||||||
],
|
],
|
||||||
runtimeConfig: {
|
runtimeConfig: {
|
||||||
dbFile: 'db.sqlite',
|
dbFile: 'db.sqlite',
|
||||||
|
templateFile: 'template.sqlite',
|
||||||
session: {
|
session: {
|
||||||
password: '699c46bd-9aaa-4364-ad01-510ee4fe7013'
|
password: '699c46bd-9aaa-4364-ad01-510ee4fe7013'
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Binary file not shown.
Loading…
Reference in New Issue