Subversion Repositories oidplus

Rev

Rev 1050 | Rev 1116 | 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.         private $conn = null;
  28.         private $prepare_cache = array();
  29.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  30.  
  31.         public function doQuery(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
  32.                 $this->last_error = null;
  33.                 if (is_null($prepared_args)) {
  34.                         try {
  35.                                 $res = $this->conn->query($sql);
  36.                         } catch (\Exception $e) {
  37.                                 $res = false;
  38.                         }
  39.                         if ($res === false) {
  40.                                 $this->last_error = $this->conn->lastErrorMsg();
  41.                                 throw new OIDplusSQLException($sql, $this->error());
  42.                         } else {
  43.                                 return new OIDplusQueryResultSQLite3($res);
  44.                         }
  45.                 } else {
  46.                         if (!is_array($prepared_args)) {
  47.                                 throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
  48.                         }
  49.  
  50.                         // convert ? ? ? to :param1 :param2 :param3 ...
  51.                         $sql = preg_replace_callback('@\\?@', function($found) {
  52.                                 static $i = 0;
  53.                                 $i++;
  54.                                 return ':param'.$i;
  55.                         }, $sql, count($prepared_args), $count);
  56.  
  57.                         if (isset($this->prepare_cache[$sql])) {
  58.                                 $stmt = $this->prepare_cache[$sql];
  59.                         } else {
  60.                                 try {
  61.                                         $stmt = $this->conn->prepare($sql);
  62.                                 } catch (\Exception $e) {
  63.                                         $stmt = false;
  64.                                 }
  65.                                 if ($stmt === false) {
  66.                                         $this->last_error = $this->conn->lastErrorMsg();
  67.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  68.                                 }
  69.                                 $this->prepare_cache[$sql] = $stmt;
  70.                         }
  71.  
  72.                         $i = 0;
  73.                         foreach ($prepared_args as &$value) {
  74.                                 $i++;
  75.                                 if ($i > $count) break;
  76.                                 if (is_bool($value)) $value = $value ? '1' : '0';
  77.                                 $stmt->bindValue(':param'.$i, $value, SQLITE3_TEXT);
  78.                         }
  79.  
  80.                         try {
  81.                                 $ps = $stmt->execute();
  82.                         } catch (\Exception $e) {
  83.                                 $ps = false;
  84.                         }
  85.                         if ($ps === false) {
  86.                                 $this->last_error = $this->conn->lastErrorMsg();
  87.                                 throw new OIDplusSQLException($sql, $this->error());
  88.                         }
  89.                         return new OIDplusQueryResultSQLite3($ps);
  90.                 }
  91.         }
  92.  
  93.         public function insert_id(): int {
  94.                 try {
  95.                         // Note: This will always give results even for tables that do not
  96.                         // have autoincrements, because SQLite3 assigns an "autoindex" for every table,
  97.                         // e.g. the config table. Therefore, our testcase will fail.
  98.                         return (int)$this->conn->lastInsertRowID();
  99.                         //return (int)$this->query('select last_insert_rowid() as id')->fetch_object()->id;
  100.                 } catch (\Exception $e) {
  101.                         return 0;
  102.                 }
  103.         }
  104.  
  105.         public function error(): string {
  106.                 $err = $this->last_error;
  107.                 if ($err == null) $err = '';
  108.                 return $err;
  109.         }
  110.  
  111.         protected function doConnect()/*: void*/ {
  112.                 if (!class_exists('SQLite3')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','SQLite3'));
  113.  
  114.                 // Try connecting to the database
  115.                 try {
  116.                         $filename   = OIDplus::baseConfig()->getValue('SQLITE3_FILE', 'userdata/database/oidplus.db');
  117.                         $flags      = SQLITE3_OPEN_READWRITE/* | SQLITE3_OPEN_CREATE*/;
  118.                         $encryption = OIDplus::baseConfig()->getValue('SQLITE3_ENCRYPTION', '');
  119.  
  120.                         $is_absolute_path = ((substr($filename,0,1) == '/') || (substr($filename,1,1) == ':'));
  121.                         if (!$is_absolute_path) {
  122.                                 // Filename must be absolute path, since OIDplus can be called from several locations (e.g. registration wizard)
  123.                                 $filename = OIDplus::localpath().$filename;
  124.                         }
  125.  
  126.                         $this->conn = new \SQLite3($filename, $flags, $encryption);
  127.                 } catch (\Exception $e) {
  128.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' ' . $e->getMessage()));
  129.                 }
  130.  
  131.                 $this->conn->createCollation('NATURAL_CMP', 'strnatcmp'); // we need that for natSort()
  132.                 $this->conn->enableExceptions(true); // Throw exceptions instead of PHP warnings
  133.  
  134.                 $this->prepare_cache = array();
  135.                 $this->last_error = null;
  136.         }
  137.  
  138.         protected function doDisconnect()/*: void*/ {
  139.                 $this->prepare_cache = array();
  140.                 $this->conn = null;
  141.         }
  142.  
  143.         private $intransaction = false;
  144.  
  145.         public function transaction_supported(): bool {
  146.                 return true;
  147.         }
  148.  
  149.         public function transaction_level(): int {
  150.                 return $this->intransaction ? 1 : 0;
  151.         }
  152.  
  153.         public function transaction_begin()/*: void*/ {
  154.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  155.                 $this->query('begin transaction');
  156.                 $this->intransaction = true;
  157.         }
  158.  
  159.         public function transaction_commit()/*: void*/ {
  160.                 $this->query('commit');
  161.                 $this->intransaction = false;
  162.         }
  163.  
  164.         public function transaction_rollback()/*: void*/ {
  165.                 $this->query('rollback');
  166.                 $this->intransaction = false;
  167.         }
  168.  
  169.         public function sqlDate(): string {
  170.                 return 'datetime()';
  171.         }
  172.  
  173.         public function natOrder($fieldname, $order='asc'): string {
  174.  
  175.                 // This collation is defined in the database plugin using SQLite3::createCollation()
  176.                 return "$fieldname COLLATE NATURAL_CMP $order";
  177.  
  178.         }
  179.  
  180.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  181.                 $slang = OIDplus::getSqlSlangPlugin('sqlite');
  182.                 if (is_null($slang)) {
  183.                         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'));
  184.                 }
  185.                 return $slang;
  186.         }
  187. }
  188.