Subversion Repositories oidplus

Rev

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

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2021 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. if (!defined('INSIDE_OIDPLUS')) die();
  21.  
  22. class OIDplusDatabaseConnectionSQLite3 extends OIDplusDatabaseConnection {
  23.         private $conn = null;
  24.         private $prepare_cache = array();
  25.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  26.  
  27.         public static function getPlugin(): OIDplusDatabasePlugin {
  28.                 return new OIDplusDatabasePluginSQLite3();
  29.         }
  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);
  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.                         if ($stmt->paramCount() != count($prepared_args)) {
  73.                                 throw new OIDplusException(_L('Prepared argument list size not matching number of prepared statement arguments'));
  74.                         }
  75.                         $i = 1;
  76.                         foreach ($prepared_args as &$value) {
  77.                                 if (is_bool($value)) $value = $value ? '1' : '0';
  78.                                 $stmt->bindValue(':param'.$i, $value, SQLITE3_TEXT);
  79.                                 $i++;
  80.                         }
  81.  
  82.                         try {
  83.                                 $ps = $stmt->execute();
  84.                         } catch (Exception $e) {
  85.                                 $ps = false;
  86.                         }
  87.                         if ($ps === false) {
  88.                                 $this->last_error = $this->conn->lastErrorMsg();
  89.                                 throw new OIDplusSQLException($sql, $this->error());
  90.                         }
  91.                         return new OIDplusQueryResultSQLite3($ps);
  92.                 }
  93.         }
  94.  
  95.         public function insert_id(): int {
  96.                 try {
  97.                         // Note: This will always give results even for tables that do not
  98.                         // have autoincrements, because SQLite3 assigns an "autoindex" for every table,
  99.                         // e.g. the config table. Therefore, our testcase will fail.
  100.                         return (int)$this->conn->lastInsertRowID();
  101.                         //return (int)$this->query('select last_insert_rowid() as id')->fetch_object()->id;
  102.                 } catch (Exception $e) {
  103.                         return 0;
  104.                 }
  105.         }
  106.  
  107.         public function error(): string {
  108.                 $err = $this->last_error;
  109.                 if ($err == null) $err = '';
  110.                 return $err;
  111.         }
  112.  
  113.         protected function doConnect()/*: void*/ {
  114.                 if (!class_exists('SQLite3')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','SQLite3'));
  115.  
  116.                 // Try connecting to the database
  117.                 try {
  118.                         $filename   = OIDplus::baseConfig()->getValue('SQLITE3_FILE', 'userdata/database/oidplus.db');
  119.                         $flags      = SQLITE3_OPEN_READWRITE/* | SQLITE3_OPEN_CREATE*/;
  120.                         $encryption = OIDplus::baseConfig()->getValue('SQLITE3_ENCRYPTION', '');
  121.  
  122.                         $is_absolute_path = ((substr($filename,0,1) == '/') || (substr($filename,1,1) == ':'));
  123.                         if (!$is_absolute_path) {
  124.                                 // Filename must be absolute path, since OIDplus can be called from several locations (e.g. registration wizard)
  125.                                 $filename = OIDplus::localpath().$filename;
  126.                         }
  127.  
  128.                         $this->conn = new SQLite3($filename, $flags, $encryption);
  129.                 } catch (Exception $e) {
  130.                         throw new OIDplusConfigInitializationException(_L('Connection to the database failed!').' ' . $e->getMessage());
  131.                 }
  132.  
  133.                 $this->conn->createCollation('NATURAL_CMP', 'strnatcmp'); // we need that for natSort()
  134.                 $this->conn->enableExceptions(true); // Throw exceptions instead of PHP warnings
  135.  
  136.                 $this->prepare_cache = array();
  137.                 $this->last_error = null;
  138.         }
  139.  
  140.         protected function doDisconnect()/*: void*/ {
  141.                 $this->prepare_cache = array();
  142.                 $this->conn = null;
  143.         }
  144.  
  145.         private $intransaction = false;
  146.  
  147.         public function transaction_supported(): bool {
  148.                 return true;
  149.         }
  150.  
  151.         public function transaction_level(): int {
  152.                 return $this->intransaction ? 1 : 0;
  153.         }
  154.  
  155.         public function transaction_begin()/*: void*/ {
  156.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  157.                 $this->query('begin transaction');
  158.                 $this->intransaction = true;
  159.         }
  160.  
  161.         public function transaction_commit()/*: void*/ {
  162.                 $this->query('commit');
  163.                 $this->intransaction = false;
  164.         }
  165.  
  166.         public function transaction_rollback()/*: void*/ {
  167.                 $this->query('rollback');
  168.                 $this->intransaction = false;
  169.         }
  170.  
  171.         public function sqlDate(): string {
  172.                 return 'datetime()';
  173.         }
  174.  
  175.         public function natOrder($fieldname, $order='asc'): string {
  176.  
  177.                 // This collation is defined in the database plugin using SQLite3::createCollation()
  178.                 return "$fieldname COLLATE NATURAL_CMP $order";
  179.  
  180.         }
  181.  
  182.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  183.                 $slang = OIDplus::getSqlSlangPlugin('sqlite');
  184.                 if (is_null($slang)) {
  185.                         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 ZIP file.','sqlite'));
  186.                 }
  187.                 return $slang;
  188.         }
  189. }