-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathVisualizationSourceQuery.java
More file actions
651 lines (579 loc) · 22.3 KB
/
VisualizationSourceQuery.java
File metadata and controls
651 lines (579 loc) · 22.3 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
/*
* Copyright (c) 2011-2019 LabKey Corporation
*
* 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 org.labkey.visualization.sql;
import org.jetbrains.annotations.NotNull;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.Container;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.OORDisplayColumnFactory;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.data.TableInfo;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.UserSchema;
import org.labkey.api.util.Pair;
import org.labkey.api.view.NotFoundException;
import org.labkey.api.visualization.IVisualizationSourceQuery;
import org.labkey.api.visualization.SQLGenerationException;
import org.labkey.api.visualization.VisualizationAggregateColumn;
import org.labkey.api.visualization.VisualizationSourceColumn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* User: brittp
* Date: Jan 27, 2011 11:14:20 AM
*/
public class VisualizationSourceQuery implements IVisualizationSourceQuery
{
private final Container _container;
private final UserSchema _schema;
private final String _queryName;
private final int _uniq;
private IVisualizationSourceQuery _joinTarget; // query this query must join to when building SQL
private String _alias = null;
private TableInfo _tinfo;
private boolean _requireLeftJoin;
private VisualizationSourceColumn _pivot;
private final Set<VisualizationSourceColumn> _measures = new LinkedHashSet<>();
private final Set<VisualizationSourceColumn> _selects = new LinkedHashSet<>();
private Set<VisualizationSourceColumn> _allSelects = null;
private final Set<VisualizationAggregateColumn> _aggregates = new LinkedHashSet<>();
private final Set<VisualizationSourceColumn> _sorts = new LinkedHashSet<>();
private List<Pair<VisualizationSourceColumn, VisualizationSourceColumn>> _joinConditions;
private final List<SimpleFilter> _filters = new ArrayList<>();
private boolean _skipVisitJoin;
public VisualizationSourceQuery(Container container, UserSchema schema, String queryName, VisualizationSourceQuery joinTarget, int uniq)
{
_container = container;
_schema = schema;
_queryName = queryName;
_joinTarget = joinTarget;
_uniq = uniq;
}
private TableInfo getTableInfo()
{
if (_tinfo == null)
_tinfo = _schema.getTable(_queryName);
if (_tinfo == null)
{
throw new NotFoundException("Could not find query '" + _queryName + "' in schema '" + _schema.getName() + "'");
}
return _tinfo;
}
private void ensureSameQuery(VisualizationSourceColumn measure)
{
if (!measure.getSchemaName().equals(getSchemaName()) || !measure.getQueryName().equals(_queryName))
{
throw new IllegalArgumentException("Attempt to add measure from " + measure.getSchemaName() + "." +
measure.getQueryName() + " to source query " + getSchemaName() + "." + _queryName);
}
}
public void setJoinConditions(List<Pair<VisualizationSourceColumn, VisualizationSourceColumn>> joinConditions)
{
_joinConditions = joinConditions;
}
@Override
public List<Pair<VisualizationSourceColumn, VisualizationSourceColumn>> getJoinConditions()
{
return _joinConditions;
}
@Override
public Container getContainer()
{
return _container;
}
public boolean requireInnerJoin()
{
if (isRequireLeftJoin())
return true;
for (VisualizationSourceColumn col : _selects)
{
if (!col.isAllowNullResults())
return true;
}
for (VisualizationAggregateColumn aggregate : _aggregates)
{
if (!aggregate.isAllowNullResults())
return true;
}
return false;
}
@Override
public boolean isRequireLeftJoin()
{
return _requireLeftJoin;
}
// This can only be toggled based on the set of columns/aggregates configurations, thus it is private
private void setRequireLeftJoin(boolean requireLeftJoin)
{
_requireLeftJoin = requireLeftJoin;
}
@Override
public void addSelect(VisualizationSourceColumn select, boolean measure)
{
ensureSameQuery(select);
_selects.add(select);
if (select.isRequireLeftJoin())
{
setRequireLeftJoin(true);
}
if (measure)
{
_measures.add(select);
}
}
@Override
public Set<VisualizationSourceColumn> getSelects(VisualizationSourceColumn.Factory factory, boolean includeRequiredExtraCols)
{
if (includeRequiredExtraCols)
{
if (_allSelects == null)
{
_allSelects = new LinkedHashSet<>(_selects);
_allSelects.addAll(getOORColumns(factory));
_allSelects.addAll(getDataLoggingColumns(factory));
}
return _allSelects;
}
return _selects;
}
public void addAggregate(VisualizationAggregateColumn aggregate)
{
ensureSameQuery(aggregate);
aggregate.ensureColumn();
_aggregates.add(aggregate);
if (aggregate.isRequireLeftJoin())
{
setRequireLeftJoin(true);
}
}
@Override
public Set<VisualizationAggregateColumn> getAggregates()
{
return _aggregates;
}
@Override
public boolean contains(VisualizationSourceColumn column)
{
return column.getSchemaName().equals(this.getSchemaName()) && column.getQueryName().equals(this.getQueryName());
}
@Override
public String getSelectListName(Set<VisualizationSourceColumn> selectAliases)
{
// If there is more than one available alias for a given value, just choose the first:
return selectAliases.iterator().next().getAlias();
}
private static void addToColMap(Map<String, Set<VisualizationSourceColumn>> colMap, String name, VisualizationSourceColumn alias)
{
Set<VisualizationSourceColumn> aliases = colMap.computeIfAbsent(name, n -> new LinkedHashSet<>());
aliases.add(alias);
}
public class PivotSourceColumn extends VisualizationSourceColumn
{
/** The value that's being used to pivot the data into this column */
private final String _pivotValue;
private final String _originalName;
PivotSourceColumn(VisualizationAggregateColumn agg, Object pivotValue, String clientAlias)
{
super(VisualizationSourceQuery.this.getSchema(), VisualizationSourceQuery.this.getQueryName(), pivotValue.toString() + "_" + agg.getOriginalName(), true, false);
_originalName = agg.getOriginalName();
_alias = pivotValue + "::" + agg.getAlias();
if (null != agg.getLabel())
_label = pivotValue + " - " + agg.getLabel();
_pivotValue = pivotValue.toString();
// Remember the alias that the client using to refer to this column
_clientAlias = clientAlias;
setInNotNullSet(agg.isInNotNullSet());
}
@Override
public String getOriginalName()
{
return _originalName;
}
@Override
public Map<String, String> toJSON()
{
Map<String, String> result = super.toJSON();
result.put("pivotValue", _pivotValue);
return result;
}
}
@Override
public Map<String, Set<VisualizationSourceColumn>> getColumnNameToValueAliasMap(VisualizationSourceColumn.Factory factory, boolean measuresOnly)
{
Map<String, Set<VisualizationSourceColumn>> colMap = new LinkedHashMap<>();
Set<VisualizationAggregateColumn> aggregates = getAggregates();
if (!aggregates.isEmpty())
{
for (VisualizationAggregateColumn aggregate : aggregates)
{
if (getPivot() != null)
{
// Aggregate with pivot:
for (Object pivotValue : getPivot().getValues())
{
VisualizationSourceColumn pivotCol = new PivotSourceColumn(aggregate, pivotValue, aggregate.getClientAlias());
addToColMap(colMap, pivotCol.getOriginalName(), pivotCol);
}
}
else
{
// Aggregate without pivot (simple grouping)
addToColMap(colMap, aggregate.getOriginalName(), aggregate);
}
}
}
if (measuresOnly)
{
for (VisualizationSourceColumn select : _measures)
{
addToColMap(colMap, select.getOriginalName(), select);
}
}
else
{
for (VisualizationSourceColumn select : getSelects(factory, true))
addToColMap(colMap, select.getOriginalName(), select);
if (getJoinConditions() != null)
{
for (Pair<VisualizationSourceColumn, VisualizationSourceColumn> join : getJoinConditions())
{
addToColMap(colMap, join.getKey().getOriginalName(), join.getKey());
addToColMap(colMap, join.getValue().getOriginalName(), join.getValue());
}
}
}
return colMap;
}
@Override
public VisualizationSourceColumn getPivot()
{
return _pivot;
}
public void setPivot(VisualizationSourceColumn pivot)
{
ensureSameQuery(pivot);
if (_pivot != null)
{
// See 12369
if (_pivot.equals(pivot))
return;
throw new IllegalArgumentException("Can't pivot a single dataset by more than one column. Attempt to pivot " +
getSchemaName() + "." + _queryName + " by both " + _pivot.getSelectName() + " and " + pivot.getSelectName());
}
_pivot = pivot;
}
public void addSort(VisualizationSourceColumn sort)
{
ensureSameQuery(sort);
_sorts.add(sort);
}
@Override
public Set<VisualizationSourceColumn> getSorts()
{
return _sorts;
}
public String getDisplayName()
{
return getSchemaName() + "." + _queryName;
}
@Override
public String getSQLAlias()
{
return "\"" + getAlias() + "\"";
}
@Override
public String getAlias()
{
if (null == _alias)
_alias = ColumnInfo.legalNameFromName(getSchemaName() + "_" + _queryName + "_" + _uniq);
return _alias;
}
public void appendColumnNames(StringBuilder sql, Set<? extends VisualizationSourceColumn> columns, boolean aggregate, boolean aliasInsteadOfName, boolean appendAlias)
{
if (columns == null || columns.isEmpty())
return;
assert !(aliasInsteadOfName && appendAlias) : "Can't both use only alias and append alias";
String leadingSep = "";
for (VisualizationSourceColumn column : columns)
{
sql.append(leadingSep);
if (aggregate && column instanceof VisualizationAggregateColumn agg)
{
if (agg.getAggregate().getSQLFunctionName(null) != null)
sql.append(agg.getAggregate().getSQLFunctionName(null)).append("(");
}
if (aliasInsteadOfName)
sql.append(column.getSQLAlias());
else
sql.append(column.getSelectName());
if (aggregate && column instanceof VisualizationAggregateColumn)
sql.append(")");
if (appendAlias)
sql.append(" AS ").append(column.getSQLAlias()).append(" @preservetitle");
leadingSep = ", ";
}
}
public String getSelectClause(VisualizationSourceColumn.Factory factory)
{
return getSelectClauseHelper(factory).toString();
}
protected StringBuilder getSelectClauseHelper(VisualizationSourceColumn.Factory factory)
{
StringBuilder selectList = new StringBuilder("SELECT ");
Set<VisualizationSourceColumn> selects = new LinkedHashSet<>();
if (_pivot != null)
selects.add(_pivot);
selects.addAll(getSelects(factory, true));
selects.addAll(_sorts);
selects.addAll(_aggregates);
appendColumnNames(selectList, selects, true, false, true);
selectList.append("\n");
return selectList;
}
public String getFromClause()
{
String schemaName = "\"" + getSchemaName() + "\"";
String queryName = "\"" + _queryName + "\"";
return "FROM " + schemaName + "." + queryName + "\n";
}
public String getGroupByClause()
{
if (_aggregates != null && !_aggregates.isEmpty())
{
StringBuilder groupBy = new StringBuilder("GROUP BY ");
Set<VisualizationSourceColumn> groupBys = new LinkedHashSet<>();
if (_pivot != null)
groupBys.add(_pivot);
groupBys.addAll(_allSelects);
groupBys.addAll(_sorts);
appendColumnNames(groupBy, groupBys, false, false, false);
groupBy.append("\n");
return groupBy.toString();
}
else
return "";
}
private void appendValueList(StringBuilder sql, VisualizationSourceColumn col)
{
if (col.getValues() != null && !col.getValues().isEmpty())
{
sql.append(" IN (");
String sep = "";
if (col.getValues().isEmpty())
{
sql.append(" NULL");
}
else
{
for (Object value : col.getValues())
{
sql.append(sep);
sql.append(SimpleFilter.FilterClause.escapeLabKeySqlValue(value, JdbcType.VARCHAR));
sep = ", ";
}
}
sql.append(")");
}
}
public String getPivotClause()
{
if (_pivot != null)
{
StringBuilder pivotClause = new StringBuilder("PIVOT ");
appendColumnNames(pivotClause, _aggregates, false, true, false);
pivotClause.append(" BY ");
appendColumnNames(pivotClause, Collections.singleton(_pivot), false, true, false);
appendValueList(pivotClause, _pivot);
pivotClause.append("\n");
return pivotClause.toString();
}
return "";
}
/**
* Currently, query does not have a notion of dependent columns- this happens only at the query view level. As
* a result, it's possible to select a set of columns that will not correctly render in a data region. One common
* example of this occurs with out-of-range indicators, where a failure to select a column's sibling out-of-range
* indicator column produces an error at render time. We address this here in a nasty way by checking every selected
* column to see if an OOR sibling column is present, and adding it to the select if so.
* @return A set of additional columns that should be selected to ensure that the columns actually requested
* by the user correctly display their out-of-range indicators.
*/
private Set<VisualizationSourceColumn> getOORColumns(VisualizationSourceColumn.Factory factory)
{
Set<FieldKey> fieldKeys = new HashSet<>();
for (VisualizationSourceColumn selectCol : this.getSelects(factory, false))
{
FieldKey oorSelect = FieldKey.fromString(selectCol.getOriginalName() + OORDisplayColumnFactory.OOR_INDICATOR_COLUMN_SUFFIX);
fieldKeys.add(oorSelect);
}
Map<FieldKey, ColumnInfo> cols = QueryService.get().getColumns(getTableInfo(), fieldKeys);
Set<VisualizationSourceColumn> oorSelects = new HashSet<>();
for (FieldKey key : cols.keySet())
oorSelects.add(factory.create(getSchema(), getQueryName(), key.toString(), true));
return oorSelects;
}
private Map<FieldKey, ColumnInfo> getFilterColumns(SimpleFilter filter)
{
Map<FieldKey, String> fieldKeys = new HashMap<>();
for (SimpleFilter.FilterClause clause : filter.getClauses())
{
for (FieldKey fieldKey : clause.getFieldKeys())
fieldKeys.put(fieldKey, fieldKey.toString());
}
return QueryService.get().getColumns(getTableInfo(), fieldKeys.keySet());
}
private Set<VisualizationSourceColumn> getDataLoggingColumns(VisualizationSourceColumn.Factory factory)
{
// Ensure any data logging columns (such as for PHI) are present
Set<VisualizationSourceColumn> dataLoggingColumns = new HashSet<>();
Set<FieldKey> fieldKeys = new HashSet<>();
for (VisualizationSourceColumn column : getSelects(factory, true))
{
fieldKeys.addAll(column.getColumnInfo().getColumnLogging().getDataLoggingColumns());
}
Map<FieldKey, ColumnInfo> cols = QueryService.get().getColumns(getTableInfo(), fieldKeys);
for (FieldKey key : cols.keySet())
{
VisualizationSourceColumn dataLoggingColumn = factory.create(getSchema(), getQueryName(), key.toString(), true);
if (!_allSelects.contains(dataLoggingColumn))
{
dataLoggingColumn.setHidden(true);
dataLoggingColumns.add(dataLoggingColumn);
}
}
return dataLoggingColumns;
}
private String appendSimpleFilter(StringBuilder where, SimpleFilter filter, String separator)
{
Map<FieldKey, ColumnInfo> filterColTypes = getFilterColumns(filter);
List<SimpleFilter.FilterClause> clauses = new ArrayList<>(filter.getClauses());
for (SimpleFilter.FilterClause clause : clauses)
{
List<FieldKey> fieldKeys = clause.getFieldKeys();
boolean allColsFound = true;
for (FieldKey fieldKey : fieldKeys)
{
if (!filterColTypes.containsKey(fieldKey))
allColsFound = false;
}
if (allColsFound)
{
where.append(separator).append(" (").append(clause.getLabKeySQLWhereClause(filterColTypes)).append(") ");
separator = " AND\n";
}
else
{
// Remove filter clauses for columns that are no longer found on the specified query.
// Removing them here ensures that we send an accurate description of the current filters to the client.
for (FieldKey fieldKey : fieldKeys)
filter.deleteConditions(fieldKey);
}
}
return separator;
}
public String getWhereClause()
{
StringBuilder where = new StringBuilder();
String sep = "WHERE ";
for (SimpleFilter filter : _filters)
{
if (filter != null)
{
sep = appendSimpleFilter(where, filter, sep);
}
}
for (VisualizationSourceColumn select : _selects)
{
if (select.getValues() != null && !select.getValues().isEmpty())
{
where.append(sep);
appendColumnNames(where, Collections.singleton(select), false, false, false);
appendValueList(where, select);
sep = " AND\n";
}
}
for (VisualizationSourceColumn sort : _sorts)
{
if (sort.getValues() != null && !sort.getValues().isEmpty() && !_selects.contains(sort))
{
where.append(sep);
appendColumnNames(where, Collections.singleton(sort), false, false, false);
appendValueList(where, sort);
sep = " AND\n";
}
}
where.append("\n");
return where.toString();
}
@Override
public String getSQL(VisualizationSourceColumn.Factory factory) throws SQLGenerationException
{
return getSelectClause(factory) + "\n" +
getFromClause() + "\n" +
getWhereClause() + "\n" +
getGroupByClause() + "\n" +
getPivotClause() + "\n";
}
@Override
public IVisualizationSourceQuery getJoinTarget()
{
return _joinTarget;
}
public void setJoinTarget(IVisualizationSourceQuery joinTarget)
{
_joinTarget = joinTarget;
}
public String getSchemaName()
{
return _schema.getSchemaName();
}
@Override
public UserSchema getSchema()
{
return _schema;
}
@Override
public String getQueryName()
{
return _queryName;
}
public void addFilter(@NotNull SimpleFilter filter)
{
if (null != filter)
_filters.add(filter);
}
public SimpleFilter[] getFilters()
{
return _filters.toArray(new SimpleFilter[0]);
}
@Override
public boolean isSkipVisitJoin()
{
return _skipVisitJoin;
}
public void setSkipVisitJoin(boolean skipVisitJoin)
{
_skipVisitJoin = skipVisitJoin;
}
}