Subversion Repositories oidplus

Rev

Rev 1116 | Rev 1160 | 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.         /**
  28.          * @var mixed|null
  29.          */
  30.         private $conn = null;
  31.  
  32.         /**
  33.          * @var string|null
  34.          */
  35.         private $last_error = null; // we need that because PDO divides prepared statement errors and normal query errors, but we have only one "error()" method
  36.  
  37.         /**
  38.          * @var bool
  39.          */
  40.         private $transactions_supported = false;
  41.  
  42.         /**
  43.          * @param string $sql
  44.          * @param array|null $prepared_args
  45.          * @return OIDplusQueryResultPDO
  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 = $this->conn->query($sql);
  52.  
  53.                         if ($res === false) {
  54.                                 $this->last_error = $this->conn->errorInfo()[2];
  55.                                 throw new OIDplusSQLException($sql, $this->error());
  56.                         } else {
  57.                                 return new OIDplusQueryResultPDO($res);
  58.                         }
  59.                 } else {
  60.                         if (!is_array($prepared_args)) {
  61.                                 throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
  62.                         }
  63.  
  64.                         foreach ($prepared_args as &$value) {
  65.                                 // We need to manually convert booleans into strings, because there is a
  66.                                 // 14 year old bug that hasn't been adressed by the PDO developers:
  67.                                 // https://bugs.php.net/bug.php?id=57157
  68.                                 if (is_bool($value)) {
  69.                                         if ($this->slangDetectionDone) {
  70.                                                 $value = $this->getSlang()->getSQLBool($value);
  71.                                         } else {
  72.                                                 // This works for everything except Microsoft Access (which needs -1 and 0)
  73.                                                 // Note: We are using '1' and '0' instead of 'true' and 'false' because MySQL converts boolean to tinyint(1)
  74.                                                 $value = $value ? '1' : '0';
  75.                                         }
  76.                                 }
  77.                         }
  78.  
  79.                         $ps = $this->conn->prepare($sql);
  80.                         if (!$ps) {
  81.                                 $this->last_error = $this->conn->errorInfo()[2];
  82.                                 throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  83.                         }
  84.  
  85.                         if (!$ps->execute($prepared_args)) {
  86.                                 $this->last_error = $ps->errorInfo()[2];
  87.                                 throw new OIDplusSQLException($sql, $this->error());
  88.                         }
  89.                         return new OIDplusQueryResultPDO($ps);
  90.                 }
  91.         }
  92.  
  93.         /**
  94.          * @return int
  95.          * @throws OIDplusException
  96.          */
  97.         public function insert_id(): int {
  98.                 try {
  99.                         $out = @($this->conn->lastInsertId());
  100.                         if ($out === false) return parent::insert_id(); // fallback method that uses the SQL slang
  101.                         return $out;
  102.                 } catch (\Exception $e) {
  103.                         return parent::insert_id(); // fallback method that uses the SQL slang
  104.                 }
  105.         }
  106.  
  107.         /**
  108.          * @return string
  109.          */
  110.         public function error(): string {
  111.                 $err = $this->last_error;
  112.                 if ($err == null) $err = '';
  113.                 return $err;
  114.         }
  115.  
  116.         /**
  117.          * @return void
  118.          * @throws OIDplusConfigInitializationException
  119.          * @throws OIDplusException
  120.          */
  121.         protected function doConnect()/*: void*/ {
  122.                 if (!class_exists('PDO')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PDO'));
  123.  
  124.                 try {
  125.                         $options = [
  126.                             \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_SILENT,
  127.                             \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  128.                             \PDO::ATTR_EMULATE_PREPARES   => true,
  129.                         ];
  130.  
  131.                         // Try connecting to the database
  132.                         $dsn      = OIDplus::baseConfig()->getValue('PDO_DSN',      'mysql:host=localhost;dbname=oidplus;charset=UTF8');
  133.                         $username = OIDplus::baseConfig()->getValue('PDO_USERNAME', 'root');
  134.                         $password = OIDplus::baseConfig()->getValue('PDO_PASSWORD', '');
  135.  
  136.                         if (stripos($dsn,"charset=") === false) $dsn = "$dsn;charset=UTF8";
  137.  
  138.                         $this->conn = new \PDO($dsn, $username, $password, $options);
  139.                 } catch (\PDOException $e) {
  140.                         $message = $e->getMessage();
  141.                         throw new OIDplusConfigInitializationException(trim(_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.         /**
  168.          * @return void
  169.          */
  170.         protected function doDisconnect()/*: void*/ {
  171.                 $this->conn = null; // the connection will be closed by removing the reference
  172.         }
  173.  
  174.         /**
  175.          * @var bool
  176.          */
  177.         private $intransaction = false;
  178.  
  179.         /**
  180.          * @return bool
  181.          */
  182.         public function transaction_supported(): bool {
  183.                 return $this->transactions_supported;
  184.         }
  185.  
  186.         /**
  187.          * @return int
  188.          */
  189.         public function transaction_level(): int {
  190.                 if (!$this->transaction_supported()) {
  191.                         // TODO?
  192.                         return 0;
  193.                 }
  194.                 return $this->intransaction ? 1 : 0;
  195.         }
  196.  
  197.         /**
  198.          * @return void
  199.          * @throws OIDplusException
  200.          */
  201.         public function transaction_begin()/*: void*/ {
  202.                 if (!$this->transaction_supported()) {
  203.                         // TODO?
  204.                         return;
  205.                 }
  206.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  207.                 $this->conn->beginTransaction();
  208.                 $this->intransaction = true;
  209.         }
  210.  
  211.         /**
  212.          * @return void
  213.          */
  214.         public function transaction_commit()/*: void*/ {
  215.                 if (!$this->transaction_supported()) {
  216.                         // TODO?
  217.                         return;
  218.                 }
  219.                 $this->conn->commit();
  220.                 $this->intransaction = false;
  221.         }
  222.  
  223.         /**
  224.          * @return void
  225.          */
  226.         public function transaction_rollback()/*: void*/ {
  227.                 if (!$this->transaction_supported()) {
  228.                         // TODO?
  229.                         return;
  230.                 }
  231.                 $this->conn->rollBack();
  232.                 $this->intransaction = false;
  233.         }
  234.  
  235. }
  236.