Skip to content

Commit

Permalink
check db exists first before creating in postgres (Ylianst#5968)
Browse files Browse the repository at this point in the history
Signed-off-by: si458 <simonsmith5521@gmail.com>
  • Loading branch information
si458 authored Mar 31, 2024
1 parent 8e8cc4b commit 1024894
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions db.js
Original file line number Diff line number Diff line change
Expand Up @@ -785,20 +785,28 @@ module.exports.CreateDB = function (parent, func) {
var dbname = (connectinArgs.database != null) ? connectinArgs.database : 'meshcentral';
delete connectinArgs.database;
obj.databaseType = 6;
const pgtools = require('pgtools');
pgtools.createdb(connectinArgs, dbname, function (err, res) {
const { Pool, Client } = require('pg');
connectinArgs.database = dbname;
Datastore = new Client(connectinArgs);
Datastore.connect();
if (err == null) {
// Create the tables and indexes
postgreSqlCreateTables(func);
} else {
// Database already existed, perform a test query to see if the main table is present
const { Pool, Client } = require('pg');
connectinArgs.database = dbname;
Datastore = new Client(connectinArgs);
Datastore.connect();
sqlDbQuery('SELECT 1 FROM pg_database WHERE datname = $1', [dbname], function (dberr, dbdocs) { // check database exists first before creating
if (dberr == null) { // database exists now check tables exists
sqlDbQuery('SELECT doc FROM main WHERE id = $1', ['DatabaseIdentifier'], function (err, docs) {
if (err == null) { setupFunctions(func); } else { postgreSqlCreateTables(func); } // If not present, create the tables and indexes
});
} else { // If not present, create the tables and indexes
const pgtools = require('pgtools');
pgtools.createdb(connectinArgs, dbname, function (err, res) {
if (err == null) {
// Create the tables and indexes
postgreSqlCreateTables(func);
} else {
// Database already existed, perform a test query to see if the main table is present
sqlDbQuery('SELECT doc FROM main WHERE id = $1', ['DatabaseIdentifier'], function (err, docs) {
if (err == null) { setupFunctions(func); } else { postgreSqlCreateTables(func); } // If not present, create the tables and indexes
});
}
});
}
});
} else if (parent.args.mongodb) {
Expand Down Expand Up @@ -1260,7 +1268,6 @@ module.exports.CreateDB = function (parent, func) {
} else if (obj.databaseType == 6) { // Postgres SQL
Datastore.query(query, args, function (error, results) {
if (error != null) {
console.log(query, args, error);
if (func) try { func(error); } catch (ex) { console.log('SQLERR4', ex); }
} else {
var docs = [];
Expand Down

0 comments on commit 1024894

Please sign in to comment.