-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPicoDatabaseQueryBuilder.php
More file actions
1125 lines (1039 loc) · 29.4 KB
/
PicoDatabaseQueryBuilder.php
File metadata and controls
1125 lines (1039 loc) · 29.4 KB
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
namespace MagicObject\Database;
use PDO;
/**
* Class PicoDatabaseQueryBuilder
*
* A query builder for constructing SQL statements programmatically. This class
* facilitates the creation of various SQL commands including SELECT, INSERT,
* UPDATE, and DELETE, while managing database-specific nuances.
*
* **Example:**
* ```php
* <?php
* $id = 100;
* $db = new PicoDatabase($credentials);
* $db->connect();
* $query = new PicoDatabaseQueryBuilder($db);
* $query
* ->select("*")
* ->from("client")
* ->where("client_id = ?", $id)
* ;
* $data = $db->fetch($query);
* echo $data['client_id']."\r\n"; // Client ID
* echo $data['name']."\r\n"; // Client name
* ```
*
* @author Kamshory
* @package MagicObject\Database
* @link https://github.com/Planetbiru/MagicObject
*/
class PicoDatabaseQueryBuilder // NOSONAR
{
/**
* Buffer to hold the constructed SQL query.
*
* @var string
*/
private $buffer = "";
/**
* Indicates whether limit and offset have been set.
*
* @var bool
*/
private $limitOffset = false;
/**
* The limit for the number of results.
*
* @var int
*/
private $limit = 0;
/**
* The offset for the results.
*
* @var int
*/
private $offset = 0;
/**
* The type of database being used.
*
* @var string
*/
private $databaseType = "mysql";
/**
* Flag indicating if values have been set.
*
* @var bool
*/
private $hasValues = false;
/**
* Initializes a new instance of the PicoDatabaseQueryBuilder class.
*
* This constructor accepts various types of database connections:
* - If a `PicoDatabase` instance is provided, the database type is retrieved from it.
* - If a `PDO` instance is provided, the driver name is used to determine the database type.
* - If a string is provided, it is assumed to be the database type.
*
* @param PicoDatabase|PDO|string $database The database connection or type.
*/
public function __construct($database)
{
if ($database instanceof PicoDatabase) {
$this->databaseType = $database->getDatabaseType();
} elseif ($database instanceof PDO) {
$driver = $database->getAttribute(PDO::ATTR_DRIVER_NAME);
$this->databaseType = PicoDatabase::getDbType($driver);
} elseif (is_string($database)) {
$this->databaseType = $database;
}
}
/**
* Get the value of the database type.
*
* @return string The database type.
*/
public function getDatabaseType()
{
return $this->databaseType;
}
/**
* Check if the database type is MySQL or MariaDB.
*
* @return bool true if the database type is MySQL or MariaDB, false otherwise.
*/
public function isMySql()
{
return strcasecmp($this->databaseType, PicoDatabaseType::DATABASE_TYPE_MYSQL) == 0 ||
strcasecmp($this->databaseType, PicoDatabaseType::DATABASE_TYPE_MARIADB) == 0;
}
/**
* Check if the database type is PostgreSQL.
*
* @return bool true if the database type is PostgreSQL, false otherwise.
*/
public function isPgSql()
{
return strcasecmp($this->databaseType, PicoDatabaseType::DATABASE_TYPE_PGSQL) == 0;
}
/**
* Check if the database type is SQLite.
*
* @return bool true if the database type is SQLite, false otherwise.
*/
public function isSqlite()
{
return strcasecmp($this->databaseType, PicoDatabaseType::DATABASE_TYPE_SQLITE) == 0;
}
/**
* Check if the database type is SQL Server.
*
* @return bool true if the database type is SQLite, false otherwise.
*/
public function isSqlServer()
{
return strcasecmp($this->databaseType, PicoDatabaseType::DATABASE_TYPE_SQLSERVER) == 0;
}
/**
* Initialize a new SQL query by resetting the buffer, limit, and offset.
*
* @return self Returns the current instance for method chaining.
*/
public function newQuery()
{
$this->buffer = "";
$this->limitOffset = false;
$this->hasValues = false;
return $this;
}
/**
* Create an insert statement.
*
* @return self Returns the current instance for method chaining.
*/
public function insert()
{
$this->buffer = "INSERT \r\n";
return $this;
}
/**
* Specify the table to insert into.
*
* @param string $query The name of the table.
* @return self Returns the current instance for method chaining.
*/
public function into($query)
{
$this->buffer .= "INTO $query\r\n";
return $this;
}
/**
* Specify the fields to insert values into.
*
* @param mixed $query The field names (string or array).
* @return self Returns the current instance for method chaining.
*/
public function fields($query)
{
if (is_array($query)) {
$this->buffer .= "(".implode(", ", $query).") \r\n";
} else {
$this->buffer .= "$query \r\n";
}
return $this;
}
/**
* Specify the values to be inserted.
*
* @param mixed $query The values to insert (string, array, or multiple parameters).
* @return self Returns the current instance for method chaining.
*/
public function values($query)
{
$count = func_num_args();
$isArray = is_array($query) && $count === 1;
$values = "";
if ($isArray) {
$vals = array_map(array($this, 'escapeValue'), $query);
$values = "(".implode(", ", $vals).")";
} else {
if ($count > 1) {
$params = array();
for ($i = 0; $i < $count; $i++) {
$params[] = func_get_arg($i);
}
$values = $this->createMatchedValue($params);
} else {
$values = $query;
}
}
if ($this->hasValues) {
$this->buffer .= ",\r\n$values";
} else {
$this->buffer .= "VALUES $values";
}
$this->hasValues = true;
return $this;
}
/**
* Create a select statement.
*
* @param string $query The fields to select (optional).
* @return self Returns the current instance for method chaining.
*/
public function select($query = "")
{
$this->buffer .= "SELECT $query\r\n";
return $this;
}
/**
* Create an alias for a field or table.
*
* @param string $query The alias to use.
* @return self Returns the current instance for method chaining.
*/
public function alias($query)
{
$this->buffer .= "AS $query\r\n";
return $this;
}
/**
* Create a delete statement.
*
* @return self Returns the current instance for method chaining.
*/
public function delete()
{
$this->buffer .= "DELETE \r\n";
return $this;
}
/**
* Specify the source table for the query.
*
* @param string $query The name of the table.
* @return self Returns the current instance for method chaining.
*/
public function from($query)
{
$this->buffer .= "FROM $query \r\n";
return $this;
}
/**
* Create a join statement.
*
* @param string $query The join details.
* @return self Returns the current instance for method chaining.
*/
public function join($query)
{
$this->buffer .= "JOIN $query \r\n";
return $this;
}
/**
* Create an inner join statement.
*
* @param string $query The join details.
* @return self Returns the current instance for method chaining.
*/
public function innerJoin($query)
{
$this->buffer .= "INNER JOIN $query \r\n";
return $this;
}
/**
* Create an outer join statement.
*
* @param string $query The join details.
* @return self Returns the current instance for method chaining.
*/
public function outerJoin($query)
{
$this->buffer .= "OUTER JOIN $query \r\n";
return $this;
}
/**
* Create a left outer join statement.
*
* @param string $query The join details.
* @return self Returns the current instance for method chaining.
*/
public function leftOuterJoin($query)
{
$this->buffer .= "LEFT OUTER JOIN $query \r\n";
return $this;
}
/**
* Create a left join statement.
*
* @param string $query The join details.
* @return self Returns the current instance for method chaining.
*/
public function leftJoin($query)
{
$this->buffer .= "LEFT JOIN $query \r\n";
return $this;
}
/**
* Create a right join statement.
*
* @param string $query The join details.
* @return self Returns the current instance for method chaining.
*/
public function rightJoin($query)
{
$this->buffer .= "RIGHT JOIN $query \r\n";
return $this;
}
/**
* Create an ON statement for JOIN operations.
*
* @param mixed $query The join condition(s).
* @return self Returns the current instance for method chaining.
*/
public function on($query)
{
$count = func_num_args();
if ($count > 1) {
$params = array();
for ($i = 0; $i < $count; $i++) {
$params[] = func_get_arg($i);
}
$buffer = $this->createMatchedValue($params);
$this->buffer .= "ON $buffer \r\n";
} else {
$this->buffer .= "ON $query \r\n";
}
return $this;
}
/**
* Create an UPDATE statement for a specified table.
*
* @param string $query The name of the table to update.
* @return self Returns the current instance for method chaining.
*/
public function update($query)
{
$this->buffer .= "UPDATE $query \r\n";
return $this;
}
/**
* Specify the fields and values to set in the UPDATE statement.
*
* @param mixed $query The field(s) and value(s) to set.
* @return self Returns the current instance for method chaining.
*/
public function set($query)
{
$count = func_num_args();
if ($count > 1) {
$params = array();
for ($i = 0; $i < $count; $i++) {
$params[] = func_get_arg($i);
}
$buffer = $this->createMatchedValue($params);
$this->buffer .= "SET $buffer \r\n";
} else {
$this->buffer .= "SET $query \r\n";
}
return $this;
}
/**
* Create a WHERE statement for filtering results.
*
* @param string $query The condition(s) for the WHERE clause.
* @return self Returns the current instance for method chaining.
*/
public function where($query)
{
$count = func_num_args();
if ($count > 1) {
$params = array();
for ($i = 0; $i < $count; $i++) {
$params[] = func_get_arg($i);
}
$buffer = $this->createMatchedValue($params);
$this->buffer .= "WHERE $buffer \r\n";
} else {
$this->buffer .= "WHERE $query \r\n";
}
return $this;
}
/**
* Binds SQL parameters by replacing placeholders with actual values.
*
* This function accepts multiple arguments, where the first argument
* is expected to be a SQL string containing `?` placeholders, and
* subsequent arguments are the values to replace them.
*
* @return string The formatted SQL query with values replaced.
*/
public function bindSqlParams()
{
$count = func_num_args();
if ($count > 1) {
$params = array();
for ($i = 0; $i < $count; $i++) {
$params[] = func_get_arg($i);
}
return $this->createMatchedValue($params);
}
return "";
}
/**
* Create a matched value string from the given arguments.
*
* @param array $args The arguments to match.
* @return string The formatted string.
*/
public function createMatchedValue($args)
{
$result = "";
if (count($args) > 1) {
$format = $args[0];
$formats = explode('?', $format);
$len = count($args) - 1;
$values = array();
for ($i = 0; $i < $len; $i++) {
$j = $i + 1;
$values[$i] = $this->escapeValue($args[$j]);
}
for ($i = 0; $i < $len; $i++) {
$result .= $formats[$i];
if ($j <= $len) {
$result .= $values[$i];
}
}
$result .= $formats[$i];
}
return $result;
}
/**
* Create an INSERT query for a specified table.
*
* @param string $table The name of the table.
* @param array $data The data to be inserted.
* @return string The constructed INSERT query.
*/
public function createInsertQuery($table, $data)
{
$fields = array_keys($data);
$values = array_values($data);
$valuesFixed = array_map(array($this, 'escapeValue'), $values);
$fieldList = implode(", ", $fields);
$valueList = implode(", ", $valuesFixed);
return "INSERT INTO $table \r\n($fieldList)\r\nVALUES($valueList)\r\n";
}
/**
* Create an UPDATE query for a specified table.
*
* @param string $table The name of the table.
* @param array $data The data to be updated.
* @param array $primaryKey The primary keys for the update condition.
* @return string The constructed UPDATE query.
*/
public function createUpdateQuery($table, $data, $primaryKey)
{
$set = array();
$condition = array();
foreach ($data as $field => $value) {
$set[] = "$field = " . $this->escapeValue($value);
}
foreach ($primaryKey as $field => $value) {
if ($value === null) {
$condition[] = "$field IS NULL";
} else {
$condition[] = "$field = " . $this->escapeValue($value);
}
}
$sets = implode(", ", $set);
$where = implode(" AND ", $condition);
return "UPDATE $table \r\nSET $sets \r\nWHERE $where\r\n";
}
/**
* Create a HAVING statement for filtering aggregated results.
*
* @param string $query The condition(s) for the HAVING clause.
* @return self Returns the current instance for method chaining.
*/
public function having($query)
{
$count = func_num_args();
if ($count > 1) {
$params = array();
for ($i = 0; $i < $count; $i++) {
$params[] = func_get_arg($i);
}
$buffer = $this->createMatchedValue($params);
$this->buffer .= "HAVING $buffer \r\n";
} elseif (!empty($query)) {
$this->buffer .= "HAVING $query \r\n";
}
return $this;
}
/**
* Create an ORDER BY statement for sorting results.
*
* @param string $query The field(s) to order by.
* @return self Returns the current instance for method chaining.
*/
public function orderBy($query)
{
if (!empty($query)) {
$this->buffer .= "ORDER BY $query \r\n";
}
return $this;
}
/**
* Create a GROUP BY statement for grouping results.
*
* @param string $query The field(s) to group by.
* @return self Returns the current instance for method chaining.
*/
public function groupBy($query)
{
if (!empty($query)) {
$this->buffer .= "GROUP BY $query \r\n";
}
return $this;
}
/**
* Set a limit on the number of results returned.
*
* @param int $limit The maximum number of results.
* @return self Returns the current instance for method chaining.
*/
public function limit($limit)
{
$this->limitOffset = true;
$this->limit = $limit;
return $this;
}
/**
* Set an offset for the results returned.
*
* @param int $offset The offset from the start of the result set.
* @return self Returns the current instance for method chaining.
*/
public function offset($offset)
{
$this->limitOffset = true;
$this->offset = $offset;
return $this;
}
/**
* Create a LOCK TABLES statement for database locking.
*
* @param string $tables Comma-separated table names to lock.
* @return string|null The LOCK TABLES statement or null if not supported.
*/
public function lockTables($tables)
{
if ($this->isMySql() || $this->isPgSql()) {
return "LOCK TABLES $tables";
}
elseif ($this->isSqlServer()) {
return "BEGIN TRANSACTION";
}
return null;
}
/**
* Create an UNLOCK TABLES statement to release table locks.
*
* @return string|null The UNLOCK TABLES statement or null if not supported.
*/
public function unlockTables()
{
if ($this->isMySql() || $this->isPgSql()) {
return "UNLOCK TABLES";
}
elseif ($this->isSqlServer()) {
return "COMMIT TRANSACTION";
}
return null;
}
/**
* Create a START TRANSACTION statement for initiating a transaction.
*
* @return string|null The START TRANSACTION statement or null if not supported.
*/
public function startTransaction()
{
if ($this->isMySql() || $this->isPgSql()) {
return "START TRANSACTION";
}
elseif ($this->isSqlite() || $this->isSqlServer()) {
return "BEGIN TRANSACTION";
}
return null;
}
/**
* Create a COMMIT statement to finalize a transaction.
*
* @return string|null The COMMIT statement or null if not supported.
*/
public function commit()
{
if ($this->isMySql() || $this->isPgSql() || $this->isSqlite()) {
return "COMMIT";
}
elseif ($this->isSqlServer()) {
return "COMMIT TRANSACTION"; // Finalizing transaction in SQL Server
}
return null;
}
/**
* Create a ROLLBACK statement to revert a transaction.
*
* @return string|null The ROLLBACK statement or null if not supported.
*/
public function rollback()
{
if ($this->isMySql() || $this->isPgSql() || $this->isSqlite()) {
return "ROLLBACK";
}
elseif ($this->isSqlServer()) {
return "ROLLBACK TRANSACTION"; // Reverting transaction in SQL Server
}
return null;
}
/**
* Escapes a raw SQL string value so it can be safely embedded inside
* an SQL statement according to the active database dialect.
*
* This method performs **SQL literal escaping only** and does NOT:
* - Add surrounding quotes (`'...'`)
* - Escape or transform newline characters (`\n`, `\r`)
* - Replace or normalize whitespace
*
* Newline characters are preserved as-is and stored correctly
* in the database. This avoids issues where line breaks would be
* converted into literal `\n` sequences.
*
* Behavior per database:
* - MySQL / MariaDB:
* - Escapes single quote `'` as `\'`
* - Escapes backslash `\` as `\\`
*
* - PostgreSQL:
* - Escapes single quote `'` as `''`
* - Escapes backslash `\` as `\\`
* - Intended for standard string literals (NOT E'' unless handled externally)
*
* - SQLite:
* - Escapes single quote `'` as `''`
* - Backslash is treated as a literal character
*
* - SQL Server:
* - Escapes single quote `'` as `''`
* - Backslash is treated as a literal character
*
* @param string $query
* Raw SQL string value to escape.
*
* @return string
* Escaped SQL string safe for inclusion inside a quoted SQL literal.
*/
public function escapeSQL($query) // NOSONAR
{
if (stripos($this->databaseType, PicoDatabaseType::DATABASE_TYPE_MYSQL) !== false
|| stripos($this->databaseType, PicoDatabaseType::DATABASE_TYPE_MARIADB) !== false) {
// MySQL / MariaDB
return str_replace(
["\\", "'"],
["\\\\", "\\'"],
$query
);
}
if (stripos($this->databaseType, PicoDatabaseType::DATABASE_TYPE_PGSQL) !== false) {
// PostgreSQL (without E'')
return str_replace(
["'", "\\"],
["''", "\\\\"],
$query
);
}
if (stripos($this->databaseType, PicoDatabaseType::DATABASE_TYPE_SQLITE) !== false) {
// SQLite
return str_replace("'", "''", $query);
}
if (stripos($this->databaseType, PicoDatabaseType::DATABASE_TYPE_SQLSERVER) !== false) {
// SQL Server
return str_replace("'", "''", $query);
}
// Default fallback
return str_replace(
["\\", "'"],
["\\\\", "\\'"],
$query
);
}
/**
* Escape a value for SQL queries.
*
* This method safely escapes different types of values (null, strings, booleans,
* numeric values, arrays, and objects) to ensure that they can be safely used in
* SQL queries. It prevents SQL injection by escaping potentially dangerous
* characters in string values and converts arrays or objects to their JSON
* representation.
*
* @param mixed $value The value to be escaped. Can be null, string, boolean,
* numeric, array, or object.
* @return string The escaped value. This will be a string representation
* of the value, properly formatted for SQL usage.
*/
public function escapeValue($value)
{
$result = null;
if ($value === null) {
// Null value
$result = 'NULL';
} elseif (is_string($value)) {
// Escape the string value
$result = "'" . $this->escapeSQL($value) . "'";
} elseif (is_bool($value)) {
// Boolean value
$result = $this->createBoolean($value);
} elseif (is_numeric($value)) {
// Numeric value
$result = (string)$value;
} elseif (is_array($value) || is_object($value)) {
// Convert array or object to JSON and escape
return $this->escapedJSONValues($value);
} else {
// Force convert to string and escape
$result = "'" . $this->escapeSQL((string)$value) . "'";
}
return $result;
}
/**
* Escapes the JSON-encoded values.
*
* This function takes an input value, encodes it into JSON format, and then escapes
* the resulting JSON string to ensure it is safe for use (e.g., preventing injection or
* special character issues).
*
* @param mixed $values The input values to be encoded into JSON and escaped.
* @return string The escaped JSON string.
*/
public function escapedJSONValues($values)
{
return $this->escapeValue(json_encode($values));
}
/**
* Convert a value to its boolean representation for SQL.
*
* For SQLite, returns '1' for true and '0' for false.
* For other databases, returns 'TRUE' for true and 'FALSE' for false.
*
* @param mixed $value The value to be converted.
* @return string The boolean representation as a string.
*/
public function createBoolean($value)
{
if($this->isSqlite())
{
return $value ? '1' : '0';
}
return $value ? 'TRUE' : 'FALSE';
}
/**
* Convert an array to a comma-separated list of escaped values.
*
* @param array $values The array of values.
* @return string The comma-separated list.
*/
public function implodeValues($values)
{
foreach ($values as $key => $value) {
$values[$key] = $this->escapeValue($value);
}
return implode(", ", $values);
}
/**
* Create a statement to execute a function.
*
* @param string $name The name of the function to execute.
* @param string $params The parameters for the function.
* @return string|null The SQL statement to execute the function or null if not supported.
*/
public function executeFunction($name, $params)
{
if ($this->isMySql() || $this->isPgSql() || $this->isSqlServer()) {
return "SELECT $name($params)";
}
return null;
}
/**
* Create a statement to execute a stored procedure.
*
* @param string $name The name of the procedure to execute.
* @param string $params The parameters for the procedure.
* @return string|null The SQL statement to execute the procedure or null if not supported.
*/
public function executeProcedure($name, $params) // NOSONAR
{
if ($this->isMySql()) {
return "CALL $name($params)";
}
elseif ($this->isPgSql()) {
return "SELECT $name($params)";
}
elseif ($this->isSqlServer()) {
return "EXEC $name $params"; // SQL Server uses EXEC to call stored procedures
}
return null;
}
/**
* Create a statement to retrieve the last inserted ID.
*
* @return self Returns the current instance for method chaining.
*/
public function lastID()
{
if ($this->isMySql()) {
$this->buffer .= "LAST_INSERT_ID()\r\n";
}
else if ($this->isPgSql()) {
$this->buffer .= "LASTVAL()\r\n";
}
else if ($this->isSqlite())
{
$this->buffer .= "last_insert_rowid()";
}
else if ($this->isSqlServer()) {
$this->buffer .= "SCOPE_IDENTITY()"; // SQL Server uses SCOPE_IDENTITY() to get the last inserted ID
}
return $this;
}
/**
* Create a statement to get the current date.
*
* @return string|null The SQL statement for the current date or null if not supported.
*/
public function currentDate()
{
if ($this->isMySql() || $this->isPgSql() || $this->isSqlite()) {
return "CURRENT_DATE";
}
else if ($this->isSqlServer()) {
return "GETDATE()"; // SQL Server uses GETDATE() for current date
}
return null;
}
/**
* Create a statement to get the current time.
*
* @return string|null The SQL statement for the current time or null if not supported.
*/
public function currentTime()
{
if ($this->isMySql() || $this->isPgSql() || $this->isSqlite()) {
return "CURRENT_TIME";
}
else if ($this->isSqlServer()) {
return "CONVERT(TIME, GETDATE())"; // SQL Server uses CONVERT for current time
}
return null;
}
/**
* Create a statement to get the current timestamp.
*
* @return string|null The SQL statement for the current timestamp or null if not supported.
*/
public function currentTimestamp()
{
if ($this->isMySql() || $this->isPgSql() || $this->isSqlite()) {
return "CURRENT_TIMESTAMP";
}
else if ($this->isSqlServer()) {
return "GETDATE()"; // SQL Server uses GETDATE() for current timestamp as well
}
return null;
}
/**
* Create a NOW statement for the current time with optional precision.
*
* @param int $precision The decimal precision of seconds (default is 0).
* @return string The NOW statement with the specified precision.
*/
public function now($precision = 0)
{
if ($this->isSqlite()) {
return "CURRENT_TIMESTAMP";
}
if ($this->isSqlServer()) {
// SQL Server's equivalent to NOW() with precision, max precision is 7
$precision = min($precision, 7); // Limit precision to 7 for SQL Server
return $precision > 0 ? "SYSDATETIMEOFFSET($precision)" : "SYSDATETIMEOFFSET"; // SQL Server's equivalent to NOW() with precision
}
if ($precision > 6) {
$precision = 6;
}
return $precision > 0 ? "NOW($precision)" : "NOW()";
}
/**
* Replace single quotes with double single quotes in a SQL string for escaping.
*
* @param string $query The SQL query string to modify.
* @return string The modified SQL query string.
*/
public function replaceQuote($query)
{
return str_replace("'", "''", $query);