forked from cosmocode/sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.php
executable file
·410 lines (352 loc) · 10.1 KB
/
helper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
<?php
/**
* @noinspection SqlNoDataSourceInspection
* @noinspection SqlDialectInspection
* @noinspection PhpComposerExtensionStubsInspection
*/
use dokuwiki\plugin\sqlite\SQLiteDB;
use dokuwiki\plugin\sqlite\Tools;
/**
* For compatibility with previous adapter implementation.
*/
if(!defined('DOKU_EXT_PDO')) define('DOKU_EXT_PDO', 'pdo');
class helper_plugin_sqlite_adapter_dummy
{
public function getName() {
return DOKU_EXT_PDO;
}
public function setUseNativeAlter($set) {}
}
/**
* DokuWiki Plugin sqlite (Helper Component)
*
* @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
* @author Andreas Gohr <gohr@cosmocode.de>
* @deprecated 2023-03-15
*/
class helper_plugin_sqlite extends DokuWiki_Plugin
{
/** @var SQLiteDB|null */
protected $adapter = null;
/** @var array result cache */
protected $data;
/**
* constructor
*/
public function __construct()
{
if (!$this->existsPDOSqlite()) {
msg('PDO SQLite support missing in this PHP install - The sqlite plugin will not work', -1);
}
$this->adapter = new helper_plugin_sqlite_adapter_dummy();
}
/**
* Get the current Adapter
* @return SQLiteDB|null
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* Keep separate instances for every call to keep database connections
*/
public function isSingleton()
{
return false;
}
/**
* check availabilty of PHP PDO sqlite3
*/
public function existsPDOSqlite()
{
if (class_exists('pdo')) {
return in_array('sqlite', \PDO::getAvailableDrivers());
}
return false;
}
/**
* Initializes and opens the database
*
* Needs to be called right after loading this helper plugin
*
* @param string $dbname
* @param string $updatedir - Database update infos
* @return bool
*/
public function init($dbname, $updatedir)
{
if(!defined('DOKU_UNITTEST')) { // for now we don't want to trigger the deprecation warning in the tests
dbg_deprecated(SQLiteDB::class);
}
try {
$this->adapter = new SQLiteDB($dbname, $updatedir, $this);
} catch (Exception $e) {
msg('SQLite: ' . $e->getMessage(), -1);
return false;
}
return true;
}
/**
* This is called from the adapter itself for backwards compatibility
*
* @param SQLiteDB $adapter
* @return void
*/
function setAdapter($adapter)
{
$this->adapter = $adapter;
}
/**
* Registers a User Defined Function for use in SQL statements
*/
public function create_function($function_name, $callback, $num_args)
{
$this->adapter->getPdo()->sqliteCreateFunction($function_name, $callback, $num_args);
}
// region query and result handling functions
/**
* Convenience function to run an INSERT OR REPLACE operation
*
* The function takes a key-value array with the column names in the key and the actual value in the value,
* build the appropriate query and executes it.
*
* @param string $table the table the entry should be saved to (will not be escaped)
* @param array $entry A simple key-value pair array (only values will be escaped)
* @return bool
*/
public function storeEntry($table, $entry)
{
try {
$this->adapter->saveRecord($table, $entry);
} catch (\Exception $e) {
msg('SQLite: ' . $e->getMessage(), -1);
return false;
}
return true;
}
/**
* Execute a query with the given parameters.
*
* Takes care of escaping
*
*
* @param string ...$args - the arguments of query(), the first is the sql and others are values
*/
public function query()
{
// get function arguments
$args = func_get_args();
// clear the cache
$this->data = null;
try {
$sql = $this->prepareSql($args);
return $this->adapter->query($sql);
} catch (\Exception $e) {
msg('SQLite: ' . $e->getMessage(), -1);
return false;
}
}
/**
* Prepare a query with the given arguments.
*
* Takes care of escaping
*
* @param array $args
* array of arguments:
* - string $sql - the statement
* - arguments...
* @return bool|string
* @throws Exception
*/
public function prepareSql($args) {
$sql = trim(array_shift($args));
$sql = rtrim($sql, ';');
if(!$sql) {
throw new \Exception('No SQL statement given', -1);
}
$argc = count($args);
if($argc > 0 && is_array($args[0])) {
$args = $args[0];
$argc = count($args);
}
// check number of arguments
$qmc = substr_count($sql, '?');
if ($argc < $qmc) {
throw new \Exception('Not enough arguments passed for statement. ' .
'Expected '.$qmc.' got '. $argc.' - '.hsc($sql));
} elseif($argc > $qmc) {
throw new \Exception('Too much arguments passed for statement. ' .
'Expected '.$qmc.' got '. $argc.' - '.hsc($sql));
}
// explode at wildcard, then join again
$parts = explode('?', $sql, $argc + 1);
$args = array_map([$this->adapter->getPdo(), 'quote'], $args);
$sql = '';
while(($part = array_shift($parts)) !== null) {
$sql .= $part;
$sql .= array_shift($args);
}
return $sql;
}
/**
* Closes the result set (and it's cursors)
*
* If you're doing SELECT queries inside a TRANSACTION, be sure to call this
* function on all your results sets, before COMMITing the transaction.
*
* Also required when not all rows of a result are fetched
*
* @param \PDOStatement $res
* @return bool
*/
public function res_close($res)
{
if (!$res) return false;
return $res->closeCursor();
}
/**
* Returns a complete result set as array
*
* @param \PDOStatement $res
* @return array
*/
public function res2arr($res, $assoc = true)
{
if (!$res) return [];
// this is a bullshit workaround for having res2arr and res2count work on one result
if (!$this->data) {
$mode = $assoc ? PDO::FETCH_ASSOC : PDO::FETCH_NUM;
$this->data = $res->fetchAll($mode);
}
return $this->data;
}
/**
* Return the next row from the result set as associative array
*
* @param \PDOStatement $res
* @param int $rownum will be ignored
*/
public function res2row($res, $rownum = 0)
{
if (!$res) return false;
return $res->fetch(\PDO::FETCH_ASSOC);
}
/**
* Return the first value from the next row.
*
* @param \PDOStatement $res
* @return mixed
*/
public function res2single($res)
{
if (!$res) return false;
$data = $res->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_ABS, 0);
if (empty($data)) {
return false;
}
return $data[0];
}
/**
* fetch the next row as zero indexed array
*
* @param \PDOStatement $res
* @return array|bool
*/
public function res_fetch_array($res)
{
if (!$res) return false;
return $res->fetch(PDO::FETCH_NUM);
}
/**
* fetch the next row as assocative array
*
* @param \PDOStatement $res
* @return array|bool
*/
public function res_fetch_assoc($res)
{
if (!$res) return false;
return $res->fetch(PDO::FETCH_ASSOC);
}
/**
* Count the number of records in result
*
* This function is really inperformant in PDO and should be avoided!
*
* @param \PDOStatement $res
* @return int
*/
public function res2count($res)
{
if (!$res) return 0;
// this is a bullshit workaround for having res2arr and res2count work on one result
if (!$this->data) {
$this->data = $this->res2arr($res);
}
return count($this->data);
}
/**
* Count the number of records changed last time
*
* @param \PDOStatement $res
* @return int
*/
public function countChanges($res)
{
if (!$res) return 0;
return $res->rowCount();
}
// endregion
// region quoting/escaping functions
/**
* Join the given values and quote them for SQL insertion
*/
public function quote_and_join($vals, $sep = ',')
{
$vals = array_map([$this->adapter->getPdo(), 'quote'], $vals);
return join($sep, $vals);
}
/**
* Quotes a string, by escaping it and adding quotes
*/
public function quote_string($string)
{
return $this->adapter->getPdo()->quote($string);
}
/**
* Similar to quote_string, but without the quotes, useful to construct LIKE patterns
*/
public function escape_string($str)
{
return trim($this->adapter->getPdo()->quote($str), "'");
}
// endregion
// region speciality functions
/**
* Split sql queries on semicolons, unless when semicolons are quoted
*
* Usually you don't need this. It's only really needed if you need individual results for
* multiple queries. For example in the admin interface.
*
* @param string $sql
* @return array sql queries
* @deprecated
*/
public function SQLstring2array($sql)
{
if(!DOKU_UNITTEST) { // for now we don't want to trigger the deprecation warning in the tests
dbg_deprecated(Tools::class . '::SQLstring2array');
}
return Tools::SQLstring2array($sql);
}
/**
* @deprecated needs to be fixed in stuct and structpublish
*/
public function doTransaction($sql, $sqlpreparing = true) {
throw new \Exception(
'This method seems to never have done what it suggests. Please use the query() function instead.'
);
}
// endregion
}