-
Notifications
You must be signed in to change notification settings - Fork 86
/
EasyDB.php
1584 lines (1487 loc) · 45.5 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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace ParagonIE\EasyDB;
use ParagonIE\EasyDB\Exception\{
EasyDBException,
InvalidIdentifier,
InvalidTableName,
MustBeOneDimensionalArray,
QueryError
};
use PDO;
use PDOStatement;
use InvalidArgumentException;
use Throwable;
use TypeError;
use function
array_fill,
array_filter,
array_keys,
array_map,
array_merge,
array_push,
array_values,
count,
explode,
gettype,
get_class,
implode,
is_array,
is_bool,
is_int,
is_null,
is_numeric,
is_object,
is_scalar,
is_string,
preg_replace,
sprintf,
str_contains,
var_export;
/**
* Class EasyDB
*
* @package ParagonIE\EasyDB
*/
class EasyDB
{
const DEFAULT_FETCH_STYLE = 0x31420000;
protected string $dbEngine = '';
protected PDO $pdo;
protected array $options = [];
protected bool $allowSeparators = false;
/**
* Dependency-Injectable constructor
*
* @param PDO $pdo
* @param string $dbEngine
* @param array $options Extra options
*/
public function __construct(PDO $pdo, string $dbEngine = '', array $options = [])
{
$this->pdo = $pdo;
$this->pdo->setAttribute(
PDO::ATTR_EMULATE_PREPARES,
false
);
$this->pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
if (empty($dbEngine)) {
$dbEngine = (string) $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
}
$this->dbEngine = $dbEngine;
$this->options = $options;
}
/**
* 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 scalar|null|object ...$params Parameters
* @return array|false
*
* @psalm-taint-sink sql $statement
*/
public function col(string $statement, int $offset = 0, ...$params): array|bool
{
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 array|false
*
* @psalm-taint-sink sql $statement
*/
public function column(string $statement, array $params = [], int $offset = 0): array|bool
{
$stmt = $this->prepare($statement);
if (!$this->is1DArray($params)) {
throw new MustBeOneDimensionalArray(
'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
* @param scalar|null|object ...$params Parameters
* @return scalar|null
*
* @psalm-taint-sink sql $statement
*/
public function cell(
string $statement,
float|object|bool|int|string|null ...$params
): float|bool|int|string|null {
return $this->single($statement, $params);
}
/**
* Alternative to run() that returns the keys as the first row, then
* the values in all subsequent rows.
*
* @param string $statement SQL query without user data
* @param scalar|null|object ...$params Parameters
* @return array[] - If successful, a 2D array
*
* @throws TypeError
*
* @psalm-taint-sink sql $statement
*/
public function csv(string $statement, float|bool|int|string|null|object ...$params): array
{
/** @var array<int, array<string, scalar>> $results */
$results = $this->safeQuery(
$statement,
$params,
self::DEFAULT_FETCH_STYLE,
false,
true
);
if (empty($results)) {
/* Array containing an array of empty keys and no subsequent rows */
return [[]];
}
$mapping = [];
array_push($mapping, array_keys($results[0]));
foreach ($results as $row) {
array_push($mapping, array_values($row));
}
return $mapping;
}
/**
* Delete rows in a database table.
*
* @param string $table Table name
* @param EasyStatement|array $conditions Defines the WHERE clause
* @return int
*
* @throws TypeError
*/
public function delete(string $table, EasyStatement|array $conditions): int
{
if ($conditions instanceof EasyStatement) {
return $this->deleteWhereStatement($table, $conditions);
}
return $this->deleteWhereArray($table, $conditions);
}
/**
* Delete rows in a database table.
*
* @param string $table Table name
* @param array $conditions Defines the WHERE clause
* @return int
*
* @throws InvalidTableName
* @throws MustBeOneDimensionalArray
* @throws TypeError
*/
protected function deleteWhereArray(string $table, array $conditions): int
{
if (empty($table)) {
throw new InvalidTableName(
'Table name must be a non-empty string.'
);
}
if (empty($conditions)) {
// Don't allow foot-bullets
return 0;
}
if (!$this->is1DArray($conditions)) {
throw new MustBeOneDimensionalArray(
'Only one-dimensional arrays are allowed.'
);
}
/** @psalm-taint-escape sql */
$queryString = 'DELETE FROM ' . $this->escapeIdentifier($table) . ' WHERE ';
// Simple array for joining the strings together
$params = [];
$placeholders = [];
/**
* @var string $i
* @var string|int|bool|float|null $v
*/
foreach ($conditions as $i => $v) {
/** @psalm-taint-escape sql */
$i = $this->escapeIdentifier($i);
if ($v === null) {
$placeholders [] = " {$i} IS NULL ";
} elseif (is_bool($v)) {
$placeholders []= $this->makeBooleanArgument($i, $v);
} else {
$placeholders []= " {$i} = ? ";
$params[] = $v;
}
}
$queryString .= implode(' AND ', $placeholders);
return (int) $this->safeQuery(
$queryString,
$params,
PDO::FETCH_BOTH,
true
);
}
/**
* Delete rows in a database table.
*
* @param string $table Table name
* @param EasyStatement $conditions Defines the WHERE clause
* @return int
*
* @throws InvalidTableName
*/
protected function deleteWhereStatement(string $table, EasyStatement $conditions): int
{
if (empty($table)) {
throw new InvalidTableName(
'Table name must be a non-empty string.'
);
}
if ($conditions->count() < 1) {
// Don't allow foot-bullets
return 0;
}
/** @psalm-taint-escape sql */
$queryString = 'DELETE FROM ' . $this->escapeIdentifier($table) . ' WHERE ' . $conditions;
$params = [];
/**
* @var ?scalar $v
*/
foreach ($conditions->values() as $v) {
$params[] = $v;
}
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 bool $quote Certain SQLs escape column names (i.e. mysql with `backticks`)
* @return string
*
* @throws InvalidIdentifier
*/
public function escapeIdentifier(string $string, bool $quote = true): string
{
if (empty($string)) {
throw new InvalidIdentifier(
'Invalid identifier: Must be a non-empty string.'
);
}
switch ($this->dbEngine) {
case 'sqlite':
$patternWithSep = '/[^.0-9a-zA-Z_\/]/';
$patternWithoutSep = '/[^0-9a-zA-Z_\/]/';
break;
default:
$patternWithSep = '/[^.0-9a-zA-Z_]/';
$patternWithoutSep = '/[^0-9a-zA-Z_]/';
}
// This behavior depends on whether or not separators are allowed.
if ($this->allowSeparators) {
$str = preg_replace($patternWithSep, '', $string);
if (str_contains($str, '.')) {
$pieces = explode('.', $str);
foreach ($pieces as $i => $p) {
/** @psalm-taint-escape sql */
$pieces[$i] = $this->escapeIdentifier($p, $quote);
}
return implode('.', $pieces);
}
} else {
$str = preg_replace($patternWithoutSep, '', $string);
if ($str !== trim($string)) {
if ($str === str_replace('.', '', $string)) {
throw new InvalidIdentifier(
'Separators (.) are not permitted.'
);
}
throw new InvalidIdentifier(
'Invalid identifier: Invalid characters supplied.'
);
}
}
// MySQL allows weirdly wrong column names:
if ($this->dbEngine !== 'mysql') {
// The first character cannot be [0-9]:
if (preg_match('/^[0-9]/', $str)) {
throw new InvalidIdentifier(
'Invalid identifier: Must begin with a letter or underscore.'
);
}
}
if ($quote) {
return match ($this->dbEngine) {
'mssql' => '[' . $str . ']',
'mysql' => '`' . $str . '`',
default => '"' . $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
* @throws MustBeOneDimensionalArray
*/
public function escapeValueSet(array $values, string $type = 'string'): string
{
if (empty($values)) {
// Default value: a sub-query that will return an empty set
return '(SELECT 1 WHERE FALSE)';
}
// No arrays of arrays, please
if (!$this->is1DArray($values)) {
throw new MustBeOneDimensionalArray(
'Only one-dimensional arrays are allowed.'
);
}
// Build our array
$join = [];
/**
* @var string|int $k
* @var string|int|bool|float|null $v
*/
foreach ($values as $k => $v) {
switch ($type) {
case 'int':
if (!is_int($v)) {
throw new InvalidArgumentException(
'Expected a integer at index ' .
(string) $k .
' of argument 1 passed to ' .
static::class .
'::' .
__METHOD__ .
'(), received ' .
$this->getValueType($v)
);
}
$join[] = $v + 0;
break;
case 'float':
case 'decimal':
case 'number':
case 'numeric':
if (!is_numeric($v)) {
throw new InvalidArgumentException(
'Expected a number at index ' .
(string) $k .
' of argument 1 passed to ' .
static::class .
'::' .
__METHOD__ .
'(), received ' .
$this->getValueType($v)
);
}
$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 ' .
(string) $k .
' of argument 1 passed to ' .
static::class .
'::' .
__METHOD__ .
'(), received ' .
$this->getValueType($v)
);
}
$join[] = $this->pdo->quote($v, PDO::PARAM_STR);
break;
default:
break 2;
}
}
if (empty($join)) {
return '(SELECT 1 WHERE FALSE)';
}
return '(' . implode(', ', $join) . ')';
}
/**
* Escape a value that will be used as a LIKE condition.
*
* Input: ("string_not%escaped")
* Output: "string\_not\%escaped"
*
* WARNING: This function always escapes wildcards using backslash!
*
* @param string $value
* @return string
*/
public function escapeLikeValue(string $value): string
{
// Backslash is used to escape wildcards.
$value = str_replace('\\', '\\\\', $value);
// Standard wildcards are underscore and percent sign.
$value = str_replace('%', '\\%', $value);
$value = str_replace('_', '\\_', $value);
if ($this->dbEngine === 'mssql') {
// MSSQL also includes character ranges.
$value = str_replace('[', '\\[', $value);
$value = str_replace(']', '\\]', $value);
}
return $value;
}
/**
* Use with SELECT COUNT queries to determine if a record exists.
*
* @param string $statement
* @param mixed ...$params
* @return bool
*
* @psalm-taint-sink sql $statement
*/
public function exists(string $statement, ...$params): bool
{
$result = $this->single($statement, $params);
return !empty($result);
}
/**
* @param string $statement
* @param scalar|null|object ...$params
* @return array|false
*
* @psalm-taint-sink sql $statement
*/
public function first(string $statement, ...$params): array|bool
{
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 $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 MustBeOneDimensionalArray
*
* @psalm-param array<string, scalar|EasyPlaceholder|null> $map
*/
public function insert(string $table, array $map): int
{
if (!empty($map)) {
if (!$this->is1DArray($map)) {
throw new MustBeOneDimensionalArray(
'Only one-dimensional arrays are allowed.'
);
}
}
list($queryString, $values) = $this->buildInsertQueryBoolSafe(
$table,
$map
);
/** @var string $queryString */
/** @var array $values */
return (int) $this->safeQuery(
$queryString,
$values,
PDO::FETCH_BOTH,
true
);
}
/**
* Insert a row into the table, ignoring on key collisions
*
* @param string $table - table name
* @param array $map - associative array of which values should be assigned to each field
* @return int
*
* @throws MustBeOneDimensionalArray
*
* @psalm-param array<string, scalar|EasyPlaceholder|null> $map
*/
public function insertIgnore(string $table, array $map): int
{
if (!empty($map)) {
if (!$this->is1DArray($map)) {
throw new MustBeOneDimensionalArray(
'Only one-dimensional arrays are allowed.'
);
}
}
list($queryString, $values) = $this->buildInsertQueryBoolSafe(
$table,
$map,
false
);
return (int) $this->safeQuery(
$queryString,
$values,
PDO::FETCH_BOTH,
true
);
}
/**
* Insert a row into the table, ignoring on key collisions
*
* @param string $table - table name
* @param array $map - associative array of which values should be assigned to each field
* @param array $on_duplicate_key_update
* @return int
*
* @throws MustBeOneDimensionalArray
*
* @psalm-param array<string, scalar|EasyPlaceholder|null> $map
* @psalm-param array<int, string> $on_duplicate_key_update
*/
public function insertOnDuplicateKeyUpdate(
string $table,
array $map,
array $on_duplicate_key_update
): int {
if (!empty($map)) {
if (!$this->is1DArray($map)) {
throw new MustBeOneDimensionalArray(
'Only one-dimensional arrays are allowed.'
);
}
}
list($queryString, $values) = $this->buildInsertQueryBoolSafe(
$table,
$map,
$on_duplicate_key_update
);
return (int) $this->safeQuery(
(string) $queryString,
$values,
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 ?scalar
*
* @throws InvalidArgumentException
*
* @psalm-param array<string, scalar|EasyPlaceholder|null> $map
*/
public function insertGet(
string $table,
array $map,
string $field
): string|int|float|bool|null {
if (empty($map)) {
throw new InvalidArgumentException('An empty array is not allowed for insertGet()');
}
if ($this->insert($table, $map) < 1) {
throw new QueryError('Insert failed');
}
$post = [];
$params = [];
/**
* @var string $i
* @var string|bool|null|int|float $v
*/
foreach ($map as $i => $v) {
// Escape the identifier to prevent stupidity
/** @psalm-taint-escape sql */
$i = $this->escapeIdentifier($i);
if ($v === null) {
$post []= " {$i} IS NULL ";
} elseif (is_bool($v)) {
$post []= $this->makeBooleanArgument($i, $v);
} else {
// We use prepared statements for handling the users' data
$post []= " {$i} = ? ";
$params[] = $v;
}
}
$conditions = implode(' AND ', $post);
// We want the latest value:
$limiter = match ($this->dbEngine) {
'mysql' => ' ORDER BY ' .
$this->escapeIdentifier($field) .
' DESC LIMIT 0, 1 ',
'pgsql' => ' ORDER BY ' .
$this->escapeIdentifier($field) .
' DESC OFFSET 0 LIMIT 1 ',
default => '',
};
/** @psalm-taint-escape sql */
$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 MustBeOneDimensionalArray
* @throws QueryError
*/
public function insertMany(string $table, array $maps): int
{
if (count($maps) < 1) {
throw new InvalidArgumentException(
'Argument 2 passed to ' .
static::class .
'::' .
__METHOD__ .
'() must contain at least one field set!'
);
}
$mapsKeys = array_keys($maps);
/** @var array-key $firstKey */
$firstKey = array_shift($mapsKeys);
/**
* @var array $first
*/
$first = $maps[$firstKey];
/**
* @var array $map
*/
foreach ($maps as $map) {
if (!$this->is1DArray($map)) {
throw new MustBeOneDimensionalArray(
'Every map in the second argument should have the same number of columns.'
);
}
}
$queryString = $this->buildInsertQuery($table, array_keys($first));
// Now let's run a query with the parameters
$stmt = $this->prepare($queryString);
$count = 0;
/**
* @var array $params
*/
foreach ($maps as $params) {
$stmt->execute(array_values($params));
$count += $stmt->rowCount();
}
return $count;
}
/**
* Wrapper for insert() and lastInsertId()
*
* Do not use this with the pgsql driver. It is extremely unreliable.
*
* @param string $table
* @param array $map
* @param string $sequenceName (optional)
* @return string
*
* @throws EasyDBException
* @throws QueryError
*
* @psalm-param array<string, scalar|EasyPlaceholder|null> $map
*/
public function insertReturnId(string $table, array $map, string $sequenceName = ''): string
{
if ($this->dbEngine === 'pgsql') {
throw new EasyDBException(
'Do not use insertReturnId() with PostgreSQL. Use insertGet() instead, ' .
'with an explicit column name rather than a sequence name.'
);
}
if (!$this->insert($table, $map)) {
throw new QueryError('Could not insert a new row into ' . $table . '.');
}
if ($sequenceName) {
return $this->lastInsertId($sequenceName);
}
return $this->lastInsertId();
}
/**
* Get a query string for an INSERT statement.
*
* @param string $table
* @param array $columns list of columns that will be inserted
* @return string
*
* @throws MustBeOneDimensionalArray
* If $columns is not a one-dimensional array.
*/
public function buildInsertQuery(string $table, array $columns): string
{
if (!empty($columns)) {
if (!$this->is1DArray($columns)) {
throw new MustBeOneDimensionalArray(
'Only one-dimensional arrays are allowed.'
);
}
}
$columns = array_map([$this, 'escapeIdentifier'], $columns);
$placeholders = array_fill(0, count($columns), '?');
return sprintf(
'INSERT INTO %s (%s) VALUES (%s)',
$this->escapeIdentifier($table),
implode(', ', $columns),
implode(', ', $placeholders)
);
}
/**
* Get an query string for an INSERT statement.
*
* @template T as array<string, scalar|null>
*
* @param string $table
* @param array $map
* @param bool|array<int, string>|null $duplicates_mode - null for straight-forward insert,
* false for ignore,
* array for on-duplicate-key-update
* @return array {0: string, 1: array}
*
* @throws MustBeOneDimensionalArray
* If $columns is not a one-dimensional array.
*
* @psalm-param array<string, scalar|EasyPlaceholder|null> $map
* @psalm-param null|false|array<int, string> $duplicates_mode
* @psalm-return array{0:string, 1:array<int, scalar>}
*
*/
public function buildInsertQueryBoolSafe(
string $table,
array $map,
array|bool|null $duplicates_mode = null
): array {
/** @var array<int, string> $columns */
$columns = [];
/** @var array<int, string> $placeholders */
$placeholders = [];
$values = [];
/**
* @var string $key
* @var scalar|EasyPlaceholder|null $value
*/
foreach ($map as $key => $value) {
$columns[] = $key;
if (is_null($value)) {
$placeholders[] = 'NULL';
} elseif (is_bool($value)) {
if ($this->dbEngine === 'sqlite') {
$placeholders[] = $value ? "'1'" : "'0'";
} else {
$placeholders[] = $value ? 'TRUE' : 'FALSE';
}
} elseif ($value instanceof EasyPlaceholder) {
$placeholders[] = $value->mask();
$values = array_merge($values, $value->values());
} else {
$placeholders[] = '?';
$values[] = $value;
}
}
$columns = array_map([$this, 'escapeIdentifier'], $columns);
/**
* @var array<int, string>
*/
$duplicates_updates = [];
if (is_array($duplicates_mode)) {
foreach ($duplicates_mode as $column_name) {
$escaped_column_name = $this->escapeIdentifier($column_name);
$duplicates_updates[] =
$escaped_column_name .
' = VALUES(' .
$escaped_column_name .
')';
}
}
$query = sprintf(
'INSERT%sINTO %s (%s) VALUES (%s)%s',
(false === $duplicates_mode ? ' IGNORE ' : ' '),
$this->escapeIdentifier($table),
implode(', ', $columns),
implode(', ', $placeholders),
(
(count($duplicates_updates) > 0)
? (
' ON DUPLICATE KEY UPDATE ' .
implode(', ', $duplicates_updates)
)
: ''
)
);
/**
* @psalm-var array{0:string, 1:array<int, scalar>}
*/
return array($query, $values);
}
/**
* Variadic shorthand for $this->safeQuery()
*
* @param string $statement SQL query without user data
* @param mixed ...$params Parameters
* @return mixed
*
* @throws TypeError
*
* @psalm-taint-sink sql $statement
*/
public function q(string $statement, ...$params): array
{
$result = $this->safeQuery(
$statement,
$params,
self::DEFAULT_FETCH_STYLE,
false,
true
);
if (!is_array($result)) {
throw new TypeError('Return value must be an array');
}
return $result;
}
/**
* Similar to $this->q() except it only returns a single row
*
* @param string $statement SQL query without user data
* @param string|int|float|bool|null ...$params Parameters
* @return array
*
* @throws TypeError
*
* @psalm-taint-sink sql $statement
*/
public function row(string $statement, ...$params): array
{
/**
* @var array|int $result
*/
$result = $this->safeQuery(
$statement,
$params,
self::DEFAULT_FETCH_STYLE,
false,
true
);
if (is_array($result)) {
$first = array_shift($result);
if (!is_array($first)) {
/* Do not TypeError on empty results */
return [];
}
return $first;
}
return [];
}
/**
* Variadic shorthand for $this->safeQuery()
*
* @param string $statement SQL query without user data
* @param scalar|null ...$params Parameters
* @return array
*
* @psalm-taint-sink sql $statement
*/
public function run(string $statement, ...$params): array
{
$results = $this->safeQuery(
$statement,
$params,