/
RelOptTableImpl.java
551 lines (484 loc) · 18.7 KB
/
RelOptTableImpl.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you 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.apache.calcite.prepare;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.materialize.Lattice;
import org.apache.calcite.plan.RelOptSchema;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelDistribution;
import org.apache.calcite.rel.RelDistributionTraitDef;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelReferentialConstraint;
import org.apache.calcite.rel.logical.LogicalTableScan;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rel.type.RelProtoDataType;
import org.apache.calcite.rel.type.RelRecordType;
import org.apache.calcite.schema.ColumnStrategy;
import org.apache.calcite.schema.FilterableTable;
import org.apache.calcite.schema.ModifiableTable;
import org.apache.calcite.schema.Path;
import org.apache.calcite.schema.ProjectableFilterableTable;
import org.apache.calcite.schema.QueryableTable;
import org.apache.calcite.schema.ScannableTable;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.SchemaVersion;
import org.apache.calcite.schema.Schemas;
import org.apache.calcite.schema.StreamableTable;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.TemporalTable;
import org.apache.calcite.schema.TranslatableTable;
import org.apache.calcite.schema.Wrapper;
import org.apache.calcite.sql.SqlAccessType;
import org.apache.calcite.sql.validate.SqlModality;
import org.apache.calcite.sql.validate.SqlMonotonicity;
import org.apache.calcite.sql2rel.InitializerExpressionFactory;
import org.apache.calcite.sql2rel.NullInitializerExpressionFactory;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.Pair;
import org.apache.calcite.util.Util;
import com.google.common.collect.ImmutableList;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
/**
* Implementation of {@link org.apache.calcite.plan.RelOptTable}.
*/
public class RelOptTableImpl extends Prepare.AbstractPreparingTable {
private final @Nullable RelOptSchema schema;
private final RelDataType rowType;
private final @Nullable Table table;
private final @Nullable Function<Class, Expression> expressionFunction;
private final ImmutableList<String> names;
/** Estimate for the row count, or null.
*
* <p>If not null, overrides the estimate from the actual table.
*
* <p>Useful when a table that contains a materialized query result is being
* used to replace a query expression that wildly underestimates the row
* count. Now the materialized table can tell the same lie. */
private final @Nullable Double rowCount;
private RelOptTableImpl(
@Nullable RelOptSchema schema,
RelDataType rowType,
List<String> names,
@Nullable Table table,
@Nullable Function<Class, Expression> expressionFunction,
@Nullable Double rowCount) {
this.schema = schema;
this.rowType = requireNonNull(rowType, "rowType");
this.names = ImmutableList.copyOf(names);
this.table = table; // may be null
this.expressionFunction = expressionFunction; // may be null
this.rowCount = rowCount; // may be null
}
public static RelOptTableImpl create(
@Nullable RelOptSchema schema,
RelDataType rowType,
List<String> names,
Expression expression) {
return new RelOptTableImpl(schema, rowType, names, null,
c -> expression, null);
}
public static RelOptTableImpl create(
@Nullable RelOptSchema schema,
RelDataType rowType,
List<String> names,
Table table,
Expression expression) {
return new RelOptTableImpl(schema, rowType, names, table,
c -> expression, table.getStatistic().getRowCount());
}
public static RelOptTableImpl create(@Nullable RelOptSchema schema, RelDataType rowType,
Table table, Path path) {
final SchemaPlus schemaPlus = MySchemaPlus.create(path);
return new RelOptTableImpl(schema, rowType, Pair.left(path), table,
getClassExpressionFunction(schemaPlus, Util.last(path).left, table),
table.getStatistic().getRowCount());
}
public static RelOptTableImpl create(@Nullable RelOptSchema schema, RelDataType rowType,
final CalciteSchema.TableEntry tableEntry, @Nullable Double rowCount) {
final Table table = tableEntry.getTable();
return new RelOptTableImpl(schema, rowType, tableEntry.path(),
table, getClassExpressionFunction(tableEntry, table), rowCount);
}
/**
* Creates a copy of this RelOptTable. The new RelOptTable will have newRowType.
*/
public RelOptTableImpl copy(RelDataType newRowType) {
return new RelOptTableImpl(this.schema, newRowType, this.names, this.table,
this.expressionFunction, this.rowCount);
}
@Override public String toString() {
return "RelOptTableImpl{"
+ "schema=" + schema
+ ", names= " + names
+ ", table=" + table
+ ", rowType=" + rowType
+ '}';
}
private static Function<Class, Expression> getClassExpressionFunction(
CalciteSchema.TableEntry tableEntry, Table table) {
return getClassExpressionFunction(tableEntry.schema.plus(), tableEntry.name,
table);
}
private static Function<Class, Expression> getClassExpressionFunction(
final SchemaPlus schema, final String tableName, final Table table) {
if (table instanceof QueryableTable) {
final QueryableTable queryableTable = (QueryableTable) table;
return clazz -> queryableTable.getExpression(schema, tableName, clazz);
} else if (table instanceof ScannableTable
|| table instanceof FilterableTable
|| table instanceof ProjectableFilterableTable) {
return clazz -> Schemas.tableExpression(schema, Object[].class, tableName,
table.getClass());
} else if (table instanceof StreamableTable) {
return getClassExpressionFunction(schema, tableName,
((StreamableTable) table).stream());
} else {
return input -> {
throw new UnsupportedOperationException();
};
}
}
public static RelOptTableImpl create(@Nullable RelOptSchema schema,
RelDataType rowType, Table table, ImmutableList<String> names) {
assert table instanceof TranslatableTable
|| table instanceof ScannableTable
|| table instanceof ModifiableTable;
return new RelOptTableImpl(schema, rowType, names, table, null, null);
}
@Override public <T extends Object> @Nullable T unwrap(Class<T> clazz) {
if (clazz.isInstance(this)) {
return clazz.cast(this);
}
if (clazz.isInstance(table)) {
return clazz.cast(table);
}
if (table instanceof Wrapper) {
final T t = ((Wrapper) table).unwrap(clazz);
if (t != null) {
return t;
}
}
if (clazz == CalciteSchema.class && schema != null) {
return clazz.cast(
Schemas.subSchema(((CalciteCatalogReader) schema).rootSchema,
Util.skipLast(getQualifiedName())));
}
return null;
}
@Override public @Nullable Expression getExpression(Class clazz) {
if (expressionFunction == null) {
return null;
}
return expressionFunction.apply(clazz);
}
@Override protected RelOptTable extend(Table extendedTable) {
RelOptSchema schema = requireNonNull(getRelOptSchema(), "relOptSchema");
final RelDataType extendedRowType =
extendedTable.getRowType(schema.getTypeFactory());
return new RelOptTableImpl(schema, extendedRowType, getQualifiedName(),
extendedTable, expressionFunction, getRowCount());
}
@Override public boolean equals(@Nullable Object obj) {
return obj instanceof RelOptTableImpl
&& this.rowType.equals(((RelOptTableImpl) obj).getRowType())
&& this.table == ((RelOptTableImpl) obj).table;
}
@Override public int hashCode() {
return (this.table == null)
? super.hashCode() : this.table.hashCode();
}
@Override public double getRowCount() {
if (rowCount != null) {
return rowCount;
}
if (table != null) {
final Double rowCount = table.getStatistic().getRowCount();
if (rowCount != null) {
return rowCount;
}
}
return 100d;
}
@Override public @Nullable RelOptSchema getRelOptSchema() {
return schema;
}
@Override public RelNode toRel(ToRelContext context) {
// Make sure rowType's list is immutable. If rowType is DynamicRecordType, creates a new
// RelOptTable by replacing with immutable RelRecordType using the same field list.
if (this.getRowType().isDynamicStruct()) {
final RelDataType staticRowType = new RelRecordType(getRowType().getFieldList());
final RelOptTable relOptTable = this.copy(staticRowType);
return relOptTable.toRel(context);
}
// If there are any virtual columns, create a copy of this table without
// those virtual columns.
final List<ColumnStrategy> strategies = getColumnStrategies();
if (strategies.contains(ColumnStrategy.VIRTUAL)) {
final RelDataTypeFactory.Builder b =
context.getCluster().getTypeFactory().builder();
for (RelDataTypeField field : rowType.getFieldList()) {
if (strategies.get(field.getIndex()) != ColumnStrategy.VIRTUAL) {
b.add(field.getName(), field.getType());
}
}
final RelOptTable relOptTable =
new RelOptTableImpl(this.schema, b.build(), this.names, this.table,
this.expressionFunction, this.rowCount) {
@Override public <T extends Object> @Nullable T unwrap(Class<T> clazz) {
if (clazz.isAssignableFrom(InitializerExpressionFactory.class)) {
return clazz.cast(NullInitializerExpressionFactory.INSTANCE);
}
return super.unwrap(clazz);
}
};
return relOptTable.toRel(context);
}
if (table instanceof TranslatableTable) {
return ((TranslatableTable) table).toRel(context, this);
}
return LogicalTableScan.create(context.getCluster(), this, context.getTableHints());
}
@Override public @Nullable List<RelCollation> getCollationList() {
if (table != null) {
return table.getStatistic().getCollations();
}
return ImmutableList.of();
}
@Override public @Nullable RelDistribution getDistribution() {
if (table != null) {
return table.getStatistic().getDistribution();
}
return RelDistributionTraitDef.INSTANCE.getDefault();
}
@Override public boolean isKey(ImmutableBitSet columns) {
if (table != null) {
return table.getStatistic().isKey(columns);
}
return false;
}
@Override public @Nullable List<ImmutableBitSet> getKeys() {
if (table != null) {
return table.getStatistic().getKeys();
}
return ImmutableList.of();
}
@Override public @Nullable List<RelReferentialConstraint> getReferentialConstraints() {
if (table != null) {
return table.getStatistic().getReferentialConstraints();
}
return ImmutableList.of();
}
@Override public RelDataType getRowType() {
return rowType;
}
@Override public boolean supportsModality(SqlModality modality) {
switch (modality) {
case STREAM:
return table instanceof StreamableTable;
default:
return !(table instanceof StreamableTable);
}
}
@Override public boolean isTemporal() {
return table instanceof TemporalTable;
}
@Override public List<String> getQualifiedName() {
return names;
}
@Override public SqlMonotonicity getMonotonicity(String columnName) {
if (table == null) {
return SqlMonotonicity.NOT_MONOTONIC;
}
List<RelCollation> collations = table.getStatistic().getCollations();
if (collations == null) {
return SqlMonotonicity.NOT_MONOTONIC;
}
for (RelCollation collation : collations) {
final RelFieldCollation fieldCollation =
collation.getFieldCollations().get(0);
final int fieldIndex = fieldCollation.getFieldIndex();
if (fieldIndex < rowType.getFieldCount()
&& rowType.getFieldNames().get(fieldIndex).equals(columnName)) {
return fieldCollation.direction.monotonicity();
}
}
return SqlMonotonicity.NOT_MONOTONIC;
}
@Override public SqlAccessType getAllowedAccess() {
return SqlAccessType.ALL;
}
/** Helper for {@link #getColumnStrategies()}. */
public static List<ColumnStrategy> columnStrategies(final RelOptTable table) {
final int fieldCount = table.getRowType().getFieldCount();
final InitializerExpressionFactory ief =
Util.first(table.unwrap(InitializerExpressionFactory.class),
NullInitializerExpressionFactory.INSTANCE);
return new AbstractList<ColumnStrategy>() {
@Override public int size() {
return fieldCount;
}
@Override public ColumnStrategy get(int index) {
return ief.generationStrategy(table, index);
}
};
}
/** Converts the ordinal of a field into the ordinal of a stored field.
* That is, it subtracts the number of virtual fields that come before it. */
public static int realOrdinal(final RelOptTable table, int i) {
List<ColumnStrategy> strategies = table.getColumnStrategies();
int n = 0;
for (int j = 0; j < i; j++) {
switch (strategies.get(j)) {
case VIRTUAL:
++n;
break;
default:
break;
}
}
return i - n;
}
/** Returns the row type of a table after any {@link ColumnStrategy#VIRTUAL}
* columns have been removed. This is the type of the records that are
* actually stored. */
public static RelDataType realRowType(RelOptTable table) {
final RelDataType rowType = table.getRowType();
final List<ColumnStrategy> strategies = columnStrategies(table);
if (!strategies.contains(ColumnStrategy.VIRTUAL)) {
return rowType;
}
final RelDataTypeFactory.Builder builder =
requireNonNull(table.getRelOptSchema(),
() -> "relOptSchema for table " + table).getTypeFactory().builder();
for (RelDataTypeField field : rowType.getFieldList()) {
if (strategies.get(field.getIndex()) != ColumnStrategy.VIRTUAL) {
builder.add(field);
}
}
return builder.build();
}
/** Implementation of {@link SchemaPlus} that wraps a regular schema and knows
* its name and parent.
*
* <p>It is read-only, and functionality is limited in other ways, it but
* allows table expressions to be generated. */
private static class MySchemaPlus implements SchemaPlus {
private final @Nullable SchemaPlus parent;
private final String name;
private final Schema schema;
MySchemaPlus(@Nullable SchemaPlus parent, String name, Schema schema) {
this.parent = parent;
this.name = name;
this.schema = schema;
}
public static MySchemaPlus create(Path path) {
final Pair<String, Schema> pair = Util.last(path);
final SchemaPlus parent;
if (path.size() == 1) {
parent = null;
} else {
parent = create(path.parent());
}
return new MySchemaPlus(parent, pair.left, pair.right);
}
@Override public @Nullable SchemaPlus getParentSchema() {
return parent;
}
@Override public String getName() {
return name;
}
@Override public @Nullable SchemaPlus getSubSchema(String name) {
final Schema subSchema = schema.getSubSchema(name);
return subSchema == null ? null : new MySchemaPlus(this, name, subSchema);
}
@Override public SchemaPlus add(String name, Schema schema) {
throw new UnsupportedOperationException();
}
@Override public void add(String name, Table table) {
throw new UnsupportedOperationException();
}
@Override public boolean removeTable(String name) {
throw new UnsupportedOperationException();
}
@Override public void add(String name,
org.apache.calcite.schema.Function function) {
throw new UnsupportedOperationException();
}
@Override public void add(String name, RelProtoDataType type) {
throw new UnsupportedOperationException();
}
@Override public void add(String name, Lattice lattice) {
throw new UnsupportedOperationException();
}
@Override public boolean isMutable() {
return schema.isMutable();
}
@Override public <T extends Object> @Nullable T unwrap(Class<T> clazz) {
return null;
}
@Override public void setPath(ImmutableList<ImmutableList<String>> path) {
throw new UnsupportedOperationException();
}
@Override public void setCacheEnabled(boolean cache) {
throw new UnsupportedOperationException();
}
@Override public boolean isCacheEnabled() {
return false;
}
@Override public @Nullable Table getTable(String name) {
return schema.getTable(name);
}
@Override public Set<String> getTableNames() {
return schema.getTableNames();
}
@Override public @Nullable RelProtoDataType getType(String name) {
return schema.getType(name);
}
@Override public Set<String> getTypeNames() {
return schema.getTypeNames();
}
@Override public Collection<org.apache.calcite.schema.Function>
getFunctions(String name) {
return schema.getFunctions(name);
}
@Override public Set<String> getFunctionNames() {
return schema.getFunctionNames();
}
@Override public Set<String> getSubSchemaNames() {
return schema.getSubSchemaNames();
}
@Override public Expression getExpression(@Nullable SchemaPlus parentSchema,
String name) {
return schema.getExpression(parentSchema, name);
}
@Override public Schema snapshot(SchemaVersion version) {
throw new UnsupportedOperationException();
}
}
}