/
DataTierManagerImpl.java
1302 lines (1232 loc) · 51.6 KB
/
DataTierManagerImpl.java
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
/*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.dqp.internal.process;
import java.io.IOException;
import java.sql.Clob;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.api.exception.query.QueryMetadataException;
import org.teiid.client.RequestMessage;
import org.teiid.common.buffer.BlockedException;
import org.teiid.common.buffer.BufferManager;
import org.teiid.common.buffer.BufferManager.TupleSourceType;
import org.teiid.common.buffer.TupleBuffer;
import org.teiid.common.buffer.TupleSource;
import org.teiid.core.CoreConstants;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.BlobType;
import org.teiid.core.types.ClobImpl;
import org.teiid.core.types.ClobType;
import org.teiid.core.types.SQLXMLImpl;
import org.teiid.core.types.XMLType;
import org.teiid.core.util.Assertion;
import org.teiid.core.util.ObjectConverterUtil;
import org.teiid.core.util.StringUtil;
import org.teiid.dqp.internal.datamgr.ConnectorManager;
import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
import org.teiid.dqp.internal.datamgr.ConnectorWork;
import org.teiid.dqp.internal.process.AbstractWorkItem.ThreadState;
import org.teiid.dqp.internal.process.DQPCore.CompletionListener;
import org.teiid.dqp.internal.process.RecordTable.ExpandingSimpleIterator;
import org.teiid.dqp.internal.process.RecordTable.SimpleIterator;
import org.teiid.dqp.internal.process.RecordTable.SimpleIteratorWrapper;
import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
import org.teiid.dqp.internal.process.TupleSourceCache.CachableVisitor;
import org.teiid.dqp.internal.process.TupleSourceCache.CopyOnReadTupleSource;
import org.teiid.dqp.message.AtomicRequestMessage;
import org.teiid.events.EventDistributor;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.logging.MessageLevel;
import org.teiid.metadata.*;
import org.teiid.metadata.Table.TriggerEvent;
import org.teiid.metadata.Table.Type;
import org.teiid.query.QueryPlugin;
import org.teiid.query.metadata.CompositeMetadataStore;
import org.teiid.query.metadata.CompositeMetadataStore.RecordHolder;
import org.teiid.query.metadata.SystemMetadata;
import org.teiid.query.metadata.TempMetadataID;
import org.teiid.query.metadata.TransformationMetadata;
import org.teiid.query.optimizer.relational.RelationalPlanner;
import org.teiid.query.parser.ParseInfo;
import org.teiid.query.processor.CollectionTupleSource;
import org.teiid.query.processor.ProcessorDataManager;
import org.teiid.query.processor.RegisterRequestParameter;
import org.teiid.query.processor.relational.RelationalNodeUtil;
import org.teiid.query.resolver.util.ResolverUtil;
import org.teiid.query.sql.lang.Command;
import org.teiid.query.sql.lang.Criteria;
import org.teiid.query.sql.lang.Query;
import org.teiid.query.sql.lang.StoredProcedure;
import org.teiid.query.sql.lang.UnaryFromClause;
import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
import org.teiid.query.sql.symbol.Constant;
import org.teiid.query.sql.symbol.ElementSymbol;
import org.teiid.query.sql.symbol.GroupSymbol;
import org.teiid.query.sql.visitor.GroupCollectorVisitor;
import org.teiid.query.tempdata.BaseIndexInfo;
import org.teiid.query.tempdata.GlobalTableStore;
import org.teiid.query.tempdata.GlobalTableStoreImpl.MatTableInfo;
import org.teiid.query.util.CommandContext;
import org.teiid.translator.CacheDirective;
import org.teiid.translator.CacheDirective.Invalidation;
import org.teiid.translator.CacheDirective.Scope;
import org.teiid.translator.TranslatorException;
/**
* Full {@link ProcessorDataManager} implementation that
* controls access to {@link ConnectorManager}s and handles system queries.
*/
public class DataTierManagerImpl implements ProcessorDataManager {
private static final int MAX_VALUE_LENGTH = 1 << 21;
private static final class ThreadBoundTask implements Callable<Void>, CompletionListener<Void> {
private final RequestWorkItem workItem;
private final TupleSource toRead;
final AtomicBoolean done = new AtomicBoolean();
private final DataTierTupleSource dtts;
private ThreadBoundTask(RequestWorkItem workItem, TupleSource toRead, DataTierTupleSource dtts) {
this.workItem = workItem;
this.toRead = toRead;
this.dtts = dtts;
}
@Override
public Void call() throws TeiidProcessingException, TeiidComponentException {
//pull the whole thing. the side effect will be saving
while (true) {
try {
if (done.get() || toRead.nextTuple() == null) {
break;
}
signalMore();
} catch (BlockedException e) {
//data not available
Future<Void> future = dtts.getScheduledFuture();
if (future != null) {
try {
future.get();
} catch (Exception e1) {
throw new TeiidComponentException(e);
}
}
}
};
return null;
}
private void signalMore() {
if (!done.get()) {
synchronized (workItem) {
if (workItem.getThreadState() != ThreadState.MORE_WORK) {
workItem.moreWork();
}
}
}
}
@Override
public void onCompletion(FutureWork<Void> future) {
signalMore();
toRead.closeSource();
dtts.fullyCloseSource();
}
}
private enum SystemTables {
VIRTUALDATABASES,
SCHEMAS,
TABLES,
DATATYPES,
COLUMNS,
KEYS,
PROCEDURES,
KEYCOLUMNS,
PROCEDUREPARAMS,
REFERENCEKEYCOLUMNS,
PROPERTIES
}
private enum SystemAdminTables {
MATVIEWS,
VDBRESOURCES,
TRIGGERS,
VIEWS,
STOREDPROCEDURES,
USAGE
}
private enum SystemAdminProcs {
SETTABLESTATS,
SETCOLUMNSTATS,
SETPROPERTY,
LOGMSG,
ISLOGGABLE,
}
private enum SystemProcs {
GETXMLSCHEMAS,
}
private static final TreeMap<String, Integer> levelMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
static {
levelMap.put("OFF", MessageLevel.NONE); //$NON-NLS-1$
levelMap.put("FATAL", MessageLevel.CRITICAL); //$NON-NLS-1$
levelMap.put("ERROR", MessageLevel.ERROR); //$NON-NLS-1$
levelMap.put("WARN", MessageLevel.WARNING); //$NON-NLS-1$
levelMap.put("INFO", MessageLevel.INFO); //$NON-NLS-1$
levelMap.put("DEBUG", MessageLevel.DETAIL); //$NON-NLS-1$
levelMap.put("TRACE", MessageLevel.TRACE); //$NON-NLS-1$
}
public static int getLevel(String level) throws TeiidProcessingException {
Integer intLevel = levelMap.get(level);
if (intLevel == null) {
throw new TeiidProcessingException(QueryPlugin.Event.TEIID30546, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30546, level, levelMap.keySet()));
}
return intLevel;
}
// Resources
DQPCore requestMgr;
private BufferManager bufferManager;
private EventDistributor eventDistributor;
private boolean detectChangeEvents;
private Map<SystemTables, BaseExtractionTable<?>> systemTables = new HashMap<SystemTables, BaseExtractionTable<?>>();
private Map<SystemAdminTables, BaseExtractionTable<?>> systemAdminTables = new HashMap<SystemAdminTables, BaseExtractionTable<?>>();
public DataTierManagerImpl(DQPCore requestMgr, BufferManager bufferMgr, boolean detectChangeEvents) {
this.requestMgr = requestMgr;
this.bufferManager = bufferMgr;
this.detectChangeEvents = detectChangeEvents;
MetadataStore ms = SystemMetadata.getInstance().getSystemStore();
TransformationMetadata tm = new TransformationMetadata(null, new CompositeMetadataStore(ms), null, null, null);
String name = SystemTables.SCHEMAS.name();
List<ElementSymbol> columns = getColumns(tm, name);
systemTables.put(SystemTables.SCHEMAS, new RecordExtractionTable<Schema>(new SchemaRecordTable(1, columns), columns) {
@Override
public void fillRow(List<Object> row, Schema model,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<Schema> iter) {
row.add(vdb.getName());
row.add(model.getName());
row.add(model.isPhysical());
row.add(model.getUUID());
row.add(model.getAnnotation());
row.add(model.getPrimaryMetamodelUri());
row.add(null);
}
});
name = SystemTables.TABLES.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.TABLES, new RecordExtractionTable<Table>(new TableSystemTable(1, 2, columns), columns) {
@Override
public void fillRow(List<Object> row, Table table,
VDBMetaData v, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<Table> iter) {
row.add(v.getName());
row.add(table.getParent().getName());
row.add(table.getName());
row.add(table.getTableType().toString());
row.add(table.getNameInSource());
row.add(table.isPhysical());
row.add(table.supportsUpdate());
row.add(table.getUUID());
row.add(table.getCardinality());
row.add(table.getAnnotation());
row.add(table.isSystem());
row.add(table.isMaterialized());
row.add(null);
}
});
name = SystemAdminTables.MATVIEWS.name();
columns = getColumns(tm, name);
systemAdminTables.put(SystemAdminTables.MATVIEWS, new RecordExtractionTable<Table>(new TableSystemTable(1, 2, columns) {
@Override
protected boolean isValid(Table s, VDBMetaData vdb,
List<Object> rowBuffer, Criteria condition)
throws TeiidProcessingException, TeiidComponentException {
if (s == null || !s.isMaterialized()) {
return false;
}
return super.isValid(s, vdb, rowBuffer, condition);
}
}, columns) {
@Override
public void fillRow(List<Object> row, Table table,
VDBMetaData v, TransformationMetadata m, CommandContext cc, SimpleIterator<Table> iter) {
String targetSchema = null;
String matTableName = null;
String state = null;
Timestamp updated = null;
Integer cardinaltity = null;
Boolean valid = null;
if (table.getMaterializedTable() == null) {
GlobalTableStore globalStore = cc.getGlobalTableStore();
matTableName = RelationalPlanner.MAT_PREFIX+table.getFullName().toUpperCase();
TempMetadataID id = globalStore.getGlobalTempTableMetadataId(matTableName);
if (id != null && id.getCacheHint() != null && id.getCacheHint().getScope() != null && Scope.VDB.compareTo(id.getCacheHint().getScope()) > 0) {
//consult the session store instead
globalStore = cc.getSessionScopedStore(false);
if (globalStore == null) {
globalStore = cc.getGlobalTableStore();
}
}
MatTableInfo info = globalStore.getMatTableInfo(matTableName);
valid = info.isValid();
state = info.getState().name();
updated = info.getUpdateTime()==-1?null:new Timestamp(info.getUpdateTime());
if (id != null) {
cardinaltity = id.getCardinality();
}
//ttl, pref_mem - not part of proper metadata
} else {
Table t = table.getMaterializedTable();
matTableName = t.getName();
targetSchema = t.getParent().getName();
}
row.add(v.getName());
row.add(table.getParent().getName());
row.add(table.getName());
row.add(targetSchema);
row.add(matTableName);
row.add(valid);
row.add(state);
row.add(updated);
row.add(cardinaltity);
}
});
name = SystemAdminTables.VDBRESOURCES.name();
columns = getColumns(tm, name);
systemAdminTables.put(SystemAdminTables.VDBRESOURCES, new BaseExtractionTable<String>(columns) {
@Override
public SimpleIterator<String> createIterator(VDBMetaData vdb,
TransformationMetadata metadata, CommandContext cc) throws QueryMetadataException, TeiidComponentException {
String[] vals = metadata.getVDBResourcePaths();
return new SimpleIteratorWrapper<String>(Arrays.asList(vals).iterator());
}
@Override
public void fillRow(List<Object> row, String filePath,
VDBMetaData v, TransformationMetadata m, CommandContext cc, SimpleIterator<String> iter) {
row.add(filePath);
row.add(new BlobType(m.getVDBResourceAsBlob(filePath)));
}
});
name = SystemTables.PROCEDURES.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.PROCEDURES, new RecordExtractionTable<Procedure>(new ProcedureSystemTable(1, 2, columns), columns) {
@Override
public void fillRow(List<Object> row, Procedure proc,
VDBMetaData v, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<Procedure> iter) {
row.add(v.getName());
row.add(proc.getParent().getName());
row.add(proc.getName());
row.add(proc.getNameInSource());
row.add(proc.getResultSet() != null);
row.add(proc.getUUID());
row.add(proc.getAnnotation());
row.add(null);
}
});
name = SystemTables.DATATYPES.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.DATATYPES, new RecordExtractionTable<Datatype>(new RecordTable<Datatype>(new int[] {0}, columns) {
@Override
public SimpleIterator<Datatype> processQuery(VDBMetaData vdb,
CompositeMetadataStore metadataStore, BaseIndexInfo<?> ii) {
return processQuery(vdb, metadataStore.getDatatypes(), ii);
}
}, columns) {
@Override
public void fillRow(List<Object> row, Datatype datatype,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<Datatype> iter) {
row.add(datatype.getName());
row.add(datatype.isBuiltin());
row.add(datatype.isBuiltin());
row.add(datatype.getName());
row.add(datatype.getJavaClassName());
row.add(datatype.getScale());
row.add(datatype.getLength());
row.add(datatype.getNullType().toString());
row.add(datatype.isSigned());
row.add(datatype.isAutoIncrement());
row.add(datatype.isCaseSensitive());
row.add(datatype.getPrecision());
row.add(datatype.getRadix());
row.add(datatype.getSearchType().toString());
row.add(datatype.getUUID());
row.add(datatype.getRuntimeTypeName());
row.add(datatype.getBasetypeName());
row.add(datatype.getAnnotation());
row.add(null);
}
});
name = SystemTables.VIRTUALDATABASES.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.VIRTUALDATABASES, new BaseExtractionTable<VDBMetaData>(columns) {
@Override
public SimpleIterator<VDBMetaData> createIterator(VDBMetaData vdb,
TransformationMetadata metadata, CommandContext cc)
throws QueryMetadataException, TeiidComponentException {
return new SimpleIteratorWrapper<VDBMetaData>(Arrays.asList(vdb).iterator());
}
@Override
public void fillRow(List<Object> row, VDBMetaData record,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<VDBMetaData> iter) {
row.add(record.getName());
row.add(String.valueOf(record.getVersion()));
}
});
name = SystemTables.PROCEDUREPARAMS.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.PROCEDUREPARAMS, new ChildRecordExtractionTable<Procedure, BaseColumn>(new ProcedureSystemTable(1, 2, columns), columns) {
@Override
public void fillRow(List<Object> row, BaseColumn param,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<BaseColumn> iter) {
Datatype dt = param.getDatatype();
row.add(vdb.getName());
String type = "ResultSet"; //$NON-NLS-1$
AbstractMetadataRecord proc = param.getParent();
boolean isOptional = false;
if (param instanceof ProcedureParameter) {
ProcedureParameter pp = (ProcedureParameter)param;
type = pp.getType().name();
isOptional = pp.isOptional();
} else {
Column pp = (Column)param;
proc = param.getParent().getParent();
}
row.add(proc.getParent().getName());
row.add(proc.getName());
row.add(param.getName());
row.add(param.getRuntimeType());
row.add(param.getPosition());
row.add(type);
row.add(isOptional);
row.add(param.getPrecision());
row.add(param.getLength());
row.add(param.getScale());
row.add(param.getRadix());
row.add(param.getNullType().toString());
row.add(param.getUUID());
row.add(param.getAnnotation());
row.add(null);
}
@Override
protected Collection<? extends BaseColumn> getChildren(final Procedure parent) {
Collection<ProcedureParameter> params = parent.getParameters();
if (parent.getResultSet() == null) {
return params;
}
//TODO: don't incur the gc cost of the temp list
Collection<Column> rsColumns = parent.getResultSet().getColumns();
ArrayList<BaseColumn> result = new ArrayList<BaseColumn>(params.size() + rsColumns.size());
result.addAll(params);
result.addAll(rsColumns);
return result;
}
});
name = SystemTables.PROPERTIES.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.PROPERTIES, new ChildRecordExtractionTable<AbstractMetadataRecord, Map.Entry<String, String>>(
new RecordTable<AbstractMetadataRecord>(new int[] {0}, columns.subList(2, 3)) {
@Override
protected void fillRow(AbstractMetadataRecord s,
List<Object> rowBuffer) {
rowBuffer.add(s.getUUID());
}
@Override
public SimpleIterator<AbstractMetadataRecord> processQuery(
VDBMetaData vdb, CompositeMetadataStore metadataStore,
BaseIndexInfo<?> ii) {
return processQuery(vdb, metadataStore.getOids(), ii);
}
@Override
protected AbstractMetadataRecord extractRecord(Object val) {
if (val != null) {
return ((RecordHolder)val).getRecord();
}
return null;
}
}, columns) {
@Override
public void fillRow(List<Object> row, Map.Entry<String,String> entry, VDBMetaData vdb, TransformationMetadata metadata, CommandContext cc, SimpleIterator<Map.Entry<String, String>> iter) {
String value = entry.getValue();
Clob clobValue = null;
if (value != null) {
clobValue = new ClobType(new ClobImpl(value));
}
row.add(entry.getKey());
row.add(entry.getValue());
row.add(((ExpandingSimpleIterator<AbstractMetadataRecord, Entry<String, String>>)iter).getCurrentParent().getUUID());
row.add(null);
row.add(clobValue);
}
@Override
protected Collection<Map.Entry<String,String>> getChildren(AbstractMetadataRecord parent) {
return parent.getProperties().entrySet();
}
});
name = SystemAdminTables.TRIGGERS.name();
columns = getColumns(tm, name);
systemAdminTables.put(SystemAdminTables.TRIGGERS, new ChildRecordExtractionTable<Table, Trigger>(new TableSystemTable(1, 2, columns), columns) {
@Override
protected void fillRow(List<Object> row, Trigger record, VDBMetaData vdb, TransformationMetadata metadata, CommandContext cc, SimpleIterator<Trigger> iter) {
Clob clobValue = null;
if (record.body != null) {
clobValue = new ClobType(new ClobImpl(record.body));
}
AbstractMetadataRecord table = ((ExpandingSimpleIterator<AbstractMetadataRecord, Trigger>)iter).getCurrentParent();
row.add(vdb.getName());
row.add(table.getParent().getName());
row.add(table.getName());
row.add(record.name);
row.add(record.triggerType);
row.add(record.triggerEvent);
row.add(record.status);
row.add(clobValue);
row.add(table.getUUID());
}
@Override
protected Collection<Trigger> getChildren(Table table) {
ArrayList<Trigger> cols = new ArrayList<Trigger>();
if (table .isVirtual()) {
if (table.getInsertPlan() != null) {
cols.add(new Trigger("it", TriggerEvent.INSERT.name(), table.isInsertPlanEnabled(), null, table.getInsertPlan())); //$NON-NLS-1$
}
if (table.getUpdatePlan() != null) {
cols.add(new Trigger("ut", TriggerEvent.UPDATE.name(), table.isUpdatePlanEnabled(), null, table.getUpdatePlan())); //$NON-NLS-1$
}
if (table.getDeletePlan() != null) {
cols.add(new Trigger("dt", TriggerEvent.DELETE.name(), table.isDeletePlanEnabled(), null, table.getDeletePlan())); //$NON-NLS-1$
}
}
return cols;
}
});
name = SystemAdminTables.VIEWS.name();
columns = getColumns(tm, name);
systemAdminTables.put(SystemAdminTables.VIEWS, new RecordExtractionTable<Table>(new TableSystemTable(1, 2, columns) {
@Override
protected boolean isValid(Table s, VDBMetaData vdb,
List<Object> rowBuffer, Criteria condition)
throws TeiidProcessingException, TeiidComponentException {
if (s == null || !s.isVirtual()) {
return false;
}
return super.isValid(s, vdb, rowBuffer, condition);
}
}, columns) {
@Override
public void fillRow(List<Object> row, Table table,
VDBMetaData v, TransformationMetadata m, CommandContext cc, SimpleIterator<Table> iter) {
row.add(v.getName());
row.add(table.getParent().getName());
row.add(table.getName());
row.add(new ClobType(new ClobImpl(table.getSelectTransformation())));
row.add(table.getUUID());
}
});
name = SystemAdminTables.STOREDPROCEDURES.name();
columns = getColumns(tm, name);
systemAdminTables.put(SystemAdminTables.STOREDPROCEDURES, new RecordExtractionTable<Procedure>(new ProcedureSystemTable(1, 2, columns) {
@Override
protected boolean isValid(Procedure s, VDBMetaData vdb,
List<Object> rowBuffer, Criteria condition)
throws TeiidProcessingException, TeiidComponentException {
if (s == null || !s.isVirtual()) {
return false;
}
return super.isValid(s, vdb, rowBuffer, condition);
}
}, columns) {
@Override
public void fillRow(List<Object> row, Procedure proc,
VDBMetaData v, TransformationMetadata m, CommandContext cc,
SimpleIterator<Procedure> iter) {
row.add(v.getName());
row.add(proc.getParent().getName());
row.add(proc.getName());
row.add(new ClobType(new ClobImpl(proc.getQueryPlan())));
row.add(proc.getUUID());
}
});
name = SystemTables.COLUMNS.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.COLUMNS, new ChildRecordExtractionTable<Table, Column>(new TableSystemTable(1, 2, columns), columns) {
@Override
protected void fillRow(List<Object> row, Column column,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<Column> iter) {
Datatype dt = column.getDatatype();
row.add(vdb.getName());
row.add(column.getParent().getParent().getName());
row.add(column.getParent().getName());
row.add(column.getName());
row.add(column.getPosition());
row.add(column.getNameInSource());
row.add(column.getRuntimeType());
row.add(column.getScale());
row.add(column.getLength());
row.add(column.isFixedLength());
row.add(column.isSelectable());
row.add(column.isUpdatable());
row.add(column.isCaseSensitive());
row.add(column.isSigned());
row.add(column.isCurrency());
row.add(column.isAutoIncremented());
row.add(column.getNullType().toString());
row.add(column.getMinimumValue());
row.add(column.getMaximumValue());
row.add(column.getDistinctValues());
row.add(column.getNullValues());
row.add(column.getSearchType().toString());
row.add(column.getFormat());
row.add(column.getDefaultValue());
row.add(dt!=null?dt.getJavaClassName():null);
row.add(column.getPrecision());
row.add(column.getCharOctetLength());
row.add(column.getRadix());
row.add(column.getUUID());
row.add(column.getAnnotation());
row.add(null);
}
@Override
protected Collection<Column> getChildren(Table parent) {
return parent.getColumns();
}
});
name = SystemTables.KEYS.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.KEYS, new ChildRecordExtractionTable<Table, KeyRecord>(new TableSystemTable(1, 2, columns), columns) {
@Override
protected void fillRow(List<Object> row, KeyRecord key,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<KeyRecord> iter) {
row.add(vdb.getName());
row.add(key.getParent().getParent().getName());
row.add(key.getParent().getName());
row.add(key.getName());
row.add(key.getAnnotation());
row.add(key.getNameInSource());
row.add(key.getType().toString());
row.add(false);
row.add((key instanceof ForeignKey)?((ForeignKey)key).getUniqueKeyID():null);
row.add(key.getUUID());
row.add(null);
}
@Override
protected Collection<KeyRecord> getChildren(Table parent) {
return parent.getAllKeys();
}
});
name = SystemTables.KEYCOLUMNS.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.KEYCOLUMNS, new ChildRecordExtractionTable<Table, List<?>>(new TableSystemTable(1, 2, columns), columns) {
@Override
protected void fillRow(List<Object> row, List<?> record,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<List<?>> iter) {
row.add(vdb.getName());
KeyRecord key = (KeyRecord) record.get(0);
Column column = (Column) record.get(1);
Integer pos = (Integer) record.get(2);
row.add(key.getParent().getParent().getName());
row.add(key.getParent().getName());
row.add(column.getName());
row.add(key.getName());
row.add(key.getType().toString());
row.add((key instanceof ForeignKey)?((ForeignKey)key).getUniqueKeyID():null);
row.add(key.getUUID());
row.add(pos);
row.add(null);
}
@Override
protected Collection<List<?>> getChildren(Table parent) {
ArrayList<List<?>> cols = new ArrayList<List<?>>();
for (KeyRecord record : parent.getAllKeys()) {
int i = 1;
for (Column col : record.getColumns()) {
cols.add(Arrays.asList(record, col, i++));
}
}
return cols;
}
});
//we key the referencekeycolumns by fk
name = SystemTables.REFERENCEKEYCOLUMNS.name();
columns = getColumns(tm, name);
systemTables.put(SystemTables.REFERENCEKEYCOLUMNS, new ChildRecordExtractionTable<Table, List<?>>(new TableSystemTable(5, 6, columns), columns) {
@Override
protected void fillRow(List<Object> row, List<?> record,
VDBMetaData vdb, TransformationMetadata metadata,
CommandContext cc, SimpleIterator<List<?>> iter) {
row.add(vdb.getName());
ForeignKey key = (ForeignKey) record.get(0);
Table pkTable = key.getReferenceKey().getParent();
Column column = (Column) record.get(1);
Short pos = (Short) record.get(2);
row.add(pkTable.getParent().getName());
row.add(pkTable.getName());
row.add(key.getReferenceKey().getColumns().get(pos-1).getName());
row.add(vdb.getName());
row.add(key.getParent().getParent().getName());
row.add(key.getParent().getName());
row.add(column.getName());
row.add(pos);
row.add(DatabaseMetaData.importedKeyNoAction);
row.add(DatabaseMetaData.importedKeyNoAction);
row.add(key.getName());
row.add(key.getReferenceKey().getName());
row.add(DatabaseMetaData.importedKeyInitiallyDeferred);
}
@Override
protected Collection<List<?>> getChildren(Table parent) {
ArrayList<List<?>> cols = new ArrayList<List<?>>();
for (KeyRecord record : parent.getForeignKeys()) {
short i = 1;
for (Column col : record.getColumns()) {
cols.add(Arrays.asList(record, col, i++));
}
}
return cols;
}
});
name = SystemAdminTables.USAGE.name();
columns = getColumns(tm, name);
systemAdminTables.put(SystemAdminTables.USAGE, new ChildRecordExtractionTable<AbstractMetadataRecord, AbstractMetadataRecord>(
new RecordTable<AbstractMetadataRecord>(new int[] {0}, columns.subList(1, 2)) {
@Override
protected void fillRow(AbstractMetadataRecord s,
List<Object> rowBuffer) {
rowBuffer.add(s.getUUID());
}
@Override
public SimpleIterator<AbstractMetadataRecord> processQuery(
VDBMetaData vdb, CompositeMetadataStore metadataStore,
BaseIndexInfo<?> ii) {
return processQuery(vdb, metadataStore.getOids(), ii);
}
@Override
protected AbstractMetadataRecord extractRecord(Object val) {
if (val != null) {
return ((RecordHolder)val).getRecord();
}
return null;
}
}, columns) {
@Override
public void fillRow(List<Object> row, AbstractMetadataRecord entry, VDBMetaData vdb, TransformationMetadata metadata, CommandContext cc, SimpleIterator<AbstractMetadataRecord> iter) {
AbstractMetadataRecord currentParent = ((ExpandingSimpleIterator<AbstractMetadataRecord, AbstractMetadataRecord>)iter).getCurrentParent();
row.add(vdb.getName());
row.add(currentParent.getUUID());
row.add(getType(currentParent));
row.add(currentParent.getParent().getName());
row.add(currentParent.getName());
row.add(null); //column usage not yet supported
row.add(entry.getUUID());
row.add(getType(entry));
if (entry instanceof Column) {
row.add(entry.getParent().getParent().getName());
row.add(entry.getParent().getName());
row.add(entry.getName());
} else {
row.add(entry.getParent().getName());
row.add(entry.getName());
row.add(null);
}
}
private String getType(AbstractMetadataRecord record) {
if (record instanceof Table) {
Table t = (Table)record;
if (t.getTableType() == Type.Table && t.isVirtual()) {
//TODO: this change should be on the Table object as well
return "View"; //$NON-NLS-1$
}
return t.getTableType().name();
}
if (record instanceof Procedure) {
Procedure p = (Procedure)record;
if (p.isFunction()) {
return p.getType().name();
}
if (p.isVirtual()) {
return "StoredProcedure"; //$NON-NLS-1$
}
return "ForeignProcedure"; //$NON-NLS-1$
}
return record.getClass().getSimpleName();
}
@Override
protected Collection<AbstractMetadataRecord> getChildren(AbstractMetadataRecord parent) {
return parent.getIncomingObjects();
}
});
}
private List<ElementSymbol> getColumns(TransformationMetadata tm,
String name) {
GroupSymbol gs = new GroupSymbol(name);
try {
ResolverUtil.resolveGroup(gs, tm);
List<ElementSymbol> columns = ResolverUtil.resolveElementsInGroup(gs, tm);
return columns;
} catch (TeiidException e) {
throw new TeiidRuntimeException(e);
}
}
public boolean detectChangeEvents() {
return detectChangeEvents;
}
public void setEventDistributor(EventDistributor eventDistributor) {
this.eventDistributor = eventDistributor;
}
public EventDistributor getEventDistributor() {
return eventDistributor;
}
public TupleSource registerRequest(CommandContext context, Command command, String modelName, final RegisterRequestParameter parameterObject) throws TeiidComponentException, TeiidProcessingException {
RequestWorkItem workItem = context.getWorkItem();
Assertion.isNotNull(workItem);
if(CoreConstants.SYSTEM_MODEL.equals(modelName) || CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)) {
return processSystemQuery(context, command, workItem.getDqpWorkContext());
}
AtomicRequestMessage aqr = createRequest(workItem, command, modelName, parameterObject.connectorBindingId, parameterObject.nodeID);
aqr.setCommandContext(context);
if (parameterObject.fetchSize > 0) {
aqr.setFetchSize(2*parameterObject.fetchSize);
}
if (parameterObject.limit > 0) {
aqr.setFetchSize(Math.min(parameterObject.limit, aqr.getFetchSize()));
}
Collection<GroupSymbol> accessedGroups = null;
if (context.getDataObjects() != null) {
accessedGroups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(command, false);
for (GroupSymbol gs : accessedGroups) {
context.accessedDataObject(gs.getMetadataID());
}
}
ConnectorManagerRepository cmr = workItem.getDqpWorkContext().getVDB().getAttachment(ConnectorManagerRepository.class);
ConnectorManager connectorManager = cmr.getConnectorManager(aqr.getConnectorName());
if (connectorManager == null) {
//can happen if sources are removed
if (RelationalNodeUtil.hasOutputParams(command)) {
throw new AssertionError("A source is required to execute a procedure returning parameters"); //$NON-NLS-1$
}
LogManager.logDetail(LogConstants.CTX_DQP, "source", aqr.getConnectorName(), "no longer exists, returning dummy results"); //$NON-NLS-1$ //$NON-NLS-2$
return CollectionTupleSource.createNullTupleSource();
}
ConnectorWork work = connectorManager.registerRequest(aqr);
if (!work.isForkable()) {
aqr.setSerial(true);
}
CacheID cid = null;
CacheDirective cd = null;
if (workItem.getRsCache() != null && command.areResultsCachable()) {
CachableVisitor cv = new CachableVisitor();
PreOrPostOrderNavigator.doVisit(command, cv, PreOrPostOrderNavigator.PRE_ORDER, true);
if (cv.cacheable) {
try {
cd = work.getCacheDirective();
} catch (TranslatorException e) {
throw new TeiidProcessingException(QueryPlugin.Event.TEIID30504, e, aqr.getConnectorName() + ": " + e.getMessage()); //$NON-NLS-1$
}
if (cd != null) {
if (cd.getScope() == Scope.NONE) {
parameterObject.doNotCache = true;
} else {
String cmdString = command.toString();
if (cmdString.length() < 100000) { //TODO: this check won't be needed if keys aren't exclusively held in memory
cid = new CacheID(workItem.getDqpWorkContext(), ParseInfo.DEFAULT_INSTANCE, cmdString);
cid.setParameters(cv.parameters);
if (cd.getInvalidation() == null || cd.getInvalidation() == Invalidation.NONE) {
CachedResults cr = workItem.getRsCache().get(cid);
if (cr != null && (cr.getRowLimit() == 0 || (parameterObject.limit > 0 && cr.getRowLimit() >= parameterObject.limit))) {
parameterObject.doNotCache = true;
LogManager.logDetail(LogConstants.CTX_DQP, "Using cache entry for", cid); //$NON-NLS-1$
work.close();
return cr.getResults().createIndexedTupleSource();
}
} else if (cd.getInvalidation() == Invalidation.IMMEDIATE) {
workItem.getRsCache().remove(cid, CachingTupleSource.getDeterminismLevel(cd.getScope()));
}
}
}
} else {
LogManager.logTrace(LogConstants.CTX_DQP, aqr.getAtomicRequestID(), "no cache directive"); //$NON-NLS-1$
}
} else {
LogManager.logTrace(LogConstants.CTX_DQP, aqr.getAtomicRequestID(), "command not cachable"); //$NON-NLS-1$
}
}
DataTierTupleSource dtts = new DataTierTupleSource(aqr, workItem, work, this, parameterObject.limit);
TupleSource result = dtts;
TupleBuffer tb = null;
if (cid != null) {
tb = getBufferManager().createTupleBuffer(aqr.getCommand().getProjectedSymbols(), aqr.getCommandContext().getConnectionId(), TupleSourceType.PROCESSOR);
result = new CachingTupleSource(this, tb, (DataTierTupleSource)result, cid, parameterObject, cd, accessedGroups, workItem);
}
if (work.isThreadBound()) {
result = handleThreadBound(workItem, aqr, work, cid, result, dtts, tb);
} else if (!aqr.isSerial()) {
dtts.addWork();
}
return result;
}
/**
* thread bound work is tricky for our execution model
*
* the strategy here is that
*
* - if the result is not already a copying tuplesource (from caching)
* then wrap in a copying tuple source
*
* - submit a workitem that will pull the results/fill the buffer,
*
* - return a tuplesource off of the buffer for use by the caller
*/
private TupleSource handleThreadBound(final RequestWorkItem workItem,
AtomicRequestMessage aqr, ConnectorWork work, CacheID cid,
TupleSource result, DataTierTupleSource dtts, TupleBuffer tb) throws AssertionError,
TeiidComponentException, TeiidProcessingException {
if (workItem.useCallingThread) {
//in any case we want the underlying work done in the thread accessing the connectorworkitem
aqr.setSerial(true);
return result; //simple case, just rely on the client using the same thread
}
if (tb == null) {
tb = getBufferManager().createTupleBuffer(aqr.getCommand().getProjectedSymbols(), aqr.getCommandContext().getConnectionId(), TupleSourceType.PROCESSOR);
}
final TupleSource ts = tb.createIndexedTupleSource(cid == null);
if (cid == null) {
result = new CopyOnReadTupleSource(tb, result) {
@Override
public void closeSource() {
ts.closeSource();
}
};
}
final ThreadBoundTask callable = new ThreadBoundTask(workItem, result, dtts);
//if serial we have to fully perform the operation with the current thread
//but we do so lazily just in case the results aren't needed
if (aqr.isSerial()) {
return new TupleSource() {
boolean processed = false;