-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MySQLQuery.php
2142 lines (1959 loc) · 85 KB
/
MySQLQuery.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
/**
* MIT License
*
* Copyright (c) 2019 Ibrahim BinAlshikh, phMysql library.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace phMysql;
/**
* A base class that is used to construct MySQL queries. It can be used as a base
* class for constructing other MySQL queries.
* @author Ibrahim
* @version 1.9.0
*/
class MySQLQuery {
/**
* A constant for the query 'delete from'.
* @since 1.0
*/
const DELETE = 'delete from ';
/**
* A constant for the query 'insert into'.
* @since 1.0
*/
const INSERT = 'insert into ';
/**
* Line feed character.
* @since 1.8.1
*/
const NL = "\n";
/**
* A constant that indicates a table structure is not linked with the instance.
* @since 1.8.3
*/
const NO_STRUCTURE = 'no_struture';
/**
* An array that contains the supported MySQL query types.
* @since 1.1
*/
const Q_TYPES = [
'select','update','delete','insert','show','create','alter','drop'
];
/**
* A constant that indicates an error has occurred while executing the query.
* @var string
* @since 1.4
*/
const QUERY_ERR = 'query_error';
/**
* A constant for the query 'select * from '.
* @since 1.0
*/
const SELECT = 'select * from ';
/**
* An attribute that is set to true if the query is an update or insert of
* blob datatype.
* @var boolean
*/
private $isFileInsert;
private $origColsNames;
/**
* The query that will be constructed using class methods.
* @var string
* @since 1.0
*/
private $query;
/**
* A string that represents the type of the query such as 'select' or 'update'.
* @var string
* @since 1.0
*/
private $queryType;
/**
* The name of the entity class at which a select
* statement result will be mapped to.
* @var string|null
* @since 1.9.0
*/
private $resultMap;
/**
* The name of database schema that the query will be executed on.
* @var string
* @since 1.8.7
*/
private $schemaName;
/**
* The linked database table.
* @var MySQLTable
*/
private $table;
/**
* Creates new instance of the class.
* @param string $tableName The name of the table that will be associated
* with the queries that will be created.
*/
public function __construct($tableName = null) {
$this->table = new MySQLTable($tableName);
$this->query = self::SELECT.$this->getTableName();
$this->queryType = 'select';
$this->setIsBlobInsertOrUpdate(false);
$this->origColsNames = [];
}
public function __toString() {
return $this->getQuery();
}
/**
* Constructs a query that can be used to alter a table and add a
* foreign key to it.
* @param ForeignKey $key An object of type <b>ForeignKey</b>.
* @since 1.4
*/
public function addForeignKey($key) {
$ownerTable = $key->getOwner();
$sourceTable = $key->getSource();
if ($sourceTable !== null && $ownerTable !== null) {
$queryStr = 'alter table '.$ownerTable->getName()
.' add constraint '.$key->getKeyName().' foreign key (';
$ownerCols = $key->getOwnerCols();
$ownerCount = count($ownerCols);
$i0 = 0;
foreach ($ownerCols as $col) {
if ($i0 + 1 == $ownerCount) {
$queryStr .= $col->getName().') ';
} else {
$queryStr .= $col->getName().', ';
}
$i0++;
}
$queryStr .= 'references '.$key->getSourceName().'(';
$sourceCols = $key->getSourceCols();
$refCount = count($sourceCols);
$i1 = 0;
foreach ($sourceCols as $col) {
if ($i1 + 1 == $refCount) {
$queryStr .= $col->getName().') ';
} else {
$queryStr .= $col->getName().', ';
}
$i1++;
}
$onDelete = $key->getOnDelete();
if ($onDelete !== null) {
$queryStr .= 'on delete '.$onDelete.' ';
}
$onUpdate = $key->getOnUpdate();
if ($onUpdate !== null) {
$queryStr .= 'on update '.$onUpdate;
}
}
$this->setQuery($queryStr, 'alter');
}
/**
* Constructs a query that can be used to add a primary key to a table.
* @param MySQLTable $tableObj The table that will have the primary key.
* @since 1.8.8
*/
public function addPrimaryKey($tableObj) {
if ($tableObj instanceof MySQLTable) {
$primaryCount = $tableObj->primaryKeyColsCount();
if ($primaryCount != 0) {
$stm = 'alter table '.$tableObj->getName().' add constraint '.$tableObj->getPrimaryKeyName().' primary key (';
$index = 0;
$alterStm = '';
$comma = ',';
foreach ($tableObj->getColumns() as $col) {
if ($col->isPrimary()) {
if ($index + 1 == $primaryCount) {
$comma = ')';
}
$stm .= $col->getName().$comma;
if ($col->isAutoInc()) {
$alterStm .= 'alter table '.$tableObj->getName().' modify '.$col.' auto_increment;'.self::NL;
}
$index++;
}
}
$stm .= ';'.MySQLQuery::NL.$alterStm;
$this->setQuery($stm, 'alter');
return;
}
}
$this->setQuery('', 'alter');
}
/**
* Constructs a query that can be used to alter the properties of a table
* given its name.
* @param array $alterOps An array that contains the alter operations.
* @since 1.4
*/
public function alter($alterOps) {
$schema = $this->getSchemaName() === null ? '' : $this->getSchemaName().'.';
$q = 'alter table '.$schema.''.$this->getStructureName().self::NL;
$count = count($alterOps);
for ($x = 0 ; $x < $count ; $x++) {
if ($x + 1 == $count) {
$q .= $alterOps[$x].';'.self::NL;
} else {
$q .= $alterOps[$x].','.self::NL;
}
}
$this->setQuery($q, 'alter');
}
/**
* Constructs a string which contains columns names that will be selected.
* @param array $colsArr It can be an indexed array which contains columns
* names as specified while creating the linked table. Or it can be an
* associative array. The key should be the name of the column and the value
* is an alias to the column. For example, If the following array is given:
* <p>
* <code>[
* 'name','id'=>'user_id','email'
* ]</code>
* </p>
* And assuming that the column names are the same as given values,
* Then the output will be the following string:
* <p>
* <code>name, id as user_id, email</code>
* </p>
* @param boolean $withTablePrefix If set to true, then column name will be
* prefixed with table name.
* @return string
* @since 1.9.0
*/
public function createColsToSelect($colsArr,$withTablePrefix) {
$retVal = '';
$tableObj = $this->getTable();
if ($tableObj instanceof JoinTable && $tableObj->hasCommon()) {
$retVal = $this->_createColsToSelectJoin($colsArr);
} else if (count($colsArr) == 0) {
$retVal = '*';
} else {
$comma = " \n";
foreach ($colsArr as $index => $colName) {
if (gettype($index) == 'string') {
$colObj = $this->getCol($index);
$colObj->setAlias($colName);
$asPart = ' as '.$colName;
} else {
$colObj = $this->getCol($colName);
$asPart = '';
}
if ($colObj instanceof MySQLColumn) {
$retVal .= $comma.$colObj->getName($withTablePrefix).$asPart;
$comma = ",\n";
}
}
}
return $retVal."\n";
}
/**
* Constructs a 'where' condition given a date.
* @param string $date A date or timestamp.
* @param string $colName The name of the column that will contain
* the date value.
* @param string $format The format of the date. The supported formats
* are:
* <ul>
* <li>YYYY-MM-DD HH:MM:SS</li>
* <li>YYYY-MM-DD</li>
* <li>YYYY</li>
* <li>MM</li>
* <li>DD</li>
* <li>HH:MM:SS</li>
* <li>HH</li>
* <li>MM</li>
* <li>SS</li>
* </ul>
*/
public static function createDateCondition($date,$colName,$format = 'YYYY-MM-DD HH:MM:SS') {
$formatInUpperCase = strtoupper(trim($format));
$condition = '';
if ($formatInUpperCase == 'YYYY-MM-DD HH:MM:SS') {
$dateTimeSplit = explode(' ', $date);
if (count($date) == 2) {
$datePart = explode('-', $dateTimeSplit[0]);
$timePart = explode(':', $dateTimeSplit[0]);
if (count($datePart) == 3 && count($timePart) == 3) {
$condition = 'year('.$colName.') = '.$datePart[0].' and '
.'month('.$colName.') = '.$datePart[1].' and '
.'day('.$colName.') = '.$datePart[2].' and '
.'hour('.$colName.') = '.$datePart[2].' and '
.'minute('.$colName.') = '.$datePart[2].' and '
.'second('.$colName.') = '.$datePart[2].' and ';
}
}
} else {
if ($formatInUpperCase == 'YYYY-MM-DD') {
$datePart = explode('-', $date);
if (count($datePart) == 3) {
$condition = 'year('.$colName.') = '.$datePart[0].' and '
.'month('.$colName.') = '.$datePart[1].' and '
.'day('.$colName.') = '.$datePart[2];
}
} else {
if ($formatInUpperCase == 'YYYY') {
$asInt = intval($date);
if ($asInt > 1900 && $asInt < 10000) {
$condition = 'year('.$colName.') = '.$date;
}
} else {
if ($formatInUpperCase == 'MM') {
$asInt = intval($date);
if ($asInt > 0 && $asInt < 13) {
$condition = 'month('.$colName.') = '.$date;
}
} else {
if ($formatInUpperCase == 'DD') {
$asInt = intval($date);
if ($asInt > 0 && $asInt < 32) {
$condition = 'day('.$colName.') = '.$date;
}
} else {
if ($formatInUpperCase == 'HH:MM:SS') {
$datePart = explode(':', $date);
if (count($datePart) == 3) {
$condition = 'hour('.$colName.') = '.$datePart[0].' and '
.'minute('.$colName.') = '.$datePart[1].' and '
.'second('.$colName.') = '.$datePart[2];
}
} else {
if ($formatInUpperCase == 'HH') {
$asInt = intval($date);
if ($asInt > 0 && $asInt < 24) {
$condition = 'hour('.$colName.') = '.$date;
}
} else {
if ($formatInUpperCase == 'SS') {
$asInt = intval($date);
if ($asInt > 0 && $asInt < 60) {
$condition = 'second('.$colName.') = '.$date;
}
} else {
if ($formatInUpperCase == 'MM') {
$asInt = intval($date);
if ($asInt > 0 && $asInt < 59) {
$condition = 'minute('.$colName.') = '.$date;
}
}
}
}
}
}
}
}
}
}
return $condition;
}
/**
* Constructs a query that can be used to create the table which is linked
* with the query class.
* @param boolean $inclComments If set to true, the generated MySQL
* query will have basic comments explaining the structure.
* @return boolean Once the query is structured, the method will return
* true. If the query is not created, the method will return false.
* @deprecated since version 1.9.0
* @since 1.5
*/
public function createStructure($inclComments = false) {
$t = $this->getTable();
if ($t instanceof MySQLTable) {
$this->_createTable($t,$inclComments);
return true;
}
return false;
}
/**
* Constructs a query that can be used to create the table which is linked
* with the query class.
* @param boolean $withComments If set to true, the generated MySQL
* query will have basic comments explaining the structure.
* @since 1.9.0
*/
public function createTable($withComments = false) {
$this->createStructure($withComments);
}
/**
* Removes a record from the table.
* @param array $columnsAndVals An associative array. The indices of the array
* should be the values of the columns and the value at each index is
* an object of type 'Column'.
* @param array $valsConds An array that can have one of the following
* values: '=','!=','<','<=','>' and '>='. The number of elements
* in this array must match number of
* elements in the array $cols. If not provided, '=' is used. Default is empty array.
* @param array $jointOps An array which contains conditional operators
* to join conditions. The operators can be logical or bitwise. Possible
* values include: &&, ||, and, or, |, &, xor. If not provided,
* 'and' is used for all values.
* @since 1.8.2
*/
public function deleteRecord($columnsAndVals,$valsConds = [],$jointOps = []) {
$colsCount = count($columnsAndVals);
$condsCount = count($valsConds);
$joinOpsCount = count($jointOps);
while ($colsCount > $condsCount) {
$valsConds[] = '=';
$condsCount = count($valsConds);
}
while (($colsCount - 1) > $joinOpsCount) {
$jointOps[] = 'and';
$joinOpsCount = count($jointOps);
}
$cols = [];
$vals = [];
foreach ($columnsAndVals as $valOrIndex => $colObjOrVal) {
if ($colObjOrVal instanceof MySQLColumn) {
$cols[] = $colObjOrVal;
$vals[] = $valOrIndex;
} else {
if (gettype($valOrIndex) == 'integer') {
$testCol = $this->getTable()->getColByIndex($valOrIndex);
} else {
$testCol = $this->getTable()->getCol($valOrIndex);
}
$cols[] = $testCol;
$vals[] = $colObjOrVal;
}
}
$queryStr = 'delete from '.$this->getTableName();
$this->setQuery($queryStr.$this->createWhereConditions($cols, $vals, $valsConds, $jointOps).';', 'delete');
}
/**
* Constructs a query that can be used to delete the table from the
* database.
* @since 1.9.0
*/
public function dropTable() {
$this->setQuery('drop table '.$this->getTableName().';', 'delete');
}
/**
* Escape any MySQL special characters from a string.
* @param string $queryStr The string that the characters will be escaped from.
* @return string A string with escaped MySQL characters.
* @deprecated since version 1.8.9
* @since 1.4
*/
public static function escapeMySQLSpeciarChars($queryStr) {
$escapedQuery = '';
$queryStr = ''.$queryStr;
if ($queryStr) {
$mysqlSpecial = [
"\\","'","\0","\b","\n"
];
$mysqlSpecialEsc = [
"\\\\","\'","\\0","\\b","\\n"
];
$count = count($mysqlSpecial);
for ($i = 0 ; $i < $count ; $i++) {
if ($i == 0) {
$escapedQuery = str_replace($mysqlSpecial[$i], $mysqlSpecialEsc[$i], $queryStr);
} else {
$escapedQuery = str_replace($mysqlSpecial[$i], $mysqlSpecialEsc[$i], $escapedQuery);
}
}
}
return $escapedQuery;
}
/**
* Returns a column from the table given its key.
* @param string $colKey The name of the column key.
* @return string|MySQLColumn The the column in the table. If no column was
* found, the method will return the string 'MySQLTable::NO_SUCH_COL'. If there is
* no table linked with the query object, the method will return the
* string MySQLQuery::NO_STRUCTURE.
* @since 1.6
*/
public function getCol($colKey) {
$structure = $this->getStructure();
$retVal = self::NO_STRUCTURE;
if ($structure instanceof MySQLTable) {
$col = $structure->getCol($colKey);
if ($col instanceof MySQLColumn) {
return $col;
}
$retVal = MySQLTable::NO_SUCH_COL;
}
return $retVal;
}
/**
* Returns the index of a column given its key.
* @param string $colKey The name of the column key.
* @return int The index of the column if found starting from 0.
* If the column was not found, the method will return -1.
* @since 1.8.4
*/
public function getColIndex($colKey) {
$col = $this->getCol($colKey);
return $col instanceof MySQLColumn ? $col->getIndex() : -1;
}
/**
* Returns the name of the column from the table given its key.
* @param string $colKey The name of the column key.
* @return string The name of the column in the table. If no column was
* found, the method will return the string MySQLTable::NO_SUCH_COL. If there is
* no table linked with the query object, the method will return the
* string MySQLQuery::NO_STRUCTURE.
* @since 1.5
*/
public function getColName($colKey) {
$col = $this->getCol($colKey);
if ($col instanceof MySQLColumn) {
return $col->getName();
}
return $col;
}
/**
* Returns the name of the entity class at which a select result will
* be mapped to.
* @return string|null If the entity name is set, the method will return
* it as string. If not set, the method will return null.
* @since 1.9.0
*/
public function getMappedEntity() {
return $this->resultMap;
}
/**
* Returns the value of the property $query.
* It is simply the query that was constructed by calling any method
* of the class.
* @return string a MySql query.
* @since 1.0
*/
public function getQuery() {
return $this->query;
}
/**
* Returns database schema name that the query will be executed on.
* A schema is a collection of tables. On the other hand, a database
* is a collection of schema. In MySQL, the two terms usually refer to the
* same thing.
* @return string Database schema name. If not set, the method will
* return null.
* @since 1.8.7
*/
public function getSchemaName() {
return $this->schemaName;
}
/**
* Constructs a query that can be used to get all tables in a schema given its name.
* The result of executing the query is a table with one colum. The name
* of the column is 'TABLE_NAME'. The column will simply contain all the
* names of the tables in the schema. If the given schema does not exist
* or has no tables, The result will be an empty table.
* @param string $schemaName The name of the schema.
* @since 1.8
*/
public function getSchemaTables($schemaName) {
$this->query = 'select TABLE_NAME from information_schema.tables where TABLE_TYPE = \'BASE TABLE\' and TABLE_SCHEMA = \''.$schemaName.'\'';
$this->queryType = 'select';
}
/**
* Constructs a query that can be used to get the names of all views in a
* schema given its name.
* The result of executing the query is a table with one column. The name
* of the column is 'TABLE_NAME'. The column will simply contain all the
* names of the views in the schema. If the given schema does not exist
* or has no views, The result will be an empty table.
* @param string $schemaName The name of the schema.
* @since 1.8
*/
public function getSchemaViews($schemaName) {
$this->query = 'select TABLE_NAME from information_schema.tables where TABLE_TYPE = \'VIEW\' and TABLE_SCHEMA = \''.$schemaName.'\'';
$this->queryType = 'select';
}
/**
* Returns the table that is used for constructing queries.
* @return MySQLTable The table that is used for constructing queries.
* @since 1.5
* @deprecated since version 1.9.0 Use MySQLQuery::getTable() instead.
*/
public function getStructure() {
return $this->getTable();
}
/**
* Returns the name of the table that is used to construct queries.
* @return string The name of the table that is used to construct queries.
* if no table is linked, the method will return the string MySQLQuery::NO_STRUCTURE.
* @since 1.5
* @deprecated since version 1.9.0 Use MySQLQuery::getTableName() instead.
*/
public function getStructureName() {
$s = $this->getStructure();
if ($s instanceof MySQLTable) {
return $s->getName();
}
return self::NO_STRUCTURE;
}
/**
* Returns the table which is associated with the query.
* @return MySQLTable The table which is used to constructs queries for.
* @since 1.9.0
*/
public function getTable() {
return $this->table;
}
/**
* Returns the name of the table which is used to constructs the queries.
* @param boolean $dbPrefix If database prefix is set and this parameter is
* set to true, the name of the table will include database prefix.
* @return string The name of the table which is used to constructs the queries.
* @since 1.9.0
*/
public function getTableName($dbPrefix = true) {
return $this->getTable()->getName($dbPrefix);
}
/**
* Returns the type of the query.
* @return string The type of the query (such as 'select', 'update').
* @since 1.0
*/
public function getType() {
return $this->queryType;
}
/**
* Constructs a query that can be used to insert a new record.
* @param array $colsAndVals An associative array. The indices must be
* columns names taken from the linked table. For example, if we have
* a table which has two columns with names 'student-id' and 'registered-course',
* then the array would look like the following:
* <p>
* <code>[<br/>
* 'student-id'=>55<br/>
* 'registered-course'=>542<br/>]</code>
* </p>
* Note that it is possible for the index to be a numeric value such as 0
* or 1. The numeric value will represents column position in the table.
* Another thing to note is that if a column does not have a value, either
* the default value of the column will be used or 'null' will be used. For
* blob data type, the value of the index must be physical path to the file.
* For boolean type, the value can be only true or false. If anything else is
* passed, it well considered as false.
* @since 1.8.2
*/
public function insertRecord($colsAndVals) {
$cols = '';
$vals = '';
$count = count($colsAndVals);
$index = 0;
$comma = '';
$columnsWithVals = [];
$defaultCols = $this->getTable()->getDefaultColsKeys();
$createdOnKey = $defaultCols['created-on'];
if ($createdOnKey !== null) {
$createdOnColObj = $this->getCol($createdOnKey);
} else {
$createdOnColObj = null;
}
foreach ($colsAndVals as $colIndex => $val) {
if ($index + 1 == $count) {
$comma = '';
} else {
$comma = ',';
}
if (gettype($colIndex) == 'integer') {
$column = $this->getTable()->getColByIndex($colIndex);
} else {
$column = $this->getTable()->getCol($colIndex);
}
if ($column instanceof MySQLColumn) {
$columnsWithVals[] = $colIndex;
$cols .= $column->getName().$comma;
$type = $column->getType();
if ($val !== 'null') {
$cleanedVal = $column->cleanValue($val);
if ($cleanedVal === null) {
if ($createdOnColObj !== null && $createdOnColObj->getIndex() == $column->getIndex()) {
$vals .= $column->cleanValue($column->getDefault()).$comma;
$createdOnColObj = null;
} else {
$vals .= 'null'.$comma;
}
} else if ($type == 'tinyblob' || $type == 'mediumblob' || $type == 'longblob') {
$fixedPath = str_replace('\\', '/', $val);
if (file_exists($fixedPath)) {
$file = fopen($fixedPath, 'r');
$data = '';
if ($file !== false) {
$fileContent = fread($file, filesize($fixedPath));
if ($fileContent !== false) {
$data = '\''.addslashes($fileContent).'\'';
$vals .= $data.$comma;
$this->setIsBlobInsertOrUpdate(true);
} else {
$vals .= 'null'.$comma;
}
fclose($file);
} else {
$vals .= 'null'.$comma;
}
} else {
$vals .= 'null'.$comma;
}
} else if ($type == 'boolean') {
if ($cleanedVal === true) {
$vals .= "'Y'".$comma;
} else {
$vals .= "'N'".$comma;
}
} else if ($createdOnColObj !== null && $createdOnColObj->getIndex() == $column->getIndex()) {
$vals .= $cleanedVal.$comma;
$createdOnColObj = null;
} else {
$vals .= $cleanedVal.$comma;
}
} else {
$vals .= 'null'.$comma;
}
}
$index++;
}
if ($createdOnColObj !== null) {
$cols .= ','.$createdOnColObj->getName();
if ($createdOnColObj->getDefault() == 'now()' || $createdOnColObj->getDefault() == 'current_timestamp') {
$vals .= ",'".date('Y-m-d H:i:s')."'";
} else {
$vals .= ','.$createdOnColObj->cleanValue($createdOnColObj->getDefault());
}
}
$cols = ' ('.$cols.')';
$vals = ' ('.$vals.')';
$this->setQuery(self::INSERT.$this->getTableName().$cols.' values'.$vals.';', 'insert');
}
/**
* Checks if the query represents a blob insert or update.
* The aim of this method is to fix an issue with setting the collation
* of the connection while executing a query.
* @return boolean The Function will return true if the query represents an
* insert or un update of blob datatype. false if not.
* @since 1.8.5
*/
public function isBlobInsertOrUpdate() {
return $this->isFileInsert;
}
/**
* Creates an object of the class which represents a join between two tables.
* For every join, there is a left table, a right table and a join
* condition. The table which
* will be on the left side of the join will be the table which is
* linked with current instance and the right table is the one which is
* supplied as a parameter to the method.
* @param $options array An associative array that contains join information.
* The available options are:
* <ul>
* <li><b>right-table</b>: This index must be set. It represents the right
* table of the join. It can be an object of type 'MySQLQuery' or an object
* of type 'MySQLTable'.</li>
* <li><b>join-cols</b>: An associative array of columns. The indices should be
* the names of columns keys taken from left table and the values should be
* columns keys taken from right table.</li>
* <li><b>join-conditions</b>: An optional array of join conditions. It can have
* values like '=' or '!='.</li>
* <li><b>join-type</b>: A string that represents the type of the join.
* It can have a value such as 'left', 'right' or 'cross'. Default is 'join'.</li>
* <li><b>alias</b>: An optional name for the table that will be created
* by the join. Default is null which means a name will be generated
* automatically.</li>
* <li><b>keys-map</b>: An optional array that can have two associative
* arrays. One with key 'left' and the other is with key 'right'. Each one
* of the two arrays can have new names for table columns keys. The indices
* in each array are the original keys names taken from joined tables and
* the values are the new keys which will exist in the joined table. It is
* simply used to map joined keys with new keys which will exist in the new
* joined table.</li>
* </ul>
*
* @return MySQLQuery|null If the join is a success, the method will return
* an object of type 'MySQLQuery' that can be used to get info from joined
* tables. If no join is formed, the method will return null.
*/
public function join($options) {
$right = isset($options['right-table']) ? $options['right-table'] : null;
$joinCols = isset($options['join-cols']) &&
gettype($options['join-cols']) == 'array' ? $options['join-cols'] : [];
$joinType = isset($options['join-type']) ? $options['join-type'] : 'join';
$conds = isset($options['join-conditions']) &&
gettype($options['join-conditions']) == 'array' ? $options['join-conditions'] : [];
$joinOps = [];
$alias = isset($options['alias']) ? $options['alias'] : null;
$keysAliases = isset($options['keys-map']) &&
gettype($options['keys-map']) == 'array' ? $options['keys-map'] : [];
if ($right instanceof MySQLQuery || $right instanceof MySQLTable) {
$joinQuery = new MySQLQuery();
$joinTable = new JoinTable($this, $right, $alias, $keysAliases);
$joinTable->setJoinType($joinType);
$joinTable->setJoinCondition($joinCols, $conds, $joinOps);
$joinQuery->setTable($joinTable);
return $joinQuery;
}
}
/**
* Constructs a query that can be used to get the number of tables in a
* schema given its name.
* The result of executing
* the query is a table with one row and one column. The column name will be
* 'tables_count' which will contain an integer value that indicates the
* number of tables in the schema. If the schema does not exist or has no tables,
* the result in the given column will be 0.
* @param string $schemaName The name of the schema.
* @since 1.8
*/
public function schemaTablesCount($schemaName) {
$this->query = 'select count(*) as tables_count from information_schema.tables where TABLE_TYPE = \'BASE TABLE\' and TABLE_SCHEMA = \''.$schemaName.'\';';
$this->queryType = 'select';
}
/**
* Constructs a query that can be used to get the number of views in a
* schema given its name.
* The result of executing the query is a table with one row and one column.
* The column name will be 'views_count' which will contain an integer
* value that indicates the number of views in the schema. If the schema
* does not exist or has no views, the result in the given column will be 0.
* @param string $schemaName The name of the schema.
* @since 1.8
*/
public function schemaViewsCount($schemaName) {
$this->query = 'select count(*) as views_count from information_schema.tables where TABLE_TYPE = \'VIEW\' and TABLE_SCHEMA = \''.$schemaName.'\';';
$this->queryType = 'select';
}
/**
* Constructs a 'select' query.
* @param array $selectOptions An associative array which contains
* options to construct different select queries. The available options are:
* <ul>
* <li><b>map-result-to</b>: A string that represents the name
* of the entity class at which query result will be mapped to. If the
* entity class is in a namespace, then this value must have the name of the
* namespace.</li>
* <li><b>columns</b>: An optional array which can have the keys of columns that
* will be select. Also, this array can be an associative array. The indices are columns
* keys and the values are aliases for the columns. In case of joins, the array can have
* two sub arrays for selecting columns from left or right table. the first
* can exist in the index 'left' and the second one in the index 'right'.</li>
* <li><b>limit</b>: The 'limit' attribute of the query.</li>
* <li><b>offset</b>: The 'offset' attribute of the query. Ignored if the
* option 'limit' is not set.</li>
* <li><b>condition-cols-and-vals</b>: An associative array. The indices can
* be values and the value at each index is an objects of type 'Column'.
* Or the indices can be column indices or columns names taken from MySQLTable object and
* the values are set for each index. The second way is recommended as one
* table might have two columns with the same values. For multiple values select,
* the value of the indices must be a sub array that can have the following indices:
*
* <ul>
* <li><b>values</b>: The values that the column can have.</li>
* <li><b>conditions</b>: An array of conditions such as '=' or a string. The
* string can only have one of two values: 'in' or 'not in'</li>
* <li><b>join-conditions</b>: An array of conditions which are used to join the
* values. The array can have one of two values: 'and' or 'or'.<li>
* </ul></li>
* <li><b>where</b>: Similar to 'condition-cols-and-vals'.</li>
* <li><b>conditions</b>: An array that can contains conditions (=, !=, <,
* <=, > or >=). If anything else is given at specific index, '=' will be used. In
* addition, If not provided or has invalid value, an array of '=' conditions
* is used.</li>
* <li><b>join-operators</b>: An array that contains a set of MySQL join operators
* like 'and' and 'or'. If not provided or has invalid value,
* an array of 'and's will be used.</li>
* <li><b>select-max</b>: A boolean value. Set to true if you want to select maximum
* value of a column. Ignored in case the option 'columns' is set.</li>
* <li><b>select-min</b>: A boolean value. Set to true if you want to select minimum
* value of a column. Ignored in case the option 'columns' or 'select-max' is set.</li>
* <li><b>column</b>: The column which contains maximum or minimum value.</li>
* <li><b>rename-to</b>: Rename the max or min column to the given name.</li>
* <li><b>group-by</b>: An indexed array that contains
* sub associative arrays which has 'group by' columns info. The sub associative
* arrays can have the following indices:
* <ul>
* <li>col: The name of the column.</li>
* </ul></li>
* <li><b>order-by</b>: An indexed array that contains
* sub associative arrays which has columns 'order by' info. The sub associative
* arrays can have the following indices:
* <ul>
* <li><b>col</b>: The name of the column.</li>
* <li>order-type: An optional string to represent the order. It can
* be 'A' for ascending or 'D' for descending</li>
* </ul></li>
* </ul>
* @since 1.8.3
*/
public function select($selectOptions = [
'columns' => [],
'condition-cols-and-vals' => [],
'conditions' => [],
'join-operators' => [],
'limit' => -1,
'offset' => -1,
'select-min' => false,
'select-max' => false,
'column' => '',
'rename-to' => '',
'order-by' => null,
'group-by' => null,
'without-select' => false
]) {
$tableObj = $this->getTable();
if ($tableObj instanceof MySQLTable) {
$selectQuery = 'select ';
$limit = isset($selectOptions['limit']) ? $selectOptions['limit'] : -1;
$offset = isset($selectOptions['offset']) ? $selectOptions['offset'] : -1;
if ($limit > 0 && $offset > 0) {
$limitPart = ' limit '.$limit.' offset '.$offset;
} else if ($limit > 0 && $offset <= 0) {
$limitPart = ' limit '.$limit;
} else {
$limitPart = '';
}
$groupByPart = '';
if (isset($selectOptions['group-by']) && gettype($selectOptions['group-by']) == 'array') {
$groupByPart = $this->_buildGroupByCondition($selectOptions['group-by']);
}
$orderByPart = '';
if (isset($selectOptions['order-by']) && gettype($selectOptions['order-by']) == 'array') {
$orderByPart = $this->_buildOrderByCondition($selectOptions['order-by']);
}
if (isset($selectOptions['columns']) && gettype($selectOptions['columns']) == 'array') {