Search in sources :

Example 56 with Table

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.Table in project beam by apache.

the class JdbcDriverTest method testTimestampWithDefaultTimezone.

@Test
public void testTimestampWithDefaultTimezone() throws Exception {
    TestTableProvider tableProvider = new TestTableProvider();
    Connection connection = JdbcDriver.connect(tableProvider, PipelineOptionsFactory.create());
    // A table with one TIMESTAMP column
    Schema schema = Schema.builder().addDateTimeField("ts").build();
    connection.createStatement().executeUpdate("CREATE EXTERNAL TABLE test (ts TIMESTAMP) TYPE 'test'");
    ReadableInstant july1 = ISODateTimeFormat.dateTimeParser().parseDateTime("2018-07-01T01:02:03Z");
    tableProvider.addRows("test", Row.withSchema(schema).addValue(july1).build());
    ResultSet selectResult = connection.createStatement().executeQuery(String.format("SELECT ts FROM test"));
    selectResult.next();
    Timestamp ts = selectResult.getTimestamp(1);
    assertThat(String.format("Wrote %s to a table, but got back %s", ISODateTimeFormat.basicDateTime().print(july1), ISODateTimeFormat.basicDateTime().print(ts.getTime())), ts.getTime(), equalTo(july1.getMillis()));
}
Also used : TestTableProvider(org.apache.beam.sdk.extensions.sql.meta.provider.test.TestTableProvider) ReadableInstant(org.joda.time.ReadableInstant) CalciteSchema(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteSchema) Schema(org.apache.beam.sdk.schemas.Schema) Connection(java.sql.Connection) CalciteConnection(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteConnection) ResultSet(java.sql.ResultSet) Timestamp(java.sql.Timestamp) Test(org.junit.Test)

Example 57 with Table

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.Table in project beam by apache.

the class JdbcDriverTest method testDriverManager_ddl.

@Test
public void testDriverManager_ddl() throws Exception {
    Connection connection = DriverManager.getConnection(JdbcDriver.CONNECT_STRING_PREFIX);
    // Ensure no tables
    final DatabaseMetaData metadata = connection.getMetaData();
    ResultSet resultSet = metadata.getTables(null, null, null, new String[] { "TABLE" });
    assertFalse(resultSet.next());
    // create external tables
    Statement statement = connection.createStatement();
    assertEquals(0, statement.executeUpdate("CREATE EXTERNAL TABLE test (id INTEGER) TYPE 'text'"));
    // Ensure table test
    resultSet = metadata.getTables(null, null, null, new String[] { "TABLE" });
    assertTrue(resultSet.next());
    assertEquals("test", resultSet.getString("TABLE_NAME"));
    assertFalse(resultSet.next());
    assertEquals(0, statement.executeUpdate("DROP TABLE test"));
    // Ensure no tables
    resultSet = metadata.getTables(null, null, null, new String[] { "TABLE" });
    assertFalse(resultSet.next());
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) CalciteConnection(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteConnection) ResultSet(java.sql.ResultSet) Matchers.containsString(org.hamcrest.Matchers.containsString) DatabaseMetaData(java.sql.DatabaseMetaData) Test(org.junit.Test)

Example 58 with Table

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.Table in project beam by apache.

the class JdbcDriverTest method testTimestampWithNonzeroTimezone.

@Test
@Ignore("https://issues.apache.org/jira/browse/CALCITE-2394")
public void testTimestampWithNonzeroTimezone() throws Exception {
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"), Locale.ROOT);
    TestTableProvider tableProvider = new TestTableProvider();
    Connection connection = JdbcDriver.connect(tableProvider, PipelineOptionsFactory.create());
    // A table with one TIMESTAMP column
    Schema schema = Schema.builder().addDateTimeField("ts").build();
    connection.createStatement().executeUpdate("CREATE EXTERNAL TABLE test (ts TIMESTAMP) TYPE 'test'");
    ReadableInstant july1 = ISODateTimeFormat.dateTimeParser().parseDateTime("2018-07-01T01:02:03Z");
    tableProvider.addRows("test", Row.withSchema(schema).addValue(july1).build());
    ResultSet selectResult = connection.createStatement().executeQuery(String.format("SELECT ts FROM test"));
    selectResult.next();
    Timestamp ts = selectResult.getTimestamp(1, cal);
    assertThat(String.format("Wrote %s to a table, but got back %s", ISODateTimeFormat.basicDateTime().print(july1), ISODateTimeFormat.basicDateTime().print(ts.getTime())), ts.getTime(), equalTo(july1.getMillis()));
}
Also used : TestTableProvider(org.apache.beam.sdk.extensions.sql.meta.provider.test.TestTableProvider) ReadableInstant(org.joda.time.ReadableInstant) Calendar(java.util.Calendar) CalciteSchema(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteSchema) Schema(org.apache.beam.sdk.schemas.Schema) Connection(java.sql.Connection) CalciteConnection(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteConnection) ResultSet(java.sql.ResultSet) Timestamp(java.sql.Timestamp) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 59 with Table

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.Table in project beam by apache.

the class SqlCreateExternalTable method execute.

@Override
public void execute(CalcitePrepare.Context context) {
    final Pair<CalciteSchema, String> pair = SqlDdlNodes.schema(context, true, name);
    if (pair.left.plus().getTable(pair.right) != null) {
        // Table exists.
        if (!ifNotExists) {
            // They did not specify IF NOT EXISTS, so give error.
            throw SqlUtil.newContextException(name.getParserPosition(), RESOURCE.tableExists(pair.right));
        }
        return;
    }
    // Table does not exist. Create it.
    if (!(pair.left.schema instanceof BeamCalciteSchema)) {
        throw SqlUtil.newContextException(name.getParserPosition(), RESOURCE.internal("Schema is not instanceof BeamCalciteSchema"));
    }
    BeamCalciteSchema schema = (BeamCalciteSchema) pair.left.schema;
    schema.getTableProvider().createTable(toTable());
}
Also used : BeamCalciteSchema(org.apache.beam.sdk.extensions.sql.impl.BeamCalciteSchema) CalciteSchema(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteSchema) BeamCalciteSchema(org.apache.beam.sdk.extensions.sql.impl.BeamCalciteSchema)

Example 60 with Table

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.Table in project beam by apache.

the class MongoDbTable method translateRexNodeToBson.

/**
 * Recursively translates a single RexNode to MongoDB Bson filter. Supports simple comparison
 * operations, negation, and nested conjunction/disjunction. Boolean fields are translated as an
 * `$eq` operation with a boolean `true`.
 *
 * @param node {@code RexNode} to translate.
 * @return {@code Bson} filter.
 */
private Bson translateRexNodeToBson(RexNode node) {
    final IntFunction<String> fieldIdToName = i -> getSchema().getField(i).getName();
    // Supported operations are described in MongoDbFilter#isSupported
    if (node instanceof RexCall) {
        RexCall compositeNode = (RexCall) node;
        List<RexLiteral> literals = new ArrayList<>();
        List<RexInputRef> inputRefs = new ArrayList<>();
        for (RexNode operand : compositeNode.getOperands()) {
            if (operand instanceof RexLiteral) {
                literals.add((RexLiteral) operand);
            } else if (operand instanceof RexInputRef) {
                inputRefs.add((RexInputRef) operand);
            }
        }
        // Operation is a comparison, since one of the operands in a field reference.
        if (inputRefs.size() == 1) {
            RexInputRef inputRef = inputRefs.get(0);
            String inputFieldName = fieldIdToName.apply(inputRef.getIndex());
            if (literals.size() > 0) {
                // Convert literal value to the same Java type as the field we are comparing to.
                Object literal = convertToExpectedType(inputRef, literals.get(0));
                switch(node.getKind()) {
                    case IN:
                        return Filters.in(inputFieldName, convertToExpectedType(inputRef, literals));
                    case EQUALS:
                        return Filters.eq(inputFieldName, literal);
                    case NOT_EQUALS:
                        return Filters.not(Filters.eq(inputFieldName, literal));
                    case LESS_THAN:
                        return Filters.lt(inputFieldName, literal);
                    case GREATER_THAN:
                        return Filters.gt(inputFieldName, literal);
                    case GREATER_THAN_OR_EQUAL:
                        return Filters.gte(inputFieldName, literal);
                    case LESS_THAN_OR_EQUAL:
                        return Filters.lte(inputFieldName, literal);
                    default:
                        // Encountered an unexpected node kind, RuntimeException below.
                        break;
                }
            } else if (node.getKind().equals(SqlKind.NOT)) {
                // Ex: `where not boolean_field`
                return Filters.not(translateRexNodeToBson(inputRef));
            } else {
                throw new RuntimeException("Cannot create a filter for an unsupported node: " + node.toString());
            }
        } else {
            // Operation is a conjunction/disjunction.
            switch(node.getKind()) {
                case AND:
                    // Recursively construct filter for each operand of conjunction.
                    return Filters.and(compositeNode.getOperands().stream().map(this::translateRexNodeToBson).collect(Collectors.toList()));
                case OR:
                    // Recursively construct filter for each operand of disjunction.
                    return Filters.or(compositeNode.getOperands().stream().map(this::translateRexNodeToBson).collect(Collectors.toList()));
                default:
                    // Encountered an unexpected node kind, RuntimeException below.
                    break;
            }
        }
        throw new RuntimeException("Encountered an unexpected node kind: " + node.getKind().toString());
    } else if (node instanceof RexInputRef && node.getType().getSqlTypeName().equals(SqlTypeName.BOOLEAN)) {
        // Boolean field, must be true. Ex: `select * from table where bool_field`
        return Filters.eq(fieldIdToName.apply(((RexInputRef) node).getIndex()), true);
    }
    throw new RuntimeException("Was expecting a RexCall or a boolean RexInputRef, but received: " + node.getClass().getSimpleName());
}
Also used : Document(org.bson.Document) PBegin(org.apache.beam.sdk.values.PBegin) LoggerFactory(org.slf4j.LoggerFactory) MongoDbIO(org.apache.beam.sdk.io.mongodb.MongoDbIO) IsBounded(org.apache.beam.sdk.values.PCollection.IsBounded) JsonToRow(org.apache.beam.sdk.transforms.JsonToRow) SimpleFunction(org.apache.beam.sdk.transforms.SimpleFunction) ProjectSupport(org.apache.beam.sdk.extensions.sql.meta.ProjectSupport) Table(org.apache.beam.sdk.extensions.sql.meta.Table) Matcher(java.util.regex.Matcher) AND(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlKind.AND) RexLiteral(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral) MapElements(org.apache.beam.sdk.transforms.MapElements) SchemaBaseBeamTable(org.apache.beam.sdk.extensions.sql.meta.SchemaBaseBeamTable) FieldType(org.apache.beam.sdk.schemas.Schema.FieldType) Collectors(java.util.stream.Collectors) FindQuery(org.apache.beam.sdk.io.mongodb.FindQuery) Serializable(java.io.Serializable) InvalidTableException(org.apache.beam.sdk.extensions.sql.meta.provider.InvalidTableException) VisibleForTesting(org.apache.beam.vendor.calcite.v1_28_0.com.google.common.annotations.VisibleForTesting) COMPARISON(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlKind.COMPARISON) POutput(org.apache.beam.sdk.values.POutput) List(java.util.List) ParDo(org.apache.beam.sdk.transforms.ParDo) BeamTableStatistics(org.apache.beam.sdk.extensions.sql.impl.BeamTableStatistics) ImmutableList(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList) Pattern(java.util.regex.Pattern) Experimental(org.apache.beam.sdk.annotations.Experimental) RexNode(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexNode) JsonWriterSettings(org.bson.json.JsonWriterSettings) SqlKind(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlKind) SelectHelpers(org.apache.beam.sdk.schemas.utils.SelectHelpers) ArrayList(java.util.ArrayList) PTransform(org.apache.beam.sdk.transforms.PTransform) Filters(com.mongodb.client.model.Filters) DefaultTableFilter(org.apache.beam.sdk.extensions.sql.meta.DefaultTableFilter) Bson(org.bson.conversions.Bson) ToJson(org.apache.beam.sdk.transforms.ToJson) JsonMode(org.bson.json.JsonMode) FieldAccessDescriptor(org.apache.beam.sdk.schemas.FieldAccessDescriptor) Row(org.apache.beam.sdk.values.Row) PipelineOptions(org.apache.beam.sdk.options.PipelineOptions) IntFunction(java.util.function.IntFunction) FieldTypeDescriptors(org.apache.beam.sdk.schemas.FieldTypeDescriptors) DoFn(org.apache.beam.sdk.transforms.DoFn) Logger(org.slf4j.Logger) BeamSqlTableFilter(org.apache.beam.sdk.extensions.sql.meta.BeamSqlTableFilter) PCollection(org.apache.beam.sdk.values.PCollection) Schema(org.apache.beam.sdk.schemas.Schema) RexCall(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexCall) SqlTypeName(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.type.SqlTypeName) RexInputRef(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexInputRef) OR(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlKind.OR) RexCall(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexCall) RexLiteral(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral) ArrayList(java.util.ArrayList) RexInputRef(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexInputRef) RexNode(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexNode)

Aggregations

Table (org.apache.calcite.schema.Table)104 Test (org.junit.Test)43 SqlStdOperatorTable (org.apache.calcite.sql.fun.SqlStdOperatorTable)38 RelOptTable (org.apache.calcite.plan.RelOptTable)33 RelDataType (org.apache.calcite.rel.type.RelDataType)22 SqlOperatorTable (org.apache.calcite.sql.SqlOperatorTable)22 SchemaPlus (org.apache.calcite.schema.SchemaPlus)20 ArrayList (java.util.ArrayList)19 List (java.util.List)19 ProjectableFilterableTable (org.apache.calcite.schema.ProjectableFilterableTable)17 ScannableTable (org.apache.calcite.schema.ScannableTable)17 JavaTypeFactoryImpl (org.apache.calcite.jdbc.JavaTypeFactoryImpl)16 FilterableTable (org.apache.calcite.schema.FilterableTable)15 AbstractTable (org.apache.calcite.schema.impl.AbstractTable)15 ResultSet (java.sql.ResultSet)14 Schema (org.apache.beam.sdk.schemas.Schema)14 Row (org.apache.beam.sdk.values.Row)14 StreamableTable (org.apache.calcite.schema.StreamableTable)14 CalciteConnection (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.jdbc.CalciteConnection)13 Map (java.util.Map)12