Nodejs and SQLite how create multiply tables?

var sqlite3 = require('sqlite3').verbose();
var md5 = require('md5');
const users = require("./users");
const usersStatistic = require("./users_statistic");
const DBSOURCE = "db.sqlite";

let db = new sqlite3.Database(DBSOURCE, (err) => {
    if (err) {
        // Cannot open database
        console.error(err.message)
        throw err
    }else{
        console.log('Connected to the SQlite database.');
        db.run(`CREATE TABLE user (
            id integer,
            first_name text, 
            last_name text,
            email text UNIQUE,
            gender text,
            ip_address text,
            CONSTRAINT email_unique UNIQUE (email)
            )`,(err) => {
            if (err) {
                // Table already created
            }else{
                // Table just created, creating some rows

                let props = '';

                for (let i = 0; i < Object.keys(users[0]).length; i++) {
                    if(i ===  Object.keys(users[0]).length - 1) {
                        props += `${Object.keys(users[0])[i]}`
                    }else {
                        props += `${Object.keys(users[0])[i]}, `
                    }
                }

                const insert = `INSERT INTO user (${props}) VALUES (?,?,?,?,?,?)`;

                for (let i = 0; i < users.length; i++) {
                    const user = users[i];

                    db.run(insert,
                        Object.values(user)
                    )
                }
            }
        });
        //Start second table
        db.run(`CREATE TABLE user_statistic (
            user_id integer,
            date text, 
            page_views integer,
            clicks integer,
            )`,(err) => {
            if (err) {
                // Table already created
            }else{
                // Table just created, creating some rows
                let props = '';

                for (let i = 0; i < Object.keys(usersStatistic[0]).length; i++) {
                    if(i ===  Object.keys(usersStatistic[0]).length - 1) {
                        props += `${Object.keys(usersStatistic[0])[i]}`
                    }else {
                        props += `${Object.keys(usersStatistic[0])[i]}, `
                    }
                }
                const insert = `INSERT INTO user (${props}) VALUES (?,?,?,?)`;

                console.log(insert)
                for (let i = 0; i < usersStatistic.length; i++) {
                    const userStatistic = usersStatistic[i];
                    db.run(insert,
                        Object.values(userStatistic)
                    )
                }
            }
        });

    }
});
module.exports = db;

and i have only fist table, second run() not created second table on db.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.