KD2 Framework  Check-in [48b410159a]

Overview
Comment:Use type hinting and better integration between SQLite3 and PDO
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | 7.3
Files: files | file ages | folders
SHA1: 48b410159a8f07c43d577087781817f217870686
User & Date: bohwaz on 2019-12-19 11:36:47
Other Links: branch diff | manifest | tags
Context
2019-12-19
11:37
Update test to reflect changes in DB APIs check-in: 2633233d00 user: bohwaz tags: 7.3
11:36
Use type hinting and better integration between SQLite3 and PDO check-in: 48b410159a user: bohwaz tags: 7.3
11:36
ErrorManager: Fix error when line is undefined check-in: 42d3f2583b user: bohwaz tags: 7.3
Changes

Modified src/lib/KD2/DB/DB.php from [dc28970951] to [a9c6080640].

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
		'haversine_distance' => [__CLASS__, 'sqlite_haversine'],
	];

	/**
	 * Class construct, expects a driver configuration
	 * @param array $driver Driver configurtaion
	 */
	public function __construct($name, array $params)
	{
		$driver = (object) [
			'type'     => $name,
			'url'      => null,
			'user'     => null,
			'password' => null,
			'options'  => [],







|







63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
		'haversine_distance' => [__CLASS__, 'sqlite_haversine'],
	];

	/**
	 * Class construct, expects a driver configuration
	 * @param array $driver Driver configurtaion
	 */
	public function __construct(string $name, array $params)
	{
		$driver = (object) [
			'type'     => $name,
			'url'      => null,
			'user'     => null,
			'password' => null,
			'options'  => [],
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
		{
			if (empty($params['file']))
			{
				throw new \BadMethodCallException('No file parameter passed.');
			}

			$driver->url = 'sqlite:' . $params['file'];




		}
		else
		{
			throw new \BadMethodCallException('Invalid driver name.');
		}

		$this->driver = $driver;
	}

	/**
	 * Connect to the currently defined driver if needed
	 * @return void
	 */
	public function connect()
	{
		if ($this->pdo)
		{
			return true;
		}

		try {
			$this->pdo = new PDO($this->driver->url, $this->driver->user, $this->driver->password, $this->driver->options);

			// Set attributes
			foreach ($this->pdo_attributes as $attr => $value)







>
>
>
>













|



|







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
		{
			if (empty($params['file']))
			{
				throw new \BadMethodCallException('No file parameter passed.');
			}

			$driver->url = 'sqlite:' . $params['file'];

			if (isset($params['flags'])) {
				$driver->options[PDO::SQLITE_ATTR_OPEN_FLAGS] = $params['flags'];
			}
		}
		else
		{
			throw new \BadMethodCallException('Invalid driver name.');
		}

		$this->driver = $driver;
	}

	/**
	 * Connect to the currently defined driver if needed
	 * @return void
	 */
	public function connect(): void
	{
		if ($this->pdo)
		{
			return;
		}

		try {
			$this->pdo = new PDO($this->driver->url, $this->driver->user, $this->driver->password, $this->driver->options);

			// Set attributes
			foreach ($this->pdo_attributes as $attr => $value)
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
				{
					$this->rollback();
				}
			});
		}

		$this->driver->password = '******';

		return true;
	}

	public function close()
	{
		$this->pdo = null;
	}

	protected function applyTablePrefix($statement)
	{
		if (strpos('__PREFIX__', $statement) !== false)
		{
			$statement = preg_replace('/(?<=\s|^)__PREFIX__(?=\w)/', $this->driver->tables_prefix, $statement);
		}

		return $statement;
	}

	public function query($statement)
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->pdo->query($statement);
	}










	public function exec($statement)
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->pdo->exec($statement);
	}

	public function execMultiple($statement)
	{
		$this->connect();

		$this->begin();






		try
		{
			if ($this->driver->type == 'mysql')
			{
				$emulate = $this->pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES);
				$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); // required to allow multiple queries in same statement

				$st = $this->prepare($statement);
				$st->execute();

				while ($st->nextRowset())
				{
					// Iterate over rowsets, see https://bugs.php.net/bug.php?id=61613 
				}

				$return = $this->commit();
			}
			else
			{
				$return = $this->pdo->exec($statement);
				$this->commit();
			}
		}
		catch (\PDOException $e)
		{
			$this->rollBack();
			throw $e;
		}
		finally
		{

			if ($this->driver->type == 'mysql')
			{
				$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $emulate);
			}
		}

		return $return;
	}

	public function createFunction($name, callable $callback)
	{
		if ($this->driver->type != 'sqlite')
		{
			throw new \LogicException('This driver does not support functions.');
		}

		if ($this->pdo)
		{
			return $this->pdo->sqliteCreateFunction($name, $callback);
		}
		else
		{
			$this->sqlite_functions[$name] = $callback;
			return true;
		}
	}

	public function import($file)
	{
		if (!is_readable($file))
		{
			throw new \RuntimeException(sprintf('Cannot read file %s', $file));
		}

		return $this->execMultiple(file_get_contents($file));
	}

	public function prepare($statement, $driver_options = [])
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->pdo->prepare($statement, $driver_options);
	}

	public function begin()







|
<
|
<
|




|









|






>
>
>
>
>
>
>
>
>
|






|




>
>
>
>
>





|
|






|










|






>
|
<







|

















|









|







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
				{
					$this->rollback();
				}
			});
		}

		$this->driver->password = '******';
	}



	public function close(): void
	{
		$this->pdo = null;
	}

	protected function applyTablePrefix(string $statement): string
	{
		if (strpos('__PREFIX__', $statement) !== false)
		{
			$statement = preg_replace('/(?<=\s|^)__PREFIX__(?=\w)/', $this->driver->tables_prefix, $statement);
		}

		return $statement;
	}

	public function query(string $statement)
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->pdo->query($statement);
	}

	/**
	 * Execute an SQL statement and return the number of affected rows
	 * returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, returns 0.
	 * It may return FALSE, even if the operation completed successfully
	 *
	 * @see https://www.php.net/manual/en/pdo.exec.php
	 * @param  string $statement SQL Query
	 * @return bool|int
	 */
	public function exec(string $statement)
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->pdo->exec($statement);
	}

	public function execMultiple(string $statement)
	{
		$this->connect();

		$this->begin();

		// Store user-set prepared emulation setting for later
		if ($this->driver->type == 'mysql') {
			$emulate = $this->pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES);
		}

		try
		{
			if ($this->driver->type == 'mysql')
			{
				// required to allow multiple queries in same statement
				$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

				$st = $this->prepare($statement);
				$st->execute();

				while ($st->nextRowset())
				{
					// Iterate over rowsets, see https://bugs.php.net/bug.php?id=61613
				}

				$return = $this->commit();
			}
			else
			{
				$return = $this->pdo->exec($statement);
				$this->commit();
			}
		}
		catch (PDOException $e)
		{
			$this->rollBack();
			throw $e;
		}
		finally
		{
			// Restore prepared statement attribute
			if ($this->driver->type == 'mysql') {

				$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $emulate);
			}
		}

		return $return;
	}

	public function createFunction(string $name, callable $callback): bool
	{
		if ($this->driver->type != 'sqlite')
		{
			throw new \LogicException('This driver does not support functions.');
		}

		if ($this->pdo)
		{
			return $this->pdo->sqliteCreateFunction($name, $callback);
		}
		else
		{
			$this->sqlite_functions[$name] = $callback;
			return true;
		}
	}

	public function import(string $file)
	{
		if (!is_readable($file))
		{
			throw new \RuntimeException(sprintf('Cannot read file %s', $file));
		}

		return $this->execMultiple(file_get_contents($file));
	}

	public function prepare(string $statement, array $driver_options = [])
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->pdo->prepare($statement, $driver_options);
	}

	public function begin()
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

	public function rollback()
	{
		$this->connect();
		return $this->pdo->rollBack();
	}

	public function lastInsertId($name = null)
	{
		$this->connect();
		return $this->pdo->lastInsertId($name);
	}

	public function lastInsertRowId()
	{
		return $this->lastInsertId();
	}





	public function quote($value, $parameter_type = PDO::PARAM_STR)
	{
		if ($this->driver->type == 'sqlite')
		{
			// PHP quote() is truncating strings on NUL bytes
			// https://bugs.php.net/bug.php?id=63419

			$value = str_replace("\0", '\\0', $value);
		}

		$this->connect();
		return $this->pdo->quote($value, $parameter_type);
	}






	public function quoteIdentifier($value)
	{
		// see https://www.codetinkerer.com/2015/07/08/escaping-column-and-table-names-in-mysql-part2.html
		if ($this->driver->type == 'mysql')
		{
			if (strlen($value) > 64)
			{
				throw new \OverflowException('MySQL column or table names cannot be longer than 64 characters.');







|





|




>
>
>
>
|













>
>
>
>
>
|







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

	public function rollback()
	{
		$this->connect();
		return $this->pdo->rollBack();
	}

	public function lastInsertId(string $name = null): string
	{
		$this->connect();
		return $this->pdo->lastInsertId($name);
	}

	public function lastInsertRowId(): string
	{
		return $this->lastInsertId();
	}

	/**
	 * Quotes a string for use in a query
	 * @see https://www.php.net/manual/en/pdo.quote.php
	 */
	public function quote(string $value, int $parameter_type = PDO::PARAM_STR): string
	{
		if ($this->driver->type == 'sqlite')
		{
			// PHP quote() is truncating strings on NUL bytes
			// https://bugs.php.net/bug.php?id=63419

			$value = str_replace("\0", '\\0', $value);
		}

		$this->connect();
		return $this->pdo->quote($value, $parameter_type);
	}

	/**
	 * Quotes an identifier (table name or column name) for use in a query
	 * @param  string $value Identifier to quote
	 * @return string Quoted identifier
	 */
	public function quoteIdentifier(string $value): string
	{
		// see https://www.codetinkerer.com/2015/07/08/escaping-column-and-table-names-in-mysql-part2.html
		if ($this->driver->type == 'mysql')
		{
			if (strlen($value) > 64)
			{
				throw new \OverflowException('MySQL column or table names cannot be longer than 64 characters.');
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
		}
		else
		{
			return sprintf('"%s"', str_replace('"', '""', $value));
		}
	}

	public function preparedQuery($query, $args = [])
	{
        assert(is_string($query));

        // Only one argument, which is an array: this is an associative array
        if (isset($args[0]) && is_array($args[0]))
        {
        	$args = $args[0];







|







387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
		}
		else
		{
			return sprintf('"%s"', str_replace('"', '""', $value));
		}
	}

	public function preparedQuery(string $query, array $args = [])
	{
        assert(is_string($query));

        // Only one argument, which is an array: this is an associative array
        if (isset($args[0]) && is_array($args[0]))
        {
        	$args = $args[0];
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577





578
579
580
581
582
583
584
585
586
587








588
589
590
591
592
593
594
595

		$st = $this->prepare($query);
		$st->execute($args);

		return $st;
	}

	public function iterate($query)
	{
		$args = array_slice(func_get_args(), 1);
		$st = $this->preparedQuery($query, $args);

		while ($row = $st->fetch())
		{
			yield $row;
		}

		unset($st);

		return;
	}

	public function get($query)
	{
		$args = array_slice(func_get_args(), 1);
		return $this->preparedQuery($query, $args)->fetchAll();
	}

	public function getAssoc($query)
	{
		$args = array_slice(func_get_args(), 1);
		$st = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $st->fetch(PDO::FETCH_NUM))
		{
			$out[$row[0]] = $row[1];
		}

		return $out;
	}

	public function getGrouped($query)
	{
		$args = array_slice(func_get_args(), 1);
		$st = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $st->fetch(PDO::FETCH_ASSOC))
		{
			$out[current($row)] = (object) $row;
		}

		return $out;
	}

	/**
	 * Runs a query and returns the first row
	 * @param  string $query SQL query
	 * @return object
	 *
	 * Accepts one or more arguments as part of bindings for the statement
	 */
	public function first($query)
	{
		$st = $this->preparedQuery($query, array_slice(func_get_args(), 1));

		return $st->fetch();
	}

	/**
	 * Runs a query and returns the first column
	 * @param  string $query SQL query
	 * @return object
	 *
	 * Accepts one or more arguments as part of bindings for the statement
	 */
	public function firstColumn($query)
	{
		$st = $this->preparedQuery($query, array_slice(func_get_args(), 1));

		return $st->fetchColumn();
	}

	/**
	 * Inserts a row in $table, using $fields as data to fill
	 * @param  string $table  Table où insérer
	 * @param  array|object $fields Champs à remplir
	 * @return boolean
	 */
	public function insert($table, $fields)
	{
		assert(is_array($fields) || is_object($fields));

		$fields = (array) $fields;

		$fields_names = array_keys($fields);
		$query = sprintf('INSERT INTO %s (%s) VALUES (:%s);', $this->quoteIdentifier($table),
			implode(', ', array_map([$this, 'quoteIdentifier'], $fields_names)), implode(', :', $fields_names));

		return $this->preparedQuery($query, $fields);
	}

	/**
	 * Updates lines in $table using $fields, selecting using $where
	 * @param  string       $table  Table name
	 * @param  array|object $fields List of fields to update
	 * @param  string       $where  Content of the WHERE clause
	 * @param  array|object $args   Arguments for the WHERE clause
	 * @return boolean
	 */
	public function update($table, $fields, $where = null, $args = [])
	{
		assert(is_string($table));
		assert((is_string($where) && strlen($where)) || is_null($where));
		assert(is_array($fields) || is_object($fields));
		assert(is_array($args) || is_object($args), 'Arguments for the WHERE clause must be a named array or object');

		// Forcer en tableau
		$fields = (array) $fields;
		$args = (array) $args;

		// No fields to update? no need to do a query
		if (empty($fields))
		{
			return false;
		}

		$column_updates = [];
		
		foreach ($fields as $key => $value)
		{
			if (is_object($value) && $value instanceof \DateTimeInterface)
			{
				$value = $value->format('Y-m-d H:i:s');
			}

			// Append to arguments
			$args['field_' . $key] = $value;

			$column_updates[] = sprintf('%s = :field_%s', $this->quoteIdentifier($key), $key);
		}

		if (is_null($where))
		{
			$where = '1';
		}

		// Assemblage de la requête
		$column_updates = implode(', ', $column_updates);
		$query = sprintf('UPDATE %s SET %s WHERE %s;', $this->quoteIdentifier($table), $column_updates, $where);

		return $this->preparedQuery($query, $args);
	}

	/**
	 * Deletes rows from a table
	 * @param  string $table Table name
	 * @param  string $where WHERE clause
	 * @return boolean
	 *
	 * Accepts one or more arguments as bindings for the WHERE clause.
	 * Warning! If run without a $where argument, will delete all rows from a table!
	 */
	public function delete($table, $where = '1')
	{
		$query = sprintf('DELETE FROM %s WHERE %s;', $table, $where);
		return $this->preparedQuery($query, array_slice(func_get_args(), 2));
	}

	/**
	 * Returns true if the condition from the WHERE clause is valid and a row exists
	 * @param  string $table Table name
	 * @param  string $where WHERE clause
	 * @return boolean
	 */
	public function test($table, $where = '1')
	{
		$args = array_merge(
			[sprintf('SELECT 1 FROM %s WHERE %s LIMIT 1;', $this->quoteIdentifier($table), $where)],
			array_slice(func_get_args(), 2)
		);

		return (bool) call_user_func_array([$this, 'firstColumn'], $args);
	}






	public function count($table, $where = '1')
	{
		$args = array_merge(
			[sprintf('SELECT COUNT(*) FROM %s WHERE %s LIMIT 1;', $this->quoteIdentifier($table), $where)],
			array_slice(func_get_args(), 2)
		);

		return (int) call_user_func_array([$this, 'firstColumn'], $args);
	}









	public function where($name)
	{
		$num_args = func_num_args();

		$value = func_get_arg($num_args - 1);

		if (is_object($value) && $value instanceof \DateTimeInterface)
		{







|

<












|

<



|

<











|

<


















|

|











|

|










|




















|






|










|


















|















|


|








|

<
|
|
<
|
<
|
|
>
>
>
>
>
|

<
|
|
<
|
<
|
|
>
>
>
>
>
>
>
>
|







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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590

591
592

593

594
595
596
597
598
599
600
601
602

603
604

605

606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623

		$st = $this->prepare($query);
		$st->execute($args);

		return $st;
	}

	public function iterate(string $query, ...$args): iterable
	{

		$st = $this->preparedQuery($query, $args);

		while ($row = $st->fetch())
		{
			yield $row;
		}

		unset($st);

		return;
	}

	public function get(string $query, ...$args): array
	{

		return $this->preparedQuery($query, $args)->fetchAll();
	}

	public function getAssoc(string $query, ...$args): array
	{

		$st = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $st->fetch(PDO::FETCH_NUM))
		{
			$out[$row[0]] = $row[1];
		}

		return $out;
	}

	public function getGrouped(string $query, ...$args): array
	{

		$st = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $st->fetch(PDO::FETCH_ASSOC))
		{
			$out[current($row)] = (object) $row;
		}

		return $out;
	}

	/**
	 * Runs a query and returns the first row
	 * @param  string $query SQL query
	 * @return object
	 *
	 * Accepts one or more arguments as part of bindings for the statement
	 */
	public function first(string $query, ...$args)
	{
		$st = $this->preparedQuery($query, $args);

		return $st->fetch();
	}

	/**
	 * Runs a query and returns the first column
	 * @param  string $query SQL query
	 * @return object
	 *
	 * Accepts one or more arguments as part of bindings for the statement
	 */
	public function firstColumn(string $query, ...$args)
	{
		$st = $this->preparedQuery($query, $args);

		return $st->fetchColumn();
	}

	/**
	 * Inserts a row in $table, using $fields as data to fill
	 * @param  string $table  Table où insérer
	 * @param  array|object $fields Champs à remplir
	 * @return boolean
	 */
	public function insert(string $table, $fields)
	{
		assert(is_array($fields) || is_object($fields));

		$fields = (array) $fields;

		$fields_names = array_keys($fields);
		$query = sprintf('INSERT INTO %s (%s) VALUES (:%s);', $this->quoteIdentifier($table),
			implode(', ', array_map([$this, 'quoteIdentifier'], $fields_names)), implode(', :', $fields_names));

		return $this->preparedQuery($query, $fields);
	}

	/**
	 * Updates lines in $table using $fields, selecting using $where
	 * @param  string       $table  Table name
	 * @param  array|object $fields List of fields to update
	 * @param  string       $where  Content of the WHERE clause
	 * @param  array|object $args   Arguments for the WHERE clause
	 * @return boolean
	 */
	public function update(string $table, $fields, string $where = null, $args = [])
	{
		assert(is_string($table));
		assert((is_string($where) && strlen($where)) || is_null($where));
		assert(is_array($fields) || is_object($fields));
		assert(is_array($args) || is_object($args), 'Arguments for the WHERE clause must be a named array or object');

		// Convert to array
		$fields = (array) $fields;
		$args = (array) $args;

		// No fields to update? no need to do a query
		if (empty($fields))
		{
			return false;
		}

		$column_updates = [];

		foreach ($fields as $key => $value)
		{
			if (is_object($value) && $value instanceof \DateTimeInterface)
			{
				$value = $value->format('Y-m-d H:i:s');
			}

			// Append to arguments
			$args['field_' . $key] = $value;

			$column_updates[] = sprintf('%s = :field_%s', $this->quoteIdentifier($key), $key);
		}

		if (is_null($where))
		{
			$where = '1';
		}

		// Final query assembly
		$column_updates = implode(', ', $column_updates);
		$query = sprintf('UPDATE %s SET %s WHERE %s;', $this->quoteIdentifier($table), $column_updates, $where);

		return $this->preparedQuery($query, $args);
	}

	/**
	 * Deletes rows from a table
	 * @param  string $table Table name
	 * @param  string $where WHERE clause
	 * @return boolean
	 *
	 * Accepts one or more arguments as bindings for the WHERE clause.
	 * Warning! If run without a $where argument, will delete all rows from a table!
	 */
	public function delete(string $table, string $where, ...$args)
	{
		$query = sprintf('DELETE FROM %s WHERE %s;', $table, $where);
		return $this->preparedQuery($query, $args);
	}

	/**
	 * Returns true if the condition from the WHERE clause is valid and a row exists
	 * @param  string $table Table name
	 * @param  string $where WHERE clause
	 * @return boolean
	 */
	public function test(string $table, string $where, ...$args): bool
	{

		$query = sprintf('SELECT 1 FROM %s WHERE %s LIMIT 1;', $this->quoteIdentifier($table), $where);
		return (bool) $this->firstColumn($query, ...$args);

	}


	/**
	 * Returns the number of rows in a table according to a WHERE clause
	 * @param  string $table Table name
	 * @param  string $where WHERE clause
	 * @return integer
	 */
	public function count(string $table, string $where, ...$args): int
	{

		$query = sprintf('SELECT COUNT(*) FROM %s WHERE %s LIMIT 1;', $this->quoteIdentifier($table), $where);
		return (int) $this->firstColumn($query, ...$args);

	}


	/**
	 * Generate a WHERE clause, can be called as a short notation:
	 * where('id', '42')
	 * or including the comparison operator:
	 * where('id', '>', '42')
	 * It accepts arrays or objects as the value. If no operator is specified, 'IN' is used.
	 * @param  string $name Column name
	 * @return string
	 */
	public function where(string $name): string
	{
		$num_args = func_num_args();

		$value = func_get_arg($num_args - 1);

		if (is_object($value) && $value instanceof \DateTimeInterface)
		{
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
			$value = $value ? 'TRUE' : 'FALSE';
		}
		elseif (is_string($value))
		{
			$value = $this->quote($value);
		}

		return sprintf('%s %s %s', $name, $operator, $value);
	}

	/**
	 * SQLite search ranking user defined function
	 * Converted from C from SQLite manual: https://www.sqlite.org/fts3.html#appendix_a
	 * @param  string $aMatchInfo
	 * @return double Score







|







697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
			$value = $value ? 'TRUE' : 'FALSE';
		}
		elseif (is_string($value))
		{
			$value = $this->quote($value);
		}

		return sprintf('%s %s %s', $this->quoteIdentifier($name), $operator, $value);
	}

	/**
	 * SQLite search ranking user defined function
	 * Converted from C from SQLite manual: https://www.sqlite.org/fts3.html#appendix_a
	 * @param  string $aMatchInfo
	 * @return double Score
741
742
743
744
745
746
747
748
749
750
751
	 */
	static public function sqlite_haversine()
	{
		if (count($geo = array_map('deg2rad', array_filter(func_get_args(), 'is_numeric'))) != 4)
		{
			throw new \InvalidArgumentException('4 arguments expected for haversine_distance');
		}
		
		return round(acos(sin($geo[0]) * sin($geo[2]) + cos($geo[0]) * cos($geo[2]) * cos($geo[1] - $geo[3])) * 6372.8, 3);
	}
}







|



769
770
771
772
773
774
775
776
777
778
779
	 */
	static public function sqlite_haversine()
	{
		if (count($geo = array_map('deg2rad', array_filter(func_get_args(), 'is_numeric'))) != 4)
		{
			throw new \InvalidArgumentException('4 arguments expected for haversine_distance');
		}

		return round(acos(sin($geo[0]) * sin($geo[2]) + cos($geo[0]) * cos($geo[2]) * cos($geo[1] - $geo[3])) * 6372.8, 3);
	}
}

Modified src/lib/KD2/DB/SQLite3.php from [6fa30c8b55] to [ce993c515a].

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

	You should have received a copy of the GNU Affero General Public License
	along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
*/

/**
 * DB_SQLite3: a generic wrapper around SQLite3, adding easier access functions
 * Compatible API with DB
 *
 * @author  bohwaz http://bohwaz.net/
 * @license AGPLv3
 */

namespace KD2\DB;

use SQLite3;
use PDO;

class SQLite3 extends DB
{
	/**
	 * @var SQLite3
	 */
	protected $db;

	/**
	 * @var int
	 */
	protected $flags;

	/**
	 * @var string
	 */
	protected $file;

	/**
	 * @var boolean
	 */
	protected $transaction = false;

	const DATE_FORMAT = 'Y-m-d H:i:s';

	public function __construct($file, $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE)
	{
		parent::__construct('sqlite', ['file' => $file]);

		$this->file = $file;
		$this->flags = $flags;
	}

	public function close()
	{
		$this->db->close();
		$this->db = null;
	}

	public function connect()
	{
		if ($this->db)


		{

			return false;


		}




		$this->db = new \SQLite3($this->file, $this->flags);

		$this->db->enableExceptions(true);

		$this->db->busyTimeout($this->pdo_attributes[PDO::ATTR_TIMEOUT] * 1000);

		foreach ($this->sqlite_functions as $name => $callback)
		{
			$this->db->createFunction($name, $callback);
		}

		// Force to rollback any outstanding transaction
		register_shutdown_function(function () {
			if ($this->db && $this->inTransaction())
			{
				$this->rollback();
			}
		});

		return true;
	}

	public function createFunction($name, callable $callback)
	{
		if ($this->db)
		{
			return $this->db->createFunction($name, $callback);
		}
		else
		{
			$this->sqlite_functions[$name] = $callback;
			return true;
		}
	}


	public function escapeString($str)
	{
		// escapeString is not binary safe: https://bugs.php.net/bug.php?id=62361
		$str = str_replace("\0", "\\0", $str);

		return SQLite3::escapeString($str);
	}

	public function quote($str, $parameter_type = null)
	{
		return '\'' . $this->escapeString($str) . '\'';
	}

	public function begin()
	{
		if ($this->transaction)







|







<









<
<
<
<
<
<
<
<
<
<







<
<
<
<
<
<
<
<
|





|

|
>
>
|
>
|
>
>

>
>
|
>
|

















|
<
|
<
|













|




|


|







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

	You should have received a copy of the GNU Affero General Public License
	along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
*/

/**
 * DB_SQLite3: a generic wrapper around SQLite3, adding easier access functions
 * Compatible API with DB, but instead of using PDO, uses SQLite3
 *
 * @author  bohwaz http://bohwaz.net/
 * @license AGPLv3
 */

namespace KD2\DB;


use PDO;

class SQLite3 extends DB
{
	/**
	 * @var SQLite3
	 */
	protected $db;











	/**
	 * @var boolean
	 */
	protected $transaction = false;

	const DATE_FORMAT = 'Y-m-d H:i:s';









	public function close(): void
	{
		$this->db->close();
		$this->db = null;
	}

	public function connect(): void
	{
		if ($this->db) {
			return;
		}

		$file = str_replace('sqlite:', '', $this->driver->url);

		if (isset($this->driver->options[PDO::SQLITE_ATTR_OPEN_FLAGS])) {
			$flags = $this->driver->options[PDO::SQLITE_ATTR_OPEN_FLAGS];
		}
		else {
			$flags = \SQLITE3_OPEN_READWRITE | \SQLITE3_OPEN_CREATE;
		}

		$this->db = new \SQLite3($file, $flags);

		$this->db->enableExceptions(true);

		$this->db->busyTimeout($this->pdo_attributes[PDO::ATTR_TIMEOUT] * 1000);

		foreach ($this->sqlite_functions as $name => $callback)
		{
			$this->db->createFunction($name, $callback);
		}

		// Force to rollback any outstanding transaction
		register_shutdown_function(function () {
			if ($this->db && $this->inTransaction())
			{
				$this->rollback();
			}
		});
	}



	public function createFunction(string $name, callable $callback): bool
	{
		if ($this->db)
		{
			return $this->db->createFunction($name, $callback);
		}
		else
		{
			$this->sqlite_functions[$name] = $callback;
			return true;
		}
	}


	public function escapeString(string $str): string
	{
		// escapeString is not binary safe: https://bugs.php.net/bug.php?id=62361
		$str = str_replace("\0", "\\0", $str);

		return \SQLite3::escapeString($str);
	}

	public function quote(string $str, int $parameter_type = 0): string
	{
		return '\'' . $this->escapeString($str) . '\'';
	}

	public function begin()
	{
		if ($this->transaction)
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

		$this->connect();
		$this->db->exec('ROLLBACK;');
		$this->transaction = false;
		return true;
	}

	public function getArgType(&$arg, $name = '')
	{
		switch (gettype($arg))
		{
			case 'double':
				return \SQLITE3_FLOAT;
			case 'integer':
			case 'boolean':
				return \SQLITE3_INTEGER;
			case 'NULL':
				return \SQLITE3_NULL;
			case 'string':
				return \SQLITE3_TEXT;
			case 'array':
				if (count($arg) == 2 
					&& in_array($arg[0], [\SQLITE3_FLOAT, \SQLITE3_INTEGER, \SQLITE3_NULL, \SQLITE3_TEXT, \SQLITE3_BLOB]))
				{
					$type = $arg[0];
					$arg = $arg[1];

					return $type;
				}







|













|







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

		$this->connect();
		$this->db->exec('ROLLBACK;');
		$this->transaction = false;
		return true;
	}

	public function getArgType(string &$arg, string $name = ''): int
	{
		switch (gettype($arg))
		{
			case 'double':
				return \SQLITE3_FLOAT;
			case 'integer':
			case 'boolean':
				return \SQLITE3_INTEGER;
			case 'NULL':
				return \SQLITE3_NULL;
			case 'string':
				return \SQLITE3_TEXT;
			case 'array':
				if (count($arg) == 2
					&& in_array($arg[0], [\SQLITE3_FLOAT, \SQLITE3_INTEGER, \SQLITE3_NULL, \SQLITE3_TEXT, \SQLITE3_BLOB]))
				{
					$type = $arg[0];
					$arg = $arg[1];

					return $type;
				}
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
	 * @return \SQLite3Stmt|boolean Returns a boolean if the query is writing
	 * to the database, or a statement if it's a read-only query.
	 *
	 * The fact that this method returns a boolean is voluntary, to avoid a bug
	 * in SQLite3/PHP where you can re-run a query by calling fetchResult
	 * on a statement. This could cause double writing.
	 */
	public function preparedQuery($query, $args = [])
	{
		assert(is_string($query));
		assert(is_array($args) || is_object($args));

		// Forcer en tableau
		$args = (array) $args;








|







197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
	 * @return \SQLite3Stmt|boolean Returns a boolean if the query is writing
	 * to the database, or a statement if it's a read-only query.
	 *
	 * The fact that this method returns a boolean is voluntary, to avoid a bug
	 * in SQLite3/PHP where you can re-run a query by calling fetchResult
	 * on a statement. This could cause double writing.
	 */
	public function preparedQuery(string $query, array $args = [])
	{
		assert(is_string($query));
		assert(is_array($args) || is_object($args));

		// Forcer en tableau
		$args = (array) $args;

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
		}
		catch (\Exception $e)
		{
			throw new \RuntimeException($e->getMessage() . "\n" . $query . "\n" . json_encode($args, true));
		}
	}

	public function query($query)
	{
		$this->connect();
		$query = $this->applyTablePrefix($query);
		return $this->db->query($query);
	}

	/**
	 * Performs a user SELECT query in the database
	 *
	 * This is meant to allow users to make SELECT statements without altering the database
	 * and staying as safe as possible.
	 *
	 * Warning! There are probably still some ways to extract valuable information
	 * for a hacker. This feature should not be available to all your users!
	 *
	 * @param  string $query SQL SELECT query
	 * @return array Rows of the result, as stdClass objects
	 */
	public function userSelectStatement($query)
	{
		if (preg_match('/;\s*(.+?)$/', $query))
		{
			throw new \LogicException('Only one single query can be executed at the same time.');
		}

		// Forbid use of some strings that could allow give hints to an attacker:
		// PRAGMA, sqlite_version(), sqlite_master table, comments
		if (preg_match('/PRAGMA\s+|sqlite_version|sqlite_master|--|\/\*|\*\/|load_extension|ATTACH\s+|randomblob|sqlite_compileoption_|sqlite_offset|sqlite_source_|zeroblob|X\'\w|0x\w|sqlite_dbpage|fts3_tokenizer/i', $query, $match))
		{
			throw new \LogicException('Invalid SQL query.');
		}

		if (!preg_match('/^\s*SELECT\s+/i', $query))
		{
			$query = 'SELECT ' . $query;
		}

		$st = $this->db->prepare($query);

		if (!$st->readOnly())
		{
			throw new \LogicException('Only read-only queries are accepted.');
		}

		return $st;
	}

	public function userSelectGet($query)
	{
		$st = $this->userSelectStatement($query);

		$res = $st->execute();

		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			$out[] = (object) $row;
		}

		return $out;
	}

	public function iterate($query)
	{
		$args = array_slice(func_get_args(), 1);
		$res = $this->preparedQuery($query, $args);

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			yield (object) $row;
		}

		unset($res);

		return;
	}

	public function get($query)
	{
		$args = array_slice(func_get_args(), 1);
		$res = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			$out[] = (object) $row;
		}

		return $out;
	}

	public function getAssoc($query)
	{
		$args = array_slice(func_get_args(), 1);
		$res = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_NUM))
		{
			$out[$row[0]] = $row[1];
		}

		return $out;
	}

	public function getGrouped($query)
	{
		$args = array_slice(func_get_args(), 1);
		$res = $this->preparedQuery($query, $args);
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			$out[current($row)] = (object) $row;
		}

		return $out;
	}

	/**
	 * Executes multiple queries in a transaction
	 */
	public function execMultiple($query)
	{
		$this->begin();

		try {
			$query = $this->applyTablePrefix($query);
			$this->db->exec($query);
		}
		catch (\Exception $e)
		{
			$this->rollback();
			throw $e;
		}

		return $this->commit();
	}

	public function exec($query)
	{
		$this->connect();
		$query = $this->applyTablePrefix($query);
		return $this->db->exec($query);
	}

	/**
	 * Runs a query and returns the first row from the result
	 * @param  string $query
	 * @return object
	 *
	 * Accepts one or more arguments for the prepared query
	 */
	public function first($query)
	{
		$res = $this->preparedQuery($query, array_slice(func_get_args(), 1));

		$row = $res->fetchArray(SQLITE3_ASSOC);
		$res->finalize();

		return is_array($row) ? (object) $row : false;
	}

	/**
	 * Runs a query and returns the first column of the first row of the result
	 * @param  string $query
	 * @return object
	 *
	 * Accepts one or more arguments for the prepared query
	 */
	public function firstColumn($query)
	{
		$res = $this->preparedQuery($query, array_slice(func_get_args(), 1));

		$row = $res->fetchArray(\SQLITE3_NUM);

		return (is_array($row) && count($row) > 0) ? $row[0] : false;
	}

	public function countRows(\SQLite3Result $result)
	{
		$i = 0;

		while ($result->fetchArray(\SQLITE3_NUM))
		{
			$i++;
		}

		$result->reset();

		return $i;
	}

	public function lastInsertId($name = null)
	{
		return $this->db->lastInsertRowId();
	}

	public function lastInsertRowId()
	{
		return $this->db->lastInsertRowId();
	}

	public function prepare($query, $driver_options = [])
	{
		$query = $this->applyTablePrefix($query);
		return $this->db->prepare($query);
	}

	public function openBlob($table, $column, $rowid, $dbname = 'main', $flags = \SQLITE3_OPEN_READONLY)
	{
		if (\PHP_VERSION_ID >= 70200)
		{
			return $this->db->openBlob($table, $column, $rowid, $dbname, $flags);
		}
		else
		{
			if ($flags != \SQLITE3_OPEN_READONLY)
			{
				throw new \Exception('Cannot open blob with read/write. Only available from PHP 7.2.0');
			}

			return $this->db->openBlob($table, $column, $rowid, $dbname);
		}
	}

	static public function getDatabaseDetailsFromString($source_string)
	{
		if (substr($source_string, 0, 16) !== "SQLite format 3\0" || strlen($source_string) < 100) {
			return null;
		}

		$user_version = bin2hex(substr($source_string, 60, 4));
		$application_id = bin2hex(substr($source_string, 68, 4));







|


|
|














|

|

|




|




|

|


|









|

|













|

<
|











|

<
|










|

<
|










|

<
|













|




|
|










|


|
|





|



|

|

|












|

|






|













|




|




|

|
|


|
















|







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
		}
		catch (\Exception $e)
		{
			throw new \RuntimeException($e->getMessage() . "\n" . $query . "\n" . json_encode($args, true));
		}
	}

	public function query(string $statement)
	{
		$this->connect();
		$statement = $this->applyTablePrefix($statement);
		return $this->db->query($statement);
	}

	/**
	 * Performs a user SELECT query in the database
	 *
	 * This is meant to allow users to make SELECT statements without altering the database
	 * and staying as safe as possible.
	 *
	 * Warning! There are probably still some ways to extract valuable information
	 * for a hacker. This feature should not be available to all your users!
	 *
	 * @param  string $query SQL SELECT query
	 * @return array Rows of the result, as stdClass objects
	 */
	public function userSelectStatement(string $statement)
	{
		if (preg_match('/;\s*(.+?)$/', $statement))
		{
			throw new \LogicException('Only one single statement can be executed at the same time.');
		}

		// Forbid use of some strings that could allow give hints to an attacker:
		// PRAGMA, sqlite_version(), sqlite_master table, comments
		if (preg_match('/PRAGMA\s+|sqlite_version|sqlite_master|--|\/\*|\*\/|load_extension|ATTACH\s+|randomblob|sqlite_compileoption_|sqlite_offset|sqlite_source_|zeroblob|X\'\w|0x\w|sqlite_dbpage|fts3_tokenizer/i', $statement, $match))
		{
			throw new \LogicException('Invalid SQL query.');
		}

		if (!preg_match('/^\s*SELECT\s+/i', $statement))
		{
			$query = 'SELECT ' . $statement;
		}

		$st = $this->db->prepare($statement);

		if (!$st->readOnly())
		{
			throw new \LogicException('Only read-only queries are accepted.');
		}

		return $st;
	}

	public function userSelectGet(string $statement): array
	{
		$st = $this->userSelectStatement($statement);

		$res = $st->execute();

		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			$out[] = (object) $row;
		}

		return $out;
	}

	public function iterate(string $statement, ...$args): iterable
	{

		$res = $this->preparedQuery($statement, $args);

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			yield (object) $row;
		}

		unset($res);

		return;
	}

	public function get(string $statement, ...$args): array
	{

		$res = $this->preparedQuery($statement, $args);
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			$out[] = (object) $row;
		}

		return $out;
	}

	public function getAssoc(string $statement, ...$args): array
	{

		$res = $this->preparedQuery($statement, $args);
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_NUM))
		{
			$out[$row[0]] = $row[1];
		}

		return $out;
	}

	public function getGrouped(string $statement, ...$args): array
	{

		$res = $this->preparedQuery($statement, $args);
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC))
		{
			$out[current($row)] = (object) $row;
		}

		return $out;
	}

	/**
	 * Executes multiple queries in a transaction
	 */
	public function execMultiple(string $statement)
	{
		$this->begin();

		try {
			$statement = $this->applyTablePrefix($statement);
			$this->db->exec($statement);
		}
		catch (\Exception $e)
		{
			$this->rollback();
			throw $e;
		}

		return $this->commit();
	}

	public function exec(string $statement)
	{
		$this->connect();
		$query = $this->applyTablePrefix($statement);
		return $this->db->exec($statement);
	}

	/**
	 * Runs a query and returns the first row from the result
	 * @param  string $query
	 * @return object|bool
	 *
	 * Accepts one or more arguments for the prepared query
	 */
	public function first(string $query, ...$args)
	{
		$res = $this->preparedQuery($query, $args);

		$row = $res->fetchArray(\SQLITE3_ASSOC);
		$res->finalize();

		return is_array($row) ? (object) $row : false;
	}

	/**
	 * Runs a query and returns the first column of the first row of the result
	 * @param  string $query
	 * @return object
	 *
	 * Accepts one or more arguments for the prepared query
	 */
	public function firstColumn(string $query, ...$args)
	{
		$res = $this->preparedQuery($query, $args);

		$row = $res->fetchArray(\SQLITE3_NUM);

		return (is_array($row) && count($row) > 0) ? $row[0] : false;
	}

	public function countRows(\SQLite3Result $result): int
	{
		$i = 0;

		while ($result->fetchArray(\SQLITE3_NUM))
		{
			$i++;
		}

		$result->reset();

		return $i;
	}

	public function lastInsertId($name = null): string
	{
		return $this->db->lastInsertRowId();
	}

	public function lastInsertRowId(): string
	{
		return $this->db->lastInsertRowId();
	}

	public function prepare(string $statement, array $driver_options = [])
	{
		$query = $this->applyTablePrefix($statement);
		return $this->db->prepare($statement);
	}

	public function openBlob(string $table, string $column, int $rowid, string $dbname = 'main', int $flags = \SQLITE3_OPEN_READONLY): resource
	{
		if (\PHP_VERSION_ID >= 70200)
		{
			return $this->db->openBlob($table, $column, $rowid, $dbname, $flags);
		}
		else
		{
			if ($flags != \SQLITE3_OPEN_READONLY)
			{
				throw new \Exception('Cannot open blob with read/write. Only available from PHP 7.2.0');
			}

			return $this->db->openBlob($table, $column, $rowid, $dbname);
		}
	}

	static public function getDatabaseDetailsFromString(string $source_string): array
	{
		if (substr($source_string, 0, 16) !== "SQLite format 3\0" || strlen($source_string) < 100) {
			return null;
		}

		$user_version = bin2hex(substr($source_string, 60, 4));
		$application_id = bin2hex(substr($source_string, 68, 4));