Subversion Repositories oidplus

Rev

Rev 502 | Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. if (!defined('INSIDE_OIDPLUS')) die();
  21.  
  22. class OIDplusDatabaseConnectionPgSql extends OIDplusDatabaseConnection {
  23.         private $conn = null;
  24.         private $already_prepared = array();
  25.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  26.  
  27.         public static function getPlugin(): OIDplusDatabasePlugin {
  28.                 return new OIDplusDatabasePluginPgSql();
  29.         }
  30.  
  31.         public function doQuery(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
  32.                 $this->last_error = null;
  33.                 if (is_null($prepared_args)) {
  34.                         $res = @pg_query($this->conn, $sql);
  35.  
  36.                         if ($res === false) {
  37.                                 $this->last_error = pg_last_error($this->conn);
  38.                                 throw new OIDplusSQLException($sql, $this->error());
  39.                         } else {
  40.                                 return new OIDplusQueryResultPgSql($res);
  41.                         }
  42.                 } else {
  43.                         if (!is_array($prepared_args)) {
  44.                                 throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
  45.                         }
  46.  
  47.                         // convert ? ? ? to $1 $2 $3
  48.                         $sql = preg_replace_callback('@\\?@', function($found) {
  49.                                 static $i = 0;
  50.                                 $i++;
  51.                                 return '$'.$i;
  52.                         }, $sql);
  53.  
  54.                         $prepare_name = 'OIDplus_ps_'.sha1($sql);
  55.                         if (!in_array($prepare_name, $this->already_prepared)) {
  56.                                 $res = @pg_prepare($this->conn, $prepare_name, $sql);
  57.                                 if ($res === false) {
  58.                                         $this->last_error = pg_last_error($this->conn);
  59.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  60.                                 }
  61.                                 $this->already_prepared[] = $prepare_name;
  62.                         }
  63.  
  64.                         foreach ($prepared_args as &$value) {
  65.                                 if (is_bool($value)) $value = $value ? '1' : '0';
  66.                         }
  67.  
  68.                         $ps = pg_execute($this->conn, $prepare_name, $prepared_args);
  69.                         if ($ps === false) {
  70.                                 $this->last_error = pg_last_error($this->conn);
  71.                                 throw new OIDplusSQLException($sql, $this->error());
  72.                         }
  73.                         return new OIDplusQueryResultPgSql($ps);
  74.                 }
  75.         }
  76.  
  77.         public function insert_id(): int {
  78.                 try {
  79.                         return (int)$this->query('select lastval() as id')->fetch_object()->id;
  80.                 } catch (Exception $e) {
  81.                         return 0;
  82.                 }
  83.         }
  84.  
  85.         public function error(): string {
  86.                 $err = $this->last_error;
  87.                 if ($err == null) $err = '';
  88.                 return $err;
  89.         }
  90.  
  91.         protected function doConnect()/*: void*/ {
  92.                 if (!function_exists('pg_connect')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PostgreSQL'));
  93.  
  94.                 // Try connecting to the database
  95.                 ob_start();
  96.                 $err = '';
  97.                 try {
  98.                         $host     = OIDplus::baseConfig()->getValue('PGSQL_HOST',     'localhost:5432');
  99.                         $username = OIDplus::baseConfig()->getValue('PGSQL_USERNAME', 'postgres');
  100.                         $password = OIDplus::baseConfig()->getValue('PGSQL_PASSWORD', '');
  101.                         $database = OIDplus::baseConfig()->getValue('PGSQL_DATABASE', 'oidplus');
  102.                         list($hostname, $port) = explode(':', "$host:5432");
  103.                         // We need to use PGSQL_CONNECT_FORCE_NEW because we require two connectoins (for isolated log message queries)
  104.                         $this->conn = pg_connect("host=$hostname user=$username password=$password port=$port dbname=$database", PGSQL_CONNECT_FORCE_NEW);
  105.                 } finally {
  106.                         # TODO: this does not seem to work?! (at least not for CLI)
  107.                         $err = ob_get_contents();
  108.                         ob_end_clean();
  109.                 }
  110.  
  111.                 if (!$this->conn) {
  112.                         throw new OIDplusConfigInitializationException(_L('Connection to the database failed!').' ' . strip_tags($err));
  113.                 }
  114.  
  115.                 $this->already_prepared = array();
  116.                 $this->last_error = null;
  117.  
  118.                 try {
  119.                         $this->query("SET NAMES 'utf8'");
  120.                 } catch (Exception $e) {
  121.                 }
  122.         }
  123.  
  124.         protected function doDisconnect()/*: void*/ {
  125.                 $this->already_prepared = array();
  126.                 if (!is_null($this->conn)) {
  127.                         pg_close($this->conn);
  128.                         $this->conn = null;
  129.                 }
  130.         }
  131.  
  132.         private $intransaction = false;
  133.  
  134.         public function transaction_supported(): bool {
  135.                 return true;
  136.         }
  137.  
  138.         public function transaction_level(): int {
  139.                 return $this->intransaction ? 1 : 0;
  140.         }
  141.  
  142.         public function transaction_begin()/*: void*/ {
  143.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  144.                 $this->query('begin transaction');
  145.                 $this->intransaction = true;
  146.         }
  147.  
  148.         public function transaction_commit()/*: void*/ {
  149.                 $this->query('commit');
  150.                 $this->intransaction = false;
  151.         }
  152.  
  153.         public function transaction_rollback()/*: void*/ {
  154.                 $this->query('rollback');
  155.                 $this->intransaction = false;
  156.         }
  157.  
  158.         public function sqlDate(): string {
  159.                 return 'now()';
  160.         }
  161.  
  162.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  163.                 $slang = OIDplus::getSqlSlangPlugin('pgsql');
  164.                 if (is_null($slang)) {
  165.                         throw new OIDplusConfigInitializationException(_L('SQL-Slang plugin "%1" is missing. Please check if it exists in the directory "plugin/sqlSlang". If it is not existing, please recover it from an SVN snapshot or OIDplus ZIP file.','pgsql'));
  166.                 }
  167.                 return $slang;
  168.         }
  169. }