check db exists first before creating in postgres (#5968)

Signed-off-by: si458 <simonsmith5521@gmail.com>

Simon Smith committed Mar 31, 2024 at 19:20 UTC 102489447da553fd91e7bc7792736615b4719cff
1 file changed +19 -12
db.js
+19 -12
@@ -785,20 +785,28 @@ module.exports.CreateDB = function (parent, func) {
785 var dbname = (connectinArgs.database != null) ? connectinArgs.database : 'meshcentral';
786 delete connectinArgs.database;
787 obj.databaseType = 6;
788 - const pgtools = require('pgtools');
789 - pgtools.createdb(connectinArgs, dbname, function (err, res) {
790 - const { Pool, Client } = require('pg');
791 - connectinArgs.database = dbname;
792 - Datastore = new Client(connectinArgs);
793 - Datastore.connect();
794 - if (err == null) {
795 - // Create the tables and indexes
796 - postgreSqlCreateTables(func);
797 - } else {
798 - // Database already existed, perform a test query to see if the main table is present
788 + const { Pool, Client } = require('pg');
789 + connectinArgs.database = dbname;
790 + Datastore = new Client(connectinArgs);
791 + Datastore.connect();
792 + sqlDbQuery('SELECT 1 FROM pg_database WHERE datname = $1', [dbname], function (dberr, dbdocs) { // check database exists first before creating
793 + if (dberr == null) { // database exists now check tables exists
794 sqlDbQuery('SELECT doc FROM main WHERE id = $1', ['DatabaseIdentifier'], function (err, docs) {
795 if (err == null) { setupFunctions(func); } else { postgreSqlCreateTables(func); } // If not present, create the tables and indexes
796 });
797 + } else { // If not present, create the tables and indexes
798 + const pgtools = require('pgtools');
799 + pgtools.createdb(connectinArgs, dbname, function (err, res) {
800 + if (err == null) {
801 + // Create the tables and indexes
802 + postgreSqlCreateTables(func);
803 + } else {
804 + // Database already existed, perform a test query to see if the main table is present
805 + sqlDbQuery('SELECT doc FROM main WHERE id = $1', ['DatabaseIdentifier'], function (err, docs) {
806 + if (err == null) { setupFunctions(func); } else { postgreSqlCreateTables(func); } // If not present, create the tables and indexes
807 + });
808 + }
809 + });
810 }
811 });
812 } else if (parent.args.mongodb) {
@@ -1260,7 +1268,6 @@ module.exports.CreateDB = function (parent, func) {
1268 } else if (obj.databaseType == 6) { // Postgres SQL
1269 Datastore.query(query, args, function (error, results) {
1270 if (error != null) {
1263 - console.log(query, args, error);
1271 if (func) try { func(error); } catch (ex) { console.log('SQLERR4', ex); }
1272 } else {
1273 var docs = [];