Subversion Repositories oidplus

Rev

Rev 1430 | 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.                         unset($value);
  93.  
  94.                         try {
  95.                                 $ps = $stmt->execute();
  96.                         } catch (\Exception $e) {
  97.                                 $ps = false;
  98.                         }
  99.                         if ($ps === false) {
  100.                                 $this->last_error = $this->conn->lastErrorMsg();
  101.                                 throw new OIDplusSQLException($sql, $this->error());
  102.                         }
  103.                         return new OIDplusQueryResultSQLite3($ps);
  104.                 }
  105.         }
  106.  
  107.         /**
  108.          * @return int
  109.          */
  110.         public function doInsertId(): int {
  111.                 try {
  112.                         // Note: This will always give results even for tables that do not
  113.                         // have autoincrements, because SQLite3 assigns an "autoindex" for every table,
  114.                         // e.g. the config table. Therefore, our testcase will fail.
  115.                         return (int)$this->conn->lastInsertRowID();
  116.                         //return (int)$this->query('select last_insert_rowid() as id')->fetch_object()->id;
  117.                 } catch (\Exception $e) {
  118.                         return 0;
  119.                 }
  120.         }
  121.  
  122.         /**
  123.          * @return string
  124.          */
  125.         public function error(): string {
  126.                 $err = $this->last_error;
  127.                 if ($err == null) $err = '';
  128.                 return $err;
  129.         }
  130.  
  131.         /**
  132.          * @return void
  133.          * @throws OIDplusConfigInitializationException
  134.          */
  135.         protected function doConnect()/*: void*/ {
  136.                 if (!class_exists('SQLite3')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','SQLite3'));
  137.  
  138.                 // Try connecting to the database
  139.                 try {
  140.                         $filename   = OIDplus::baseConfig()->getValue('SQLITE3_FILE', 'userdata/database/oidplus.db');
  141.                         $flags      = SQLITE3_OPEN_READWRITE/* | SQLITE3_OPEN_CREATE*/;
  142.                         $encryption = OIDplus::baseConfig()->getValue('SQLITE3_ENCRYPTION', '');
  143.  
  144.                         $is_absolute_path = ((substr($filename,0,1) == '/') || (substr($filename,1,1) == ':'));
  145.                         if (!$is_absolute_path) {
  146.                                 // Filename must be absolute path, since OIDplus can be called from several locations (e.g. registration wizard)
  147.                                 $filename = OIDplus::localpath().$filename;
  148.                         }
  149.  
  150.                         $this->conn = new \SQLite3($filename, $flags, $encryption);
  151.                 } catch (\Exception $e) {
  152.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' ' . $e->getMessage()));
  153.                 }
  154.  
  155.                 $this->conn->createCollation('NATURAL_CMP', 'strnatcmp'); // we need that for natSort()
  156.                 $this->conn->enableExceptions(true); // Throw exceptions instead of PHP warnings (preferred as of PHP 8.3)
  157.  
  158.                 $this->prepare_cache = array();
  159.                 $this->last_error = null;
  160.         }
  161.  
  162.         /**
  163.          * @return void
  164.          */
  165.         protected function doDisconnect()/*: void*/ {
  166.                 $this->prepare_cache = array();
  167.                 $this->conn = null;
  168.         }
  169.  
  170.         /**
  171.          * @var bool
  172.          */
  173.         private $intransaction = false;
  174.  
  175.         /**
  176.          * @return bool
  177.          */
  178.         public function transaction_supported(): bool {
  179.                 return true;
  180.         }
  181.  
  182.         /**
  183.          * @return int
  184.          */
  185.         public function transaction_level(): int {
  186.                 return $this->intransaction ? 1 : 0;
  187.         }
  188.  
  189.         /**
  190.          * @return void
  191.          * @throws OIDplusException
  192.          */
  193.         public function transaction_begin()/*: void*/ {
  194.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  195.                 $this->query('begin transaction');
  196.                 $this->intransaction = true;
  197.         }
  198.  
  199.         /**
  200.          * @return void
  201.          * @throws OIDplusException
  202.          */
  203.         public function transaction_commit()/*: void*/ {
  204.                 $this->query('commit');
  205.                 $this->intransaction = false;
  206.         }
  207.  
  208.         /**
  209.          * @return void
  210.          * @throws OIDplusException
  211.          */
  212.         public function transaction_rollback()/*: void*/ {
  213.                 $this->query('rollback');
  214.                 $this->intransaction = false;
  215.         }
  216.  
  217.         /**
  218.          * @return string
  219.          */
  220.         public function sqlDate(): string {
  221.                 return 'datetime()';
  222.         }
  223.  
  224.         /**
  225.          * @param bool $mustExist
  226.          * @return OIDplusSqlSlangPlugin|null
  227.          * @throws OIDplusConfigInitializationException
  228.          */
  229.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  230.                 $slang = OIDplus::getSqlSlangPlugin('sqlite');
  231.                 if (is_null($slang)) {
  232.                         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 GIT/SVN snapshot or OIDplus archive file.','sqlite'));
  233.                 }
  234.                 return $slang;
  235.         }
  236.  
  237.         /**
  238.          * @return array
  239.          */
  240.         public function getExtendedInfo(): array {
  241.                 $filename  = OIDplus::baseConfig()->getValue('SQLITE3_FILE', 'userdata/database/oidplus.db');
  242.                 return array(
  243.                         _L('Filename') => $filename
  244.                 );
  245.         }
  246.  
  247. }
  248.