From c4efc9a21d90c3c2477fd72df565a22ddd3a5728 Mon Sep 17 00:00:00 2001 From: Bofh Date: Sun, 27 Nov 2022 21:17:38 +0100 Subject: [PATCH] Add PgDatabase class for Postgres connections --- classes/PgDatabase.php | 71 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/classes/PgDatabase.php b/classes/PgDatabase.php index cfde8bc..b86c6c3 100644 --- a/classes/PgDatabase.php +++ b/classes/PgDatabase.php @@ -1,5 +1,74 @@ 'instance parameter is not correctly formatted'], 400); + if (!preg_match('/^[a-zA-Z0-9\.\-\_]+$/', $software)) + apiresult(['error' => 'software parameter is not correctly formatted'], 400); + + $GLOBALS['IS_PHP'] = true; + require 'api/v1/config/get/mod.php'; + unset($GLOBALS['IS_PHP']); + + $found = false; + foreach ($GLOBALS['api_data']['hosts'][$software] as $ins_cfg) { + if ($ins_cfg['instance'] === $instance) { + $found = $ins_cfg; + break; + } + } + if ($found === false) return; + $config = []; + $config_raw = explode("\n", trim($found['config'])); + foreach ($config_raw as $ln) { + $k = substr($ln, 0, strpos($ln,'=')); + $v = substr($ln, strpos($ln,'=')+1); + $config[$k] = $v; + } + + $this->db = pg_connect( + ' host='.$config['psql_host']. + ' port='.$config['psql_port']. + ' dbname='.$config['psql_db']. + ' user='.$config['psql_username']. + ' password='.$config['psql_password']. + '') or apiresult('Could not connect to postgres: '.pg_last_error()); + } + + public function is_ok() { + return $this->db !== null; + } + + public function query($sql) { + $result = pg_query($sql); + if (!$result) apiresult('The postgres query has failed: '.pg_last_error()); + return $result; + } + + public function fetch_all($sql) { + $data = []; + $result = $this->query($sql); + while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) { + $data []= $line; + } + pg_free_result($result); + return $data; + } + + public function close($result=null) { + if ($result !== null) + pg_free_result($result); + pg_close($this->db); + } }