-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJSql_DataObjectMap_QueryBuilder.java
More file actions
executable file
·1731 lines (1476 loc) · 58.6 KB
/
JSql_DataObjectMap_QueryBuilder.java
File metadata and controls
executable file
·1731 lines (1476 loc) · 58.6 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
package picoded.dstack.jsql;
// Java imports
import java.util.*;
import java.util.logging.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.SQLException;
// Picoded imports
import picoded.core.conv.*;
import picoded.core.common.*;
import picoded.dstack.*;
import picoded.dstack.core.*;
import picoded.dstack.jsql.JSql_DataObjectMapUtil;
import picoded.dstack.connector.jsql.*;
import picoded.core.struct.*;
import picoded.core.struct.query.*;
import picoded.core.struct.query.condition.*;
import picoded.core.struct.query.internal.*;
import picoded.core.struct.MutablePair;
/**
* Protected class, used to orgainze the various DataObjectMap query builder logic.
*
* The larger intention is to keep the DataObjectMap class more maintainable and unit testable
*
* For simplicity of the documentation here, the examples used for the query being built is loosely based on
*
* ```
* SELECT oID FROM TABLENAME WHERE softDelete = 0 AND sourceOfLead = "post office"
* ```
**/
public class JSql_DataObjectMap_QueryBuilder {
//-----------------------------------------------------------------------------------------------
//
// Constructor with config
//
//-----------------------------------------------------------------------------------------------
/**
* Main internal dataobject map to fetch config / etc
*/
protected JSql_DataObjectMap dataMap = null;
/**
* Constructor with the config map
*/
public JSql_DataObjectMap_QueryBuilder(JSql_DataObjectMap inMap) {
dataMap = inMap;
// Preloading memoizers in constructor,
// as its the only lock-free segment that is
// guranteed to be thread safe
preloadMemoizers();
}
/**
* Preloading of memoizer functions, this is done to ensure race conditions
* in multi threaded setup is avoided
*/
private void preloadMemoizers() {
getFixedTableNameList();
getFixedTableNamePrimaryKeyJoinSet();
}
//-----------------------------------------------------------------------------------------------
//
// Fixed table configuration utilities
//
// Note that special care was made such that all "memoizer" commands are "thread safe"
// without the need for locks.
//
//-----------------------------------------------------------------------------------------------
/**
* @return the fixedTable config map if it exists, else returns null
*/
private GenericConvertMap<String, Object> getFixedTableFullConfigMap() {
return dataMap.configMap.getGenericConvertStringMap("fixedTableMap", null);
}
/// Internal memoizer for the getFixedTableNameList
private List<String> _getFixedTableNameList = null;
/**
* @return Set of fixed table names if avaliable
*/
private List<String> getFixedTableNameList() {
// Fetch Cache result
if (_getFixedTableNameList != null) {
return _getFixedTableNameList;
}
// Result list to build
List<String> resList = new ArrayList<String>();
// Get the table map
GenericConvertMap<String, Object> tableMap = getFixedTableFullConfigMap();
if (tableMap != null) {
// Get the key set
resList.addAll(tableMap.keySet());
// Register memoizer, and return
_getFixedTableNameList = resList;
return resList;
}
// memoizer blank result and return it
_getFixedTableNameList = resList;
return resList;
}
/**
* @param table alias name
* @return the fixed table name
*/
private String getFixedTableNameFromAlias(String aliasName) {
int idx = Integer.parseInt(aliasName.substring(1));
return getFixedTableNameList().get(idx);
}
/**
* @param Fixed table name
* @return the fixed table name config
*/
private GenericConvertMap<String, Object> getFixedTableConfig(String tableName) {
return getFixedTableFullConfigMap().getGenericConvertStringMap(tableName, "{}");
}
/**
* @param Fixed table name
*
* @return the object key set that the collumns support
*/
private Set<String> getFixedTableObjectKeySet(String tableName) {
return getFixedTableConfig(tableName).keySet();
}
/**
* @param Fixed table name
* @param the object key name
*
* @return the collumn config used, normalized as a map - throws exception if config does not exist
*/
private GenericConvertMap<String, Object> getFixedTableCollumnConfig(String tableName,
String objectKey) {
// Get table specific config
GenericConvertMap<String, Object> tableConfig = getFixedTableConfig(tableName);
// Check for collumn setting
if (tableConfig.get(objectKey) == null) {
throw new RuntimeException("Missing valid '" + objectKey
+ "' config for fixed table setup with '" + tableName + "'");
}
// Lets try get it as a map first
GenericConvertMap<String, Object> res = tableConfig.getGenericConvertStringMap(objectKey,
null);
// Return it if not null
if (res != null) {
return res;
}
// Not stored as a map, assume a string instead, and remap it
res = new GenericConvertHashMap<>();
res.put("name", objectKey);
res.put("type", tableConfig.getString(objectKey));
// Return remapped config
return res;
}
/**
* @param Fixed table name
* @param the object key name
*
* @return the collumn name used
*/
private String getFixedTableCollumnName(String tableName, String objectKey) {
// Get collumn specific config - throws exception if config does not exist
GenericConvertMap<String, Object> collumnConfig = getFixedTableCollumnConfig(tableName,
objectKey);
// Ge the collumn name
String name = collumnConfig.getString("name");
// Validate, and return
if (name == null || name.length() <= 0) {
throw new RuntimeException("Missing valid collumn name config for '" + objectKey
+ "' within fixed table setup of '" + tableName + "'");
}
return name;
}
/**
* @param Fixed table name
* @param the object key name
*
* @return the collumn type used
*/
private String getFixedTableCollumnType(String tableName, String objectKey) {
// Get collumn specific config - throws exception if config does not exist
GenericConvertMap<String, Object> collumnConfig = getFixedTableCollumnConfig(tableName,
objectKey);
// Ge the collumn name
String type = collumnConfig.getString("type");
// Validate, and return
if (type == null || type.length() <= 0) {
throw new RuntimeException("Missing valid collumn type config for '" + objectKey
+ "' within fixed table setup of '" + tableName + "'");
}
return type;
}
/// Internal memoizer for `getFixedTableNamePrimaryKeyJoinSet`
private Set<String> _getFixedTableNamePrimaryKeyJoinSet = null;
/**
* @return Set of fixed table that requires primary key joins
*/
private Set<String> getFixedTableNamePrimaryKeyJoinSet() {
// Get from memoizer
if (_getFixedTableNamePrimaryKeyJoinSet != null) {
return _getFixedTableNamePrimaryKeyJoinSet;
}
// Boolean result if primary key joins is needed
Set<String> pkJoinSet = new HashSet<String>();
// Get the table names
List<String> tableNameSet = getFixedTableNameList();
// And iterate it
for (String tableName : tableNameSet) {
// Get the "_oid" collumn config, this also function as a quick config check
GenericConvertMap<String, Object> oidConfig = getFixedTableCollumnConfig(tableName, "_oid");
// Skip if primary key join is configured to be skipped
if (oidConfig.getBoolean("skipPrimaryKeyJoin", false)) {
continue;
}
// Build the result set
pkJoinSet.add(tableName);
}
// Return the result
_getFixedTableNamePrimaryKeyJoinSet = pkJoinSet;
return pkJoinSet;
}
//-----------------------------------------------------------------------------------------------
//
// _oid key set
//
//-----------------------------------------------------------------------------------------------
/**
* Query builder used to build the oID query, without where clause.
*
* Can be used either to return a collumn of oID, or a single row/collumn of "rcount",
* representing the number of rows.
*
* This take advantage of UNION for the fixed table, without joins.@interface
* This is not to be used together with the much larger complex joins
*/
private StringBuilder primaryKeyQueryBuilder(boolean isRcount) {
// The query string to build
StringBuilder queryStr = new StringBuilder();
// Get fixed table name set
Set<String> fixedTableNames = getFixedTableNamePrimaryKeyJoinSet();
//------------------------------------------------------------------
// If no fixed tablenames, return the heavily simplified query
// with only the primary table map
//------------------------------------------------------------------
// Perform simple primary key query if possible
if (fixedTableNames.size() <= 0) {
// Select clause
queryStr.append("SELECT ");
// Handle rcount mode
if (isRcount) {
queryStr.append("COUNT(*) AS rcount FROM ");
} else {
queryStr.append("oID FROM ");
}
// Primary table to query
queryStr.append(dataMap.primaryKeyTable);
// Return query string
return queryStr;
}
//------------------------------------------------------------------
// Complex fixed and dynamic query required here
//------------------------------------------------------------------
// oID collumn first
queryStr.append("SELECT oID FROM ").append(dataMap.primaryKeyTable).append("\n");
// Join the oid collumn for the resepctive tables
for (String tableName : fixedTableNames) {
queryStr.append("UNION \n");
queryStr.append("SELECT ").append(getFixedTableCollumnName(tableName, "_oid"));
queryStr.append(" AS oID FROM ").append(tableName).append(" \n");
}
// Row count would require a nested query of the oID,
// to be wrapped with the row count clause
if (isRcount) {
// lets build the wrapped query
StringBuilder queryWrap = new StringBuilder();
queryWrap.append("SELECT COUNT(*) AS rcount FROM (\n");
queryWrap.append(queryStr);
queryWrap.append(")");
// And return it wrapped
return queryWrap;
}
// Return the query string with oID
return queryStr;
}
/**
* Get and returns all the GUID's, note that due to its
* potential of returning a large data set, production use
* should be avoided.
*
* @return JSqlResult, with the oID collumn filled with result
*/
public JSqlResult getOidKeyJSqlResult() {
return dataMap.sqlObj.query(primaryKeyQueryBuilder(false).toString(), EmptyArray.OBJECT);
}
/**
* Get and returns all the GUID's, note that due to its
* potential of returning a large data set, production use
* should be avoided.
*
* @return set of keys
*/
public Set<String> getOidKeySet() {
// Get raw jsql result
JSqlResult r = getOidKeyJSqlResult();
// Convert it into a set
if (r == null || r.get("oID") == null) {
return new HashSet<String>();
}
return ListValueConv.toStringSet(r.getObjectList("oID"));
}
//-----------------------------------------------------------------------------------------------
//
// OrderBy string processing
//
//-----------------------------------------------------------------------------------------------
/**
* Sanatize the order by string, and places the field name as query arguments
*
* @param Raw order by string
*
* @return Order by function obj
**/
public static OrderBy<DataObject> getOrderByObject(String rawString) {
// Clear out excess whtiespace
rawString = rawString.trim().replaceAll("\\s+", " ");
if (rawString.length() <= 0) {
throw new RuntimeException("Unexpected blank found in OrderBy query : " + rawString);
}
return new OrderBy<DataObject>(rawString);
}
//-----------------------------------------------------------------------------------------------
//
// Query Builder Utils
//
//-----------------------------------------------------------------------------------------------
/**
* Scan the given list of object key names and split the query plan between both
*
* @param List of object keys to be queries
*
* @return Split keyname set, with the first (left) used for dynamic keys, and right used for fixed tables
*/
private MutablePair<List<String>, List<String>> splitCollumnListForDynamicAndFixedQuery(
Collection<String> queryKeyNames) {
// List of object keys for fixed and dynamic tables respectively
Set<String> fixedKeyNames = new HashSet<String>();
Set<String> dynamicKeyNames = new HashSet<String>();
// Get fixed table name set
List<String> fixedTableNameSet = getFixedTableNameList();
// Lets process all the fixed table key names
//-----------------------------------------------
for (String tableName : fixedTableNameSet) {
// Get the keynames of the table
Set<String> tableKeyNameSet = getFixedTableObjectKeySet(tableName);
// Lets iterate each table key name
for (String tableKeyName : tableKeyNameSet) {
// if table key name is in the query, register it
if (queryKeyNames.contains(tableKeyName)) {
fixedKeyNames.add(tableKeyName);
}
}
}
// Lets process all the dynamic table key names
//-----------------------------------------------
for (String queryKey : queryKeyNames) {
// Check if its already handled in fixed tables
if (fixedKeyNames.contains(queryKey)) {
continue;
}
// Set it up as a dynamic key
dynamicKeyNames.add(queryKey);
}
// Coonvert set into list
List<String> fixedKeyNamesList = new ArrayList<String>();
List<String> dynamicKeyNamesList = new ArrayList<String>();
fixedKeyNamesList.addAll(fixedKeyNames);
dynamicKeyNamesList.addAll(dynamicKeyNames);
// Return result as mutable pair
return new MutablePair<>(dynamicKeyNamesList, fixedKeyNamesList);
}
//-----------------------------------------------------------------------------------------------
//
// Internal query builder
//
//-----------------------------------------------------------------------------------------------
/**
* Scan the query, for any OR/NOT clauses, which would need NULL values support.
* And populate its respective result `Set<String>` which is passed as the first param.
*
* This function operates recursively
*/
private void scanQueryForWhereClauseFields(Set<String> resSet, Query baseQuery) {
// Skip non combination query objects (they are handled elsewhere)
if (baseQuery == null || !baseQuery.isCombinationOperator()) {
return;
}
// Lets process the OR/NOT clause
QueryType type = baseQuery.type();
if (type == QueryType.OR || type == QueryType.NOT) {
// Get the field map, and add all the relevent fields
Map<String, List<Query>> fieldMap = baseQuery.fieldQueryMap();
resSet.addAll(fieldMap.keySet());
}
// Lets do a recursion scan
List<Query> childList = baseQuery.childrenQuery();
for (Query subQuery : childList) {
scanQueryForWhereClauseFields(resSet, subQuery);
}
}
/**
* Scan the given query keys, to deduce which collumn should have "NULL" support.
* Generating this set is important to ensure proper query support with NULL values.
*
* This works by scanning orderby clause, that does not have a corresponding equality check
* Or where clauses with inequality check / null equality check
*
* @param baseQuery being evaluated, to be scanned for OR clauses
* @param fieldQueryMap used to get the object key to sub query condition mapping
* @param set of raw order keys to scan
* @param set of raw where keys to scan
*
* @return key set where NULL support is needed
*/
private Set<String> extractCollumnsWhichMustSupportNullValues( //
Query baseQuery, //
Map<String, List<Query>> fieldQueryMap, //
Collection<String> rawOrderByClauseCollumns, //
Collection<String> rawWhereClauseCollumns //
) { //
// Prepare the return result
Set<String> keysWhichMustHandleNullValues = new HashSet<>();
// Scan for collumns within OR clauses
scanQueryForWhereClauseFields(keysWhichMustHandleNullValues, baseQuery);
// Process the order by string
if (rawOrderByClauseCollumns != null) {
for (String collumn : rawOrderByClauseCollumns) {
// Collumn names to skip setup (reseved keywords?)
if (collumn.equalsIgnoreCase("_oid") || collumn.equalsIgnoreCase("oID")) {
continue;
}
// There is no query / query map, so NULL must be supported
if (fieldQueryMap == null) {
keysWhichMustHandleNullValues.add(collumn);
continue;
}
// Check if any query is used with order by clause
List<Query> toReplaceQueries = fieldQueryMap.get(collumn);
// No query filtering was done, therefor, NULL must be suported
if (toReplaceQueries == null || toReplaceQueries.size() <= 0) {
keysWhichMustHandleNullValues.add(collumn);
continue;
}
for (Query subQuery : toReplaceQueries) {
// Check for inequality condition, where NULL must be supported
// @TODO consider optimizing != null handling
if (subQuery.operatorSymbol().equalsIgnoreCase("!=")) {
keysWhichMustHandleNullValues.add(collumn);
break;
}
// Check for equality condition, with NULL values
if (subQuery.operatorSymbol().equalsIgnoreCase("=")
&& subQuery.defaultArgumentValue() == null) {
keysWhichMustHandleNullValues.add(collumn);
break;
}
}
// There are equality checks, which would filter out NULL values
// therefor order by collumn is not added to the NULL support list
}
}
// For each collumnName in the collumnNameSet, scan for inequality check
// or equality with null check - to map its use case for "keysWhichMustHandleNullValues"
if (rawWhereClauseCollumns != null) {
for (String collumn : rawWhereClauseCollumns) {
// Collumn names to skip setup (reseved keywords?)
if (collumn.equalsIgnoreCase("_oid") || collumn.equalsIgnoreCase("oID")) {
continue;
}
// The query list to do processing on
List<Query> toReplaceQueries = fieldQueryMap.get(collumn);
// Skip if no query was found needed processing
if (toReplaceQueries == null || toReplaceQueries.size() <= 0) {
continue;
}
// Check for inequality condition, where NULL must be supported
for (Query subQuery : toReplaceQueries) {
// Check for inequality condition, where NULL must be supported
// @TODO consider optimizing != null handling
if (subQuery.operatorSymbol().equalsIgnoreCase("!=")) {
keysWhichMustHandleNullValues.add(collumn);
break;
}
// Check for equality condition, with NULL values
if (subQuery.operatorSymbol().equalsIgnoreCase("=")
&& subQuery.defaultArgumentValue() == null) {
keysWhichMustHandleNullValues.add(collumn);
break;
}
}
}
}
// The keys to support
return keysWhichMustHandleNullValues;
}
/**
* Given the dynamic/fixed object keys, and it sequence -
* generate out the table alias map.
*/
private Map<String, String> generateCollumnTableAliasMap( //
List<String> dynamicTableKeys, //
List<String> fixedTableKeys //
) { //
// alias mapping of the collumn names (the result)
Map<String, String> objectKeyTableAliasMap = new HashMap<>();
// Dynamic table keys handling
//-------------------------------------------------------------------
for (int i = 0; i < dynamicTableKeys.size(); ++i) {
// Get the keyname
String keyName = dynamicTableKeys.get(i);
// Collumn names to skip setup (reseved keywords?)
if (keyName.equalsIgnoreCase("_oid") || keyName.equalsIgnoreCase("oID")) {
continue;
}
// collumn names that requires setup
objectKeyTableAliasMap.put(keyName, "D" + i);
}
// Fixed table keys handling
//-------------------------------------------------------------------
// Get fixed table name set
List<String> fixedTableNameList = getFixedTableNameList();
// And iterate all the fixed tables in sequence
for (int i = 0; i < fixedTableNameList.size(); ++i) {
// Get the table name
String tableName = fixedTableNameList.get(i);
// Get the keynames of the table
Set<String> tableKeyNameSet = getFixedTableObjectKeySet(tableName);
// Lets iterate each table key name
for (String tableKeyName : tableKeyNameSet) {
// if table key name is in the query, register it
if (fixedTableKeys.indexOf(tableKeyName) >= 0) {
// collumn names that requires setup
objectKeyTableAliasMap.put(tableKeyName, "F" + i);
}
}
}
// Return result
return objectKeyTableAliasMap;
}
/**
* Lets build the core inner join query string,
* given the required filtered collumn names.
*
* This is appended to the "SELECT DP.oID FROM" statement
*
* Its expected result without any collumns provided would be
*
* ```
* ```
*
* Alternatively, if collumn names are provided (as part of the WHERE / ORDER BY clause),
* it will generate an additional inner join line
*
* ```
* INNER JOIN (SELECT oID, nVl, sVl, tVl FROM DD_TABLENAME WHERE kID="softDelete") AS D0 ON (DP.oID = D0.oID)
* INNER JOIN (SELECT oID, nVl, sVl, tVl FROM DD_TABLENAME WHERE kID="sourceOfLead") AS D1 ON (DP.oID = D1.oID)
* ```
*
* @param collumns that is needed, in the given order
* @param collumnWhichMustHandleNullValues to perform left join, instead of inner join, to support NULL values
*
* @return pair of query string, with query args
*/
private MutablePair<StringBuilder, List<Object>> dynamicTableJoinBuilder(List<String> collumns,
Set<String> collumnWhichMustHandleNullValues) {
// Settings needed from main DataObjectMap
String primaryKeyTable = dataMap.primaryKeyTable;
String dataStorageTable = dataMap.dataStorageTable;
// The query string to build
StringBuilder queryStr = new StringBuilder();
List<Object> queryArg = new ArrayList<>();
// Add table name to join from first
// queryStr.append(primaryKeyTable).append(" AS DP \n");
// No collumns required (fast ending)
if (collumns == null || collumns.size() <= 0) {
return new MutablePair<>(queryStr, queryArg);
}
// For each collumn that is required, perform an inner join
// where applicable, skipping left join.
//
// This represents the more "optimized" joins
for (int i = 0; i < collumns.size(); ++i) {
// Get the collumn name
String collumnName = collumns.get(i);
// Skip the "LEFT JOIN" collumn
if (collumnWhichMustHandleNullValues.contains(collumnName)) {
continue;
}
// Single collumn "INNER JOIN"
queryStr.append("INNER JOIN (SELECT oID, nVl, sVl, tVl FROM ").append(dataStorageTable) //
.append(" WHERE kID=? AND idx=?) AS D" + i + " ON (") //
.append("DP.oID = D" + i + ".oID) \n");
// With arguments
queryArg.add(collumnName);
queryArg.add(0);
}
// Perform the much slower (expensive) inner join
for (int i = 0; i < collumns.size(); ++i) {
// Get the collumn name
String collumnName = collumns.get(i);
// Skip the "INNER JOIN" collumn
if (!collumnWhichMustHandleNullValues.contains(collumnName)) {
continue;
}
// Single collumn "LEFT JOIN"
queryStr.append("LEFT JOIN (SELECT oID, nVl, sVl, tVl FROM ").append(dataStorageTable) //
.append(" WHERE kID=? AND idx=?) AS D" + i + " ON (") //
.append("DP.oID = D" + i + ".oID) \n");
// With arguments
queryArg.add(collumnName);
queryArg.add(0);
}
// Return the full query
return new MutablePair<>(queryStr, queryArg);
}
/**
* Lets build the fixed table outer join query string,
* given the required filtered collumn names.
*
* This is designed to be appended to the dynamic table query,
* and is not designed to be used alone.
*
* Its expected result without any collumns provided would be blank
*
* ```
* ```
*
* Alternatively, if collumn names are provided (as part of the WHERE / ORDER BY clause),
* it will generate an additional outer join line
*
* ```
* LEFT JOIN FIXED_TABLE_A AS F0 ON DP.oID = F0.oID
* LEFT JOIN FIXED_TABLE_B AS F1 ON DP.oID = F1.oID
* ```
*
* @param collumns that is needed, in the given order
* @param collumnWhichMustHandleNullValues to perform left join, instead of inner join, to support NULL values
*
* @return pair of query string, with query args
*/
private MutablePair<StringBuilder, List<Object>> fixedTableJoinBuilder(List<String> collumns,
Set<String> collumnWhichMustHandleNullValues) {
// The query string to build
StringBuilder queryStr = new StringBuilder();
List<Object> queryArg = new ArrayList<>();
// Fixed table keys handling
//-------------------------------------------------------------------
// Get fixed table name set
List<String> fixedTableNameList = getFixedTableNameList();
// And iterate all the fixed tables in sequence
for (int i = 0; i < fixedTableNameList.size(); ++i) {
// Get the table name
String tableName = fixedTableNameList.get(i);
// Get the keynames of the table
Set<String> tableKeyNameSet = getFixedTableObjectKeySet(tableName);
// Indicate if the fixed table is the be queried
boolean includeFixedTable = false;
// Lets iterate the collumn names
for (String objKey : collumns) {
if (tableKeyNameSet.contains(objKey)) {
includeFixedTable = true;
break;
}
}
// Skip current table if tis not needed
if (!includeFixedTable) {
break;
}
// OK - assume the current table needs to be include, build the query
queryStr.append("LEFT JOIN ").append(tableName); //
queryStr.append(" AS F" + i + " ON DP.oID = F0."
+ getFixedTableCollumnName(tableName, "_oid")); //
queryStr.append("\n");
}
// Return the full query
return new MutablePair<>(queryStr, queryArg);
}
/**
* Given the where clause query object, rewrite it to query against the joint dynamic table used internally.
*
* This replaces the respective "object key" with the "TABLE_ALIAS.s/n/tVl" respectively.
*
* @param query object to rewrite (and return)
* @param field to query mapping
* @param arg name to arg value mapping
* @param object key to table alias name mapping
* @param list of dynamic keys to handle
*
* @return rewritten queryObj
*/
private Query dynamicTableQueryRewrite( //
Query queryObj, Map<String, List<Query>> fieldQueryMap, //
Map<String, Object> queryArgMap, //
Map<String, String> objectKeyTableAliasMap, //
List<String> dynamicKeyNames //
) {
// Lets iterate the dynamic key names
// and rewrite each ddynamic key
for (String collumn : dynamicKeyNames) {
// The query list to do processing on
List<Query> toReplaceQueries = fieldQueryMap.get(collumn);
// Skip if no query was found needed processing
if (toReplaceQueries == null || toReplaceQueries.size() <= 0) {
continue;
}
// Special handling for _oid
if (collumn.equalsIgnoreCase("_oid") || collumn.equals("oID")) {
// Scan for the query to remap to DP.oID
for (Query toReplace : toReplaceQueries) {
Query replacement = QueryFilter.basicQueryFromTokens(
//
queryArgMap, "DP.oID", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
// Replaces old query with new query
queryObj = queryObj.replaceQuery(toReplace, replacement);
}
continue;
}
// Get the replacment table alias
String collumnTableAlias = objectKeyTableAliasMap.get(collumn);
// Scan for the query to perform replacements
for (Query toReplace : toReplaceQueries) {
// Get the argument
Object argObj = queryArgMap.get(toReplace.argumentName());
// Setup the replacement query
Query replacement = null;
if (argObj == null) {
// Does special NULL handling
replacement = QueryFilter.basicQueryFromTokens(queryArgMap, collumnTableAlias
+ ".sVl", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
//
// Lets do special SQL condition overwriting
// to properly support null equality checks
//
// This works around known limitations of SQL
// requiring NULL checks as the "IS NULL" or "IS NOT NULL"
// varient
//
// https://www.tutorialspoint.com/sql/sql-null-values.htm#:~:text=The%20SQL%20NULL%20is%20the,a%20field%20that%20contains%20spaces.
//
if (toReplace.operatorSymbol().equalsIgnoreCase("!=")) {
replacement = new JSql_QueryStringOverwrite( //
replacement, // The replacement query, in case is still needed
"(" + collumnTableAlias + ".sVl IS NOT NULL OR " + replacement.toString()
+ ")");
} else if (toReplace.operatorSymbol().equalsIgnoreCase("=")) {
replacement = new JSql_QueryStringOverwrite( //
replacement, // The replacement query, in case is still needed
"(" + collumnTableAlias + ".sVl IS NULL OR " + replacement.toString() + ")");
}
} else if (argObj instanceof Number) {
// Does special numeric handling
replacement = QueryFilter.basicQueryFromTokens(queryArgMap, collumnTableAlias
+ ".nVl", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
} else if (argObj instanceof String) {
if (toReplace.operatorSymbol().equalsIgnoreCase("LIKE")) {
// Like operator maps to tVl
replacement = QueryFilter.basicQueryFromTokens(queryArgMap, collumnTableAlias
+ ".tVl", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
} else {
// Else it maps to sVl, with applied limits
replacement = QueryFilter.basicQueryFromTokens(queryArgMap, collumnTableAlias
+ ".sVl", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
// Update the argument with limits
queryArgMap.put(toReplace.argumentName(),
JSql_DataObjectMapUtil.shortenStringValue(argObj.toString()));
//
// Special handling of != once again
// due to SQL quirk with NULL values
//
// `col != "value"`, is remapped as
// `col != "value" OR col IS NULL`
//
if (toReplace.operatorSymbol().equalsIgnoreCase("!=")) {
replacement = new JSql_QueryStringOverwrite( //
replacement, // The replacement query, in case is still needed
"(" + collumnTableAlias + ".sVl IS NULL OR " + replacement.toString() + ")");
}
}
} else if (argObj instanceof Boolean) {
// note that due to a bug in dstack before 26 Aug 2024,
// ... all boolean values were stored as json (Core_DataType.JSON, 31)
// ...thus entry is stored with the values: nVl = NULL, sVL = null, tVl = "true" or "false"
// ... thus, for boolean, we need to query against tVl to support legacy values
// ... this bug has been fixed in newer versions of dstack...
// ... where the entry is stored with the values: nVl = 1 or 0, sVL = "true" or "false", tVl = "true" or "false"
replacement = QueryFilter.basicQueryFromTokens(queryArgMap, collumnTableAlias
+ ".tVl", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
}
// Unprocessed arg type
if (replacement == null) {
throw new RuntimeException("Unexpeced query argument (unknown type) : " + argObj);
}
// Replaces old query with new rewritten query
queryObj = queryObj.replaceQuery(toReplace, replacement);
}
}
return queryObj;
}
/**
* Given the where clause query object, rewrite it to query against the joint fixed table used internally.
*
* This replaces the respective "object key" with the "TABLE_ALIAS.collumn_name" respectively.
*
* @param query object to rewrite (and return)
* @param field to query mapping
* @param arg name to arg value mapping
* @param object key to table alias name mapping
* @param list of dynamic keys to handle
*
* @return rewritten queryObj
*/
private Query fixedTableQueryRewrite( //
Query queryObj, Map<String, List<Query>> fieldQueryMap, //
Map<String, Object> queryArgMap, //
Map<String, String> objectKeyTableAliasMap, //
List<String> fixedKeyNames //
) {
// Lets iterate the fixed table key names
// and rewrite each object key
for (String collumn : fixedKeyNames) {
// The query list to do processing on
List<Query> toReplaceQueries = fieldQueryMap.get(collumn);
// Skip if no query was found needed processing
if (toReplaceQueries == null || toReplaceQueries.size() <= 0) {
continue;
}
// Special handling for _oid
if (collumn.equalsIgnoreCase("_oid") || collumn.equals("oID")) {
// Scan for the query to remap to DP.oID
for (Query toReplace : toReplaceQueries) {
Query replacement = QueryFilter.basicQueryFromTokens(
//
queryArgMap, "DP.oID", toReplace.operatorSymbol(), ":" + toReplace.argumentName() //
);
// Replaces old query with new query
queryObj = queryObj.replaceQuery(toReplace, replacement);
}
continue;
}
// Get the replacment table alias
String collumnTableAlias = objectKeyTableAliasMap.get(collumn);
String fixedTableName = getFixedTableNameFromAlias(collumnTableAlias);
String fixedTableCollumnName = getFixedTableCollumnName(fixedTableName, collumn);
// Scan for the query to perform replacements