Subversion Repositories oidplus

Rev

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

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