Subversion Repositories oidplus

Rev

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