soselo/classes/PgDatabase.php

88 lines
2.3 KiB
PHP
Raw Normal View History

2022-11-24 22:41:05 +00:00
<?php
class PgDatabase {
private $db = null;
public function __construct($software=null, $instance=null) {
if ($software === null) {
$url = trim($_SERVER['REQUEST_URI'], '/');
$url = substr($url, 7); // api/vX/
$ps = explode('/', $url);
if ($ps[0] !== 'database') return;
$software = $ps[1];
}
$config = null;
if ($instance === null)
$config = instance_config($software);
else $config = instance_config($software, $instance);
2022-11-27 23:54:24 +00:00
if ($config === null) return;
$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(['error' => 'Could not connect to postgres: '.pg_last_error()], 500);
}
public function is_ok() {
return $this->db !== null;
}
public function escape($str) {
return pg_escape_string($this->db, $str);
}
public function query($sql) {
$result = pg_query($this->db, $sql);
if (!$result) apiresult('The postgres query has failed: '.pg_last_error());
return $result;
}
public function fetch($sql, $cache=null) {
$sql = trim($sql);
cronjob_db_create__check_cachecfg($GLOBALS['ap_software'],
$GLOBALS['ap_instance'], $sql, $cache);
$cache_key = $GLOBALS['ap_software'].$GLOBALS['ap_instance'].$sql;
if ($cache !== null) {
$cached = content_cache__get($cache_key);
if ($cached !== null)
return $cached;
}
$result = $this->query($sql);
$data = pg_fetch_assoc($result);
if ($cache !== null)
content_cache__put($cache_key, $cache, $data);
return $data;
}
public function fetch_all($sql, $cache=null) {
$sql = trim($sql);
cronjob_db_create__check_cachecfg($GLOBALS['ap_software'],
$GLOBALS['ap_instance'], $sql, $cache);
$cache_key = $GLOBALS['ap_software'].$GLOBALS['ap_instance'].$sql;
if ($cache !== null) {
$cached = content_cache__get($cache_key);
if ($cached !== null)
return $cached;
}
$data = [];
$result = $this->query($sql);
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$data []= $line;
}
pg_free_result($result);
if ($cache !== null)
content_cache__put($cache_key, $cache, $data);
return $data;
}
public function close($result=null) {
if ($result !== null)
pg_free_result($result);
pg_close($this->db);
}
2022-11-24 22:41:05 +00:00
}