forked from flourishlib/flourish-classes
-
Notifications
You must be signed in to change notification settings - Fork 10
/
fORMDatabase.php
1333 lines (1129 loc) · 44.7 KB
/
fORMDatabase.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
/**
* Holds a single instance of the fDatabase class and provides database manipulation functionality for ORM code
*
* @copyright Copyright (c) 2007-2011 Will Bond, others
* @author Will Bond [wb] <[email protected]>
* @author Craig Ruksznis, iMarc LLC [cr-imarc] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fORMDatabase
*
*/
class fORMDatabase
{
// The following constants allow for nice looking callbacks to static methods
const addHavingClause = 'fORMDatabase::addHavingClause';
const addOrderByClause = 'fORMDatabase::addOrderByClause';
const addPrimaryKeyWhereParams = 'fORMDatabase::addPrimaryKeyWhereParams';
const addWhereClause = 'fORMDatabase::addWhereClause';
const attach = 'fORMDatabase::attach';
const injectFromAndGroupByClauses = 'fORMDatabase::injectFromAndGroupByClauses';
const makeCondition = 'fORMDatabase::makeCondition';
const parseSearchTerms = 'fORMDatabase::parseSearchTerms';
const reset = 'fORMDatabase::reset';
const retrieve = 'fORMDatabase::retrieve';
const splitHavingConditions = 'fORMDatabase::splitHavingConditions';
/**
* An array of fDatabase objects
*
* @var array
*/
static private $database_objects = array();
/**
* If the PCRE engine supports unicode character properties
*
* @var boolean
*/
static private $pcre_supports_unicode_character_properties = NULL;
/**
* Allows attaching an fDatabase-compatible objects for by ORM code
*
* If a `$name` other than `default` is used, any fActiveRecord classes
* that should use it will need to be configured by passing the class name
* and `$name` to ::mapClassToDatabase(). The `$name` parameter should be
* unique per database or database master/slave setup.
*
* The `$role` is used by code to allow for master/slave database setups.
* There can only be one database object attached for either of the roles,
* `'read'` or `'write'`. If the role `'both'` is specified, it will
* be applied to both the `'read'` and `'write'` roles. Any sort of logic
* for picking one out of multiple databases should be done before this
* method is called.
*
* @param fDatabase $database An object that is compatible with fDatabase
* @param string $name The name for the database instance
* @param string $role If the database should be used for `'read'`, `'write'` or `'both'` operations
* @return void
*/
static public function attach($database, $name='default', $role='both')
{
$valid_roles = array('both', 'write', 'read');
if (!in_array($role, $valid_roles)) {
throw new fProgrammerException(
'The role specified, %1$s, is invalid. Must be one of: %2$s.',
$role,
join(', ', $valid_roles)
);
}
if (!isset(self::$database_objects[$name])) {
self::$database_objects[$name] = array();
}
settype($role, 'array');
if ($role == array('both')) {
$role = array('write', 'read');
}
foreach ($role as $_role) {
self::$database_objects[$name][$_role] = $database;
}
}
/**
* Translated the where condition for a single column into a SQL clause
*
* @param fDatabase $db The database the query will be run on
* @param fSchema $schema The schema for the database
* @param array $params The parameters for the fDatabase::query() call
* @param string $table The table to create the condition for
* @param string $column The column to store the value in, may also be shorthand column name like `table.column` or `table=>related_table.column`
* @param string $operator Should be `'='`, `'!='`, `'!'`, `'<>'`, `'<'`, `'<='`, `'>'`, `'>='`, `'IN'`, `'NOT IN'`
* @param mixed $values The value(s) to escape
* @param string $escaped_column The escaped column to use in the SQL
* @param string $placeholder This allows overriding the placeholder
* @return array The modified parameters
*/
static private function addColumnCondition($db, $schema, $params, $table, $column, $operator, $values, $escaped_column=NULL, $placeholder=NULL)
{
// Some objects when cast to an array turn the members into array keys
if (!is_object($values)) {
settype($values, 'array');
} else {
$values = array($values);
}
// Make sure we have an array with something in it to compare to
if (!$values) { $values = array(NULL); }
// If the table and column specified are real and not some combination
$real_column = $escaped_column === NULL && $placeholder === NULL;
if ($escaped_column === NULL) {
$escaped_column = $db->escape('%r', (strpos($column, '.') === FALSE) ? $table . '.' . $column : $column);
}
list($table, $column) = self::getTableAndColumn($schema, $table, $column);
if ($placeholder === NULL && !in_array($operator, array('=:', '!=:', '<:', '<=:', '>:', '>=:'))) {
$placeholder = $schema->getColumnInfo($table, $column, 'placeholder');
}
// More than one value
if (sizeof($values) > 1) {
switch ($operator) {
case '=':
$non_null_values = array();
$has_null = FALSE;
foreach ($values as $value) {
if ($value === NULL) {
$has_null = TRUE;
continue;
}
$non_null_values[] = $value;
}
if ($has_null) {
$params[0] .= '(' . $escaped_column . ' IS NULL OR ';
}
$params[0] .= $escaped_column . ' IN (' . $placeholder . ')';
$params[] = $non_null_values;
if ($has_null) {
$params[0] .= ')';
}
break;
case '!':
$non_null_values = array();
$has_null = FALSE;
foreach ($values as $value) {
if ($value === NULL) {
$has_null = TRUE;
continue;
}
$non_null_values[] = $value;
}
if ($has_null) {
$params[0] .= '(' . $escaped_column . ' IS NOT NULL AND ';
}
$params[0] .= $escaped_column . ' NOT IN (' . $placeholder . ')';
$params[] = $non_null_values;
if ($has_null) {
$params[0] .= ')';
}
break;
case '~':
$condition = array();
foreach ($values as $value) {
$condition[] = $escaped_column . ' LIKE %s';
$params[] = '%' . $value . '%';
}
$params[0] .= '(' . join(' OR ', $condition) . ')';
break;
case '=~':
$condition = array();
foreach ($values as $value) {
$condition[] = $escaped_column . ' LIKE %s';
$params[] = $value;
}
$params[0] .= '(' . join(' OR ', $condition) . ')';
break;
case '^~':
$condition = array();
foreach ($values as $value) {
$condition[] = $escaped_column . ' LIKE %s';
$params[] = $value . '%';
}
$params[0] .= '(' . join(' OR ', $condition) . ')';
break;
case '$~':
$condition = array();
foreach ($values as $value) {
$condition[] = $escaped_column . ' LIKE %s';
$params[] = '%' . $value;
}
$params[0] .= '(' . join(' OR ', $condition) . ')';
break;
case '&~':
$condition = array();
foreach ($values as $value) {
$condition[] = $escaped_column . ' LIKE %s';
$params[] = '%' . $value . '%';
}
$params[0] .= '(' . join(' AND ', $condition) . ')';
break;
case '!~':
$condition = array();
foreach ($values as $value) {
$condition[] = $escaped_column . ' NOT LIKE %s';
$params[] = '%' . $value . '%';
}
$params[0] .= '(' . join(' AND ', $condition) . ')';
break;
default:
throw new fProgrammerException(
'An invalid array comparison operator, %s, was specified for an array of values',
$operator
);
break;
}
// A single value
} else {
if ($values === array()) {
$value = NULL;
} else {
$value = current($values);
}
switch ($operator) {
case '!:':
$operator = '<>:';
case '=:':
case '<:':
case '<=:':
case '>:':
case '>=:':
$params[0] .= $escaped_column . ' ';
$params[0] .= substr($operator, 0, -1) . ' ';
// If the column to match is a function, split the function
// name off so we can escape the column name
$prefix = '';
$suffix = '';
if (preg_match('#^([^(]+\()\s*([^\s]+)\s*(\))$#D', $value, $parts)) {
$prefix = $parts[1];
$value = $parts[2];
$suffix = $parts[3];
}
$params[0] .= $prefix . $db->escape('%r', (strpos($value, '.') === FALSE) ? $table . '.' . $value : $value) . $suffix;
break;
case '=':
if ($value === NULL) {
$operator = 'IS';
}
$params[0] .= $escaped_column . ' ' . $operator . ' ' . $placeholder;
$params[] = $value;
break;
case '!':
$operator = '<>';
if ($value !== NULL) {
$params[0] .= '(';
} else {
$operator = 'IS NOT';
}
$params[0] .= $escaped_column . ' ' . $operator . ' ' . $placeholder;
$params[] = $value;
if ($value !== NULL) {
$params[0] .= ' OR ' . $escaped_column . ' IS NULL)';
}
break;
case '<':
case '<=':
case '>':
case '>=':
$params[0] .= $escaped_column . ' ' . $operator . ' ' . $placeholder;
$params[] = $value;
break;
case '~':
$params[0] .= $escaped_column . ' LIKE %s';
$params[] = '%' . $value . '%';
break;
case '^~':
$params[0] .= $escaped_column . ' LIKE %s';
$params[] = $value . '%';
break;
case '$~':
$params[0] .= $escaped_column . ' LIKE %s';
$params[] = '%' . $value;
break;
case '!~':
$params[0] .= $escaped_column . ' NOT LIKE %s';
$params[] = '%' . $value . '%';
break;
default:
throw new fProgrammerException(
'An invalid comparison operator, %s, was specified for a single value',
$operator
);
break;
}
}
return $params;
}
/**
* Creates a `HAVING` clause from an array of conditions
*
* @internal
*
* @param fDatabase $db The database the query will be executed on
* @param fSchema $schema The schema for the database
* @param array $params The params for the fDatabase::query() call
* @param string $table The table the query is being executed on
* @param array $conditions The array of conditions - see fRecordSet::build() for format
* @return array The params with the `HAVING` clause added
*/
static public function addHavingClause($db, $schema, $params, $table, $conditions)
{
$i = 0;
foreach ($conditions as $expression => $value) {
if ($i) {
$params[0] .= ' AND ';
}
// Splits the operator off of the end of the expression
if (in_array(substr($expression, -3), array('!=:', '>=:', '<=:', '<>:'))) {
$operator = strtr(
substr($expression, -3),
array('<>:' => '!:', '!=:' => '!:')
);
$expression = substr($expression, 0, -3);
} elseif (in_array(substr($expression, -2), array('<=', '>=', '!=', '<>', '=:', '!:', '<:', '>:'))) {
$operator = strtr(
substr($expression, -2),
array('<>' => '!', '!=' => '!')
);
$expression = substr($expression, 0, -2);
} else {
$operator = substr($expression, -1);
$expression = substr($expression, 0, -1);
}
// Quotes the identifier in the expression
preg_match('#^([^(]+\()\s*([^\s]+)\s*(\))$#D', $expression, $parts);
$expression = $parts[1] . $db->escape('%r', $parts[2]) . $parts[3];
// The AVG, SUM and COUNT functions all return a number
$function = strtolower(substr($parts[2], 0, -1));
$placeholder = (in_array($function, array('avg', 'sum', 'count'))) ? '%f' : NULL;
// This removes stray quoting inside of {route} specified for shorthand column names
$expression = preg_replace('#(\{\w+)"\."(\w+\})#', '\1.\2', $expression);
$params = self::addColumnCondition($db, $schema, $params, $table, $parts[2], $operator, $value, $expression, $placeholder);
$i++;
}
return $params;
}
/**
* Adds an `ORDER BY` clause to an array of params for an fDatabase::query() call
*
* @internal
*
* @param fDatabase $db The database the query will be executed on
* @param fSchema $schema The schema object for the database the query will be executed on
* @param array $params The parameters for the fDatabase::query() call
* @param string $table The table any ambigious column references will refer to
* @param array $order_bys The array of order bys to use - see fRecordSet::build() for format
* @return array The params with a SQL `ORDER BY` clause added
*/
static public function addOrderByClause($db, $schema, $params, $table, $order_bys)
{
$expressions = array();
foreach ($order_bys as $column => $direction) {
if ((!is_string($column) && !is_object($column) && !is_numeric($column)) || !strlen(trim($column))) {
throw new fProgrammerException(
'An invalid sort column, %s, was specified',
$column
);
}
$direction = strtoupper($direction);
if (!in_array($direction, array('ASC', 'DESC'))) {
throw new fProgrammerException(
'An invalid direction, %s, was specified',
$direction
);
}
if (preg_match('#^((?:max|min|avg|sum|count)\()?((?:(?:(?:"?\w+"?\.)?"?\w+(?:\{[\w.]+\})?"?=>)?"?(?:(?:\w+"?\."?)?\w+)(?:\{[\w.]+\})?"?\.)?"?(?:\w+)"?)(?:\))?$#D', $column, $matches)) {
// Parse the expression and get a table and column to determine the data type
list ($clause_table, $clause_column) = self::getTableAndColumn($schema, $table, $matches[2]);
$column_type = $schema->getColumnInfo($clause_table, $clause_column, 'type');
// Make sure each column is qualified with a table name
if (strpos($matches[2], '.') === FALSE) {
$matches[2] = $table . '.' . $matches[2];
}
$matches[2] = $db->escape('%r', $matches[2]);
// Text columns are converted to lowercase for more accurate sorting
if (in_array($column_type, array('varchar', 'char', 'text'))) {
$expression = 'LOWER(' . $matches[2] . ')';
} else {
$expression = $matches[2];
}
// If the column is in an aggregate function, add the function back in
if ($matches[1]) {
$expression = $matches[1] . $expression . ')';
}
$expressions[] = $expression . ' ' . $direction;
} else {
$expressions[] = $column . ' ' . $direction;
}
}
$params[0] .= join(', ', $expressions);
return $params;
}
/**
* Add the appropriate SQL and params for a `WHERE` clause condition for primary keys of the table specified
*
* @internal
*
* @param fSchema $schema The schema for the database the query will be run on
* @param array $params The currently constructed params for fDatabase::query() - the first param should be a SQL statement
* @param string $table The table to build the where clause for
* @param string $table_alias The alias for the table
* @param array &$values The values array for the fActiveRecord object
* @param array &$old_values The old values array for the fActiveRecord object
* @return array The params to pass to fDatabase::query(), including the new primary key where condition
*/
static public function addPrimaryKeyWhereParams($schema, $params, $table, $table_alias, &$values, &$old_values)
{
$pk_columns = $schema->getKeys($table, 'primary');
$column_info = $schema->getColumnInfo($table);
$conditions = array();
foreach ($pk_columns as $pk_column) {
$value = fActiveRecord::retrieveOld($old_values, $pk_column, $values[$pk_column]);
// This makes sure the query performs the way an insert will
if ($value === NULL && $column_info[$pk_column]['not_null'] && $column_info[$pk_column]['default'] !== NULL) {
$value = $column_info[$pk_column]['default'];
}
$params[] = $table_alias . '.' . $pk_column;
$params[] = $value;
$conditions[] = self::makeCondition($schema, $table, $pk_column, '=', $value);
}
$params[0] .= join(' AND ', $conditions);
return $params;
}
/**
* Adds a `WHERE` clause, from an array of conditions, to the parameters for an fDatabase::query() call
*
* @internal
*
* @param fDatabase $db The database the query will be executed on
* @param fSchema $schema The schema for the database
* @param array $params The parameters for the fDatabase::query() call
* @param string $table The table any ambigious column references will refer to
* @param array $conditions The array of conditions - see fRecordSet::build() for format
* @return array The params with the SQL `WHERE` clause added
*/
static public function addWhereClause($db, $schema, $params, $table, $conditions)
{
$i = 0;
foreach ($conditions as $column => $values) {
if ($i) {
$params[0] .= ' AND ';
}
if (in_array(substr($column, -3), array('!=:', '>=:', '<=:', '<>:'))) {
$operator = strtr(
substr($column, -3),
array('<>:' => '!:', '!=:' => '!:')
);
$column = substr($column, 0, -3);
} elseif (in_array(substr($column, -2), array('<=', '>=', '!=', '<>', '=~', '!~', '&~', '^~', '$~', '><', '=:', '!:', '<:', '>:'))) {
$operator = strtr(
substr($column, -2),
array('<>' => '!', '!=' => '!')
);
$column = substr($column, 0, -2);
} else {
$operator = substr($column, -1);
$column = substr($column, 0, -1);
}
if (!is_object($values)) {
settype($values, 'array');
} else {
$values = array($values);
}
if (!$values) { $values = array(NULL); }
$new_values = array();
foreach ($values as $value) {
if (is_object($value) && is_callable(array($value, '__toString'))) {
$value = $value->__toString();
} elseif (is_object($value)) {
$value = (string) $value;
}
$new_values[] = $value;
}
$values = $new_values;
// Multi-column condition
if (preg_match('#(?<!\|)\|(?!\|)#', $column)) {
$columns = explode('|', $column);
$operators = array();
foreach ($columns as &$_column) {
if (in_array(substr($_column, -3), array('!=:', '>=:', '<=:', '<>:'))) {
$operators[] = strtr(
substr($_column, -3),
array('<>:' => '!:', '!=:' => '!:')
);
$_column = substr($_column, 0, -3);
} elseif (in_array(substr($_column, -2), array('<=', '>=', '!=', '<>', '=~', '!~', '&~', '^~', '$~', '=:', '!:', '<:', '>:'))) {
$operators[] = strtr(
substr($_column, -2),
array('<>' => '!', '!=' => '!')
);
$_column = substr($_column, 0, -2);
} elseif (!ctype_alnum(substr($_column, -1))) {
$operators[] = substr($_column, -1);
$_column = substr($_column, 0, -1);
}
}
$operators[] = $operator;
if (sizeof($operators) == 1) {
// Make sure every column is qualified by a table name
$new_columns = array();
foreach ($columns as $column) {
if (strpos($column, '.') === FALSE) {
$column = $table . '.' . $column;
}
$new_columns[] = $column;
}
$columns = $new_columns;
// Handle fuzzy searches
if ($operator == '~') {
// If the value to search is a single string value, parse it for search terms
if (sizeof($values) == 1 && is_string($values[0])) {
$values = self::parseSearchTerms($values[0], TRUE);
}
// Skip fuzzy matches with no values to match
if ($values === array()) {
$params[0] .= ' 1 = 1 ';
$i++;
continue;
}
$condition = array();
foreach ($values as $value) {
$sub_condition = array();
foreach ($columns as $column) {
$sub_condition[] = $db->escape('%r', $column) . ' LIKE %s';
$params[] = '%' . $value . '%';
}
$condition[] = '(' . join(' OR ', $sub_condition) . ')';
}
$params[0] .= ' (' . join(' AND ', $condition) . ') ';
// Handle intersection
} elseif ($operator == '><') {
if (sizeof($columns) != 2 || sizeof($values) != 2) {
throw new fProgrammerException(
'The intersection operator, %s, requires exactly two columns and two values',
$operator
);
}
$escaped_columns = array(
$db->escape('%r', $columns[0]),
$db->escape('%r', $columns[1])
);
list($column_1_table, $column_1) = self::getTableAndColumn($schema, $table, $columns[0]);
list($column_2_table, $column_2) = self::getTableAndColumn($schema, $table, $columns[1]);
$placeholders = array(
$schema->getColumnInfo($column_1_table, $column_1, 'placeholder'),
$schema->getColumnInfo($column_2_table, $column_2, 'placeholder')
);
if ($values[1] === NULL) {
$part_1 = '(' . $escaped_columns[1] . ' IS NULL AND ' . $escaped_columns[0] . ' = ' . $placeholders[0] . ')';
$part_2 = '(' . $escaped_columns[1] . ' IS NOT NULL AND ' . $escaped_columns[0] . ' <= ' . $placeholders[0] . ' AND ' . $escaped_columns[1] . ' >= ' . $placeholders[1] . ')';
$params[] = $values[0];
$params[] = $values[0];
$params[] = $values[0];
} else {
$part_1 = '(' . $escaped_columns[0] . ' <= ' . $placeholders[0] . ' AND ' . $escaped_columns[1] . ' >= ' . $placeholders[1] . ')';
$part_2 = '(' . $escaped_columns[0] . ' >= ' . $placeholders[0] . ' AND ' . $escaped_columns[0] . ' <= ' . $placeholders[0] . ')';
$params[] = $values[0];
$params[] = $values[0];
$params[] = $values[0];
$params[] = $values[1];
}
$params[0] .= ' (' . $part_1 . ' OR ' . $part_2 . ') ';
} else {
throw new fProgrammerException(
'An invalid comparison operator, %s, was specified for multiple columns',
$operator
);
}
// Handle OR combos
} else {
if (sizeof($columns) != sizeof($values)) {
throw new fProgrammerException(
'When creating an %1$s where clause there must be an equal number of columns and values, however %2$s column(s) and %3$s value(s) were provided',
'OR',
sizeof($columns),
sizeof($values)
);
}
if (sizeof($columns) != sizeof($operators)) {
throw new fProgrammerException(
'When creating an %s where clause there must be a comparison operator for each column, however one or more is missing',
'OR'
);
}
$params[0] .= ' (';
$iterations = sizeof($columns);
for ($j=0; $j<$iterations; $j++) {
if ($j) {
$params[0] .= ' OR ';
}
$params = self::addColumnCondition($db, $schema, $params, $table, $columns[$j], $operators[$j], $values[$j]);
}
$params[0] .= ') ';
}
// Concatenated columns
} elseif (strpos($column, '||') !== FALSE) {
$parts = explode('||', $column);
$new_parts = array();
foreach ($parts as $part) {
$part = trim($part);
if ($part[0] != "'") {
$new_parts[] = $db->escape('%r', $part);
} else {
$new_parts[] = $part;
}
}
$escaped_column = join('||', $new_parts);
$params = self::addColumnCondition($db, $schema, $params, $table, $column, $operator, $values, $escaped_column, '%s');
// Single column condition
} else {
$params = self::addColumnCondition($db, $schema, $params, $table, $column, $operator, $values);
}
$i++;
}
return $params;
}
/**
* Takes a table name, cleans off quoting and removes the schema name if unambiguous
*
* @param fSchema $schema The schema object for the database being inspected
* @param string $table The table name to be made cleaned
* @return string The cleaned table name
*/
static private function cleanTableName($schema, $table)
{
$table = str_replace('"', '', $table);
$tables = array_flip($schema->getTables());
if (!isset($tables[$table])) {
$short_table = preg_replace('#^\w\.#', '', $table);
if (isset($tables[$short_table])) {
$table = $short_table;
}
}
return strtolower($table);
}
/**
* Creates a `FROM` clause from a join array
*
* @internal
*
* @param fDatabase $db The database the query will be run on
* @param array $joins The joins to create the `FROM` clause out of
* @return string The from clause (does not include the word `FROM`)
*/
static private function createFromClauseFromJoins($db, $joins)
{
$sql = '';
foreach ($joins as $join) {
// Here we handle the first table in a join
if ($join['join_type'] == 'none') {
$sql .= $db->escape('%r', $join['table_name']);
if ($join['table_alias'] != $join['table_name']) {
$sql .= ' ' . $db->escape('%r', $join['table_alias']);
}
// Here we handle all other joins
} else {
$sql .= ' ' . strtoupper($join['join_type']) . ' ' . $db->escape('%r', $join['table_name']);
if ($join['table_alias'] != $join['table_name']) {
$sql .= ' ' . $db->escape('%r', $join['table_alias']);
}
if (!empty($join['on_clause_fields'])) {
$sql .= ' ON ' . $db->escape('%r', $join['on_clause_fields'][0]) . ' = ' . $db->escape('%r', $join['on_clause_fields'][1]);
}
}
}
return $sql;
}
/**
* Creates join information for the table shortcut provided
*
* @internal
*
* @param fSchema $schema The schema object for the tables/joins
* @param string $table The primary table
* @param string $table_alias The primary table alias
* @param string $related_table The related table
* @param string $route The route to the related table
* @param array &$joins The names of the joins that have been created
* @param array &$used_aliases The aliases that have been used
* @return string The name of the significant join created
*/
static private function createJoin($schema, $table, $table_alias, $related_table, $route, &$joins, &$used_aliases)
{
$routes = fORMSchema::getRoutes($schema, $table, $related_table);
if (!isset($routes[$route])) {
throw new fProgrammerException(
'An invalid route, %1$s, was specified for the relationship from %2$s to %3$s',
$route,
$table,
$related_table
);
}
if (isset($joins[$table . '_' . $related_table . '{' . $route . '}'])) {
return $table . '_' . $related_table . '{' . $route . '}';
}
// If the route uses a join table
if (isset($routes[$route]['join_table'])) {
$join = array(
'join_type' => 'LEFT JOIN',
'table_name' => $routes[$route]['join_table'],
'table_alias' => self::createNewAlias($routes[$route]['join_table'], $used_aliases),
'on_clause_fields' => array()
);
$join2 = array(
'join_type' => 'LEFT JOIN',
'table_name' => $related_table,
'table_alias' => self::createNewAlias($related_table, $used_aliases),
'on_clause_fields' => array()
);
if ($table != $related_table) {
$join['on_clause_fields'][] = $table_alias . '.' . $routes[$route]['column'];
$join['on_clause_fields'][] = $join['table_alias'] . '.' . $routes[$route]['join_column'];
$join2['on_clause_fields'][] = $join['table_alias'] . '.' . $routes[$route]['join_related_column'];
$join2['on_clause_fields'][] = $join2['table_alias'] . '.' . $routes[$route]['related_column'];
} else {
$join['on_clause_fields'][] = $table_alias . '.' . $routes[$route]['column'];
$join['on_clause_fields'][] = $join['table_alias'] . '.' . $routes[$route]['join_related_column'];
$join2['on_clause_fields'][] = $join['table_alias'] . '.' . $routes[$route]['join_column'];
$join2['on_clause_fields'][] = $join2['table_alias'] . '.' . $routes[$route]['related_column'];
}
$joins[$table . '_' . $related_table . '{' . $route . '}_join'] = $join;
$joins[$table . '_' . $related_table . '{' . $route . '}'] = $join2;
// If the route is a direct join
} else {
$join = array(
'join_type' => 'LEFT JOIN',
'table_name' => $related_table,
'table_alias' => self::createNewAlias($related_table, $used_aliases),
'on_clause_fields' => array()
);
if ($table != $related_table) {
$join['on_clause_fields'][] = $table_alias . '.' . $routes[$route]['column'];
$join['on_clause_fields'][] = $join['table_alias'] . '.' . $routes[$route]['related_column'];
} else {
$join['on_clause_fields'][] = $table_alias . '.' . $routes[$route]['related_column'];
$join['on_clause_fields'][] = $join['table_alias'] . '.' . $routes[$route]['column'];
}
$joins[$table . '_' . $related_table . '{' . $route . '}'] = $join;
}
return $table . '_' . $related_table . '{' . $route . '}';
}
/**
* Creates a new table alias
*
* @internal
*
* @param string $table The table to create an alias for
* @param array &$used_aliases The aliases that have been used
* @return string The alias to use for the table
*/
static private function createNewAlias($table, &$used_aliases)
{
if (!in_array($table, $used_aliases)) {
$used_aliases[] = $table;
return $table;
}
// This will strip any schema name off the beginning
$table = preg_replace('#^\w+\.#', '', $table);
$i = 1;
while(in_array($table . $i, $used_aliases)) {
$i++;
}
$used_aliases[] = $table . $i;
return $table . $i;
}
/**
* Gets the table and column name from a shorthand column name
*
* @param fSchema $schema The schema for the database
* @param string $table The table to use when no table is specified in the shorthand
* @param string $column The shorthand column definition - see fRecordSet::build() for possible syntaxes
* @return array The $table and $column, suitable for use with fSchema
*/
static private function getTableAndColumn($schema, $table, $column)
{
// Handle shorthand column names like table.column and table=>related_table.column
if (preg_match('#((?:"?\w+"?\.)?"?\w+)(?:\{[\w.]+\})?"?\."?(\w+)"?$#D', $column, $match)) {
$table = $match[1];
$column = $match[2];
}
$table = self::cleanTableName($schema, $table);
$column = str_replace('"', '', $column);
return array($table, $column);
}
/**
* Finds all of the table names in the SQL and creates the appropriate `FROM` and `GROUP BY` clauses with all necessary joins
*
* The SQL string should contain two placeholders, `:from_clause` and
* `:group_by_clause`, although the later may be omitted if necessary. All
* columns should be qualified with their full table name.
*
* Here is an example SQL string to pass in presumming that the tables
* users and groups are in a relationship:
*
* {{{
* SELECT users.* FROM :from_clause WHERE groups.group_id = 5 :group_by_clause ORDER BY lower(users.first_name) ASC
* }}}
*
* @internal
*
* @param fDatabase $db The database the query is to be executed on
* @param fSchema $schema The schema for the database
* @param array $params The parameters for the fDatabase::query() call
* @param string $table The main table to be queried
* @return array The params with the SQL `FROM` and `GROUP BY` clauses injected
*/
static public function injectFromAndGroupByClauses($db, $schema, $params, $table)
{
$table_with_schema = $table;
$table = self::cleanTableName($schema, $table);
$joins = array();
if (strpos($params[0], ':from_clause') === FALSE) {
throw new fProgrammerException(
'No %1$s placeholder was found in:%2$s',
':from_clause',
"\n" . $params[0]
);
}
$has_group_by_placeholder = (strpos($params[0], ':group_by_clause') !== FALSE) ? TRUE : FALSE;
// Separate the SQL from quoted values
preg_match_all("#(?:'(?:''|\\\\'|\\\\[^']|[^'\\\\])*')|(?:[^']+)#", $params[0], $matches);
$table_alias = $table;
$used_aliases = array();
$table_map = array();
// If we are not passing in existing joins, start with the specified table
if (!$joins) {
$joins[] = array(
'join_type' => 'none',
'table_name' => $table,
'table_alias' => $table_alias
);
}
$used_aliases[] = $table_alias;
foreach ($matches[0] as $match) {
if ($match[0] != "'") {
// This removes quotes from around . in the {route} specified of a shorthand column name
$match = preg_replace('#(\{\w+)"\."(\w+\})#', '\1.\2', $match);
preg_match_all('#(?<!\w|"|=>)((?:"?((?:\w+"?\."?)?\w+)(?:\{([\w.]+)\})?"?=>)?("?(?:\w+"?\."?)?\w+)(?:\{([\w.]+)\})?"?)\."?\w+"?(?=[^\w".{])#m', $match, $table_matches, PREG_SET_ORDER);
foreach ($table_matches as $table_match) {
if (!isset($table_match[5])) {
$table_match[5] = NULL;
}
if (!empty($table_match[2])) {
$table_match[2] = self::cleanTableName($schema, $table_match[2]);
}
$table_match[4] = self::cleanTableName($schema, $table_match[4]);
if (in_array($db->getType(), array('oracle', 'db2'))) {
foreach (array(2, 3, 4, 5) as $subpattern) {
if (isset($table_match[$subpattern])) {
$table_match[$subpattern] = strtolower($table_match[$subpattern]);
}
}
}
// This is a related table that is going to join to a once-removed table