forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnection.php
495 lines (426 loc) · 14.3 KB
/
Connection.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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\SQLite3;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\TableName;
use CodeIgniter\Exceptions\InvalidArgumentException;
use Exception;
use SQLite3;
use SQLite3Result;
use stdClass;
/**
* Connection for SQLite3
*
* @extends BaseConnection<SQLite3, SQLite3Result>
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
public $DBDriver = 'SQLite3';
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '`';
/**
* @var bool Enable Foreign Key constraint or not
*/
protected $foreignKeys = false;
/**
* The milliseconds to sleep
*
* @var int|null milliseconds
*
* @see https://www.php.net/manual/en/sqlite3.busytimeout
*/
protected $busyTimeout;
/**
* The setting of the "synchronous" flag
*
* @var int<0, 3>|null flag
*
* @see https://www.sqlite.org/pragma.html#pragma_synchronous
*/
protected ?int $synchronous = null;
/**
* @return void
*/
public function initialize()
{
parent::initialize();
if ($this->foreignKeys) {
$this->enableForeignKeyChecks();
}
if (is_int($this->busyTimeout)) {
$this->connID->busyTimeout($this->busyTimeout);
}
if (is_int($this->synchronous)) {
if (! in_array($this->synchronous, [0, 1, 2, 3], true)) {
throw new InvalidArgumentException('Invalid synchronous value.');
}
$this->connID->exec('PRAGMA synchronous = ' . $this->synchronous);
}
}
/**
* Connect to the database.
*
* @return SQLite3
*
* @throws DatabaseException
*/
public function connect(bool $persistent = false)
{
if ($persistent && $this->DBDebug) {
throw new DatabaseException('SQLite3 doesn\'t support persistent connections.');
}
try {
if ($this->database !== ':memory:' && ! str_contains($this->database, DIRECTORY_SEPARATOR)) {
$this->database = WRITEPATH . $this->database;
}
$sqlite = (! isset($this->password) || $this->password !== '')
? new SQLite3($this->database)
: new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password);
$sqlite->enableExceptions(true);
return $sqlite;
} catch (Exception $e) {
throw new DatabaseException('SQLite3 error: ' . $e->getMessage());
}
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
$this->close();
$this->initialize();
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
$this->connID->close();
}
/**
* Select a specific database table to use.
*/
public function setDatabase(string $databaseName): bool
{
return false;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
$version = SQLite3::version();
return $this->dataCache['version'] = $version['versionString'];
}
/**
* Execute the query
*
* @return false|SQLite3Result
*/
protected function execute(string $sql)
{
try {
return $this->isWriteType($sql)
? $this->connID->exec($sql)
: $this->connID->query($sql);
} catch (Exception $e) {
log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [
'message' => $e->getMessage(),
'exFile' => clean_path($e->getFile()),
'exLine' => $e->getLine(),
'trace' => render_backtrace($e->getTrace()),
]);
if ($this->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
}
return false;
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
return $this->connID->changes();
}
/**
* Platform-dependant string escape
*/
protected function _escapeString(string $str): string
{
if (! $this->connID instanceof SQLite3) {
$this->initialize();
}
return $this->connID->escapeString($str);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
if ((string) $tableName !== '') {
return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''
. ' AND "NAME" NOT LIKE \'sqlite!_%\' ESCAPE \'!\''
. ' AND "NAME" LIKE ' . $this->escape($tableName);
}
return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''
. ' AND "NAME" NOT LIKE \'sqlite!_%\' ESCAPE \'!\''
. (($prefixLimit && $this->DBPrefix !== '')
? ' AND "NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . '%\' ' . sprintf($this->likeEscapeStr, $this->likeEscapeChar)
: '');
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*
* @param string|TableName $table
*/
protected function _listColumns($table = ''): string
{
if ($table instanceof TableName) {
$tableName = $this->escapeIdentifier($table);
} else {
$tableName = $this->protectIdentifiers($table, true, null, false);
}
return 'PRAGMA TABLE_INFO(' . $tableName . ')';
}
/**
* @param string|TableName $tableName
*
* @return false|list<string>
*
* @throws DatabaseException
*/
public function getFieldNames($tableName)
{
$table = ($tableName instanceof TableName) ? $tableName->getTableName() : $tableName;
// Is there a cached result?
if (isset($this->dataCache['field_names'][$table])) {
return $this->dataCache['field_names'][$table];
}
if (! $this->connID instanceof SQLite3) {
$this->initialize();
}
$sql = $this->_listColumns($tableName);
$query = $this->query($sql);
$this->dataCache['field_names'][$table] = [];
foreach ($query->getResultArray() as $row) {
// Do we know from where to get the column's name?
if (! isset($key)) {
if (isset($row['column_name'])) {
$key = 'column_name';
} elseif (isset($row['COLUMN_NAME'])) {
$key = 'COLUMN_NAME';
} elseif (isset($row['name'])) {
$key = 'name';
} else {
// We have no other choice but to just get the first element's key.
$key = key($row);
}
}
$this->dataCache['field_names'][$table][] = $row[$key];
}
return $this->dataCache['field_names'][$table];
}
/**
* Returns an array of objects with field data
*
* @return list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
if (false === $query = $this->query('PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, false) . ')')) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
if (empty($query)) {
return [];
}
$retVal = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $query[$i]->name;
$retVal[$i]->type = $query[$i]->type;
$retVal[$i]->max_length = null;
$retVal[$i]->nullable = isset($query[$i]->notnull) && ! (bool) $query[$i]->notnull;
$retVal[$i]->default = $query[$i]->dflt_value;
// "pk" (either zero for columns that are not part of the primary key,
// or the 1-based index of the column within the primary key).
// https://www.sqlite.org/pragma.html#pragma_table_info
$retVal[$i]->primary_key = ($query[$i]->pk === 0) ? 0 : 1;
}
return $retVal;
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
$sql = "SELECT 'PRIMARY' as indexname, l.name as fieldname, 'PRIMARY' as indextype
FROM pragma_table_info(" . $this->escape(strtolower($table)) . ") as l
WHERE l.pk <> 0
UNION ALL
SELECT sqlite_master.name as indexname, ii.name as fieldname,
CASE
WHEN ti.pk <> 0 AND sqlite_master.name LIKE 'sqlite_autoindex_%' THEN 'PRIMARY'
WHEN sqlite_master.name LIKE 'sqlite_autoindex_%' THEN 'UNIQUE'
WHEN sqlite_master.sql LIKE '% UNIQUE %' THEN 'UNIQUE'
ELSE 'INDEX'
END as indextype
FROM sqlite_master
INNER JOIN pragma_index_xinfo(sqlite_master.name) ii ON ii.name IS NOT NULL
LEFT JOIN pragma_table_info(" . $this->escape(strtolower($table)) . ") ti ON ti.name = ii.name
WHERE sqlite_master.type='index' AND sqlite_master.tbl_name = " . $this->escape(strtolower($table)) . ' COLLATE NOCASE';
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$query = $query->getResultObject();
$tempVal = [];
foreach ($query as $row) {
if ($row->indextype === 'PRIMARY') {
$tempVal['PRIMARY']['indextype'] = $row->indextype;
$tempVal['PRIMARY']['indexname'] = $row->indexname;
$tempVal['PRIMARY']['fields'][$row->fieldname] = $row->fieldname;
} else {
$tempVal[$row->indexname]['indextype'] = $row->indextype;
$tempVal[$row->indexname]['indexname'] = $row->indexname;
$tempVal[$row->indexname]['fields'][$row->fieldname] = $row->fieldname;
}
}
$retVal = [];
foreach ($tempVal as $val) {
$obj = new stdClass();
$obj->name = $val['indexname'];
$obj->fields = array_values($val['fields']);
$obj->type = $val['indextype'];
$retVal[$obj->name] = $obj;
}
return $retVal;
}
/**
* Returns an array of objects with Foreign key data
*
* @return array<string, stdClass>
*/
protected function _foreignKeyData(string $table): array
{
if (! $this->supportsForeignKeys()) {
return [];
}
$query = $this->query("PRAGMA foreign_key_list({$table})")->getResult();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->id]['constraint_name'] = null;
$indexes[$row->id]['table_name'] = $table;
$indexes[$row->id]['foreign_table_name'] = $row->table;
$indexes[$row->id]['column_name'][] = $row->from;
$indexes[$row->id]['foreign_column_name'][] = $row->to;
$indexes[$row->id]['on_delete'] = $row->on_delete;
$indexes[$row->id]['on_update'] = $row->on_update;
$indexes[$row->id]['match'] = $row->match;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* Returns platform-specific SQL to disable foreign key checks.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return 'PRAGMA foreign_keys = OFF';
}
/**
* Returns platform-specific SQL to enable foreign key checks.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return 'PRAGMA foreign_keys = ON';
}
/**
* Returns the last error code and message.
* Must return this format: ['code' => string|int, 'message' => string]
* intval(code) === 0 means "no error".
*
* @return array<string, int|string>
*/
public function error(): array
{
return [
'code' => $this->connID->lastErrorCode(),
'message' => $this->connID->lastErrorMsg(),
];
}
/**
* Insert ID
*/
public function insertID(): int
{
return $this->connID->lastInsertRowID();
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
return $this->connID->exec('BEGIN TRANSACTION');
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
return $this->connID->exec('END TRANSACTION');
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
return $this->connID->exec('ROLLBACK');
}
/**
* Checks to see if the current install supports Foreign Keys
* and has them enabled.
*/
public function supportsForeignKeys(): bool
{
$result = $this->simpleQuery('PRAGMA foreign_keys');
return (bool) $result;
}
}