Subversion Repositories oidplus

Rev

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