{"size": 978, "ext": "js", "max_stars_repo_path": "backend/db.js", "max_stars_repo_name": "ohhskar-school/gitrack", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backend/db.js", "max_issues_repo_name": "ohhskar-school/gitrack", "max_issues_repo_issues_event_min_datetime": "2021-04-08T08:11:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T05:35:36.000Z", "max_forks_repo_path": "backend/db.js", "max_forks_repo_name": "ohhskar-school/gitrack", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 7, "max_forks_count": null, "avg_line_length": 19.56, "max_line_length": 46, "alphanum_fraction": 0.5777096115}
const sqlite3 = require('sqlite3');
const { open } = require('sqlite');
const debug = require('debug')('backend:db');
const schema = require('./schema');

let filename;

switch (process.env.NODE_ENV) {
  case 'PROD':
    filename = './gitrack-prod.db';
    break;
  case 'TEST':
    filename = './gitrack-test.db';
    sqlite3.verbose();
    break;
  default:
  case 'DEV':
    filename = './gitrack-dev.db';
    sqlite3.verbose();
    break;
}

async function initDB() {
  try {
    const db = await open({
      filename,
      driver: sqlite3.cached.Database,
    });

    debug('Connected to the tables database');
    debug('Adding tables to DB');
    schema.forEach(async (val) => {
      try {
        db.run(val);
      } catch (err) {
        debug('Error creating table');
        debug(err);
      }
    });

    return db;
  } catch (err) {
    debug('Error connecting to the database');
    debug(err);
    return process.exit(1);
  }
}

module.exports = initDB();
