org.apache.calcite.schema.QueryableTable Java Examples

The following examples show how to use org.apache.calcite.schema.QueryableTable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EnumerableTableScan.java    From Bats with Apache License 2.0 6 votes vote down vote up
public static Class deduceElementType(Table table) {
  if (table instanceof QueryableTable) {
    final QueryableTable queryableTable = (QueryableTable) table;
    final Type type = queryableTable.getElementType();
    if (type instanceof Class) {
      return (Class) type;
    } else {
      return Object[].class;
    }
  } else if (table instanceof ScannableTable
      || table instanceof FilterableTable
      || table instanceof StreamableTable) {
    return Object[].class;
  } else {
    return Object.class;
  }
}
 
Example #2
Source File: Smalls.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * A function that sums the second column of first input cursor, second
 * column of first input and the given int.
 */
public static QueryableTable processCursors(final int offset,
    final Enumerable<Object[]> a, final Enumerable<IntString> b) {
  return new AbstractQueryableTable(Object[].class) {
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      return typeFactory.builder()
          .add("result", SqlTypeName.INTEGER)
          .build();
    }

    public <T> Queryable<T> asQueryable(QueryProvider queryProvider,
        SchemaPlus schema, String tableName) {
      final Enumerable<Integer> enumerable =
          a.zip(b, (v0, v1) -> ((Integer) v0[1]) + v1.n + offset);
      //noinspection unchecked
      return (Queryable) enumerable.asQueryable();
    }
  };
}
 
Example #3
Source File: Smalls.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * A function that adds a number to the first column of input cursor
 */
public static QueryableTable processCursor(final int offset,
    final Enumerable<Object[]> a) {
  return new AbstractQueryableTable(Object[].class) {
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      return typeFactory.builder()
          .add("result", SqlTypeName.INTEGER)
          .build();
    }

    public <T> Queryable<T> asQueryable(QueryProvider queryProvider,
        SchemaPlus schema, String tableName) {
      final Enumerable<Integer> enumerable =
          a.select(a0 -> offset + ((Integer) a0[0]));
      //noinspection unchecked
      return (Queryable) enumerable.asQueryable();
    }
  };
}
 
Example #4
Source File: Smalls.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static QueryableTable oneThreePlus(String s) {
  List<Integer> items;
  // Argument is null in case SQL contains function call with expression.
  // Then the engine calls a function with null arguments to get getRowType.
  if (s == null) {
    items = ImmutableList.of();
  } else {
    Integer latest = Integer.parseInt(s.substring(1, s.length() - 1));
    items = ImmutableList.of(1, 3, latest);
  }
  final Enumerable<Integer> enumerable = Linq4j.asEnumerable(items);
  return new AbstractQueryableTable(Integer.class) {
    public <E> Queryable<E> asQueryable(
        QueryProvider queryProvider, SchemaPlus schema, String tableName) {
      //noinspection unchecked
      return (Queryable<E>) enumerable.asQueryable();
    }

    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      return typeFactory.builder().add("c", SqlTypeName.INTEGER).build();
    }
  };
}
 
Example #5
Source File: TableFunctionImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static CallImplementor createImplementor(final Method method) {
  return RexImpTable.createImplementor(
      new ReflectiveCallNotNullImplementor(method) {
        public Expression implement(RexToLixTranslator translator,
            RexCall call, List<Expression> translatedOperands) {
          Expression expr = super.implement(translator, call,
              translatedOperands);
          final Class<?> returnType = method.getReturnType();
          if (QueryableTable.class.isAssignableFrom(returnType)) {
            Expression queryable = Expressions.call(
                Expressions.convert_(expr, QueryableTable.class),
                BuiltInMethod.QUERYABLE_TABLE_AS_QUERYABLE.method,
                Expressions.call(DataContext.ROOT,
                    BuiltInMethod.DATA_CONTEXT_GET_QUERY_PROVIDER.method),
                Expressions.constant(null, SchemaPlus.class),
                Expressions.constant(call.getOperator().getName(), String.class));
            expr = Expressions.call(queryable,
                BuiltInMethod.QUERYABLE_AS_ENUMERABLE.method);
          } else {
            expr = Expressions.call(expr,
                BuiltInMethod.SCANNABLE_TABLE_SCAN.method, DataContext.ROOT);
          }
          return expr;
        }
      }, NullPolicy.NONE, false);
}
 
Example #6
Source File: TableFunctionImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a {@link TableFunctionImpl} from a method. */
public static TableFunction create(final Method method) {
  if (!Modifier.isStatic(method.getModifiers())) {
    Class clazz = method.getDeclaringClass();
    if (!classHasPublicZeroArgsConstructor(clazz)) {
      throw RESOURCE.requireDefaultConstructor(clazz.getName()).ex();
    }
  }
  final Class<?> returnType = method.getReturnType();
  if (!QueryableTable.class.isAssignableFrom(returnType)
      && !ScannableTable.class.isAssignableFrom(returnType)) {
    return null;
  }
  CallImplementor implementor = createImplementor(method);
  return new TableFunctionImpl(method, implementor);
}
 
Example #7
Source File: EnumerableTableFunctionScan.java    From calcite with Apache License 2.0 6 votes vote down vote up
private boolean isQueryable() {
  if (!(getCall() instanceof RexCall)) {
    return false;
  }
  final RexCall call = (RexCall) getCall();
  if (!(call.getOperator() instanceof SqlUserDefinedTableFunction)) {
    return false;
  }
  final SqlUserDefinedTableFunction udtf =
      (SqlUserDefinedTableFunction) call.getOperator();
  if (!(udtf.getFunction() instanceof TableFunctionImpl)) {
    return false;
  }
  final TableFunctionImpl tableFunction =
      (TableFunctionImpl) udtf.getFunction();
  final Method method = tableFunction.method;
  return QueryableTable.class.isAssignableFrom(method.getReturnType());
}
 
Example #8
Source File: EnumerableTableScan.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static Class deduceElementType(Table table) {
  if (table instanceof QueryableTable) {
    final QueryableTable queryableTable = (QueryableTable) table;
    final Type type = queryableTable.getElementType();
    if (type instanceof Class) {
      return (Class) type;
    } else {
      return Object[].class;
    }
  } else if (table instanceof ScannableTable
      || table instanceof FilterableTable
      || table instanceof ProjectableFilterableTable
      || table instanceof StreamableTable) {
    return Object[].class;
  } else {
    return Object.class;
  }
}
 
Example #9
Source File: RelOptTableImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
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();
    };
  }
}
 
Example #10
Source File: QueryableRelBuilder.java    From calcite with Apache License 2.0 6 votes vote down vote up
RelNode toRel(Queryable<T> queryable) {
  if (queryable instanceof QueryableDefaults.Replayable) {
    //noinspection unchecked
    ((QueryableDefaults.Replayable) queryable).replay(this);
    return rel;
  }
  if (queryable instanceof AbstractTableQueryable) {
    final AbstractTableQueryable tableQueryable =
        (AbstractTableQueryable) queryable;
    final QueryableTable table = tableQueryable.table;
    final CalciteSchema.TableEntry tableEntry =
        CalciteSchema.from(tableQueryable.schema)
            .add(tableQueryable.tableName, tableQueryable.table);
    final RelOptTableImpl relOptTable =
        RelOptTableImpl.create(null, table.getRowType(translator.typeFactory),
            tableEntry, null);
    if (table instanceof TranslatableTable) {
      return ((TranslatableTable) table).toRel(translator.toRelContext(),
          relOptTable);
    } else {
      return LogicalTableScan.create(translator.cluster, relOptTable, ImmutableList.of());
    }
  }
  return translator.translate(queryable.getExpression());
}
 
Example #11
Source File: TableFunctions.java    From mat-calcite-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static QueryableTable getInboundReferences(Object r) {
    List<HeapReference> references;
    if (!(r instanceof HeapReference)) {
        references = Collections.emptyList();
    } else {
        HeapReference ref = (HeapReference) r;
        ISnapshot snapshot = ref.getIObject().getSnapshot();
        try {
            references = collectReferences
                    (
                            snapshot,
                            snapshot.getInboundRefererIds(ref.getIObject().getObjectId())
                    );
        } catch (SnapshotException e) {
            throw new RuntimeException("Cannot extract inbound references from " + r, e);
        }
    }
    return new HeapReferenceTable(references, true);
}
 
Example #12
Source File: TableFunctions.java    From mat-calcite-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static QueryableTable getValues(Object r) {
    List<HeapReference> references;
    if (!(r instanceof HeapReference)) {
        references = Collections.emptyList();
    } else {
        HeapReference ref = (HeapReference) r;
        try {
            ICollectionExtractor collectionExtractor = CollectionExtractionUtils.findCollectionExtractor(ref.getIObject());
            if (collectionExtractor == null) {
                references = Collections.emptyList();
            } else {
                references = collectReferences(ref.getIObject().getSnapshot(), collectionExtractor.extractEntryIds(ref.getIObject()));
            }
        } catch (SnapshotException e) {
            throw new RuntimeException("Cannot extract values from " + ref, e);
        }
    }
    return new HeapReferenceTable(references, false);
}
 
Example #13
Source File: TableFunctions.java    From mat-calcite-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static QueryableTable getMapEntries(Object r) {
    List<HeapReference[]> references;
    if (!(r instanceof HeapReference)) {
        references = Collections.emptyList();
    } else {
        HeapReference ref = (HeapReference) r;
        try {
            ExtractedMap extractedMap = CollectionsActions.extractMap(ref.getIObject());
            if (extractedMap == null) {
                references = Collections.emptyList();
            } else {
                references = new ArrayList<>();
                for (Map.Entry<IObject, IObject> entry : extractedMap) {
                    references.add(new HeapReference[]{
                            HeapReference.valueOf(entry.getKey()),
                            HeapReference.valueOf(entry.getValue())
                    });
                }
            }
        } catch (SnapshotException e) {
            throw new RuntimeException("Cannot extract values from " + ref, e);
        }
    }
    return new HeapReferencesTable(new String[]{"key", "value"}, references);
}
 
Example #14
Source File: TableFunctions.java    From mat-calcite-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static QueryableTable getRetainedSet(Object r) {
    List<HeapReference> references;
    if (!(r instanceof HeapReference)) {
        references = Collections.emptyList();
    } else {
        HeapReference ref = (HeapReference) r;
        ISnapshot snapshot = ref.getIObject().getSnapshot();
        try {
            references = collectReferences
                    (
                            snapshot,
                            snapshot.getRetainedSet(new int[]{ref.getIObject().getObjectId()}, new VoidProgressListener())
                    );
        } catch (SnapshotException e) {
            throw new RuntimeException("Cannot extract retained set from " + r, e);
        }
    }
    return new HeapReferenceTable(references, true);
}
 
Example #15
Source File: CodesFunction.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static QueryableTable getTable(String name) {

    return new AbstractQueryableTable(Object[].class) {
      @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) {
        return typeFactory.builder()
            .add("TYPE", SqlTypeName.VARCHAR)
            .add("CODEVALUE", SqlTypeName.VARCHAR)
            .build();
      }

      @Override public Queryable<String[]> asQueryable(QueryProvider queryProvider,
                                                       SchemaPlus schema,
                                                       String tableName) {
        if (name == null) {
          return Linq4j.<String[]>emptyEnumerable().asQueryable();
        }
        return Linq4j.asEnumerable(new String[][]{
            new String[]{"HASHCODE", "" + name.hashCode()},
            new String[]{"BASE64",
                Base64.getEncoder().encodeToString(name.getBytes(StandardCharsets.UTF_8))}
        }).asQueryable();
      }
    };
  }
 
Example #16
Source File: EnumerableTableScan.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns whether EnumerableTableScan can generate code to handle a
 * particular variant of the Table SPI.
 * @deprecated
 **/
@Deprecated
public static boolean canHandle(Table table) {
  if (table instanceof TransientTable) {
    // CALCITE-3673: TransientTable can't be implemented with Enumerable
    return false;
  }
  // See org.apache.calcite.prepare.RelOptTableImpl.getClassExpressionFunction
  return table instanceof QueryableTable
      || table instanceof FilterableTable
      || table instanceof ProjectableFilterableTable
      || table instanceof ScannableTable;
}
 
Example #17
Source File: TableFunctions.java    From mat-calcite-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static QueryableTable getOutboundReferences(Object r) {
    List<NamedReference> references;
    if (!(r instanceof HeapReference)) {
        references = Collections.emptyList();
    } else {
        HeapReference ref = (HeapReference) r;
        references = ref.getIObject().getOutboundReferences();
    }
    return new OutboundReferencesTable(references);
}
 
Example #18
Source File: CloneSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Table createCloneTable(QueryProvider queryProvider,
    QueryableTable sourceTable, String name) {
  final Queryable<Object> queryable =
      sourceTable.asQueryable(queryProvider, sourceSchema, name);
  final JavaTypeFactory typeFactory =
      ((CalciteConnection) queryProvider).getTypeFactory();
  return createCloneTable(typeFactory, Schemas.proto(sourceTable),
      ImmutableList.of(), null, queryable);
}
 
Example #19
Source File: EnumerableTableScanRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelNode convert(RelNode rel) {
  LogicalTableScan scan = (LogicalTableScan) rel;
  final RelOptTable relOptTable = scan.getTable();
  final Table table = relOptTable.unwrap(Table.class);
  // The QueryableTable can only be implemented as ENUMERABLE convention,
  // but some test QueryableTables do not really implement the expressions,
  // just skips the QueryableTable#getExpression invocation and returns early.
  if (table instanceof QueryableTable || relOptTable.getExpression(Object.class) != null) {
    return EnumerableTableScan.create(scan.getCluster(), relOptTable);
  }

  return null;
}
 
Example #20
Source File: AbstractTableQueryable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public AbstractTableQueryable(QueryProvider queryProvider,
    SchemaPlus schema, QueryableTable table, String tableName) {
  this.queryProvider = queryProvider;
  this.schema = schema;
  this.table = table;
  this.tableName = tableName;
}
 
Example #21
Source File: CloneSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override protected Map<String, Table> getTableMap() {
  final Map<String, Table> map = new LinkedHashMap<>();
  for (String name : sourceSchema.getTableNames()) {
    final Table table = sourceSchema.getTable(name);
    if (table instanceof QueryableTable) {
      final QueryableTable sourceTable = (QueryableTable) table;
      map.put(name,
          createCloneTable(MATERIALIZATION_CONNECTION, sourceTable, name));
    }
  }
  return map;
}
 
Example #22
Source File: TableFunctionImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Type getElementType(List<Object> arguments) {
  final Table table = apply(arguments);
  if (table instanceof QueryableTable) {
    QueryableTable queryableTable = (QueryableTable) table;
    return queryableTable.getElementType();
  } else if (table instanceof ScannableTable) {
    return Object[].class;
  }
  throw new AssertionError("Invalid table class: " + table + " "
      + table.getClass());
}
 
Example #23
Source File: TableScanNode.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a TableScanNode.
 *
 * <p>Tries various table SPIs, and negotiates with the table which filters
 * and projects it can implement. Adds to the Enumerable implementations of
 * any filters and projects that cannot be implemented by the table. */
static TableScanNode create(Compiler compiler, TableScan rel,
    ImmutableList<RexNode> filters, ImmutableIntList projects) {
  final RelOptTable relOptTable = rel.getTable();
  final ProjectableFilterableTable pfTable =
      relOptTable.unwrap(ProjectableFilterableTable.class);
  if (pfTable != null) {
    return createProjectableFilterable(compiler, rel, filters, projects,
        pfTable);
  }
  final FilterableTable filterableTable =
      relOptTable.unwrap(FilterableTable.class);
  if (filterableTable != null) {
    return createFilterable(compiler, rel, filters, projects,
        filterableTable);
  }
  final ScannableTable scannableTable =
      relOptTable.unwrap(ScannableTable.class);
  if (scannableTable != null) {
    return createScannable(compiler, rel, filters, projects,
        scannableTable);
  }
  //noinspection unchecked
  final Enumerable<Row> enumerable = relOptTable.unwrap(Enumerable.class);
  if (enumerable != null) {
    return createEnumerable(compiler, rel, enumerable, null, filters,
        projects);
  }
  final QueryableTable queryableTable =
      relOptTable.unwrap(QueryableTable.class);
  if (queryableTable != null) {
    return createQueryable(compiler, rel, filters, projects,
        queryableTable);
  }
  throw new AssertionError("cannot convert table " + relOptTable
      + " to enumerable");
}
 
Example #24
Source File: CloneSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType, final List<RelCollation> collations,
    final List<ColumnMetaData.Rep> repList, final Enumerable<T> source) {
  final Type elementType;
  if (source instanceof QueryableTable) {
    elementType = ((QueryableTable) source).getElementType();
  } else if (protoRowType.apply(typeFactory).getFieldCount() == 1) {
    if (repList != null) {
      elementType = repList.get(0).clazz;
    } else {
      elementType = Object.class;
    }
  } else {
    elementType = Object[].class;
  }
  return new ArrayTable(
      elementType,
      protoRowType,
      Suppliers.memoize(() -> {
        final ColumnLoader loader =
            new ColumnLoader<>(typeFactory, source, protoRowType,
                repList);
        final List<RelCollation> collation2 =
            collations.isEmpty()
                && loader.sortField >= 0
                ? RelCollations.createSingleton(loader.sortField)
                : collations;
        return new ArrayTable.Content(loader.representationValues,
            loader.size(), collation2);
      }));
}
 
Example #25
Source File: Smalls.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** A function that generates multiplication table of {@code ncol} columns x
 * {@code nrow} rows. */
public static QueryableTable multiplicationTable(final int ncol,
    final int nrow, Integer offset) {
  final int offs = offset == null ? 0 : offset;
  return new AbstractQueryableTable(Object[].class) {
    public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      final RelDataTypeFactory.Builder builder = typeFactory.builder();
      builder.add("row_name", typeFactory.createJavaType(String.class));
      final RelDataType int_ = typeFactory.createJavaType(int.class);
      for (int i = 1; i <= ncol; i++) {
        builder.add("c" + i, int_);
      }
      return builder.build();
    }

    public Queryable<Object[]> asQueryable(QueryProvider queryProvider,
        SchemaPlus schema, String tableName) {
      final List<Object[]> table = new AbstractList<Object[]>() {
        @Override public Object[] get(int index) {
          Object[] cur = new Object[ncol + 1];
          cur[0] = "row " + index;
          for (int j = 1; j <= ncol; j++) {
            cur[j] = j * (index + 1) + offs;
          }
          return cur;
        }

        @Override public int size() {
          return nrow;
        }
      };
      return Linq4j.asEnumerable(table).asQueryable();
    }
  };
}
 
Example #26
Source File: EnumerableTableScan.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Returns whether EnumerableTableScan can generate code to handle a
 * particular variant of the Table SPI. */
public static boolean canHandle(Table table) {
  // FilterableTable and ProjectableFilterableTable cannot be handled in
  // enumerable convention because they might reject filters and those filters
  // would need to be handled dynamically.
  return table instanceof QueryableTable
      || table instanceof ScannableTable;
}
 
Example #27
Source File: MaterializationTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
public QueryableTable foo(int count) {
  return Smalls.generateStrings(count);
}
 
Example #28
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static QueryableTable eval(String s) {
  return oneThreePlus(s);
}
 
Example #29
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public QueryableTable eval(String s) {
  return oneThreePlus(s);
}
 
Example #30
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public QueryableTable eval(Integer s) {
  return generateStrings(s);
}