Subversion Repositories oidplus

Rev

Rev 1086 | Rev 1130 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 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. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusDatabaseConnectionPgSql extends OIDplusDatabaseConnection {
  27.         private $conn = null;
  28.         private $already_prepared = array();
  29.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  30.  
  31.         /**
  32.          * @param string $sql
  33.          * @param array|null $prepared_args
  34.          * @return OIDplusQueryResultPgSql
  35.          * @throws OIDplusException
  36.          */
  37.         public function doQuery(string $sql, array $prepared_args=null): OIDplusQueryResult {
  38.                 $this->last_error = null;
  39.                 if (is_null($prepared_args)) {
  40.                         $res = @pg_query($this->conn, $sql);
  41.  
  42.                         if ($res === false) {
  43.                                 $this->last_error = pg_last_error($this->conn);
  44.                                 throw new OIDplusSQLException($sql, $this->error());
  45.                         } else {
  46.                                 return new OIDplusQueryResultPgSql($res);
  47.                         }
  48.                 } else {
  49.                         if (!is_array($prepared_args)) {
  50.                                 throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
  51.                         }
  52.  
  53.                         // convert ? ? ? to $1 $2 $3
  54.                         $sql = preg_replace_callback('@\\?@', function($found) {
  55.                                 static $i = 0;
  56.                                 $i++;
  57.                                 return '$'.$i;
  58.                         }, $sql, count($prepared_args));
  59.  
  60.                         $prepare_name = 'OIDplus_ps_'.sha1($sql);
  61.                         if (!in_array($prepare_name, $this->already_prepared)) {
  62.                                 $res = @pg_prepare($this->conn, $prepare_name, $sql);
  63.                                 if ($res === false) {
  64.                                         $this->last_error = pg_last_error($this->conn);
  65.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  66.                                 }
  67.                                 $this->already_prepared[] = $prepare_name;
  68.                         }
  69.  
  70.                         foreach ($prepared_args as &$value) {
  71.                                 if (is_bool($value)) $value = $value ? '1' : '0';
  72.                         }
  73.  
  74.                         $ps = pg_execute($this->conn, $prepare_name, $prepared_args);
  75.                         if ($ps === false) {
  76.                                 $this->last_error = pg_last_error($this->conn);
  77.                                 throw new OIDplusSQLException($sql, $this->error());
  78.                         }
  79.                         return new OIDplusQueryResultPgSql($ps);
  80.                 }
  81.         }
  82.  
  83.         /**
  84.          * @return int
  85.          */
  86.         public function insert_id(): int {
  87.                 try {
  88.                         return (int)$this->query('select lastval() as id')->fetch_object()->id;
  89.                 } catch (\Exception $e) {
  90.                         return 0;
  91.                 }
  92.         }
  93.  
  94.         /**
  95.          * @return string
  96.          */
  97.         public function error(): string {
  98.                 $err = $this->last_error;
  99.                 if ($err == null) $err = '';
  100.                 return $err;
  101.         }
  102.  
  103.         /**
  104.          * @return void
  105.          * @throws OIDplusConfigInitializationException
  106.          * @throws OIDplusException
  107.          */
  108.         protected function doConnect()/*: void*/ {
  109.                 if (!function_exists('pg_connect')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PostgreSQL'));
  110.  
  111.                 // Try connecting to the database
  112.                 ob_start();
  113.                 $err = '';
  114.                 try {
  115.                         $host     = OIDplus::baseConfig()->getValue('PGSQL_HOST',     'localhost:5432');
  116.                         $username = OIDplus::baseConfig()->getValue('PGSQL_USERNAME', 'postgres');
  117.                         $password = OIDplus::baseConfig()->getValue('PGSQL_PASSWORD', '');
  118.                         $database = OIDplus::baseConfig()->getValue('PGSQL_DATABASE', 'oidplus');
  119.                         $socket   = OIDplus::baseConfig()->getValue('PGSQL_SOCKET',   '');
  120.                         if ($socket != '') {
  121.                                 $hostname = $socket;
  122.                                 $port = '';
  123.                         } else {
  124.                                 list($hostname, $port) = explode(':', "$host:5432");
  125.                         }
  126.  
  127.                         $connection_string = array();
  128.                         if ($hostname != '') $connection_string[] = "host=$hostname";
  129.                         if ($username != '') $connection_string[] = "user=$username";
  130.                         if ($password != '') $connection_string[] = "password=$password";
  131.                         if ($port     != '') $connection_string[] = "port=$port";
  132.                         if ($database != '') $connection_string[] = "dbname=$database";
  133.  
  134.                         // We need to use PGSQL_CONNECT_FORCE_NEW because we require two connectoins (for isolated log message queries)
  135.                         $this->conn = pg_connect(implode(' ', $connection_string), PGSQL_CONNECT_FORCE_NEW);
  136.                 } finally {
  137.                         # TODO: this does not seem to work?! (at least not for CLI)
  138.                         $err = ob_get_contents();
  139.                         ob_end_clean();
  140.                 }
  141.  
  142.                 if (!$this->conn) {
  143.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' ' . strip_tags($err)));
  144.                 }
  145.  
  146.                 $this->already_prepared = array();
  147.                 $this->last_error = null;
  148.  
  149.                 try {
  150.                         $this->query("SET NAMES 'utf8'");
  151.                 } catch (\Exception $e) {
  152.                 }
  153.         }
  154.  
  155.         /**
  156.          * @return void
  157.          */
  158.         protected function doDisconnect()/*: void*/ {
  159.                 $this->already_prepared = array();
  160.                 if (!is_null($this->conn)) {
  161.                         pg_close($this->conn);
  162.                         $this->conn = null;
  163.                 }
  164.         }
  165.  
  166.         /**
  167.          * @var bool
  168.          */
  169.         private $intransaction = false;
  170.  
  171.         /**
  172.          * @return bool
  173.          */
  174.         public function transaction_supported(): bool {
  175.                 return true;
  176.         }
  177.  
  178.         /**
  179.          * @return int
  180.          */
  181.         public function transaction_level(): int {
  182.                 return $this->intransaction ? 1 : 0;
  183.         }
  184.  
  185.         /**
  186.          * @return void
  187.          * @throws OIDplusException
  188.          */
  189.         public function transaction_begin()/*: void*/ {
  190.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  191.                 $this->query('begin transaction');
  192.                 $this->intransaction = true;
  193.         }
  194.  
  195.         /**
  196.          * @return void
  197.          * @throws OIDplusException
  198.          */
  199.         public function transaction_commit()/*: void*/ {
  200.                 $this->query('commit');
  201.                 $this->intransaction = false;
  202.         }
  203.  
  204.         /**
  205.          * @return void
  206.          * @throws OIDplusException
  207.          */
  208.         public function transaction_rollback()/*: void*/ {
  209.                 $this->query('rollback');
  210.                 $this->intransaction = false;
  211.         }
  212.  
  213.         /**
  214.          * @return string
  215.          */
  216.         public function sqlDate(): string {
  217.                 return 'now()';
  218.         }
  219.  
  220.         /**
  221.          * @param bool $mustExist
  222.          * @return OIDplusSqlSlangPlugin|null
  223.          * @throws OIDplusConfigInitializationException
  224.          */
  225.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  226.                 $slang = OIDplus::getSqlSlangPlugin('pgsql');
  227.                 if (is_null($slang)) {
  228.                         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 TAR.GZ file.','pgsql'));
  229.                 }
  230.                 return $slang;
  231.         }
  232. }
  233.