Subversion Repositories oidplus

Rev

Rev 789 | Rev 863 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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