Subversion Repositories oidplus

Rev

Rev 1050 | Rev 1116 | 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 OIDplusDatabaseConnectionPDO extends OIDplusDatabaseConnection {
  27.         private $conn = null;
  28.         private $last_error = null; // we need that because PDO divides prepared statement errors and normal query errors, but we have only one "error()" method
  29.         private $transactions_supported = false;
  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 = $this->conn->query($sql);
  35.  
  36.                         if ($res === false) {
  37.                                 $this->last_error = $this->conn->errorInfo()[2];
  38.                                 throw new OIDplusSQLException($sql, $this->error());
  39.                         } else {
  40.                                 return new OIDplusQueryResultPDO($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.                         foreach ($prepared_args as &$value) {
  48.                                 // We need to manually convert booleans into strings, because there is a
  49.                                 // 14 year old bug that hasn't been adressed by the PDO developers:
  50.                                 // https://bugs.php.net/bug.php?id=57157
  51.                                 if (is_bool($value)) {
  52.                                         if ($this->slangDetectionDone) {
  53.                                                 $value = $this->getSlang()->getSQLBool($value);
  54.                                         } else {
  55.                                                 // This works for everything except Microsoft Access (which needs -1 and 0)
  56.                                                 // Note: We are using '1' and '0' instead of 'true' and 'false' because MySQL converts boolean to tinyint(1)
  57.                                                 $value = $value ? '1' : '0';
  58.                                         }
  59.                                 }
  60.                         }
  61.  
  62.                         $ps = $this->conn->prepare($sql);
  63.                         if (!$ps) {
  64.                                 $this->last_error = $this->conn->errorInfo()[2];
  65.                                 throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  66.                         }
  67.  
  68.                         if (!$ps->execute($prepared_args)) {
  69.                                 $this->last_error = $ps->errorInfo()[2];
  70.                                 throw new OIDplusSQLException($sql, $this->error());
  71.                         }
  72.                         return new OIDplusQueryResultPDO($ps);
  73.                 }
  74.         }
  75.  
  76.         public function insert_id(): int {
  77.                 try {
  78.                         $out = @($this->conn->lastInsertId());
  79.                         if ($out === false) return parent::insert_id(); // fallback method that uses the SQL slang
  80.                         return $out;
  81.                 } catch (\Exception $e) {
  82.                         return parent::insert_id(); // fallback method that uses the SQL slang
  83.                 }
  84.         }
  85.  
  86.         public function error(): string {
  87.                 $err = $this->last_error;
  88.                 if ($err == null) $err = '';
  89.                 return $err;
  90.         }
  91.  
  92.         protected function doConnect()/*: void*/ {
  93.                 if (!class_exists('PDO')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PDO'));
  94.  
  95.                 try {
  96.                         $options = [
  97.                             \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_SILENT,
  98.                             \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  99.                             \PDO::ATTR_EMULATE_PREPARES   => true,
  100.                         ];
  101.  
  102.                         // Try connecting to the database
  103.                         $dsn      = OIDplus::baseConfig()->getValue('PDO_DSN',      'mysql:host=localhost;dbname=oidplus;charset=UTF8');
  104.                         $username = OIDplus::baseConfig()->getValue('PDO_USERNAME', 'root');
  105.                         $password = OIDplus::baseConfig()->getValue('PDO_PASSWORD', '');
  106.  
  107.                         if (stripos($dsn,"charset=") === false) $dsn = "$dsn;charset=UTF8";
  108.  
  109.                         $this->conn = new \PDO($dsn, $username, $password, $options);
  110.                 } catch (\PDOException $e) {
  111.                         $message = $e->getMessage();
  112.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' '.$message));
  113.                 }
  114.  
  115.                 $this->last_error = null;
  116.  
  117.                 try {
  118.                         @$this->conn->exec("SET NAMES 'utf8'");
  119.                 } catch (\Exception $e) {
  120.                 }
  121.  
  122.                 // We check if the DBMS supports autocommit.
  123.                 // Attention: Check it after you have sent a query already, because Microsoft Access doesn't seem to allow
  124.                 // changing auto commit once a query was executed ("Attribute cannot be set now SQLState: S1011")
  125.                 // Note: For some weird reason we *DO* need to redirect the output to "$dummy", otherwise it won't work!
  126.                 $sql = "select name from ###config where 1=0";
  127.                 $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  128.                 $dummy = $this->conn->query($sql);
  129.                 try {
  130.                         $this->conn->beginTransaction();
  131.                         $this->conn->rollBack();
  132.                         $this->transactions_supported = true;
  133.                 } catch (\Exception $e) {
  134.                         $this->transactions_supported = false;
  135.                 }
  136.         }
  137.  
  138.         protected function doDisconnect()/*: void*/ {
  139.                 $this->conn = null; // the connection will be closed by removing the reference
  140.         }
  141.  
  142.         private $intransaction = false;
  143.  
  144.         public function transaction_supported(): bool {
  145.                 return $this->transactions_supported;
  146.         }
  147.  
  148.         public function transaction_level(): int {
  149.                 if (!$this->transaction_supported()) {
  150.                         // TODO?
  151.                         return 0;
  152.                 }
  153.                 return $this->intransaction ? 1 : 0;
  154.         }
  155.  
  156.         public function transaction_begin()/*: void*/ {
  157.                 if (!$this->transaction_supported()) {
  158.                         // TODO?
  159.                         return;
  160.                 }
  161.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  162.                 $this->conn->beginTransaction();
  163.                 $this->intransaction = true;
  164.         }
  165.  
  166.         public function transaction_commit()/*: void*/ {
  167.                 if (!$this->transaction_supported()) {
  168.                         // TODO?
  169.                         return;
  170.                 }
  171.                 $this->conn->commit();
  172.                 $this->intransaction = false;
  173.         }
  174.  
  175.         public function transaction_rollback()/*: void*/ {
  176.                 if (!$this->transaction_supported()) {
  177.                         // TODO?
  178.                         return;
  179.                 }
  180.                 $this->conn->rollBack();
  181.                 $this->intransaction = false;
  182.         }
  183.  
  184. }
  185.