56 lines
1.5 KiB
PHP
56 lines
1.5 KiB
PHP
<?php
|
|
|
|
class PgDatabase {
|
|
private $db = null;
|
|
|
|
public function __construct() {
|
|
$instance = isset($_GET['instance']) ? trim($_GET['instance']) : null;
|
|
if ($instance === null) return;
|
|
$url = trim($_SERVER['REQUEST_URI'], '/');
|
|
$url = substr($url, 7); // api/vX/
|
|
$ps = explode('/', $url);
|
|
if ($ps[0] !== 'database') return;
|
|
$software = $ps[1];
|
|
|
|
if (!preg_match('/^[a-zA-Z0-9\.\-\_]+$/', $instance))
|
|
apiresult(['error' => 'instance parameter is not correctly formatted'], 400);
|
|
if (!preg_match('/^[a-zA-Z0-9\.\-\_]+$/', $software))
|
|
apiresult(['error' => 'software parameter is not correctly formatted'], 400);
|
|
|
|
$config = instance_config($software, $instance);
|
|
$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);
|
|
}
|
|
}
|