-
Notifications
You must be signed in to change notification settings - Fork 85
/
EasyDB.php
858 lines (810 loc) · 25.1 KB
/
EasyDB.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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
<?php
declare (strict_types=1);
namespace ParagonIE\EasyDB;
use \ParagonIE\EasyDB\Exception as Issues;
/**
* Class EasyDB
* @package ParagonIE\EasyDB
*/
class EasyDB
{
/**
* @var string
*/
protected $dbengine = null;
/**
* @var \PDO
*/
protected $pdo = null;
/**
* Dependency-Injectable constructor
*
* @param \PDO $pdo
* @param string $dbEngine
*/
public function __construct(\PDO $pdo, string $dbEngine = '')
{
$this->pdo = clone $pdo;
$this->pdo->setAttribute(
\PDO::ATTR_EMULATE_PREPARES,
false
);
$this->pdo->setAttribute(
\PDO::ATTR_ERRMODE,
\PDO::ERRMODE_EXCEPTION
);
$this->dbengine = $dbEngine;
}
/**
* Variadic version of $this->column()
*
*
* @param string $statement SQL query without user data
* @param int $offset How many columns from the left are we grabbing
* from each row?
* @param mixed ...$params Parameters
* @return mixed
*/
public function col(string $statement, int $offset = 0, ...$params)
{
return $this->column($statement, $params, $offset);
}
/**
* Fetch a column
*
* @param string $statement SQL query without user data
* @param array $params Parameters
* @param int $offset How many columns from the left are we grabbing
* from each row?
* @return mixed
*/
public function column(string $statement, array $params = [], int $offset = 0)
{
$stmt = $this->pdo->prepare($statement);
if (!$this->is1DArray($params)) {
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
$stmt->execute($params);
return $stmt->fetchAll(
\PDO::FETCH_COLUMN,
$offset
);
}
/**
* Variadic version of $this->single()
*
* @param string $statement SQL query without user data
* @params mixed ...$params Parameters
* @return mixed
*/
public function cell(string $statement, ...$params)
{
return $this->single($statement, $params);
}
/**
* Delete rows in a database table.
*
* @param string $table - table name
* @param array $conditions - WHERE clause
* @return int
* @throws \InvalidArgumentException
*/
public function delete(string $table, array $conditions): int
{
if (empty($table)) {
throw new \InvalidArgumentException(
'Table name must be a non-empty string.'
);
}
if (empty($conditions)) {
// Don't allow foot-bullets
return 0;
}
if (!$this->is1DArray($conditions)){
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
$queryString = 'DELETE FROM ' . $this->escapeIdentifier($table) . ' WHERE ';
// Simple array for joining the strings together
$params = [];
$arr = [];
foreach ($conditions as $i => $v) {
$i = $this->escapeIdentifier($i);
if ($v === null) {
$arr [] = " {$i} IS NULL ";
} elseif ($v === true) {
$arr [] = " {$i} = TRUE ";
} elseif ($v === false) {
$arr [] = " {$i} = FALSE ";
} else {
$arr []= " {$i} = ? ";
$params[] = $v;
}
}
$queryString .= \implode(' AND ', $arr);
return (int) $this->safeQuery(
$queryString,
$params,
\PDO::FETCH_BOTH,
true
);
}
/**
* Make sure only valid characters make it in column/table names
*
* @ref https://stackoverflow.com/questions/10573922/what-does-the-sql-standard-say-about-usage-of-backtick
*
* @param string $string - table or column name
* @param boolean $quote - certain SQLs escape column names (i.e. mysql with `backticks`)
* @return string
*/
public function escapeIdentifier(string $string, $quote = true): string
{
if (empty($string)) {
throw new Issues\InvalidIdentifier(
'Invalid identifier: Must be a non-empty string.'
);
}
$str = \preg_replace('/[^0-9a-zA-Z_]/', '', $string);
// The first character cannot be [0-9]:
if (\preg_match('/^[0-9]/', $str)) {
throw new Issues\InvalidIdentifier(
'Invalid identifier: Must begin with a letter or underscore.'
);
}
if ($quote) {
switch ($this->dbengine) {
case 'mssql':
return '[' . $str . ']';
case 'mysql':
return '`' . $str . '`';
default:
return '"' . $str . '"';
}
}
return $str;
}
/**
* Create a parenthetical statement e.g. for NOT IN queries.
*
* Input: ([1, 2, 3, 5], int)
* Output: "(1,2,3,5)"
*
* @param array $values
* @param string $type
* @return string
* @throws \InvalidArgumentException
*/
public function escapeValueSet(array $values, string $type = 'string'): string
{
if (empty($values)) {
// Default value: a subquery that will return an empty set
return '(SELECT 1 WHERE FALSE)';
}
// No arrays of arrays, please
if (!$this->is1DArray($values)) {
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
// Build our array
$join = [];
foreach ($values as $k => $v) {
switch ($type) {
case 'int':
if (!\is_int($v)) {
throw new \InvalidArgumentException(
'Expected a integer at index ' .
$k .
' of argument 1 passed to ' .
static::class .
'::' .
__METHOD__ .
'(), receieved ' .
(
(
\is_scalar($v) || \is_array($v)
)
? \gettype($v)
: (
\is_object($v)
? ('an instance of ' . \get_class($v))
: \var_export($v, true)
)
)
);
}
$join[] = (int) $v + 0;
break;
case 'float':
case 'decimal':
case 'number':
case 'numeric':
if (!\is_numeric($v)) {
throw new \InvalidArgumentException(
'Expected a number at index ' .
$k .
' of argument 1 passed to ' .
static::class .
'::' .
__METHOD__ .
'(), receieved ' .
(
(
\is_scalar($v) || \is_array($v)
)
? \gettype($v)
: (
\is_object($v)
? ('an instance of ' . \get_class($v))
: \var_export($v, true)
)
)
);
}
$join[] = (float) $v + 0.0;
break;
case 'string':
if (\is_numeric($v)) {
$v = (string) $v;
}
if (!\is_string($v)) {
throw new \InvalidArgumentException(
'Expected a string at index ' .
$k .
' of argument 1 passed to ' .
static::class .
'::' .
__METHOD__ .
'(), receieved ' .
(
(
\is_scalar($v) || \is_array($v)
)
? \gettype($v)
: (
\is_object($v)
? ('an instance of ' . \get_class($v))
: \var_export($v, true)
)
)
);
}
$join[] = $this->pdo->quote($v, \PDO::PARAM_STR);
break;
default:
break 2;
}
}
if (empty($join)) {
return '(SELECT 1 WHERE FALSE)';
}
return '(' . \implode(', ', $join) . ')';
}
/**
* Use with SELECT COUNT queries to determine if a record exists.
*
* @param string $statement
* @param array ...$params
* @return bool
*/
public function exists(string $statement, ...$params): bool
{
$result = $this->single($statement, $params);
return !empty($result);
}
/**
* Get the first column of each row
*
* @param $statement
* @param array ...$params
* @return mixed
*/
public function first(string $statement, ...$params)
{
return $this->column($statement, $params, 0);
}
/**
* Which database driver are we operating on?
*
* @return string
*/
public function getDriver(): string
{
return $this->dbengine;
}
/**
* Return a copy of the PDO object (to prevent it from being modified
* to disable safety/security features).
*
* @return \PDO
*/
public function getPdo(): \PDO
{
return (clone $this->pdo);
}
/**
* Insert a new row to a table in a database.
*
* @param string $table - table name
* @param array $map - associative array of which values should be assigned to each field
* @return int
* @throws \InvalidArgumentException
*/
public function insert(string $table, array $map): int
{
if (!empty($map)) {
if (!$this->is1DArray($map)){
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
}
// Begin query string
$queryString = 'INSERT INTO ' . $this->escapeIdentifier($table) . ' (';
$phold = [];
$_keys = [];
$params = [];
foreach ($map as $k => $v) {
if ($v !== null) {
$_keys[] = $k;
if ($v === true) {
$phold[] = 'TRUE';
} elseif ($v === false) {
$phold[] = 'FALSE';
} else {
// When all else fails, use prepared statements:
$phold[] = '?';
$params[] = $v;
}
}
}
// Let's make sure our keys are escaped.
$keys = [];
foreach ($_keys as $i => $v) {
$keys[] = $this->escapeIdentifier($v);
}
// Now let's append a list of our columns.
$queryString .= \implode(', ', $keys);
// This is the middle piece.
$queryString .= ') VALUES (';
// Now let's concatenate the ? placeholders
$queryString .= \implode(', ', $phold);
// Necessary to close the open ( above
$queryString .= ');';
return (int) $this->safeQuery(
$queryString,
$params,
\PDO::FETCH_BOTH,
true
);
}
/**
* Insert a new record then get a particular field from the new row
*
* @param string $table
* @param array $map
* @param string $field
* @return mixed
* @throws \Exception
*/
public function insertGet(string $table, array $map, string $field)
{
if ($this->insert($table, $map) < 1) {
throw new \Exception('Insert failed');
}
$post = [];
$params = [];
foreach ($map as $i => $v) {
// Escape the identifier to prevent stupidity
$i = $this->escapeIdentifier($i);
if ($v === null) {
$post []= " {$i} IS NULL ";
} elseif ($v === true) {
$post []= " {$i} = TRUE ";
} elseif ($v === false) {
$post []= " {$i} = FALSE ";
} else {
// We use prepared statements for handling the users' data
$post []= " {$i} = ? ";
$params[] = $v;
}
}
$conditions = \implode(' AND ', $post);
// We want the latest value:
switch ($this->dbengine) {
case 'mysql':
$limiter = ' ORDER BY '.
$this->escapeIdentifier($field).
' DESC LIMIT 0, 1 ';
break;
case 'pgsql':
$limiter = ' ORDER BY '.
$this->escapeIdentifier($field).
' DESC OFFSET 0 LIMIT 1 ';
break;
default:
$limiter = '';
}
$query = 'SELECT ' .
$this->escapeIdentifier($field).
' FROM ' .
$this->escapeIdentifier($table).
' WHERE ' .
$conditions .
$limiter;
return $this->single($query, $params);
}
/**
* Insert many new rows to a table in a database. using the same prepared statement
*
* @param string $table - table name
* @param array $maps - array of associative array specifying values should be assigned to each field
* @return int
* @throws \InvalidArgumentException
* @throws Issues\QueryError
*/
public function insertMany(string $table, array $maps): int
{
$first = $maps[0];
foreach ($maps as $map) {
if (!$this->is1DArray($map)) {
throw new \InvalidArgumentException(
'Every map in the second argument should have the same number of columns.'
);
}
}
// Begin query string
$queryString = 'INSERT INTO ' . $this->escapeIdentifier($table) . ' (';
// Let's make sure our keys are escaped.
$keys = \array_keys($first);
foreach ($keys as $i => $v) {
$keys[$i] = $this->escapeIdentifier($v);
}
// Now let's append a list of our columns.
$queryString .= \implode(', ', $keys);
// This is the middle piece.
$queryString .= ') VALUES (';
// Now let's concatenate the ? placeholders
$queryString .= \implode(
', ',
\array_fill(0, \count($first), '?')
);
// Necessary to close the open ( above
$queryString .= ');';
// Now let's run a query with the parameters
$exec = false;
$stmt = $this->pdo->prepare($queryString);
$count = 0;
foreach ($maps as $params) {
$stmt->execute(\array_values($params));
$count += $stmt->rowCount();
}
return $count;
}
/**
* Variadic shorthand for $this->safeQuery()
*
* @param string $statement SQL query without user data
* @param mixed ...$params Parameters
* @return mixed
*/
public function q(string $statement, ...$params)
{
return $this->safeQuery($statement, $params);
}
/**
* Similar to $this->q() except it only returns a single row
*
* @param string $statement SQL query without user data
* @param mixed ...$params Parameters
* @return mixed
*/
public function row(string $statement, ...$params)
{
$result = $this->safeQuery($statement, $params);
if (\is_array($result)) {
return \array_shift($result);
}
return [];
}
/**
* Variadic shorthand for $this->safeQuery()
*
* @param string $statement SQL query without user data
* @params mixed ...$params Parameters
* @return mixed - If successful, a 2D array
*/
public function run(string $statement, ...$params)
{
return $this->safeQuery($statement, $params);
}
/**
* Perform a Parameterized Query
*
* @param string $statement The query string (hopefully untainted
* by user input)
* @param array $params The parameters (used in prepared
* statements)
* @param int $fetchStyle PDO::FETCH_STYLE
* @param bool $returnNumAffected Return the number of rows affected?
* @return array|int
* @throws \InvalidArgumentException
* @throws Issues\QueryError
*/
public function safeQuery(
string $statement,
array $params = [],
int $fetchStyle = \PDO::FETCH_ASSOC,
bool $returnNumAffected = false
) {
if (empty($params)) {
$stmt = $this->pdo->query($statement);
if ($returnNumAffected) {
return $stmt->rowCount();
}
return $stmt->fetchAll($fetchStyle);
}
if (!$this->is1DArray($params)) {
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
$stmt = $this->pdo->prepare($statement);
$stmt->execute($params);
if ($returnNumAffected) {
return $stmt->rowCount();
}
return $stmt->fetchAll($fetchStyle);
}
/**
* Fetch a single result -- useful for SELECT COUNT() queries
*
* @param string $statement
* @param array $params
* @return mixed
* @throws \InvalidArgumentException
* @throws Issues\QueryError
*/
public function single(string $statement, array $params = [])
{
if (!$this->is1DArray($params)) {
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
$stmt = $this->pdo->prepare($statement);
$stmt->execute($params);
return $stmt->fetchColumn(0);
}
/**
* Update a row in a database table.
*
* @param string $table Table name
* @param array $changes Associative array of which values should be
* assigned to each field
* @param array $conditions WHERE clause
* @return int
* @throws \InvalidArgumentException
* @throws Issues\QueryError
*/
public function update(string $table, array $changes, array $conditions): int
{
if (empty($changes) || empty($conditions)) {
return 0;
}
if (!$this->is1DArray($changes) || !$this->is1DArray($conditions)) {
throw new \InvalidArgumentException(
'Only one-dimensional arrays are allowed.'
);
}
$queryString = 'UPDATE ' . $this->escapeIdentifier($table) . ' SET ';
$params = [];
// The first set (pre WHERE)
$pre = [];
foreach ($changes as $i => $v) {
$i = $this->escapeIdentifier($i);
if ($v === null) {
$pre []= " {$i} = NULL";
} elseif ($v === true) {
$pre []= " {$i} = TRUE";
} elseif ($v === false) {
$pre []= " {$i} = FALSE";
} else {
$pre []= " {$i} = ?";
$params[] = $v;
}
}
$queryString .= \implode(', ', $pre);
$queryString .= " WHERE ";
// The last set (post WHERE)
$post = [];
foreach ($conditions as $i => $v) {
$i = $this->escapeIdentifier($i);
if ($v === null) {
$post []= " {$i} IS NULL";
} elseif ($v === true) {
$post []= " {$i} = TRUE";
} elseif ($v === false) {
$post []= " {$i} = FALSE";
} else {
$post []= " {$i} = ? ";
$params[] = $v;
}
}
$queryString .= \implode(' AND ', $post);
return (int) $this->safeQuery(
$queryString,
$params,
\PDO::FETCH_BOTH,
true
);
}
/**
***************************************************************************
***************************************************************************
**** PUNTER METHODS - see PDO class definition ****
***************************************************************************
***************************************************************************
**/
/**
* Initiates a transaction
*
* @return bool
*/
public function beginTransaction(): bool
{
return $this->pdo->beginTransaction();
}
/**
* Commits a transaction
*
* @return bool
*/
public function commit(): bool
{
return $this->pdo->commit();
}
/**
* Fetch the SQLSTATE associated with the last operation on the database
* handle
*
* @return mixed
*/
public function errorCode()
{
return $this->pdo->errorCode();
}
/**
* Fetch extended error information associated with the last operation on
* the database handle
*
* @return array
*/
public function errorInfo(): array
{
return $this->pdo->errorInfo();
}
/**
* Execute an SQL statement and return the number of affected rows
*/
public function exec(...$args): int
{
return $this->pdo->exec(...$args);
}
/**
* Retrieve a database connection attribute
*
* @param mixed ...$args
* @return mixed
*/
public function getAttribute(...$args)
{
return $this->pdo->getAttribute(...$args);
}
/**
* Return an array of available PDO drivers
*
* @return array
*/
public function getAvailableDrivers(): array
{
return $this->pdo->getAvailableDrivers();
}
/**
* Checks if inside a transaction
*
* @return bool
*/
public function inTransaction(): bool
{
return $this->pdo->inTransaction();
}
/**
* Returns the ID of the last inserted row or sequence value
*
* @param mixed ...$args
* @return string
*/
public function lastInsertId(...$args): string
{
return $this->pdo->lastInsertId(...$args);
}
/**
* Prepares a statement for execution and returns a statement object
*
* @param mixed ...$args
* @return \PDOStatement
*/
public function prepare(...$args): \PDOStatement
{
return $this->pdo->prepare(...$args);
}
/**
* Executes an SQL statement, returning a result set as a PDOStatement object
*
* @param mixed ...$args
* @return \PDOStatement
*/
public function query(...$args): \PDOStatement
{
return $this->pdo->query(...$args);
}
/**
* Quotes a string for use in a query
*
* @param mixed ...$args
* @return string
*/
public function quote(...$args): string
{
return $this->pdo->quote(...$args);
}
/**
* Rolls back a transaction
*
* @return bool
*/
public function rollBack(): bool
{
return $this->pdo->rollBack();
}
/**
* Set an attribute
*
* @param int $attr
* @param mixed $value
* @return bool
* @throws \Exception
*/
public function setAttribute(int $attr, $value): bool
{
if ($attr === \PDO::ATTR_EMULATE_PREPARES) {
throw new \Exception(
'EasyDB does not allow the use of emulated prepared statements, which would be a security downgrade.'
);
}
if ($attr === \PDO::ATTR_ERRMODE) {
throw new \Exception(
'EasyDB only allows the safest-by-default error mode (exceptions).'
);
}
return $this->pdo->setAttribute($attr, $value);
}
/**
* Make sure none of this array's elements are arrays
*
* @param array $params
* @return bool
*/
public function is1DArray(array $params): bool
{
return (
\count($params) === \count($params, COUNT_RECURSIVE) &&
\count(\array_filter($params, 'is_array')) < 1
);
}
}