forked from glpi-project/glpi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractDatabase.php
1574 lines (1440 loc) · 42.3 KB
/
AbstractDatabase.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
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2018 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
namespace Glpi\Database;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
use DBmysqlIterator;
use GlpitestSQLError;
use PDO;
use PDOStatement;
use Session;
use Timer;
use Toolbox;
/**
* @property-read string|string[] $dbhost Database host.
* @property-read string $dbuser Database user.
* @property-read string $dbpassword Database password.
* @property-read string $dbdefault Database name.
*
* @since 10.0.0
*/
abstract class AbstractDatabase
{
/**
* Database host.
* Can be a string or an array of string (round robin).
*
* @var string|string[]
*/
protected $dbhost;
/**
* Database user.
*
* @var string
*/
protected $dbuser;
/**
* Database password.
*
* @var string
*/
protected $dbpassword;
/**
* Database name.
*
* @var string
*/
protected $dbdefault;
/**
* Database handler.
*
* @var PDO
*/
protected $dbh;
/**
* Slave management.
*
* @var boolean
*/
protected $slave = false;
/**
* Is connected to the DB ?
*
* @var boolean
*/
protected $connected = false;
/**
* Is cache disabled ?
*
* @var boolean
*/
protected $cache_disabled = false;
/**
* Execution time (can be a boolean flag to enable computation or the computation result).
*
* @var string
*/
protected $execution_time;
/**
* Enable timer
*
* @var boolean
*/
protected $timer_enabled = false;
/**
* Constructor / Connect to the database.
*
* @param array $params Connection parameters
* @param integer $server host number
*
* @return void
*/
public function __construct(array $params = [], $server = null)
{
$requireds = [
'driver',
'host',
'user',
'pass',
'dbname'
];
$missing = [];
foreach ($requireds as $required) {
if (!array_key_exists($required, $params)) {
$missing[] = $required;
}
}
if (count($missing)) {
$msg = sprintf(
__('Missing parameters: %1$s'),
implode(', ', $missing)
);
throw new \RuntimeException($msg);
}
$this->driver = $params['driver'];
$this->dbhost = $params['host'];
$this->dbuser = $params['user'];
$this->dbpassword = $params['pass'];
$this->dbdefault = $params['dbname'];
$this->connect($server);
}
/**
* PDO driver to use.
*
* @return string
*
* @since 10.0.0
*/
abstract public function getDriver(): string;
/**
* Executes a PDO prepared query
*
* @param string $query The query string to execute
* @param array $params Query parameters; if any
*
* @return PDOStatement
*
* @since 10.0.0
*/
public function execute(string $query, array $params = []): PDOStatement
{
$stmt = $this->dbh->prepare($query, $this->getPrepareParameters());
foreach ($params as &$value) {
if ('null' == strtolower($value)) {
$value = null;
}
}
$stmt->execute($params);
return $stmt;
}
/**
* Get prepare parameters
*
* @return array
*/
abstract public function getPrepareParameters() :array;
/**
* Connect using current database settings.
*
* @param integer $server host number
*
* @return void
*/
abstract public function connect($server = null);
/**
* Execute a RAW query.
* Direct usage is discouraged, use specific method instead when possible.
*
* @param string $query Query to execute
* @param array $params Query parameters; if any
*
* @global array $CFG_GLPI
* @global array $DEBUG_SQL
* @global integer $SQL_TOTAL_REQUEST
*
* @return PDOStatement|boolean Query result handler
*
* @throws GlpitestSQLError
*
* @since 10.0.0
*/
public function rawQuery(string $query, array $params = [])
{
global $CFG_GLPI, $DEBUG_SQL, $SQL_TOTAL_REQUEST;
$is_debug = isset($_SESSION['glpi_use_mode']) && ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE);
if ($is_debug && $CFG_GLPI["debug_sql"]) {
$SQL_TOTAL_REQUEST++;
$DEBUG_SQL["queries"][$SQL_TOTAL_REQUEST] = $query;
}
if ($is_debug && $CFG_GLPI["debug_sql"] || $this->timer_enabled === true) {
$TIMER = new Timer();
$TIMER->start();
}
try {
$res = $this->execute($query, $params);
if ($is_debug && $CFG_GLPI["debug_sql"]) {
$DEBUG_SQL["times"][$SQL_TOTAL_REQUEST] = $TIMER->getTime();
}
if ($this->timer_enabled === true) {
$this->execution_time = $TIMER->getTime(0, true);
}
return $res;
} catch (\Exception $e) {
// no translation for error logs
$error = " *** SQL query error:\n SQL: ".$query."\n Error: ".
$e->getMessage()."\n";
$error .= print_r($params, true) . "\n";
$error .= $e->getTraceAsString();
Toolbox::logSqlError($error);
if (($is_debug || isAPI()) && $CFG_GLPI["debug_sql"]) {
$DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $e->getMessage();
}
}
return false;
}
/**
* Execute a SQL query and die (optionnaly with a message) if it fails.
*
* @param string $query Query to execute
* @param string|null $message Explanation of query
* @param array $params Query parameters; if any
*
* @return PDOStatement
*
* @since 10.0.0
*/
public function rawQueryOrDie(string $query, $message = null, array $params = []): PDOStatement
{
$res = $this->rawQuery($query, $params);
if (!$res) {
//TRANS: %1$s is the description, %2$s is the query, %3$s is the error message
$message = sprintf(
__('%1$s - Error during the database query: %2$s - Error is %3$s'),
$message,
$query,
$this->error()
);
if (isCommandLine()) {
throw new \RuntimeException($message);
} else {
echo $message . "\n";
die(1);
}
}
return $res;
}
/**
* Prepare a SQL query.
*
* @param string $query Query to prepare
*
* @return PDOStatement|boolean statement object or FALSE if an error occurred.
*
* @throws GlpitestSQLError
*/
public function prepare(string $query)
{
global $CFG_GLPI, $DEBUG_SQL, $SQL_TOTAL_REQUEST;
try {
$res = $this->dbh->prepare($query);
return $res;
} catch (\Exception $e) {
// no translation for error logs
$error = " *** SQL prepare error:\n SQL: ".$query."\n Error: ".
$e->getMessage()."\n";
$error .= $e->getTraceAsString();
Toolbox::logInFile("sql-errors", $error);
if (class_exists('GlpitestSQLError')) { // For unit test
throw new GlpitestSQLError($error, 0, $e);
}
if (isset($_SESSION['glpi_use_mode'])
&& $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE
&& $CFG_GLPI["debug_sql"]) {
$SQL_TOTAL_REQUEST++;
$DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $e->getMessage();
}
}
return false;
}
/**
* Give result from a sql result.
*
* @param PDOStatement $result result handler
* @param integer $i Row offset to give
* @param integer|string $field Field to give
*
* @return mixed Value of the Row $i and the Field $field of the $result
*
* @deprecated 10.0.0
*/
public function result(PDOStatement $result, int $i, $field)
{
$seek_mode = (is_int($field) ? PDO::FETCH_NUM : PDO::FETCH_ASSOC);
$rows = $result->fetchAll($seek_mode);
if (false !== $rows && isset($rows[$i]) && isset($rows[$i][$field])) {
return $rows[$i][$field];
}
return null;
}
/**
* Number of rows.
*
* @param PDOStatement $result result handler
*
* @return integer number of rows
*/
public function numrows(PDOStatement $result): int
{
return $result->rowCount();
}
/**
* Fetch array of the next row of a Mysql query.
*
* @param PDOStatement $result result handler
*
* @return string[]|null array results
*
* @since 10.0.0
*/
public function fetchArray(PDOStatement $result)
{
$result->setFetchMode(PDO::FETCH_NUM);
return $result->fetch();
}
/**
* Fetch row of the next row of a query.
*
* @param PDOStatement $result result handler
*
* @return mixed|null result row
*
* @since 10.0.0
*/
public function fetchRow(PDOStatement $result)
{
return $result->fetch();
}
/**
* Fetch assoc of the next row of a query.
*
* @param PDOStatement $result result handler
*
* @return string[]|null result associative array
*
* @since 10.0.0
*/
public function fetchAssoc(PDOStatement $result)
{
$result->setFetchMode(PDO::FETCH_ASSOC);
return $result->fetch();
}
/**
* Fetch object of the next row of an SQL query.
*
* @param PDOStatement $result result handler
*
* @return object|null
*
* @since 10.0.0
*/
public function fetchObject(PDOStatement $result)
{
$result->setFetchMode(PDO::FETCH_OBJ);
return $result->fetch();
}
/**
* Give ID of the last inserted item by database
*
* @param string $table Table name (required for some db engines)
*
* @return mixed
*
* @since 10.0.0
*/
abstract public function insertId(string $table);
/**
* List tables in database
*
* @param string $table Table name condition (glpi_% as default to retrieve only glpi tables)
* @param array $where Where clause to append
*
* @return DBmysqlIterator
*/
public function listTables(string $table = 'glpi_%', array $where = []): DBmysqlIterator
{
$iterator = $this->request([
'SELECT' => 'table_name AS TABLE_NAME',
'FROM' => 'information_schema.tables',
'WHERE' => [
'table_schema' => $this->dbdefault,
'table_type' => 'BASE TABLE',
'table_name' => ['LIKE', $table]
] + $where
]);
return $iterator;
}
/**
* List fields of a table
*
* @param string $table Table name condition
* @param boolean $usecache If use field list cache (default true)
*
* @return mixed list of fields
*/
public function listFields(string $table, bool $usecache = true)
{
static $cache = [];
if (!$this->cache_disabled && $usecache && isset($cache[$table])) {
return $cache[$table];
}
$iterator = $this->request([
'SELECT' => 'column_name AS COLUMN_NAME',
'FROM' => 'information_schema.columns',
'WHERE' => [
'table_schema' => $this->dbdefault,
'table_name' => $table
]
]);
if (count($iterator)) {
$cache[$table] = [];
while ($data = $iterator->next()) {
$cache[$table][$data["COLUMN_NAME"]] = $data;
}
return $cache[$table];
}
return [];
}
/**
* List indexes of a table
*
* @param string $table Table name condition
* @param boolean $usecache If use field list cache (default true)
*
* @return mixed list of indexed columns
*
* @since 10.0.0
*/
public function listIndexes(string $table, bool $usecache = true)
{
static $icache = [];
if (!$this->cache_disabled && $usecache && isset($icache[$table])) {
return $icache[$table];
}
$iterator = $this->request([
'SELECT' => ['index_name AS INDEX_NAME', 'column_name AS COLUMN_NAME'],
'FROM' => 'information_schema.statistics',
'WHERE' => [
'table_schema' => $this->dbdefault,
'table_name' => $table
]
]);
if (count($iterator)) {
$icache[$table] = [];
while ($data = $iterator->next()) {
$icache[$table][$data["INDEX_NAME"]][] = $data['COLUMN_NAME'];
}
return $icache[$table];
}
return [];
}
/**
* Free result memory
*
* @param PDOStatement $result PDO statement
*
* @return boolean TRUE on success or FALSE on failure.
*
* @since 10.0.0
*/
public function freeResult(PDOStatement $result): bool
{
return $result->closeCursor();
}
/**
* Returns the numerical value of the error message from previous operation
*
* @return int|null error number from the last function, or 0 (zero) if no error occurred.
*/
public function errno()
{
return $this->dbh->errorCode();
}
/**
* Returns the text of the error message from previous operation
*
* @return string error text from the last function, or '' (empty string) if no error occurred.
*/
public function error(): string
{
$error = $this->dbh->errorInfo();
if (isset($error[2])) {
return $error[2];
} else {
return '';
}
}
/**
* Close SQL connection
*
* @return boolean TRUE on success or FALSE on failure.
*/
public function close(): bool
{
if ($this->dbh) {
$this->dbh = null;
return true;
}
return false;
}
/**
* is a slave database ?
*
* @return boolean
*/
public function isSlave(): bool
{
return $this->slave;
}
/**
* Execute all the request in a file
*
* @param string $path with file full path
*
* @return boolean true if all query are successfull
*/
public function runFile(string $path): bool
{
$DBf_handle = fopen($path, "rt");
if (!$DBf_handle) {
return false;
}
$formattedQuery = "";
$lastresult = false;
while (!feof($DBf_handle)) {
// specify read length to be able to read long lines
$buffer = fgets($DBf_handle, 102400);
// do not strip comments due to problems when # in begin of a data line
$formattedQuery .= $buffer;
if ((substr(rtrim($formattedQuery), -1) == ";")
&& (substr(rtrim($formattedQuery), -4) != ">")
&& (substr(rtrim($formattedQuery), -4) != "160;")) {
$formattedQuerytorun = $formattedQuery;
// Do not use the $DB->query
if ($this->rawQuery($formattedQuerytorun)) { //if no success continue to concatenate
$formattedQuery = "";
$lastresult = true;
if (!isCommandLine()) {
// Flush will prevent proxy to timeout as it will receive data.
// Flush requires a content to be sent, so we sent sp&aces as multiple spaces
// will be shown as a single one on browser.
echo ' ';
flush();
}
} else {
$lastresult = false;
}
}
}
return $lastresult;
}
/**
* Instanciate a Simple DBIterator
*
* Examples =
* $DB->request("glpi_states")
* $DB->request("glpi_states", ['ID' => 1])
*
* Examples =
* ["id" => NULL]
* ["OR" => ["id" => 1, "NOT" => ["state" => 3]]]
* ["AND" => ["id" => 1, ["NOT" => ["state" => [3, 4, 5], "toto" => 2]]]]
*
* FIELDS name or array of field names
* ORDER name or array of field names
* LIMIT max of row to retrieve
* START first row to retrieve
*
* @param string|string[] $table Table name or array of names
* @param string|string[] $crit String or array of fields/values, ex ["id" => 1]), if empty => all rows
* (default '')
* @param boolean $debug To log the request (default false)
*
* @return DBmysqlIterator
*/
public function request($table, $crit = "", $debug = false): DBmysqlIterator
{
$iterator = new DBmysqlIterator($this);
$iterator->execute($table, $crit, $debug);
return $iterator;
}
/**
* Instanciate a Simple DBIterator on RAW SQL (discouraged!)
*
* Examples =
* $DB->requestRaw("select * from glpi_states")
*
* @param string $sql SQL RAW query to execute
*
* @return DBmysqlIterator
*
* @since 9.4
*/
public function requestRaw(string $sql): DBmysqlIterator
{
$iterator = new DBmysqlIterator($this);
$iterator->executeRaw($sql);
return $iterator;
}
/**
* Get information about DB connection for showSystemInformations
*
* @since 0.84
*
* @return string[] Array of label / value
*/
abstract public function getInfo(): array;
/**
* Get a global DB lock
*
* @since 0.84
*
* @param string $name lock's name
*
* @return boolean
*/
abstract public function getLock(string $name): bool;
/**
* Release a global DB lock
*
* @since 0.84
*
* @param string $name lock's name
*
* @return boolean
*/
abstract public function releaseLock(string $name): bool;
/**
* Check if a table exists
*
* @since 9.2
* @since 10.0 Added $usecache parameter.
*
* @param string $tablename Table name
* @param boolean $usecache If use table list cache
*
* @return boolean
*/
public function tableExists(string $tablename, $usecache = true): bool
{
static $table_cache = [];
if (!$this->cache_disabled && $usecache && in_array($tablename, $table_cache)) {
return true;
}
// Retrieve all tables if cache is empty but enabled, in order to fill cache
// with all known tables
$retrieve_all = !$this->cache_disabled && empty($table_cache);
$result = $this->listTables($retrieve_all ? 'glpi_%' : $tablename);
$found_tables = [];
while ($data = $result->next()) {
$found_tables[] = $data['TABLE_NAME'];
}
if (!$this->cache_disabled) {
$table_cache = array_unique(array_merge($table_cache, $found_tables));
}
if (in_array($tablename, $found_tables)) {
return true;
}
return false;
}
/**
* Check if a field exists
*
* @since 9.2
*
* @param string $table Table name for the field we're looking for
* @param string $field Field name
* @param boolean $usecache Use cache; @see Database::listFields(), defaults to true
*
* @return boolean
*/
public function fieldExists(string $table, string $field, bool $usecache = true): bool
{
if ($fields = $this->listFields($table, $usecache)) {
if (isset($fields[$field])) {
return true;
}
return false;
}
return false;
}
/**
* Check if an index exists
*
* @since 10.0
*
* @param string $table Table name for the field we're looking for
* @param string|array $field Field(s) name(s)
* @param string $name Index name
* @param boolean $usecache Use cache; @see Database::listIndexes(), defaults to true
*
* @return boolean
*
* @since 10.0.0
*/
public function indexExists(string $table, $field, $name = null, bool $usecache = true): bool
{
if (!$this->tableExists($table)) {
trigger_error("Table $table does not exists", E_USER_WARNING);
return false;
}
if (!is_array($field)) {
$field = [$field];
}
if ($indexes = $this->listIndexes($table, $usecache)) {
foreach ($indexes as $key => $current) {
if (null !== $name && $key == $name) {
//an index with the name already exists
return true;
}
sort($current);
sort($field);
if (array_values($current) == $field) {
return true;
}
}
return false;
}
return false;
}
/**
* Disable table cache globally; usefull for migrations
*
* @return void
*/
public function disableTableCaching()
{
$this->cache_disabled = true;
}
/**
* Quote a value for a specified type
*
* @param mixed $value Value to quote
* @param integer $type Value type, defaults to PDO::PARAM_STR
*
* @return mixed
*
* @since 10.0.0
*/
public function quote($value, int $type = \PDO::PARAM_STR)
{
return $this->dbh->quote($value, $type);
}
/**
* Get character used to quote names
*
* @return string
*
* @since 10.0.0
*/
abstract public static function getQuoteNameChar(): string;
/**
* Quote field name
*
* @since 9.3
*
* @param \QueryExpression|string $name of field to quote (or table.field)
*
* @return string
*/
public function quoteName($name): string
{
//handle verbatim names
if ($name instanceof \QueryExpression) {
return $name->getValue();
}
//handle aliases
$names = preg_split('/ AS /i', $name);
if (count($names) > 2) {
throw new \RuntimeException(
'Invalid field name ' . $name
);
}
if (count($names) == 2) {
$name = $this->quoteName($names[0]);
$name .= ' AS ' . $this->quoteName($names[1]);
return $name;
} else {
if (strpos($name, '.')) {
$n = explode('.', $name, 2);
$table = $this->quoteName($n[0]);
$field = ($n[1] === '*') ? $n[1] : $this->quoteName($n[1]);
return "$table.$field";
}
$quote = static::getQuoteNameChar();
$qname = $quote . str_replace($quote, $quote.$quote, $name) . $quote; // Escape backquotes
return ($name[0] == $quote ? $name : ($name === '*') ? $name : $qname);
}
}
/**
* Quote value for insert/update
*
* @param mixed $value Value
*
* @return mixed
*
* @since 10.0.0 Method is more static
*/
public function quoteValue($value)
{
if ($value instanceof \QueryParam || $value instanceof \QueryExpression) {
//no quote for query parameters nor expressions
$value = $value->getValue();
} elseif ($value === null || $value === 'NULL' || $value === 'null') {
$value = 'NULL';
} elseif (!$this->isNameQuoted($value)) {
$value = $this->quote($value);
}
return $value;
}
/**
* Builds an insert statement
*
* @since 9.3
*
* @param \QueryExpression|string $table Table name
* @param array $params Query parameters ([field name => field value)
*
* @return string
*/
public function buildInsert($table, array &$params): string
{
$query = "INSERT INTO " . $this->quoteName($table) . " (";
$fields = [];
$keys = [];
foreach ($params as $key => $value) {
$fields[] = $this->quoteName($key);
if ($value instanceof \QueryExpression) {
$keys[] = $value->getValue();
unset($params[$key]);
} else {
$keys[] = ':' . trim($key, '`');
}
}
$query .= implode(', ', $fields);
$query .= ") VALUES (";
$query .= implode(", ", $keys);
$query .= ")";
return $query;
}
/**
* Insert a row in the database
*
* @since 9.3
*
* @param string $table Table name
* @param array $params Query parameters ([field name => field value)
*
* @return PDOStatement|boolean
*/
public function insert(string $table, array $params)
{
$result = $this->rawQuery(
$this->buildInsert($table, $params),
$params
);
return $result;
}
/**
* Insert a row in the database and die
* (optionnaly with a message) if it fails
*
* @since 9.3
*
* @param string $table Table name
* @param array $params Query parameters ([field name => field value)
* @param string|null $message Explanation of query
*
* @return PDOStatement
*/
public function insertOrDie(string $table, array $params, $message = null): PDOStatement
{
$insert = $this->buildInsert($table, $params);
$res = $this->rawQuery($insert, $params);
if (!$res) {