Subversion Repositories oidplus

Rev

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