Subversion Repositories oidplus

Rev

Rev 1160 | Rev 1220 | 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 OIDplusDatabaseConnectionSQLite3 extends OIDplusDatabaseConnection {
  27.         /**
  28.          * @var mixed|null
  29.          */
  30.         private $conn = null;
  31.  
  32.         /**
  33.          * @var array
  34.          */
  35.         private $prepare_cache = array();
  36.  
  37.         /**
  38.          * @var string|null
  39.          */
  40.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  41.  
  42.         /**
  43.          * @param string $sql
  44.          * @param array|null $prepared_args
  45.          * @return OIDplusQueryResultSQLite3
  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.                         try {
  52.                                 $res = $this->conn->query($sql);
  53.                         } catch (\Exception $e) {
  54.                                 $res = false;
  55.                         }
  56.                         if ($res === false) {
  57.                                 $this->last_error = $this->conn->lastErrorMsg();
  58.                                 throw new OIDplusSQLException($sql, $this->error());
  59.                         } else {
  60.                                 return new OIDplusQueryResultSQLite3($res);
  61.                         }
  62.                 } else {
  63.                         // convert ? ? ? to :param1 :param2 :param3 ...
  64.                         $sql = preg_replace_callback('@\\?@', function($found) {
  65.                                 static $i = 0;
  66.                                 $i++;
  67.                                 return ':param'.$i;
  68.                         }, $sql, count($prepared_args), $count);
  69.  
  70.                         if (isset($this->prepare_cache[$sql])) {
  71.                                 $stmt = $this->prepare_cache[$sql];
  72.                         } else {
  73.                                 try {
  74.                                         $stmt = $this->conn->prepare($sql);
  75.                                 } catch (\Exception $e) {
  76.                                         $stmt = false;
  77.                                 }
  78.                                 if ($stmt === false) {
  79.                                         $this->last_error = $this->conn->lastErrorMsg();
  80.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  81.                                 }
  82.                                 $this->prepare_cache[$sql] = $stmt;
  83.                         }
  84.  
  85.                         $i = 0;
  86.                         foreach ($prepared_args as &$value) {
  87.                                 $i++;
  88.                                 if ($i > $count) break;
  89.                                 if (is_bool($value)) $value = $value ? '1' : '0';
  90.                                 $stmt->bindValue(':param'.$i, $value, SQLITE3_TEXT);
  91.                         }
  92.  
  93.                         try {
  94.                                 $ps = $stmt->execute();
  95.                         } catch (\Exception $e) {
  96.                                 $ps = false;
  97.                         }
  98.                         if ($ps === false) {
  99.                                 $this->last_error = $this->conn->lastErrorMsg();
  100.                                 throw new OIDplusSQLException($sql, $this->error());
  101.                         }
  102.                         return new OIDplusQueryResultSQLite3($ps);
  103.                 }
  104.         }
  105.  
  106.         /**
  107.          * @return int
  108.          */
  109.         public function doInsertId(): int {
  110.                 try {
  111.                         // Note: This will always give results even for tables that do not
  112.                         // have autoincrements, because SQLite3 assigns an "autoindex" for every table,
  113.                         // e.g. the config table. Therefore, our testcase will fail.
  114.                         return (int)$this->conn->lastInsertRowID();
  115.                         //return (int)$this->query('select last_insert_rowid() as id')->fetch_object()->id;
  116.                 } catch (\Exception $e) {
  117.                         return 0;
  118.                 }
  119.         }
  120.  
  121.         /**
  122.          * @return string
  123.          */
  124.         public function error(): string {
  125.                 $err = $this->last_error;
  126.                 if ($err == null) $err = '';
  127.                 return $err;
  128.         }
  129.  
  130.         /**
  131.          * @return void
  132.          * @throws OIDplusConfigInitializationException
  133.          */
  134.         protected function doConnect()/*: void*/ {
  135.                 if (!class_exists('SQLite3')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','SQLite3'));
  136.  
  137.                 // Try connecting to the database
  138.                 try {
  139.                         $filename   = OIDplus::baseConfig()->getValue('SQLITE3_FILE', 'userdata/database/oidplus.db');
  140.                         $flags      = SQLITE3_OPEN_READWRITE/* | SQLITE3_OPEN_CREATE*/;
  141.                         $encryption = OIDplus::baseConfig()->getValue('SQLITE3_ENCRYPTION', '');
  142.  
  143.                         $is_absolute_path = ((substr($filename,0,1) == '/') || (substr($filename,1,1) == ':'));
  144.                         if (!$is_absolute_path) {
  145.                                 // Filename must be absolute path, since OIDplus can be called from several locations (e.g. registration wizard)
  146.                                 $filename = OIDplus::localpath().$filename;
  147.                         }
  148.  
  149.                         $this->conn = new \SQLite3($filename, $flags, $encryption);
  150.                 } catch (\Exception $e) {
  151.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' ' . $e->getMessage()));
  152.                 }
  153.  
  154.                 $this->conn->createCollation('NATURAL_CMP', 'strnatcmp'); // we need that for natSort()
  155.                 $this->conn->enableExceptions(true); // Throw exceptions instead of PHP warnings
  156.  
  157.                 $this->prepare_cache = array();
  158.                 $this->last_error = null;
  159.         }
  160.  
  161.         /**
  162.          * @return void
  163.          */
  164.         protected function doDisconnect()/*: void*/ {
  165.                 $this->prepare_cache = array();
  166.                 $this->conn = null;
  167.         }
  168.  
  169.         /**
  170.          * @var bool
  171.          */
  172.         private $intransaction = false;
  173.  
  174.         /**
  175.          * @return bool
  176.          */
  177.         public function transaction_supported(): bool {
  178.                 return true;
  179.         }
  180.  
  181.         /**
  182.          * @return int
  183.          */
  184.         public function transaction_level(): int {
  185.                 return $this->intransaction ? 1 : 0;
  186.         }
  187.  
  188.         /**
  189.          * @return void
  190.          * @throws OIDplusException
  191.          */
  192.         public function transaction_begin()/*: void*/ {
  193.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  194.                 $this->query('begin transaction');
  195.                 $this->intransaction = true;
  196.         }
  197.  
  198.         /**
  199.          * @return void
  200.          * @throws OIDplusException
  201.          */
  202.         public function transaction_commit()/*: void*/ {
  203.                 $this->query('commit');
  204.                 $this->intransaction = false;
  205.         }
  206.  
  207.         /**
  208.          * @return void
  209.          * @throws OIDplusException
  210.          */
  211.         public function transaction_rollback()/*: void*/ {
  212.                 $this->query('rollback');
  213.                 $this->intransaction = false;
  214.         }
  215.  
  216.         /**
  217.          * @return string
  218.          */
  219.         public function sqlDate(): string {
  220.                 return 'datetime()';
  221.         }
  222.  
  223.         /**
  224.          * @param bool $mustExist
  225.          * @return OIDplusSqlSlangPlugin|null
  226.          * @throws OIDplusConfigInitializationException
  227.          */
  228.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  229.                 $slang = OIDplus::getSqlSlangPlugin('sqlite');
  230.                 if (is_null($slang)) {
  231.                         throw new OIDplusConfigInitializationException(_L('SQL-Slang plugin "%1" is missing. Please check if it exists in the directory "plugin/sqlSlang". If it is not existing, please recover it from an SVN snapshot or OIDplus TAR.GZ file.','sqlite'));
  232.                 }
  233.                 return $slang;
  234.         }
  235. }
  236.