-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParametrizedSqlQueryUtil.php
830 lines (682 loc) · 27.4 KB
/
ParametrizedSqlQueryUtil.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
<?php
namespace Ling\ParametrizedSqlQuery;
use Ling\BabyYaml\BabyYamlUtil;
use Ling\Bat\ArrayTool;
use Ling\Bat\StringTool;
use Ling\CheapLogger\CheapLogger;
use Ling\ParametrizedSqlQuery\Exception\ParametrizedSqlQueryException;
use Ling\ParametrizedSqlQuery\Helper\ParametrizedSqlQueryHelper;
use Ling\SqlQuery\SqlQuery;
use Ling\UniversalLogger\UniversalLoggerInterface;
/**
* The ParametrizedSqlQueryUtil class.
*
* See @page(conception notes) for more details.
*
*
*
*/
class ParametrizedSqlQueryUtil
{
/**
* This property holds the regex for an inner marker.
* @var string
*/
protected static $regMarker = '!:([a-z%A-Z_0-9]+)!';
/**
* This property holds the regex for a variable.
* @var string
*/
protected static $regVariable = '!\$([a-zA-Z_0-9]+)!';
/**
* This property holds the list of available operators (by default) for this instance.
* This list is defined by @page(the open admin protocol).
* @var array
*/
protected static $operators = [
"=",
">",
">=",
"<",
"<=",
"!=",
"like",
"%like%",
"%like",
"like%",
"not_like",
"%not_like%",
"%not_like",
"not_like%",
"in",
"not_in",
"between",
"not_between",
"null",
"is_not_null",
];
/**
* This property holds temporarily the routines for this instance.
* @var array
*/
private $_options;
/**
* This property holds the markers used by this instance.
* I use it to avoid repetition of markers.
* It's used only in the context of the getSqlQuery method.
* @var array
*/
protected $_markers;
/**
* This property holds the _processedMarkers for this instance.
*
* Usually, there is no problem with the same marker name being used multiple time.
* For instance, the marker :expression could be used multiple times, such as in:
*
* - id like :%expression% or identifier like :%expression%, ...
*
* However, there are some cases where using the same marker is undesirable.
* Including:
*
* - with the where treatment, when the applyOperatorAndValueRoutine method is executed, it already creates
* a marker. So when the prepareExpression method is used after, it shouldn't re-create that marker.
* This is done by putting the marker created by the applyOperatorAndValueRoutine method in this processed markers array.
* This array is reset for every tag item. See the source code for more.
*
*
*
*
* @var array
*/
protected $_processedMarkers;
/**
* This property holds the $_colName2colExpression for this instance.
* It's used only in the context of the getSqlQuery method.
* It's an array of alias => column expression representing the allowed columns.
*
*
* @var array
*/
protected $_colName2colExpression;
/**
* This property holds the logger for this instance.
* @var UniversalLoggerInterface
*/
protected $logger;
/**
* This property holds the developerVariables for this instance.
* @var array
*/
protected $developerVariables;
/**
* Builds the ParametrizedSqlQueryUtil instance.
*/
public function __construct()
{
$this->logger = null;
$this->developerVariables = [];
}
/**
* Sets the developerVariables.
*
* @param mixed $developerVariables
*/
public function setDeveloperVariables($developerVariables)
{
$this->developerVariables = $developerVariables;
}
/**
* Returns an SqlQuery instance parametrized using the given request declaration and params.
* Or throws an exception if something wrong occurs.
*
* For more information about the request declaration structure, see @page(the conception notes).
*
*
*
*
* @param array $requestDeclaration
* @param array $tags
* Array of tagItems, each of which being an array with the following structure:
* - tag_id: string. The tag name
* - ?variables: array. The tag variables if any
*
*
*
* @return SqlQuery
* @throws ParametrizedSqlQueryException
*/
public function getSqlQuery(array $requestDeclaration, array $tags = []): SqlQuery
{
$this->_markers = [];
$query = new SqlQuery();
$query->setDefaultWhereValue(""); // pure style
if (ArrayTool::arrayKeyExistAll(['table', 'base_fields'], $requestDeclaration)) {
//--------------------------------------------
// BASE
//--------------------------------------------
$fields = $requestDeclaration['base_fields'];
$hasBaseWhere = false;
if (false === is_array($fields)) {
$fields = [$fields];
}
$this->_colName2colExpression = ParametrizedSqlQueryHelper::getColumnName2ColumnExpression($fields);
$query->setTable($requestDeclaration['table']);
foreach ($fields as $field) {
$query->addField($field);
}
if (array_key_exists("base_joins", $requestDeclaration)) {
$baseJoin = $requestDeclaration['base_joins'];
if (false === is_array($baseJoin)) {
$baseJoin = [$baseJoin];
}
foreach ($baseJoin as $join) {
$query->addJoin($join);
}
}
if (array_key_exists("base_group_by", $requestDeclaration)) {
$baseGroupBy = $requestDeclaration['base_group_by'];
if (false === is_array($baseGroupBy)) {
$baseGroupBy = [$baseGroupBy];
}
foreach ($baseGroupBy as $groupBy) {
$query->addGroupBy($groupBy);
}
}
if (array_key_exists("base_where", $requestDeclaration)) {
$hasBaseWhere = true;
$baseWhere = $requestDeclaration['base_where'];
if (false === is_array($baseWhere)) {
$baseWhere = [$baseWhere];
}
foreach($baseWhere as $where){
$this->resolveDeveloperVariable($where);
$query->addWhere($where);
}
}
if (array_key_exists("base_having", $requestDeclaration)) {
$baseHaving = $requestDeclaration['base_having'];
if (false === is_array($baseHaving)) {
$baseHaving = [$baseHaving];
}
foreach ($baseHaving as $having) {
$query->addHaving($having);
}
}
if (array_key_exists("base_order", $requestDeclaration)) {
$baseOrder = $requestDeclaration['base_order'];
if (false === is_array($baseOrder)) {
$baseOrder = [$baseOrder];
}
foreach ($baseOrder as $orderBy) {
$p = explode(' ', $orderBy, 2);
$query->addOrderBy($p[0], $p[1]);
}
}
//--------------------------------------------
// TAG BASED
//--------------------------------------------
$fields = $requestDeclaration['fields'] ?? [];
$joins = $requestDeclaration['joins'] ?? [];
$where = $requestDeclaration['where'] ?? [];
$groupBy = $requestDeclaration['group_by'] ?? [];
$having = $requestDeclaration['having'] ?? [];
$order = $requestDeclaration['order'] ?? [];
$this->_options = $requestDeclaration['options'] ?? [];
$tagOptions = $this->_options["tag_options"] ?? [];
$whereBlocks = [];
$limitVariables = [];
foreach ($tags as $tagItem) {
$this->_processedMarkers = [];
$tagName = $tagItem['tag_id'];
$tagVariables = $tagItem['variables'] ?? [];
if ('limit' === $tagName) {
$limitVariables = array_merge($limitVariables, $tagVariables);
continue;
}
$thisTagOptions = $tagOptions[$tagName] ?? [];
//--------------------------------------------
// WHERE PREPARATION
//--------------------------------------------
if (array_key_exists($tagName, $where)) {
$whereExpr = $where[$tagName];
if (array_key_exists("operator_and_value", $thisTagOptions)) {
$this->applyOperatorAndValueRoutine($whereExpr, $thisTagOptions['operator_and_value'], $tagVariables, $thisTagOptions);
}
$realWhereExpression = $this->prepareExpression($whereExpr, $tagName, $tagVariables, $thisTagOptions);
$whereBlocks[] = $realWhereExpression;
}
//--------------------------------------------
// GROUP BY
//--------------------------------------------
if (array_key_exists($tagName, $groupBy)) {
$query->addGroupBy($groupBy[$tagName]);
}
//--------------------------------------------
// ORDER
//--------------------------------------------
if (array_key_exists($tagName, $order)) {
$orderExpr = $order[$tagName];
$realOrderExpression = $this->prepareExpression($orderExpr, $tagName, $tagVariables, $thisTagOptions);
$p = explode(' ', $realOrderExpression, 2);
$query->addOrderBy($p[0], $p[1]);
}
}
//--------------------------------------------
// WHERE RESOLUTION
//--------------------------------------------
if ($whereBlocks) {
$sWhere = "";
if(true===$hasBaseWhere){
$baseWhereSep = $requestDeclaration['base_where_sep']??"and";
$sWhere .= " " . $baseWhereSep . " " . PHP_EOL;
}
$sWhere .= implode(PHP_EOL, $whereBlocks);
$sWhere .= PHP_EOL;
$query->addWhere($sWhere);
}
if ($this->_markers) {
$query->addMarkers($this->_markers);
}
//--------------------------------------------
// LIMIT
//--------------------------------------------
/**
* Limit is special, it's defined statically.
* If the developer used variable, then only those values can be overridden by the user.
*/
$limit = $requestDeclaration['limit'] ?? null;
if ($limit) {
$page = $limit['page'];
$pageLength = $limit['page_length'] ?? null;
if ('$page' === $page) {
if (array_key_exists("page", $limitVariables)) {
$page = $limitVariables["page"];
} else {
if (array_key_exists("default_limit_page", $this->_options)) {
$page = $this->_options['default_limit_page'];
} else {
$this->error("The \"page\" variable was defined by the developer, but not set by the user (for the limit clause), and no default value was set by the developer.");
}
}
}
if ('$page_length' === $pageLength) {
if (array_key_exists("page_length", $limitVariables)) {
$pageLength = $limitVariables["page_length"];
} else {
if (array_key_exists("default_limit_page_length", $this->_options)) {
$pageLength = $this->_options['default_limit_page_length'];
} else {
$this->error("The \"page_length\" variable was defined by the developer, but not set by the user (for the limit clause), and no default value was set by the developer.");
}
}
}
if ($pageLength) {
if ('all' !== $pageLength) {
$offset = ((int)$page - 1) * (int)$pageLength;
$query->setLimit($offset, $pageLength);
}
}
// else just one big page (i.e. no pagination)
}
// az(__FILE__, $query->getSqlQuery(), $this->_markers);
return $query;
} else {
$this->error("Some mandatory field is missing. It could be one either the \"table\" property, or the \"base_fields\" property.");
}
}
//--------------------------------------------
//
//--------------------------------------------
/**
* Sets the logger.
*
* @param UniversalLoggerInterface $logger
*/
public function setLogger(UniversalLoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Logs a message if a logger has been set.
*
* @param mixed $message
* @param string $channel
*/
protected function log($message, string $channel = "debug")
{
if (null !== $this->logger) {
$this->logger->log($message, $channel);
}
}
//--------------------------------------------
//
//--------------------------------------------
/**
* Throws an exception.
*
*
* @param string $message
* @throws ParametrizedSqlQueryException
*/
protected function error(string $message)
{
throw new ParametrizedSqlQueryException($message);
}
/**
* Returns the sql expression to inject in a sql query,
* and stores the markers (if any) in the _markers array.
*
* This method also:
* - resolves the $variables
* - resolves the inner marker notation
*
*
*
*
* @param string $expr
* @param string $tagName
* @param array $tagVariables
* @param array $tagOptions
* @return string
* @throws \Exception
*/
protected function prepareExpression(string $expr, string $tagName, array $tagVariables, array $tagOptions): string
{
//--------------------------------------------
// PREPARE VARIABLES
//--------------------------------------------
$exprVariables = [];
if (preg_match_all(self::$regVariable, $expr, $match)) {
$exprVariables = $match[1];
}
foreach ($exprVariables as $variable) {
if (array_key_exists($variable, $tagVariables)) {
$value = $tagVariables[$variable];
// SPECIAL VARIABLES
//--------------------------------------------
switch ($variable) {
case "column":
if (true === array_key_exists($value, $this->_colName2colExpression)) {
$value = $this->_colName2colExpression[$value];
} else {
$this->error("Unexpected value for variable \"column\" (tag=$tagName).");
}
break;
case "direction":
if (false === in_array($value, ["asc", 'desc'], true)) {
$this->error("Unexpected value for variable \"direction\" (tag=$tagName).");
}
break;
case "operator":
$operators = $tagOptions['operators'] ?? self::$operators;
if (false === in_array($value, $operators, true)) {
$this->error("Unexpected value for variable \"operator\" (tag=$tagName).");
}
switch ($value) {
case "%like%":
case "like%":
case "%like":
$value = 'LIKE';
break;
case "not_like":
case "%not_like%":
case "not_like%":
case "%not_like":
$value = 'NOT LIKE';
break;
case "in":
case "not_in":
case "between":
case "not_between":
$value = 'between ()';
$this->error("Not implemented yet, with special operator $value.");
break;
case "null":
$value = 'IS NULL';
break;
case "is_not_null":
$value = 'IS NOT NULL';
break;
default:
break;
}
break;
case "page":
$value = (int)$value;
break;
}
// now inject the SAFE value in the "tag expression".
$expr = preg_replace('!\$' . $variable . '\b!', $value, $expr);
} else {
$this->error("Variable not provided by the user: $variable.");
}
}
//--------------------------------------------
// EXTRACT MARKERS
//--------------------------------------------
$internalMarkers = [];
if (preg_match_all(self::$regMarker, $expr, $match)) {
$internalMarkers = $match[1];
/**
* If the expression contains the same tag multiple times, we reduce it to one tag because it's the same tag.
*
* Example:
* - general_search:
* id like %expression% or
* identifier like %expression% or
* pseudo like %expression% ...
*/
$internalMarkers = array_unique($internalMarkers);
$internalMarkers = array_diff($internalMarkers, $this->_processedMarkers);
}
//--------------------------------------------
// NOW UPDATE THE VARIABLES IF NECESSARY
//--------------------------------------------
foreach ($internalMarkers as $internalMarker) {
$varName = str_replace('%', '', $internalMarker);
if (array_key_exists($varName, $tagVariables)) {
$value = $tagVariables[$varName];
//--------------------------------------------
// HANDLING LIKE-WRAPPING
//--------------------------------------------
$value = $this->resolveInternalMarkerPercent($internalMarker, $value, $tagOptions);
//--------------------------------------------
// PREPARING MARKERS
//--------------------------------------------
$markerName = $this->getNewMarkerName($varName);
$expr = preg_replace('!:%?' . $varName . '%?(?:\b|\s|$)!', ':' . $markerName . ' ', $expr);
$this->_markers[$markerName] = $value;
} else {
$this->error("The variable $varName was not provided (tag=$tagName).");
}
}
return $expr;
}
/**
* Resolves the percent symbol in internal marker notation, and returns the result.
* It returns an array with the following entries:
*
* - 0: the sql marker name
* - 1: the value to bind to that marker
*
*
* @param string $internalMarkerName
* The internal marker without the colon prefix.
*
* @param mixed $value
* The marker value
* @param array $tagOptions
*
* @return string
*/
protected function resolveInternalMarkerPercent(string $internalMarkerName, $value, array $tagOptions): string
{
$underscoreChar = $this->_options['sql_like_underscore_char'] ?? '_';
$percentChar = $this->_options['sql_like_percent_char'] ?? '%';
$escapeUnderscore = $tagOptions['escape_underscore'] ?? true;
$escapePercent = $tagOptions['escape_percent'] ?? true;
if (false !== strpos($internalMarkerName, '%')) {
// escaping the user value
if (true === $escapePercent) {
$value = str_replace($percentChar, '\\' . $percentChar, $value);
}
if (true === $escapeUnderscore) {
$value = str_replace($underscoreChar, '\\' . $underscoreChar, $value);
}
if ('%' === substr($internalMarkerName, 0, 1)) {
$value = $percentChar . $value;
}
if ('%' === substr($internalMarkerName, -1)) {
$value = $value . $percentChar;
}
}
return $value;
}
/**
*
* Applies the transformIfLike routine to the given expression.
*
* See @page(the routines section) in the documentation for more info.
*
* Note: the tags array might be updated.
*
*
*
*
* @param string $expression
* @param array $transformLikeOptions
* @param array $tags
* @param array $tagOptions
* @throws \Exception
*/
protected function applyOperatorAndValueRoutine(string &$expression, array $transformLikeOptions, array &$tags, array $tagOptions)
{
$source = $transformLikeOptions['source'];
$target = $transformLikeOptions['target'];
if (
preg_match('!\$' . $source . '\b!', $expression) &&
preg_match('!:' . $target . '\b!', $expression) &&
array_key_exists($source, $tags) &&
array_key_exists($target, $tags)
) {
$sourceValue = $tags[$source];
$targetValue = $tags[$target];
/**
* /~https://github.com/lingtalfi/NotationFan/blob/master/sql-unofficial-standard-comparison-operators.md
*/
switch ($sourceValue) {
case "%like%":
case "%not_like%":
case "%like":
case "%not_like":
case "like%":
case "not_like%":
$markerName = $this->getNewMarkerName($target, true);
switch ($sourceValue) {
case "%like%":
case "%not_like%":
$internalMarkerName = "%$markerName%";
break;
case "%like":
case "%not_like":
$internalMarkerName = "%$markerName";
break;
case "like%":
case "not_like%":
$internalMarkerName = "$markerName%";
break;
}
$newValue = $this->resolveInternalMarkerPercent($internalMarkerName, $targetValue, $tagOptions);
$this->_markers[$markerName] = $newValue;
$expression = preg_replace('!:' . $target . '\b!', ':' . $markerName, $expression);
break;
case "in":
case "not_in":
$keyword = ("in" === $sourceValue) ? "IN" : "NOT IN";
if (false === is_array($targetValue)) {
$targetValue = BabyYamlUtil::parseCsv($targetValue);
}
$marker = "in_tag";
$ins = [];
foreach ($targetValue as $v) {
$markerName = $this->getNewMarkerName($marker, true);
$this->_markers[$markerName] = $v;
$ins[] = ":" . $markerName;
$tags[$markerName] = $v;
}
$sIn = $keyword . "(" . implode(', ', $ins) . ") ";
$expression = preg_replace('!:' . $target . '\b!', ' ', $expression);
$expression = preg_replace('!\$' . $source . '\b!', $sIn, $expression);
break;
case "between":
case "not_between":
$keyword = ("between" === $sourceValue) ? "BETWEEN" : "NOT BETWEEN";
if (false === is_array($targetValue)) {
$targetValue = BabyYamlUtil::parseCsv($targetValue);
}
$marker = "between_tag";
if (is_array($targetValue)) {
if (2 === count($targetValue)) {
$betweens = [];
foreach ($targetValue as $v) {
$markerName = $this->getNewMarkerName($marker, true);
$this->_markers[$markerName] = $v;
$betweens[] = ":" . $markerName;
$tags[$markerName] = $v;
}
$sBetween = $keyword . "(" . implode(' AND ', $betweens) . ") ";
$expression = preg_replace('!:' . $target . '\b!', ' ', $expression);
$expression = preg_replace('!\$' . $source . '\b!', $sBetween, $expression);
} else {
$this->error("count != 2 (keyword=between, expression=$expression).");
}
} else {
$this->error("Target value not an array (keyword=between, expression=$expression)");
}
break;
case "is_null":
case "is_not_null":
$keyword = ("is_null" === $sourceValue) ? "IS NULL" : "IS NOT NULL";
$expression = preg_replace('!:' . $target . '\b!', ' ', $expression);
unset($tags[$target]);
$expression = preg_replace('!\$' . $source . '\b!', $keyword, $expression);
break;
case "=":
case ">":
case ">=":
case "<":
case "<=":
case "!=":
break;
default:
$this->error("Unknown operator: $sourceValue.");
break;
}
}
}
/**
* Returns a unique marker name that's not already in the _markers array.
*
* @param string $marker
* @param bool $isFinal
* @return string
*/
protected function getNewMarkerName(string $marker, bool $isFinal = false): string
{
$res = StringTool::incrementNumericalSuffix($marker, $this->_markers, true);
if (true === $isFinal) {
$this->_processedMarkers[] = $res;
}
return $res;
}
/**
* Resolves the developer variables in the given expr.
*
* @param string $expr
*/
protected function resolveDeveloperVariable(string &$expr){
foreach($this->developerVariables as $k => $v){
$expr = str_replace('${'. $k .'}', $v, $expr);
}
}
}