<?php
namespace com\whitemagicsoftware;
require "login.php";
use PDO;
use PDOException;
class Database extends Obj {
private static $instance;
private $dataStore;
public function __construct() {
global $dbhost;
global $dbname;
global $dbuser;
global $dbpass;
try {
$this->setDataStore(
new PDO( "pgsql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass ) );
}
catch( PDOException $ex ) {
$this->log( $ex->getMessage() );
}
}
public static function get() {
if( self::$instance === null ) {
self::$instance = new Database();
}
return self::$instance;
}
public function call( $proc, $params = "" ) {
$args = array();
$count = 0;
$placeholders = "";
foreach( func_get_args() as $key => $parameter ) {
if( $key < 2 ) continue;
$count++;
$placeholders = empty( $placeholders ) ? "?" : "$placeholders,?";
array_push( $args, $parameter );
}
$sql = "";
if( empty( $params ) ) {
$sql = "SELECT recipe.$proc( $placeholders )";
}
else if( strpos( $params, "," ) !== false ) {
$sql = "SELECT $params FROM recipe.$proc( $placeholders )";
}
else {
$sql = "SELECT recipe.$proc( $placeholders ) AS $params";
}
$db = $this->getDataStore();
$statement = $db->prepare( $sql );
for( $i = 1; $i <= $count; $i++ ) {
$statement->bindParam( $i, $args[$i - 1] );
}
try {
$result = null;
if( $statement->execute() === true ) {
$result = $statement->fetchAll( PDO::FETCH_ASSOC );
$this->decodeArray( $result );
}
else {
$info = $statement->errorInfo();
$this->log( "SQL failed: $sql" );
$this->log( "Error: ". $info[2] );
}
}
catch( PDOException $ex ) {
$this->log( $ex->getMessage() );
}
return $result;
}
public function arrayToString( $array ) {
return "{" . implode( ",", (array)$array ) . "}";
}
public function toArray( $set ) {
$set = (array)$set;
$result = array();
foreach( $set as $s ) {
if( is_array( $s ) ) {
$result[] = $this->toArray( $s );
}
else {
$result[] = '"' . str_replace( '"', '\\"', $s ) . '"';
}
}
return '{' . implode( ",", $result ) . '}';
}
private function decodeArray( &$array ) {
if( is_array( $array ) ) {
array_map( array( $this, "decodeArray" ), $array );
}
else {
$array = utf8_decode( $array );
}
}
private function getDataStore() {
return $this->dataStore;
}
private function setDataStore( $dataStore ) {
$dataStore->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->dataStore = $dataStore;
}
}