javascriptnode.jssqlitenode-sqlite3

Sqlite3 database empty after running migration in javascript


this is db.js

const sqlite3 = require('sqlite3').verbose();
const path = require('path')
const { migrationScript } = require('../db/migrations/migrate');
const WDIR = process.cwd();
const DB_PATH = path.join(WDIR, 'db', 'DB.db');

const db = new sqlite3.Database(DB_PATH, (err) => {if (err) { console.log(err);}});
db.run(migrationScript, (err) => {if (err) { console.log(err);}})
db.close()

migrate.js doesn't even matter as it's just a const multiline string and it gets ignored

no matter what i type in it. i also get no erros. after execution it creates a 0kb file that ofcourse doesn't have any tables or nothing. im mentioning that migrationscript starts with pragma foreign_keys = on, but again it doens't seem to even read it. i tried using serialize and doing the db.run inside it, didn't matter. yes i checked, migrationScript object is NOT empty inside db.js. it seems fine


Solution

  • Use db.exec() rather than db.run() to execute a string containing multiple queries.

    db.exec(migrationScript, (err) => {if (err) { console.log(err);}})