-
Notifications
You must be signed in to change notification settings - Fork 9
/
SQLiteDB.php
526 lines (466 loc) · 14.8 KB
/
SQLiteDB.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
<?php
/**
* @noinspection SqlNoDataSourceInspection
* @noinspection SqlDialectInspection
* @noinspection PhpComposerExtensionStubsInspection
*/
namespace dokuwiki\plugin\sqlite;
use dokuwiki\Extension\Event;
use dokuwiki\Logger;
/**
* Helpers to access a SQLite Database with automatic schema migration
*/
class SQLiteDB
{
public const FILE_EXTENSION = '.sqlite3';
/** @var \PDO */
protected $pdo;
/** @var string */
protected $schemadir;
/** @var string */
protected $dbname;
/** @var \helper_plugin_sqlite */
protected $helper;
/**
* Constructor
*
* @param string $dbname Database name
* @param string $schemadir directory with schema migration files
* @param \helper_plugin_sqlite $sqlitehelper for backwards compatibility
* @throws \Exception
*/
public function __construct($dbname, $schemadir, $sqlitehelper = null)
{
global $plugin_controller;
if (!$plugin_controller->isEnabled('sqlite')) {
throw new \Exception('SQLite plugin seems to be disabled.');
}
if (!class_exists('pdo') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
throw new \Exception('SQLite PDO driver not available');
}
// backwards compatibility, circular dependency
$this->helper = $sqlitehelper;
if (!$this->helper) {
$this->helper = new \helper_plugin_sqlite();
}
$this->helper->setAdapter($this);
$this->schemadir = $schemadir;
$this->dbname = $dbname;
$file = $this->getDbFile();
$this->pdo = new \PDO(
'sqlite:' . $file,
null,
null,
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_TIMEOUT => 10, // wait for locks up to 10 seconds
]
);
try {
// See https://www.sqlite.org/wal.html
$this->exec('PRAGMA journal_mode=WAL');
} catch (\Exception $e) {
// this is not critical, but we log it as error. FIXME might be degraded to debug later
Logger::error('SQLite: Could not set WAL mode.', $e, $e->getFile(), $e->getLine());
}
if ($schemadir !== '') {
// schema dir is empty, when accessing the DB from Admin interface instead of plugin context
$this->applyMigrations();
}
Functions::register($this->pdo);
}
/**
* Try optimizing the database before closing the connection.
*
* @see https://www.sqlite.org/pragma.html#pragma_optimize
*/
public function __destruct()
{
try {
$this->exec("PRAGMA analysis_limit=400");
$this->exec('PRAGMA optimize;');
} catch (\Exception $e) {
// ignore failures, this is not essential and not available until 3.18.0.
}
}
/**
* Do not serialize the DB connection
*
* @return array
*/
public function __sleep()
{
$this->pdo = null;
return array_keys(get_object_vars($this));
}
/**
* On deserialization, reinit database connection
*/
public function __wakeup()
{
$this->__construct($this->dbname, $this->schemadir, $this->helper);
}
// region public API
/**
* Direct access to the PDO object
* @return \PDO
*/
public function getPdo()
{
return $this->pdo;
}
/**
* Execute a statement and return it
*
* @param string $sql
* @param ...mixed|array $parameters
* @return \PDOStatement Be sure to close the cursor yourself
* @throws \PDOException
*/
public function query($sql, ...$parameters)
{
$start = microtime(true);
if ($parameters && is_array($parameters[0])) $parameters = $parameters[0];
// Statement preparation sometime throws ValueErrors instead of PDOExceptions, we streamline here
try {
$stmt = $this->pdo->prepare($sql);
} catch (\Throwable $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode(), $e);
}
$eventData = [
'sqlitedb' => $this,
'sql' => &$sql,
'parameters' => &$parameters,
'stmt' => $stmt
];
$event = new Event('PLUGIN_SQLITE_QUERY_EXECUTE', $eventData);
if ($event->advise_before()) {
$stmt->execute($parameters);
}
$event->advise_after();
$time = microtime(true) - $start;
if ($time > 0.2) {
Logger::debug('[sqlite] slow query: (' . $time . 's)', [
'sql' => $sql,
'parameters' => $parameters,
'backtrace' => explode("\n", dbg_backtrace())
]);
}
return $stmt;
}
/**
* Execute a statement and return metadata
*
* Returns the last insert ID on INSERTs or the number of affected rows
*
* @param string $sql
* @param ...mixed|array $parameters
* @return int
* @throws \PDOException
*/
public function exec($sql, ...$parameters)
{
$stmt = $this->query($sql, ...$parameters);
$count = $stmt->rowCount();
$stmt->closeCursor();
if ($count && preg_match('/^INSERT /i', $sql)) {
return $this->queryValue('SELECT last_insert_rowid()');
}
return $count;
}
/**
* Simple query abstraction
*
* Returns all data
*
* @param string $sql
* @param ...mixed|array $params
* @return array
* @throws \PDOException
*/
public function queryAll($sql, ...$params)
{
$stmt = $this->query($sql, ...$params);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
/**
* Query one single row
*
* @param string $sql
* @param ...mixed|array $params
* @return array|null
* @throws \PDOException
*/
public function queryRecord($sql, ...$params)
{
$stmt = $this->query($sql, ...$params);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (is_array($row) && count($row)) {
return $row;
}
return null;
}
/**
* Insert or replace the given data into the table
*
* @param string $table
* @param array $data
* @param bool $replace Conflict resolution, replace or ignore
* @return array|null Either the inserted row or null if nothing was inserted
* @throws \PDOException
*/
public function saveRecord($table, $data, $replace = true)
{
$columns = array_map(static fn($column) => '"' . $column . '"', array_keys($data));
$values = array_values($data);
$placeholders = array_pad([], count($columns), '?');
if ($replace) {
$command = 'REPLACE';
} else {
$command = 'INSERT OR IGNORE';
}
/** @noinspection SqlResolve */
$sql = $command . ' INTO "' . $table . '" (' . implode(',', $columns) . ') VALUES (' . implode(
',',
$placeholders
) . ')';
$stm = $this->query($sql, $values);
$success = $stm->rowCount();
$stm->closeCursor();
if ($success) {
$sql = 'SELECT * FROM "' . $table . '" WHERE rowid = last_insert_rowid()';
return $this->queryRecord($sql);
}
return null;
}
/**
* Execute a query that returns a single value
*
* @param string $sql
* @param ...mixed|array $params
* @return mixed|null
* @throws \PDOException
*/
public function queryValue($sql, ...$params)
{
$result = $this->queryAll($sql, ...$params);
if (is_array($result) && count($result)) {
return array_values($result[0])[0];
}
return null;
}
/**
* Execute a query that returns a list of key-value pairs
*
* The first column is used as key, the second as value. Any additional colums are ignored.
*
* @param string $sql
* @param ...mixed|array $params
* @return array
*/
public function queryKeyValueList($sql, ...$params)
{
$result = $this->queryAll($sql, ...$params);
if (!$result) return [];
if (count(array_keys($result[0])) != 2) {
throw new \RuntimeException('queryKeyValueList expects a query that returns exactly two columns');
}
[$key, $val] = array_keys($result[0]);
return array_combine(
array_column($result, $key),
array_column($result, $val)
);
}
// endregion
// region meta handling
/**
* Get a config value from the opt table
*
* @param string $opt Config name
* @param mixed $default What to return if the value isn't set
* @return mixed
* @throws \PDOException
*/
public function getOpt($opt, $default = null)
{
$value = $this->queryValue("SELECT val FROM opts WHERE opt = ?", [$opt]);
if ($value === null) {
return $default;
}
return $value;
}
/**
* Set a config value in the opt table
*
* @param $opt
* @param $value
* @throws \PDOException
*/
public function setOpt($opt, $value)
{
$this->exec('REPLACE INTO opts (opt,val) VALUES (?,?)', [$opt, $value]);
}
/**
* @return string
*/
public function getDbName()
{
return $this->dbname;
}
/**
* @return string
*/
public function getDbFile()
{
global $conf;
return $conf['metadir'] . '/' . $this->dbname . self::FILE_EXTENSION;
}
/**
* Create a dump of the database and its contents
*
* @return string
* @throws \Exception
*/
public function dumpToFile($filename)
{
$fp = fopen($filename, 'w');
if (!$fp) {
throw new \Exception('Could not open file ' . $filename . ' for writing');
}
$tables = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='table'");
$indexes = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='index'");
foreach ($tables as $table) {
fwrite($fp, "DROP TABLE IF EXISTS '{$table['name']}';\n");
}
foreach ($tables as $table) {
fwrite($fp, $table['sql'] . ";\n");
}
foreach ($tables as $table) {
$sql = "SELECT * FROM " . $table['name'];
$res = $this->query($sql);
while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
$values = implode(',', array_map(function ($value) {
if ($value === null) return 'NULL';
return $this->pdo->quote($value);
}, $row));
fwrite($fp, "INSERT INTO '{$table['name']}' VALUES ({$values});\n");
}
$res->closeCursor();
}
foreach ($indexes as $index) {
fwrite($fp, $index['sql'] . ";\n");
}
fclose($fp);
return $filename;
}
// endregion
// region migration handling
/**
* Apply all pending migrations
*
* Each migration is executed in a transaction which is rolled back on failure
* Migrations can be files in the schema directory or event handlers
*
* @throws \Exception
*/
protected function applyMigrations()
{
$currentVersion = $this->currentDbVersion();
$latestVersion = $this->latestDbVersion();
if ($currentVersion === $latestVersion) return;
for ($newVersion = $currentVersion + 1; $newVersion <= $latestVersion; $newVersion++) {
$data = [
'dbname' => $this->dbname,
'from' => $currentVersion,
'to' => $newVersion,
'file' => $this->getMigrationFile($newVersion),
'sqlite' => $this->helper,
'adapter' => $this,
];
$event = new Event('PLUGIN_SQLITE_DATABASE_UPGRADE', $data);
$this->pdo->beginTransaction();
try {
if ($event->advise_before()) {
// standard migration file
$sql = Tools::SQLstring2array(file_get_contents($data['file']));
foreach ($sql as $query) {
$this->pdo->exec($query);
}
} elseif (!$event->result) {
// advise before returned false, but the result was false
throw new \PDOException('Plugin event did not signal success');
}
$this->setOpt('dbversion', $newVersion);
$this->pdo->commit();
$event->advise_after();
} catch (\Exception $e) {
// something went wrong, rollback
$this->pdo->rollBack();
throw $e;
}
}
// vacuum the database to free up unused space
$this->pdo->exec('VACUUM');
}
/**
* Read the current version from the opt table
*
* The opt table is created here if not found
*
* @return int
* @throws \PDOException
*/
protected function currentDbVersion()
{
try {
$version = $this->getOpt('dbversion', 0);
return (int)$version;
} catch (\PDOException $e) {
if (!preg_match('/no such table/', $e->getMessage())) {
// if this is not a "no such table" error, there is something wrong see #80
Logger::error(
'SQLite: Could not read dbversion from opt table due to unexpected error',
[
'dbname' => $this->dbname,
'exception' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
],
__FILE__,
__LINE__
);
}
// add the opt table - if this fails too, let the exception bubble up
$sql = "CREATE TABLE IF NOT EXISTS opts (opt TEXT NOT NULL PRIMARY KEY, val NOT NULL DEFAULT '')";
$this->exec($sql);
return 0;
}
}
/**
* Get the version this db should have
*
* @return int
* @throws \PDOException
*/
protected function latestDbVersion()
{
if (!file_exists($this->schemadir . '/latest.version')) {
throw new \PDOException('No latest.version in schema dir');
}
return (int)trim(file_get_contents($this->schemadir . '/latest.version'));
}
/**
* Get the migrartion file for the given version
*
* @param int $version
* @return string
*/
protected function getMigrationFile($version)
{
return sprintf($this->schemadir . '/update%04d.sql', $version);
}
// endregion
}