Skip to content

Commit

Permalink
Checking for tables at startup
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexeiKharchev committed Nov 3, 2024
1 parent 5e627cb commit 3806c35
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/services/sql_init.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,24 @@ const dbReady = utils.deferred();

cls.init(initDbConnection);

function schemaExists() {
function checkTableExistsInDb(TableName) {
return !!sql.getValue(`SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'options'`);
WHERE type = 'table' AND name = '${TableName}'`);
}

function schemaExists() {
return checkTableExistsInDb('options');
}

function readTableNamesFromSchema(schema) {
return schema.split(";").reduce((acc, str) => str.includes("CREATE TABLE IF NOT EXISTS ") ?
[...acc, str.replaceAll("\n", '').replace(/^.*CREATE TABLE IF NOT EXISTS[ \t]+"([^"]*)".*/, "$1")] : acc, []);
}

function getTableInitializingQuery(schema, tblName) {
return schema.split(";").filter((str) => {
return str.includes(tblName);
});
}

function isDbInitialized() {
Expand All @@ -38,6 +53,18 @@ async function initDbConnection() {
return;
}

const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, 'UTF-8');

readTableNamesFromSchema(schema).forEach((tblName) => {
if (!checkTableExistsInDb(tblName)) {
log.info(`Table ${tblName} not found in DB, creating ...`);
getTableInitializingQuery(schema, tblName).forEach((sQuery) => {
sql.execute(sQuery);
log.info(sQuery);
});
}
})

await migrationService.migrateIfNecessary();

sql.execute('CREATE TEMP TABLE "param_list" (`paramId` TEXT NOT NULL PRIMARY KEY)');
Expand Down Expand Up @@ -131,7 +158,7 @@ function createDatabaseForSync(options, syncServerHost = '', syncProxy = '') {
sql.transactional(() => {
sql.executeScript(schema);

require('./options_init.js').initNotSyncedOptions(false, { syncServerHost, syncProxy });
require('./options_init.js').initNotSyncedOptions(false, { syncServerHost, syncProxy });

// document options required for sync to kick off
for (const opt of options) {
Expand Down

0 comments on commit 3806c35

Please sign in to comment.