Subversion Repositories oidplus

Rev

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