My favorites | Sign in
Logo
                
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.visualization.datasource.query;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.visualization.datasource.base.InvalidQueryException;
import com.google.visualization.datasource.base.MessagesEnum;

import com.ibm.icu.util.ULocale;

import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;
import java.util.Set;

/**
* Holds the query data and clauses. This class is the result of parsing the query
* string that comes from the user.
* The clauses that can be included in a query are: select, filter, sort, group by, pivot, options,
* labels, format, limit, and offset.
* For more details see the
* <a href="http://code.google.com/apis/visualization/documentation/querylanguage.html">
* query language reference
* </a>.
* A Query can be executed by the query engine
* (see: {@link com.google.visualization.datasource.DataSourceHelper#applyQuery}).
* It can be split in 2 Query objects based on the Capabilities value
* (see: {@link com.google.visualization.datasource.DataSourceHelper#splitQuery}).
*
* Note on errors: Since this class handles a user generated query, all errors
* (of type INVALID_QUERY) should provide a descriptive error message for both
* the user.
*
* @author Itai R.
* @author Yonatan B.Y.
*/
public class Query {

/**
* Log.
*/
private static final Log log = LogFactory.getLog(Query.class.getName());

/**
* Checks the given list for duplicates. Throws an exception if a duplicate
* is found, giving as a message a description containing information on which
* item was found to be duplicate, and in which clause it occurred (the
* clause name is given).
*
* @param selectionColumns The list to check for duplicates.
* @param clauseName The clause name to report in the exception message.
* @param userLocale The user locale.
*
* @throws InvalidQueryException Thrown if a duplicate was found.
*/
private static<T> void checkForDuplicates(List<T>
selectionColumns, String clauseName, ULocale userLocale) throws InvalidQueryException {
for (int i = 0; i < selectionColumns.size(); i++) {
T col = selectionColumns.get(i);
for (int j = i + 1; j < selectionColumns.size(); j++) {
if (col.equals(selectionColumns.get(j))) {
String[] args = {col.toString(), clauseName};
String messageToLogAndUser = MessagesEnum.COLUMN_ONLY_ONCE.getMessageWithArgs(userLocale,
args);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}
}

/**
* The required sort order.
*/
private QuerySort sort = null;

/**
* The required selection.
* If the selection is null, or is empty, the original
* selection that was defined in the report is used.
*/
protected QuerySelection selection = null;

/**
* The required filter.
* If the filter is null, then the results are not filtered at all.
*/
private QueryFilter filter = null;

/**
* The required grouping.
*/
private QueryGroup group = null;

/**
* The required pivoting.
*/
private QueryPivot pivot = null;

/**
* Max number of rows to return to caller.
* If the caller specified this parameter, and the data table returned from
* the data source contains more than this number of rows, then the result is
* truncated, and the query result contains a warning with this reason.
* If this value is set to -1, which can only be done internally, this is ignored.
* (0 is a legal value, denoting no rows should be retrieved).
*/
private int rowLimit = -1;

/**
* The number of rows that should be removed from the beginning of the
* data table.
* Together with the row limit parameter, this enables pagination.
* The default value is 0, (skip 0 rows) - which means start from the
* first row.
*/
private int rowOffset = 0;

/**
* Additional options for the query.
*/
private QueryOptions options = null;

/**
* Column labels as specified in the query.
*/
private QueryLabels labels = null;

/**
* Column formatting patterns as specified in the query.
*/
private QueryFormat userFormatOptions = null;

/**
* The user locale, Used to create localized messages.
*/
private ULocale localeForUserMessages = null;

/**
* Constructs a new, empty, query.
*/
public Query() {
}

/**
* Set the required sort of the query result.
*
* @param sort The required sort of the query result.
*/
public void setSort(QuerySort sort) {
this.sort = sort;
}

/**
* Returns the required sort of the query result.
*
* @return The required sort of the query result.
*/
public QuerySort getSort() {
return sort;
}

/**
* Returns true if the query has a non empty sort-by section.
*
* @return True if the query has a non empty sort-by section.
*/
public boolean hasSort() {
return (sort != null) && (!sort.isEmpty());
}

/**
* Set the required selection of the query result.
*
* @param selection The required selection of the query result.
*/
public void setSelection(QuerySelection selection) {
this.selection = selection;
}

/**
* Returns the required selection of the query result.
*
* @return The required selection of the query result.
*/
public QuerySelection getSelection() {
return selection;
}

/**
* Returns true if there is a non-trivial selection, i.e. if not all columns
* should be selected.
*
* @return True if there is a non-trivial selection.
*/
public boolean hasSelection() {
return (selection != null) && (!selection.isEmpty());
}

/**
* Set the required filter of this query.
*
* @param filter The required filter of this query.
*/
public void setFilter(QueryFilter filter) {
this.filter = filter;
}

/**
* Returns the required filter of this query.
*
* @return The required filter of this query.
*/
public QueryFilter getFilter() {
return filter;
}

/**
* Returns whether or not this query has a filter defined.
*
* @return true if this query has a filter defined.
*/
public boolean hasFilter() {
return (filter != null);
}

/**
* Sets the required group of the query result.
*
* @param group The required group of the query result.
*/
public void setGroup(QueryGroup group) {
this.group = group;
}

/**
* Sets the required pivot of the query result.
*
* @param pivot The required pivot of the query result.
*/
public void setPivot(QueryPivot pivot) {
this.pivot = pivot;
}

/**
* Returns the required group of the query result.
*
* @return The required group of the query result.
*/
public QueryGroup getGroup() {
return group;
}

/**
* Returns true if the query has a group-by section.
*
* @return True if the query has a group-by section.
*/
public boolean hasGroup() {
return group != null && !group.getColumnIds().isEmpty();
}

/**
* Returns the required pivot of the query result.
*
* @return The required pivot of the query result.
*/
public QueryPivot getPivot() {
return pivot;
}

/**
* Returns true if the query has a pivot-by section.
*
* @return True if the query has a pivot-by section.
*/
public boolean hasPivot() {
return pivot != null && !pivot.getColumnIds().isEmpty();
}


/**
* Returns the maximum number of rows to return to the caller.
* If the caller specified this parameter, and the data table returned from
* the data source contains more than this number of rows, then the result is
* truncated, and the query result contains a warning with this reason.
* If this value is set to -1 it is just ignored, but this can only be done
* internally.
*
* @return The maximum number of rows to return to the caller.
*/
public int getRowLimit() {
return rowLimit;
}

/**
* Sets the max number of rows to return to the caller.
* If the caller specified this parameter, and the data table returned from
* the data source contains more than this number of rows, then the result is
* truncated, and the query result contains a warning with this reason.
* By default, this is set to -1, which means that no limit is requested.
*
* If there is is an attempt to set the limit value to any negative number
* smaller than -1 (which means no limit), then an InvalidQueryException is
* thrown.
*
* @param rowLimit The max number of rows to return.
*
* @throws InvalidQueryException Thrown if an invalid value is specified.
*/
public void setRowLimit(int rowLimit) throws InvalidQueryException {
if (rowLimit < -1) {
String messageToLogAndUser = "Invalid value for row limit: " + rowLimit;
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
this.rowLimit = rowLimit;
}

/**
* Sets the max number of rows to return to the caller, based on another
* query.
*
* @param originalQuery The query from which the row limit should be taken.
*/
public void copyRowLimit(Query originalQuery) {
rowLimit = originalQuery.getRowLimit();
}

/**
* Returns true if this query has a row limit set. A value of -1 means no
* limit so in case of -1 this function returns true.
*
* @return True if this query has a row limit set.
*/
public boolean hasRowLimit() {
return rowLimit > -1;
}

/**
* Returns the number of rows that should be removed from the beginning of the
* data table.
* Together with the row limit parameter, this enables pagination.
* The default value is 0, (skip 0 rows) - which means to start from the
* first row.
*
* @return The number of rows to skip from the beginning of the table.
*/
public int getRowOffset() {
return rowOffset;
}

/**
* Sets the number of rows that should be removed from the beginning of the
* data table.
* Together with the row limit parameter, this enables pagination.
* The default value is 0, (skip 0 rows) - which means to start from the
* first row.
*
* If there is is an attempt to set the offset value to any negative number,
* then an InvalidQueryException is thrown.
*
* @param rowOffset The number of rows to skip from the beginning of the
* table.
*
* @throws InvalidQueryException Thrown if an invalid value is specified.
*/
public void setRowOffset(int rowOffset) throws InvalidQueryException {
if (rowOffset < 0) {
String messageToLogAndUser = MessagesEnum.INVALID_OFFSET.getMessageWithArgs(
localeForUserMessages, Integer.toString(rowOffset));
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
this.rowOffset = rowOffset;
}

/**
* Sets the number of rows to skip, based on another query.
*
* @param originalQuery The query from which the row offset should be taken.
*/
public void copyRowOffset(Query originalQuery) {
rowOffset = originalQuery.getRowOffset();
}

/**
* Returns true if this query has a row offset set. A value of 0 means no
* offset so in case of 0 this function returns true.
*
* @return True if this query has a row offset set.
*/
public boolean hasRowOffset() {
return rowOffset > 0;
}

/**
* Returns the query formatting options.
*
* @return The query formatting options.
*/
public QueryFormat getUserFormatOptions() {
return userFormatOptions;
}

/**
* Sets the user formatting options map.
* @param userFormatOptions A map of patterns to column IDs.
*/
public void setUserFormatOptions(QueryFormat userFormatOptions) {
this.userFormatOptions = userFormatOptions;
}

/**
* Returns true if this query has user format options defined.
*
* @return True if this query has user format options defined.
*/
public boolean hasUserFormatOptions() {
return (userFormatOptions != null)
&& (!userFormatOptions.getColumns().isEmpty());
}

/**
* Returns the query labels.
*
* @return The query labels.
*/
public QueryLabels getLabels() {
return labels;
}

/**
* Sets the query labels.
* @param labels A map of labels to column IDs.
*/
public void setLabels(QueryLabels labels) {
this.labels = labels;
}

/**
* Returns true if this query has labels defined.
*
* @return True if this query has labels defined.
*/
public boolean hasLabels() {
return (labels != null)
&& (!labels.getColumns().isEmpty());
}

/**
* Returns the options for this query.
*
* @return The options for this query.
*/
public QueryOptions getOptions() {
return options;
}

/**
* Sets the required options for this query.
*
* @param options The required options.
*/
public void setOptions(QueryOptions options) {
this.options = options;
}

/**
* Returns true if this query has any nondefault options set.
*
* @return True if this query has any nondefault options set.
*/
public boolean hasOptions() {
return (options != null)
&& (!options.isDefault());
}

/**
* Returns true if the query is empty, i.e. has no clauses or all the clauses are empty.
*
* @return true if the query is empty.
*/
public boolean isEmpty() {
return (!hasSort() && !hasSelection() && !hasFilter() && !hasGroup() && !hasPivot()
&& !hasRowLimit() && !hasRowOffset() && !hasUserFormatOptions() && !hasLabels()
&& !hasOptions());
}


/**
* Sets the user locale for creating localized messages.
* @param userLocale the user locale.
*/
public void setLocaleForUserMessages(ULocale localeForUserMessges) {
this.localeForUserMessages = localeForUserMessges;
}

/**
* Copies all information from the given query to this query.
*
* @param query The query to copy from.
*/
public void copyFrom(Query query) {
setSort(query.getSort());
setSelection(query.getSelection());
setFilter(query.getFilter());
setGroup(query.getGroup());
setPivot(query.getPivot());
copyRowLimit(query);
copyRowOffset(query);
setUserFormatOptions(query.getUserFormatOptions());
setLabels(query.getLabels());
setOptions(query.getOptions());
}

/**
* Validates the query. Runs a sanity check on the query, verifies that there are no
* duplicates, and that the query follows a basic set of rules required for its execution.
*
* Specifically, verifies the following:
* - There are no duplicate columns in the clauses.
* - No column appears both as a selection and as an aggregation.
* - When aggregation is used, checks that all selected columns are valid (a column is valid if
* it is either grouped-by, or is a scalar function column the arguments of which are all
* valid columns).
* - No column is both grouped-by, and aggregated in, the select clause.
* - No column both appears as pivot, and aggregated in, the select clause.
* - No grouping/pivoting is used when there is no aggregation in the select clause.
* - If aggregation is used in the select clause, no column is ordered-by that is not in the
* select clause.
* - No column appears both as a group-by and a pivot.
* - If pivoting is used, the order by clause does not contain aggregation columns.
* - The order-by clause does not contain aggregation columns that were not defined in the select
* clause.
*
* @throws InvalidQueryException
*/
public void validate() throws InvalidQueryException {
// Set up some variables.
List<String> groupColumnIds =
hasGroup() ? group.getColumnIds() : Lists.<String>newArrayList();
List<AbstractColumn> groupColumns = hasGroup() ? group.getColumns() :
Lists.<AbstractColumn>newArrayList();
List<String> pivotColumnIds =
hasPivot() ? pivot.getColumnIds() : Lists.<String>newArrayList();
List<AbstractColumn> selectionColumns = hasSelection()
? selection.getColumns() : Lists.<AbstractColumn>newArrayList();
List<AggregationColumn> selectionAggregated =
hasSelection() ? selection.getAggregationColumns() :
Lists.<AggregationColumn>newArrayList();
List<SimpleColumn> selectionSimple = hasSelection()
? selection.getSimpleColumns() : Lists.<SimpleColumn>newArrayList();
List<ScalarFunctionColumn> selectedScalarFunctionColumns = hasSelection()
? selection.getScalarFunctionColumns()
: Lists.<ScalarFunctionColumn>newArrayList();
selectedScalarFunctionColumns.addAll(selectedScalarFunctionColumns);
List<AbstractColumn> sortColumns = hasSort() ? sort.getColumns() :
Lists.<AbstractColumn>newArrayList();
List<AggregationColumn> sortAggregated = hasSort()
? sort.getAggregationColumns()
: Lists.<AggregationColumn>newArrayList();

// Check for duplicates.
checkForDuplicates(selectionColumns, "SELECT", localeForUserMessages);
checkForDuplicates(sortColumns, "ORDER BY", localeForUserMessages);
checkForDuplicates(groupColumnIds, "GROUP BY", localeForUserMessages);
checkForDuplicates(pivotColumnIds, "PIVOT", localeForUserMessages);

// Cannot have aggregations in either group by, pivot, or where.
if (hasGroup()) {
for (AbstractColumn column : group.getColumns()) {
if (!column.getAllAggregationColumns().isEmpty()) {
String messageToLogAndUser = MessagesEnum.CANNOT_BE_IN_GROUP_BY.getMessageWithArgs(
localeForUserMessages, column.toQueryString());
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}
if (hasPivot()) {
for (AbstractColumn column : pivot.getColumns()) {
if (!column.getAllAggregationColumns().isEmpty()) {
String messageToLogAndUser = MessagesEnum.CANNOT_BE_IN_PIVOT.getMessageWithArgs(
localeForUserMessages, column.toQueryString());
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}
if (hasFilter()) {
List<AggregationColumn> filterAggregations = filter.getAggregationColumns();
if (!filterAggregations.isEmpty()) {
String messageToLogAndUser = MessagesEnum.CANNOT_BE_IN_WHERE.getMessageWithArgs(
localeForUserMessages, filterAggregations.get(0).toQueryString());;
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}

// A column cannot appear both as an aggregation column and as a regular
// column in the selection.
for (SimpleColumn column1 : selectionSimple) {
String id = column1.getColumnId();
for (AggregationColumn column2 : selectionAggregated) {
if (id.equals(column2.getAggregatedColumn().getId())) {
String messageToLogAndUser = MessagesEnum.SELECT_WITH_AND_WITHOUT_AGG.getMessageWithArgs(
localeForUserMessages, id);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}

// When aggregation is used, check that all selected columns are valid
// (a column is valid if it is either grouped-by, or is a
// scalar function column whose arguments are all valid columns).
if (!selectionAggregated.isEmpty()) {
for (AbstractColumn col : selectionColumns) {
checkSelectedColumnWithGrouping(groupColumns, col);
}
}

// Cannot group by a column that appears in an aggregation.
if (hasSelection() && hasGroup()) {
for (AggregationColumn column : selectionAggregated) {
String id = column.getAggregatedColumn().getId();
if (groupColumnIds.contains(id)) {
String messageToLogAndUser = MessagesEnum.COL_AGG_NOT_IN_SELECT.getMessageWithArgs(
localeForUserMessages, id);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}

// Cannot use grouping or pivoting when no aggregations are defined in the
// selection.
if (hasGroup() && selectionAggregated.isEmpty()) {
String messageToLogAndUser = MessagesEnum.CANNOT_GROUP_WITNOUT_AGG.getMessage(
localeForUserMessages);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
if (hasPivot() && selectionAggregated.isEmpty()) {
String messageToLogAndUser = MessagesEnum.CANNOT_PIVOT_WITNOUT_AGG.getMessage(
localeForUserMessages);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}

// Cannot order by a column that is not in the selection when aggregations
// are defined.
if (hasSort() && !selectionAggregated.isEmpty()) {
for (AbstractColumn column : sort.getColumns()) {
String messageToLogAndUser = MessagesEnum.COL_IN_ORDER_MUST_BE_IN_SELECT.getMessageWithArgs(
localeForUserMessages, column.toQueryString());
checkColumnInList(selection.getColumns(), column,
messageToLogAndUser);
}
}

// Cannot pivot by a column that appears in an aggregation.
if (hasPivot()) {
for (AggregationColumn column : selectionAggregated) {
String id = column.getAggregatedColumn().getId();
if (pivotColumnIds.contains(id)) {
String messageToLogAndUser = MessagesEnum.AGG_IN_SELECT_NO_PIVOT.getMessageWithArgs(
localeForUserMessages, id);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}

// Cannot have a column appear in both group by and pivot.
if (hasGroup() && hasPivot()) {
for (String id : groupColumnIds) {
if (pivotColumnIds.contains(id)) {
String messageToLogAndUser = MessagesEnum.NO_COL_IN_GROUP_AND_PIVOT.getMessageWithArgs(
localeForUserMessages, id);
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}

// Cannot order by aggregation column when pivoting is used.
if (hasPivot() && !sortAggregated.isEmpty()) {
AggregationColumn column = sortAggregated.get(0);
String messageToLogAndUser = MessagesEnum.NO_AGG_IN_ORDER_WHEN_PIVOT.getMessageWithArgs(
localeForUserMessages, column.getAggregatedColumn().getId());
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}

// Cannot order by aggregation columns that weren't defined in the
// selection.
for (AggregationColumn column : sortAggregated) {
String messageToLogAndUser = MessagesEnum.AGG_IN_ORDER_NOT_IN_SELECT.getMessageWithArgs(
localeForUserMessages, column.toQueryString());
checkColumnInList(selectionAggregated, column, messageToLogAndUser);
}

Set<AbstractColumn> labelColumns = (hasLabels()
? labels.getColumns() : Sets.<AbstractColumn>newHashSet());
Set<AbstractColumn> formatColumns = (hasUserFormatOptions()
? userFormatOptions.getColumns() : Sets.<AbstractColumn>newHashSet());

if (hasSelection()) {
for (AbstractColumn col : labelColumns) {
if (!selectionColumns.contains(col)) {
String messageToLogAndUser = MessagesEnum.LABEL_COL_NOT_IN_SELECT.getMessageWithArgs(
localeForUserMessages, col.toQueryString());
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
for (AbstractColumn col : formatColumns) {
if (!selectionColumns.contains(col)) {
String messageToLogAndUser = MessagesEnum.FORMAT_COL_NOT_IN_SELECT.getMessageWithArgs(
localeForUserMessages, col.toQueryString());
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}
}
}

/**
* Returns all simple column IDs in use in all parts of the query.
*
* @return All simple column IDs in use in all parts of the query.
*/
public Set<String> getAllColumnIds() {
Set<String> result = Sets.newHashSet();
if (hasSelection()) {
for (AbstractColumn col : selection.getColumns()) {
result.addAll(col.getAllSimpleColumnIds());
}
}
if (hasSort()) {
for (AbstractColumn col : sort.getColumns()) {
result.addAll(col.getAllSimpleColumnIds());
}
}
if (hasGroup()) {
result.addAll(getGroup().getSimpleColumnIds());
}
if (hasPivot()) {
result.addAll(getPivot().getSimpleColumnIds());
}
if (hasFilter()) {
result.addAll(getFilter().getAllColumnIds());
}
if (hasLabels()) {
for (AbstractColumn col : labels.getColumns()) {
result.addAll(col.getAllSimpleColumnIds());
}
}
if (hasUserFormatOptions()) {
for (AbstractColumn col : userFormatOptions.getColumns()) {
result.addAll(col.getAllSimpleColumnIds());
}
}

return result;
}

/**
* Returns all aggregation columns used in all parts of this query.
*
* @return All aggregation columns used in all parts of this query.
*/
public Set<AggregationColumn> getAllAggregations() {
Set<AggregationColumn> result = Sets.newHashSet();
if (hasSelection()) {
result.addAll(selection.getAggregationColumns());
}
if (hasSort()) {
for (AbstractColumn col : sort.getColumns()) {
if (col instanceof AggregationColumn) {
result.add((AggregationColumn) col);
}
}
}

if (hasLabels()) {
for (AbstractColumn col : labels.getColumns()) {
if (col instanceof AggregationColumn) {
result.add((AggregationColumn) col);
}
}
}
if (hasUserFormatOptions()) {
for (AbstractColumn col : userFormatOptions.getColumns()) {
if (col instanceof AggregationColumn) {
result.add((AggregationColumn) col);
}
}
}
return result;
}

/**
* Returns all scalar function columns in this query.
*
* @return All scalar function columns in this query.
*/
public Set<ScalarFunctionColumn> getAllScalarFunctionsColumns() {
Set<ScalarFunctionColumn> mentionedScalarFunctionColumns =
Sets.newHashSet();
if (hasSelection()) {
mentionedScalarFunctionColumns.addAll(
selection.getScalarFunctionColumns());
}
if (hasFilter()) {
mentionedScalarFunctionColumns.addAll(filter.getScalarFunctionColumns());
}
if (hasGroup()) {
mentionedScalarFunctionColumns.addAll(group.getScalarFunctionColumns());
}
if (hasPivot()) {
mentionedScalarFunctionColumns.addAll(pivot.getScalarFunctionColumns());
}
if (hasSort()) {
mentionedScalarFunctionColumns.addAll(sort.getScalarFunctionColumns());
}
if (hasLabels()) {
mentionedScalarFunctionColumns.addAll(labels.getScalarFunctionColumns());
}
if (hasUserFormatOptions()) {
mentionedScalarFunctionColumns.addAll(userFormatOptions.getScalarFunctionColumns());
}
return mentionedScalarFunctionColumns;
}


/**
* Checks that the given column is valid, i.e., is in the given list of
* columns, or is a scalar function column and all its inner columns are
* valid (i.e., in the list).
*
* @param columns The given list of columns.
* @param column The given column.
* @param messageToLogAndUser The error message for the exception that is
* thrown when the column is not in the list.
*
* @throws InvalidQueryException Thrown when the column is invalid.
*/
private void checkColumnInList(List<? extends AbstractColumn> columns,
AbstractColumn column, String messageToLogAndUser)
throws InvalidQueryException {
if (columns.contains(column)) {
return;
} else if (column instanceof ScalarFunctionColumn) {
List<AbstractColumn> innerColumns =
((ScalarFunctionColumn) column).getColumns();
for (AbstractColumn innerColumn : innerColumns) {
checkColumnInList(columns, innerColumn, messageToLogAndUser);
}
} else {
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
}

/**
* Checks the selection of the given column is valid, given the group
* columns. A column is valid in this sense if it is either grouped-by, or is
* a scalar function column whose arguments are all valid columns.
*
* @param groupColumns The group columns.
* @param col The selected column.
*
* @throws InvalidQueryException Thrown when the given column is a simple
* column that is not grouped by.
*/
private void checkSelectedColumnWithGrouping(
List<AbstractColumn> groupColumns, AbstractColumn col)
throws InvalidQueryException {
if (col instanceof SimpleColumn) {
if (!groupColumns.contains(col)) {
String messageToLogAndUser = MessagesEnum.ADD_COL_TO_GROUP_BY_OR_AGG.getMessageWithArgs(
localeForUserMessages, col.getId());
log.error(messageToLogAndUser);
throw new InvalidQueryException(messageToLogAndUser);
}
} else if (col instanceof ScalarFunctionColumn) {
// A selected scalar function column is valid if it is grouped by, or if
// its inner columns are all valid.
if (!groupColumns.contains(col)) {
List<AbstractColumn> innerColumns =
((ScalarFunctionColumn) col).getColumns();
for (AbstractColumn innerColumn : innerColumns) {
checkSelectedColumnWithGrouping(groupColumns, innerColumn);
}
}
}
// An aggregation column is always valid (the inner aggregated column
// validity is checked elsewhere).
}

@Override
public int hashCode() {
final int prime = 37;
int result = 1;
result = prime * result + ((filter == null) ? 0 : filter.hashCode());
result = prime * result + ((group == null) ? 0 : group.hashCode());
result = prime * result + ((labels == null) ? 0 : labels.hashCode());
result = prime * result + ((options == null) ? 0 : options.hashCode());
result = prime * result + ((pivot == null) ? 0 : pivot.hashCode());
result = prime * result + rowLimit;
result = prime * result + rowOffset;
result = prime * result + ((selection == null) ? 0 : selection.hashCode());
result = prime * result + ((sort == null) ? 0 : sort.hashCode());
result = prime * result + ((userFormatOptions == null) ? 0 : userFormatOptions.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Query other = (Query) obj;
if (filter == null) {
if (other.filter != null) {
return false;
}
} else if (!filter.equals(other.filter)) {
return false;
}
if (group == null) {
if (other.group != null) {
return false;
}
} else if (!group.equals(other.group)) {
return false;
}
if (labels == null) {
if (other.labels != null) {
return false;
}
} else if (!labels.equals(other.labels)) {
return false;
}
if (options == null) {
if (other.options != null) {
return false;
}
} else if (!options.equals(other.options)) {
return false;
}
if (pivot == null) {
if (other.pivot != null) {
return false;
}
} else if (!pivot.equals(other.pivot)) {
return false;
}
if (rowLimit != other.rowLimit) {
return false;
}
if (rowOffset != other.rowOffset) {
return false;
}
if (selection == null) {
if (other.selection != null) {
return false;
}
} else if (!selection.equals(other.selection)) {
return false;
}
if (sort == null) {
if (other.sort != null) {
return false;
}
} else if (!sort.equals(other.sort)) {
return false;
}
if (userFormatOptions == null) {
if (other.userFormatOptions != null) {
return false;
}
} else if (!userFormatOptions.equals(other.userFormatOptions)) {
return false;
}
return true;
}

/**
* Creates a comma separated string of the query strings of the given columns.
*
* @param l The list of columns.
*
* @return A comma separated string of the query strings of the given columns.
*/
/* package */ static String columnListToQueryString(List<AbstractColumn> l) {
StrBuilder builder = new StrBuilder();
List<String> stringList = Lists.newArrayList();
for (AbstractColumn col : l) {
stringList.add(col.toQueryString());
}
builder.appendWithSeparators(stringList, ", ");
return builder.toString();
}

/**
* Creates a query-language representation of the given string, i.e., delimits it with either
* double-quotes (") or single-quotes ('). Throws a runtime exception if the given string
* contains both double-quotes and single-quotes and so cannot be expressed in the query
* language.
*
* @param s The string to create a query-language representation for.
*
* @return The query-language representation of the given string.
*/
/* package */ static String stringToQueryStringLiteral(String s) {
if (s.contains("\"")) {
if (s.contains("'")) {
throw new RuntimeException("Cannot represent string that contains both double-quotes (\") "
+ " and single quotes (').");
} else {
return "'" + s + "'";
}
} else {
return "\"" + s + "\"";
}
}

/**
* Returns a string that when fed to the query parser will yield an identical Query.
* Used mainly for debugging purposes.
*
* @return The query string.
*/
public String toQueryString() {
List<String> clauses = Lists.newArrayList();
if (hasSelection()) {
clauses.add("SELECT " + selection.toQueryString());
}
if (hasFilter()) {
clauses.add("WHERE " + filter.toQueryString());
}
if (hasGroup()) {
clauses.add("GROUP BY " + group.toQueryString());
}
if (hasPivot()) {
clauses.add("PIVOT " + pivot.toQueryString());
}
if (hasSort()) {
clauses.add("ORDER BY " + sort.toQueryString());
}
if (hasRowLimit()) {
clauses.add("LIMIT " + rowLimit);
}
if (hasRowOffset()) {
clauses.add("OFFSET " + rowOffset);
}
if (hasLabels()) {
clauses.add("LABEL " + labels.toQueryString());
}
if (hasUserFormatOptions()) {
clauses.add("FORMAT " + userFormatOptions.toQueryString());
}
if (hasOptions()) {
clauses.add("OPTIONS " + options.toQueryString());
}
StrBuilder result = new StrBuilder();
result.appendWithSeparators(clauses, " ");
return result.toString();
}
}
Show details Hide details

Change log

r44 by chartsboy on Sep 08, 2009   Diff
Externalize error messages

Go to: 
Project members, sign in to write a code review

Older revisions

r18 by shubay on Jun 18, 2009   Diff
Add maven support. Move src/java to
src/main/java.
r5 by shubay on May 24, 2009   Diff
Fix bug - do not allow queries with
aggregations in group/pivot/where.
r2 by shubay on May 21, 2009   Diff
Snapshot - version 1.0 release
candidate 1.
All revisions of this file

File info

Size: 35974 bytes, 1095 lines

File properties

svn:executable
*