Repository navigation
Expand file tree
/
Copy pathijq.java
More file actions
1103 lines (933 loc) · 43.9 KB
/
Copy pathijq.java
File metadata and controls
1103 lines (933 loc) · 43.9 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
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.aesh:aesh:3.18.0 org.aesh:readline:3.18.0
//DEPS com.google.code.gson:gson:2.14.0
//JAVA 17+
import org.aesh.AeshConsoleRunner;
import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandResult;
import org.aesh.command.impl.completer.FileOptionCompleter;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Arguments;
import org.aesh.command.option.Option;
import org.aesh.command.settings.Settings;
import org.aesh.command.settings.SettingsBuilder;
import org.aesh.readline.prompt.Prompt;
import com.google.gson.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Interactive JSON Query Shell - A shell-like tool for querying JSON data
*/
public class ijq {
static SelectionManager selectionManager = new SelectionManager();
static AeshConsoleRunner runner;
public static void main(String[] args) throws Exception {
// Print welcome message
System.out.println("Interactive JSON Query Shell (ijq)");
System.out.println("Type 'help' for available commands, 'exit' to quit");
System.out.println();
// Process command line arguments if any
if (args.length > 0) {
// TODO: Handle command line arguments for initial loading
}
Settings settings = SettingsBuilder.builder()
.promptSupplier(() -> Prompt.builder().line(selectionManager.getPrompt()).build())
.enableExport(false)
.build();
AeshConsoleRunner.builder()
.command(PrintCommand.class)
.command(LoadCommand.class)
.command(ScanCommand.class)
.command(SelectCommand.class)
.command(SetCommand.class)
.command(UseCommand.class)
.command(ListCommand.class)
.command(HelpCommand.class)
.addExitCommand().settings(settings)
.start();
}
// ==================== Data Model ====================
/**
* Interface for JSON items that can be lazy-loaded
*/
interface JsonItem {
JsonElement getValue();
Path getOrigin();
}
/**
* Lazy-loaded JSON item from a file
*/
static class LazyJsonItem implements JsonItem {
private final Path origin;
private JsonElement value;
private boolean loaded = false;
public LazyJsonItem(Path origin) {
this.origin = origin;
}
@Override
public JsonElement getValue() {
if (!loaded) {
try {
String content = Files.readString(origin);
value = JsonParser.parseString(content);
loaded = true;
} catch (IOException e) {
throw new RuntimeException("Failed to load JSON from: " + origin, e);
}
}
return value;
}
@Override
public Path getOrigin() {
return origin;
}
}
/**
* Direct JSON item without file origin
*/
static class DirectJsonItem implements JsonItem {
private final JsonElement value;
public DirectJsonItem(JsonElement value) {
this.value = value;
}
@Override
public JsonElement getValue() {
return value;
}
@Override
public Path getOrigin() {
return null;
}
}
/**
* Represents a selection of JSON items
*/
static class Selection {
private final String id;
private final List<JsonItem> items;
public Selection(String id, List<JsonItem> items) {
this.id = id;
this.items = new ArrayList<>(items);
}
public String getId() {
return id;
}
public List<JsonItem> getItems() {
return items;
}
public int size() {
return items.size();
}
public String toString() {
return id + "[#" + items.size() + "]";
}
}
/**
* Manages selections and their IDs
*/
static class SelectionManager {
private final Map<String, Selection> selections = new LinkedHashMap<>();
private int nextId = 1;
private String currentId = null;
public SelectionManager() {
// Initialize with empty selection
createSelection(new ArrayList<>());
}
public Selection createSelection(List<JsonItem> items) {
String id = "$" + nextId++;
Selection selection = new Selection(id, items);
selections.put(id, selection);
selections.put("$$", selection); // Always update current alias
currentId = id;
return selection;
}
public Selection getCurrentSelection() {
return selections.get(currentId);
}
public Selection getSelection(String id) {
if (id == null || id.equals("$$")) {
return getCurrentSelection();
}
return selections.get(id);
}
public void setNamedSelection(String name, Selection source) {
if (name.matches("\\$\\d+")) {
throw new IllegalArgumentException("Cannot use numbered IDs for named selections");
}
selections.put(name, new Selection(name, source.getItems()));
currentId = name;
selections.put("$$", selections.get(name));
}
public void setCurrentSelection(String id) {
Selection sel = selections.get(id);
if (sel == null) {
throw new IllegalArgumentException("Selection not found: " + id);
}
currentId = id;
selections.put("$$", sel);
}
public String getPrompt() {
Selection current = getCurrentSelection();
return String.format("\u001B[32m%s>\u001B[0m ", current);
}
}
// ==================== Commands ====================
@CommandDefinition(name = "print", description = "Print all currently selected items")
public static class PrintCommand implements Command {
@Option(name = "details", shortName = 'd', hasValue = false,
description = "Include origin information for each item")
private boolean details;
@Arguments(arity = "0..*", description = "Optional TOP/LIMIT/WHERE clauses (same syntax as select)")
private List<String> args;
@Override
public CommandResult execute(CommandInvocation invocation) {
Selection current = selectionManager.getCurrentSelection();
List<JsonItem> items = current.getItems();
if (args != null && !args.isEmpty()) {
String query = String.join(" ", args);
try {
// Use a temporary, implicit SELECT to apply the same
// TOP/LIMIT/WHERE clauses, without creating a new selection.
SelectQuery selectQuery = SelectQueryParser.parse(query);
items = selectQuery.execute(items);
} catch (Exception e) {
invocation.println("Error executing query: " + e.getMessage());
return CommandResult.FAILURE;
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonArray array = new JsonArray();
for (JsonItem item : items) {
if (details) {
JsonObject wrapper = new JsonObject();
wrapper.add("value", item.getValue());
Path origin = item.getOrigin();
wrapper.addProperty("origin", origin != null ? origin.toString() : null);
array.add(wrapper);
} else {
array.add(item.getValue());
}
}
invocation.println(gson.toJson(array));
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "load", description = "Load JSON from a file")
public static class LoadCommand implements Command {
@Argument(description = "Path to JSON file", required = true)
private Path path;
@Override
public CommandResult execute(CommandInvocation invocation) {
if (!Files.exists(path)) {
invocation.println("Error: File not found: " + path);
return CommandResult.FAILURE;
}
if (!Files.isRegularFile(path)) {
invocation.println("Error: Not a file: " + path);
return CommandResult.FAILURE;
}
try {
JsonItem json = new LazyJsonItem(path);
JsonElement element = json.getValue();
List<JsonItem> items = new ArrayList<>();
if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
for (JsonElement elem : array) {
items.add(new DirectJsonItem(elem));
}
} else {
items.add(json);
}
Selection newSelection = selectionManager.createSelection(items);
invocation.println("Loaded " + items.size() + " item(s) into " + newSelection.getId());
} catch (JsonSyntaxException e) {
invocation.println("Error parsing JSON: " + e.getMessage());
return CommandResult.FAILURE;
}
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "scan", description = "Scan and load JSON files matching a pattern")
public static class ScanCommand implements Command {
@Argument(description = "Path pattern (supports globbing)", required = true, completer = FileOptionCompleter.class)
private String path;
private static boolean containsGlobbing(String str) {
return str.contains("*") || str.contains("?") ||
str.contains("[") || str.contains("]") ||
str.contains("{") || str.contains("}");
}
@Override
public CommandResult execute(CommandInvocation invocation) {
String pattern = path.toString();
List<JsonItem> items = new ArrayList<>();
Path startPath;
String globPattern;
// Check if pattern contains any globbing characters
if (!containsGlobbing(pattern)) {
// No globbing - treat as directory path and append **/*.json for recursive scan
startPath = Paths.get(pattern);
String normalizedPattern = pattern.replaceAll("\\\\", "/");
// Handle trailing path separator
normalizedPattern = normalizedPattern.endsWith("/")
? normalizedPattern.substring(0, normalizedPattern.length() - 1)
: normalizedPattern;
globPattern = normalizedPattern + "/**.json";
} else {
// Pattern contains globbing - find longest prefix without globbing
String separator = pattern.contains("/") ? "/" : "\\";
String[] parts = pattern.split("[/\\\\]");
StringBuilder prefixBuilder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (containsGlobbing(parts[i])) {
break;
}
if (i > 0) {
prefixBuilder.append(separator);
}
prefixBuilder.append(parts[i]);
}
String prefix = prefixBuilder.toString();
if (prefix.isEmpty()) {
startPath = Paths.get(".");
} else {
startPath = Paths.get(prefix);
}
globPattern = pattern;
}
if (!Files.exists(startPath)) {
invocation.println("Error: Base path does not exist: " + startPath);
return CommandResult.FAILURE;
}
// Normalize the glob pattern to use forward slashes for cross-platform compatibility
// TODO: we should be careful, because the user could be using backslashes to escape
// globbing characters. So perhaps we should have improved heuristics, something like:
// if there are any forward slashes any backslash is very likely to be used to escape
// the next character. But what if there are none? Something like "data\*.json" is
// very likely to be a path, but can we think of a heuristic that will work in most
// situations?
String normalizedGlobPattern = globPattern.replace("\\", "/");
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + normalizedGlobPattern);
try (Stream<Path> paths = Files.walk(startPath)) {
List<Path> matchedPaths = paths
.filter(Files::isRegularFile)
.filter(p -> matcher.matches(p))
.collect(Collectors.toList());
for (Path path : matchedPaths) {
items.add(new LazyJsonItem(path));
}
} catch (IOException e) {
invocation.println("Error scanning files: " + e.getMessage());
return CommandResult.FAILURE;
}
Selection newSelection = selectionManager.createSelection(items);
invocation.println("Scanned " + items.size() + " file(s) into " + newSelection.getId());
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "select", description = "Filter and transform the current selection")
public static class SelectCommand implements Command {
@Arguments(arity = "0..*", description = "SELECT query (e.g., 'select * where field = value')")
private List<String> args;
@Override
public CommandResult execute(CommandInvocation invocation) {
if (args == null || args.isEmpty()) {
invocation.println("Error: Please provide a SELECT query");
return CommandResult.FAILURE;
}
String query = String.join(" ", args);
try {
SelectQuery selectQuery = SelectQueryParser.parse(query);
Selection current = selectionManager.getCurrentSelection();
List<JsonItem> results = selectQuery.execute(current.getItems());
Selection newSelection = selectionManager.createSelection(results);
invocation.println("Selected " + results.size() + " item(s) into " + newSelection.getId());
} catch (Exception e) {
invocation.println("Error executing query: " + e.getMessage());
return CommandResult.FAILURE;
}
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "set", description = "Name a selection")
public static class SetCommand implements Command {
@Arguments(arity = "0..*", description = "SET command (e.g., 'set $mydata = $1' or 'set $mydata')")
private List<String> args;
@Override
public CommandResult execute(CommandInvocation invocation) {
if (args == null || args.isEmpty()) {
invocation.println("Error: Please provide a SET command");
return CommandResult.FAILURE;
}
String command = String.join(" ", args);
try {
if (command.contains("=")) {
// set $X = $Y
String[] parts = command.split("=");
if (parts.length != 2) {
invocation.println("Error: Invalid SET syntax");
return CommandResult.FAILURE;
}
String targetId = parts[0].trim();
String sourceId = parts[1].trim();
if (!targetId.startsWith("$") || !sourceId.startsWith("$")) {
invocation.println("Error: Selection IDs must start with $");
return CommandResult.FAILURE;
}
Selection source = selectionManager.getSelection(sourceId);
if (source == null) {
invocation.println("Error: Source selection not found: " + sourceId);
return CommandResult.FAILURE;
}
selectionManager.setNamedSelection(targetId, source);
invocation.println("Set " + targetId + " = " + sourceId +
" (" + source.size() + " items)");
} else {
// set $X - associate name with current selection
String targetId = command.trim();
if (!targetId.startsWith("$")) {
invocation.println("Error: Selection ID must start with $");
return CommandResult.FAILURE;
}
Selection current = selectionManager.getCurrentSelection();
selectionManager.setNamedSelection(targetId, current);
invocation.println("Set " + targetId + " = " + current.getId() +
" (" + current.size() + " items)");
}
} catch (IllegalArgumentException e) {
invocation.println("Error: " + e.getMessage());
return CommandResult.FAILURE;
}
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "use", description = "Switch to a named or numbered selection")
public static class UseCommand implements Command {
@Arguments(arity = "0..*", description = "Selection ID to switch to (e.g., 'use $mydata' or 'use $1')")
private List<String> args;
@Override
public CommandResult execute(CommandInvocation invocation) {
if (args == null || args.isEmpty()) {
invocation.println("Error: Please provide a selection ID");
return CommandResult.FAILURE;
}
String targetId = args.get(0).trim();
if (!targetId.startsWith("$")) {
invocation.println("Error: Selection ID must start with $");
return CommandResult.FAILURE;
}
try {
selectionManager.setCurrentSelection(targetId);
Selection current = selectionManager.getCurrentSelection();
invocation.println("Switched to " + targetId + " (" + current.size() + " items)");
} catch (IllegalArgumentException e) {
invocation.println("Error: " + e.getMessage());
return CommandResult.FAILURE;
}
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "list", description = "List all selections")
public static class ListCommand implements Command {
@Option(name = "all", shortName = 'a', hasValue = false,
description = "Show all selections including numeric ones")
private boolean showAll;
@Override
public CommandResult execute(CommandInvocation invocation) {
Map<String, Selection> selections = selectionManager.selections;
invocation.println("Available selections:");
invocation.println("");
boolean foundAny = false;
for (Map.Entry<String, Selection> entry : selections.entrySet()) {
String id = entry.getKey();
Selection selection = entry.getValue();
// Skip $$ alias as it's just a pointer to current
if (id.equals("$$")) {
continue;
}
// Skip numeric IDs unless -a flag is set
if (!showAll && id.matches("\\$\\d+")) {
continue;
}
String currentMarker = id.equals(selectionManager.currentId) ? " (current)" : "";
invocation.println(String.format(" %s%s", selection, currentMarker));
foundAny = true;
}
if (!foundAny) {
if (showAll) {
invocation.println(" No selections available");
} else {
invocation.println(" No named selections available");
invocation.println(" Use 'list -a' to show all selections including numeric ones");
}
}
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "help", description = "Show help information")
public static class HelpCommand implements Command {
@Override
public CommandResult execute(CommandInvocation invocation) {
invocation.println("Interactive JSON Query Shell (ijq)");
invocation.println("=================================");
invocation.println("");
invocation.println("COMMANDS:");
invocation.println("");
invocation.println(" print [-d] [TOP/LIMIT/WHERE clauses]");
invocation.println(" Print items in the current selection");
invocation.println(" -d : Include origin information for each item");
invocation.println(" Supports the same TOP, LIMIT and WHERE clauses as select:");
invocation.println(" print top 10");
invocation.println(" print where field = 'value'");
invocation.println(" print limit 5,10 where field > 100");
invocation.println("");
invocation.println(" load <path>");
invocation.println(" Load JSON from a file. If the file contains an array,");
invocation.println(" each element becomes an item. Otherwise, the entire");
invocation.println(" content becomes a single item.");
invocation.println("");
invocation.println(" scan <pattern>");
invocation.println(" Scan for JSON files matching a glob pattern.");
invocation.println(" Each matched file becomes an item (lazy-loaded).");
invocation.println(" Example: scan db/metadata/**/*.json");
invocation.println("");
invocation.println(" select <query>");
invocation.println(" Filter and transform the current selection using SQL-like syntax.");
invocation.println(" Examples:");
invocation.println(" select *");
invocation.println(" select field1, field2");
invocation.println(" select {field1, field2 as name}");
invocation.println(" select * where field = 'value'");
invocation.println(" select top 10 *");
invocation.println(" select limit 5,10 * where field > 100");
invocation.println("");
invocation.println(" set <command>");
invocation.println(" Manage named selections:");
invocation.println(" set $name = $1 : Create/update named selection from $1");
invocation.println(" set $name : Name the current selection");
invocation.println("");
invocation.println(" use $name");
invocation.println(" Switch to a named or numbered selection, making it current");
invocation.println("");
invocation.println(" list [-a]");
invocation.println(" List all named selections");
invocation.println(" -a : Show all selections including numeric ones ($1, $2, etc.)");
invocation.println("");
invocation.println(" exit");
invocation.println(" Exit the shell");
invocation.println("");
invocation.println("SELECTIONS:");
invocation.println(" Each operation creates a new selection with an ID: $1, $2, $3, ...");
invocation.println(" $$ always refers to the current/latest selection");
invocation.println(" The prompt shows: <selection-id>[#<item-count>]>");
invocation.println("");
return CommandResult.SUCCESS;
}
}
// ==================== Query Parser and Executor ====================
static class SelectQuery {
boolean selectAll = false;
List<FieldSelection> fields = new ArrayList<>();
WhereClause whereClause = null;
Integer limitOffset = null;
Integer limitCount = null;
public List<JsonItem> execute(List<JsonItem> items) {
List<JsonItem> result = new ArrayList<>(items);
// Apply WHERE clause
if (whereClause != null) {
result = result.stream()
.filter(item -> whereClause.evaluate(item.getValue()))
.collect(Collectors.toList());
}
// Apply LIMIT
if (limitOffset != null || limitCount != null) {
int offset = limitOffset != null ? limitOffset : 0;
int count = limitCount != null ? limitCount : result.size();
result = result.stream()
.skip(offset)
.limit(count)
.collect(Collectors.toList());
}
// Apply field selection
if (!selectAll && !fields.isEmpty()) {
result = result.stream()
.map(item -> {
JsonElement value = item.getValue();
if (!value.isJsonObject()) {
return new DirectJsonItem(JsonNull.INSTANCE);
}
JsonObject obj = value.getAsJsonObject();
if (fields.size() == 1 && fields.get(0).alias == null) {
// Single field without alias - return the value directly
String fieldName = fields.get(0).name;
JsonElement fieldValue = obj.get(fieldName);
return new DirectJsonItem(fieldValue != null ? fieldValue : JsonNull.INSTANCE);
} else {
// Multiple fields or aliased field - return object
JsonObject newObj = new JsonObject();
for (FieldSelection field : fields) {
JsonElement fieldValue = obj.get(field.name);
if (fieldValue != null) {
String outputName = field.alias != null ? field.alias : field.name;
newObj.add(outputName, fieldValue);
}
}
return new DirectJsonItem(newObj);
}
})
.collect(Collectors.toList());
}
return result;
}
}
static class FieldSelection {
String name;
String alias;
public FieldSelection(String name, String alias) {
this.name = name;
this.alias = alias;
}
}
static class WhereClause {
private final Expression expression;
public WhereClause(Expression expression) {
this.expression = expression;
}
public boolean evaluate(JsonElement element) {
return expression.evaluate(element);
}
}
interface Expression {
boolean evaluate(JsonElement element);
}
static class ComparisonExpression implements Expression {
String field;
String operator;
String value;
boolean valueIsNull;
public ComparisonExpression(String field, String operator, String value) {
this(field, operator, value, false);
}
public ComparisonExpression(String field, String operator, String value, boolean valueIsNull) {
this.field = field;
this.operator = operator;
this.value = value;
this.valueIsNull = valueIsNull;
}
@Override
public boolean evaluate(JsonElement element) {
JsonElement fieldValue;
if (field.equals("*")) {
// '*' refers to the item's own value, so comparisons work even
// after a single-field projection turned items into literals
// (e.g. numbers/strings/null) rather than JSON objects.
fieldValue = element;
} else {
if (!element.isJsonObject()) {
return false;
}
JsonObject obj = element.getAsJsonObject();
fieldValue = obj.get(field);
}
boolean fieldIsNull = fieldValue == null || fieldValue.isJsonNull();
if (valueIsNull) {
// Comparing against the null literal: only equality/inequality
// are meaningful (already validated at parse time).
return operator.equals("=") ? fieldIsNull : !fieldIsNull;
}
if (fieldIsNull) {
// A missing/null field cannot equal any given non-null value,
// but it is considered not-equal ('<>') to it.
return operator.equals("<>");
}
String fieldStr = fieldValue.isJsonPrimitive() ?
fieldValue.getAsString() : fieldValue.toString();
return switch (operator) {
case "=" -> fieldStr.equals(value);
case "<>" -> !fieldStr.equals(value);
case ">" -> compareNumeric(fieldStr, value) > 0;
case "<" -> compareNumeric(fieldStr, value) < 0;
case ">=" -> compareNumeric(fieldStr, value) >= 0;
case "<=" -> compareNumeric(fieldStr, value) <= 0;
case "contains" -> fieldStr.contains(value);
default -> false;
};
}
private int compareNumeric(String a, String b) {
try {
double aNum = Double.parseDouble(a);
double bNum = Double.parseDouble(b);
return Double.compare(aNum, bNum);
} catch (NumberFormatException e) {
return a.compareTo(b);
}
}
}
static class LogicalExpression implements Expression {
Expression left;
String operator; // "and", "or"
Expression right;
public LogicalExpression(Expression left, String operator, Expression right) {
this.left = left;
this.operator = operator;
this.right = right;
}
@Override
public boolean evaluate(JsonElement element) {
if (operator.equalsIgnoreCase("and")) {
return left.evaluate(element) && right.evaluate(element);
} else if (operator.equalsIgnoreCase("or")) {
return left.evaluate(element) || right.evaluate(element);
}
return false;
}
}
static class NotExpression implements Expression {
Expression expression;
public NotExpression(Expression expression) {
this.expression = expression;
}
@Override
public boolean evaluate(JsonElement element) {
return !expression.evaluate(element);
}
}
static class SelectQueryParser {
public static SelectQuery parse(String query) {
SelectQuery sq = new SelectQuery();
String[] tokens = tokenize(query);
int pos = 0;
// Check for TOP or LIMIT
if (pos < tokens.length && tokens[pos].equalsIgnoreCase("top")) {
pos++;
if (pos >= tokens.length) {
throw new IllegalArgumentException("Expected number after TOP");
}
sq.limitCount = Integer.parseInt(tokens[pos++]);
sq.limitOffset = 0;
} else if (pos < tokens.length && tokens[pos].equalsIgnoreCase("limit")) {
pos++;
if (pos >= tokens.length) {
throw new IllegalArgumentException("Expected numbers after LIMIT");
}
// Note: tokenize() always splits ',' into its own token, so a
// "limit offset,count" spec arrives as separate tokens
// ("offset", ",", "count") rather than a single "offset,count"
// token; handle both forms explicitly.
int firstNumber = Integer.parseInt(tokens[pos++]);
if (pos < tokens.length && tokens[pos].equals(",")) {
pos++;
if (pos >= tokens.length) {
throw new IllegalArgumentException("Expected count after ',' in LIMIT");
}
sq.limitOffset = firstNumber;
sq.limitCount = Integer.parseInt(tokens[pos++]);
} else {
sq.limitOffset = 0;
sq.limitCount = firstNumber;
}
}
// Parse field selection
if (pos < tokens.length && tokens[pos].equals("*")) {
sq.selectAll = true;
pos++;
} else if (pos < tokens.length && tokens[pos].equals("{")) {
// Field list in braces
pos++;
while (pos < tokens.length && !tokens[pos].equals("}")) {
String fieldName = tokens[pos++];
String alias = null;
if (pos < tokens.length && tokens[pos].equalsIgnoreCase("as")) {
pos++;
if (pos < tokens.length) {
alias = tokens[pos++];
}
}
sq.fields.add(new FieldSelection(fieldName, alias));
if (pos < tokens.length && tokens[pos].equals(",")) {
pos++;
}
}
if (pos < tokens.length && tokens[pos].equals("}")) {
pos++;
}
} else if (pos < tokens.length) {
// Single field or comma-separated fields
while (pos < tokens.length && !tokens[pos].equalsIgnoreCase("where")) {
String fieldName = tokens[pos++];
if (fieldName.equals(",")) continue;
String alias = null;
if (pos < tokens.length && tokens[pos].equalsIgnoreCase("as")) {
pos++;
if (pos < tokens.length && !tokens[pos].equalsIgnoreCase("where")) {
alias = tokens[pos++];
}
}
sq.fields.add(new FieldSelection(fieldName, alias));
if (pos < tokens.length && tokens[pos].equals(",")) {
pos++;
}
}
}
// Parse WHERE clause
if (pos < tokens.length && tokens[pos].equalsIgnoreCase("where")) {
pos++;
sq.whereClause = new WhereClause(parseExpression(tokens, pos));
}
return sq;
}
private static Expression parseExpression(String[] tokens, int startPos) {
// Simple implementation - parse basic comparisons and AND/OR
// This is a simplified parser; a full implementation would handle parentheses
List<String> exprTokens = new ArrayList<>();
for (int i = startPos; i < tokens.length; i++) {
exprTokens.add(tokens[i]);
}
return parseExpressionTokens(exprTokens);
}
// Parses a (sub-)list of WHERE tokens, recursing so that any number of
// AND/OR clauses (and a leading NOT) are honored instead of only the
// first split.
private static Expression parseExpressionTokens(List<String> exprTokens) {
if (exprTokens.isEmpty()) {
throw new IllegalArgumentException("Empty WHERE clause");
}
// Handle NOT: it binds only to the single comparison that follows it,
// not to any subsequent AND/OR clauses.
if (exprTokens.get(0).equalsIgnoreCase("not")) {
List<String> rest = exprTokens.subList(1, exprTokens.size());
if (rest.size() < 3) {
throw new IllegalArgumentException("Invalid expression after NOT");
}
Expression notExpr = new NotExpression(parseSimpleExpression(rest.subList(0, 3)));
if (rest.size() > 3) {
String op = rest.get(3);
if (op.equalsIgnoreCase("and") || op.equalsIgnoreCase("or")) {
Expression right = parseExpressionTokens(rest.subList(4, rest.size()));
return new LogicalExpression(notExpr, op.toLowerCase(), right);
}
throw new IllegalArgumentException("Expected AND/OR after NOT expression");
}
return notExpr;
}
// Look for AND/OR operators, recursing on both sides so that any
// further AND/OR clauses are preserved rather than dropped.
for (int i = 0; i < exprTokens.size(); i++) {
if (exprTokens.get(i).equalsIgnoreCase("or")) {
List<String> left = exprTokens.subList(0, i);
List<String> right = exprTokens.subList(i + 1, exprTokens.size());
return new LogicalExpression(
parseExpressionTokens(left),
"or",
parseExpressionTokens(right)
);
}
}
for (int i = 0; i < exprTokens.size(); i++) {
if (exprTokens.get(i).equalsIgnoreCase("and")) {
List<String> left = exprTokens.subList(0, i);
List<String> right = exprTokens.subList(i + 1, exprTokens.size());
return new LogicalExpression(
parseExpressionTokens(left),
"and",
parseExpressionTokens(right)
);
}
}
return parseSimpleExpression(exprTokens);