Search in sources :

Example 31 with DocTableInfo

use of io.crate.metadata.doc.DocTableInfo in project crate by crate.

the class CopyToPlan method bind.

@VisibleForTesting
public static BoundCopyTo bind(AnalyzedCopyTo copyTo, CoordinatorTxnCtx txnCtx, NodeContext nodeCtx, Row parameters, SubQueryResults subQueryResults) {
    Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(txnCtx, nodeCtx, x, parameters, subQueryResults);
    DocTableInfo table = (DocTableInfo) copyTo.tableInfo();
    List<String> partitions = resolvePartitions(Lists2.map(copyTo.table().partitionProperties(), x -> x.map(eval)), table);
    List<Symbol> outputs = new ArrayList<>();
    Map<ColumnIdent, Symbol> overwrites = null;
    boolean columnsDefined = false;
    final List<String> outputNames = new ArrayList<>(copyTo.columns().size());
    if (!copyTo.columns().isEmpty()) {
        // TODO: remove outputNames?
        for (Symbol symbol : copyTo.columns()) {
            assert symbol instanceof Reference : "Only references are expected here";
            RefVisitor.visitRefs(symbol, r -> outputNames.add(r.column().sqlFqn()));
            outputs.add(DocReferences.toSourceLookup(symbol));
        }
        columnsDefined = true;
    } else {
        Reference sourceRef;
        if (table.isPartitioned() && partitions.isEmpty()) {
            // table is partitioned, insert partitioned columns into the output
            overwrites = new HashMap<>();
            for (Reference reference : table.partitionedByColumns()) {
                if (!(reference instanceof GeneratedReference)) {
                    overwrites.put(reference.column(), reference);
                }
            }
            if (overwrites.size() > 0) {
                sourceRef = table.getReference(DocSysColumns.DOC);
            } else {
                sourceRef = table.getReference(DocSysColumns.RAW);
            }
        } else {
            sourceRef = table.getReference(DocSysColumns.RAW);
        }
        outputs = List.of(sourceRef);
    }
    Settings settings = genericPropertiesToSettings(copyTo.properties().map(eval));
    WriterProjection.CompressionType compressionType = settingAsEnum(WriterProjection.CompressionType.class, COMPRESSION_SETTING.get(settings));
    WriterProjection.OutputFormat outputFormat = settingAsEnum(WriterProjection.OutputFormat.class, OUTPUT_FORMAT_SETTING.get(settings));
    if (!columnsDefined && outputFormat == WriterProjection.OutputFormat.JSON_ARRAY) {
        throw new UnsupportedFeatureException("Output format not supported without specifying columns.");
    }
    WhereClause whereClause = new WhereClause(copyTo.whereClause(), partitions, Collections.emptySet());
    return new BoundCopyTo(outputs, table, whereClause, Literal.of(DataTypes.STRING.sanitizeValue(eval.apply(copyTo.uri()))), compressionType, outputFormat, outputNames.isEmpty() ? null : outputNames, columnsDefined, overwrites, settings);
}
Also used : UnsupportedFeatureException(io.crate.exceptions.UnsupportedFeatureException) GenericPropertiesConverter.genericPropertiesToSettings(io.crate.analyze.GenericPropertiesConverter.genericPropertiesToSettings) Match(io.crate.planner.optimizer.matcher.Match) BoundCopyTo(io.crate.analyze.BoundCopyTo) DependencyCarrier(io.crate.planner.DependencyCarrier) RefVisitor(io.crate.expression.symbol.RefVisitor) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) TableStats(io.crate.statistics.TableStats) Settings(org.elasticsearch.common.settings.Settings) Map(java.util.Map) OUTPUT_FORMAT_SETTING(io.crate.analyze.CopyStatementSettings.OUTPUT_FORMAT_SETTING) DocSysColumns(io.crate.metadata.doc.DocSysColumns) DocTableInfo(io.crate.metadata.doc.DocTableInfo) NodeContext(io.crate.metadata.NodeContext) LogicalPlan(io.crate.planner.operators.LogicalPlan) Captures(io.crate.planner.optimizer.matcher.Captures) GeneratedReference(io.crate.metadata.GeneratedReference) Collect(io.crate.planner.operators.Collect) Set(java.util.Set) Lists2(io.crate.common.collections.Lists2) ExecutionPlan(io.crate.planner.ExecutionPlan) OptimizeCollectWhereClauseAccess(io.crate.planner.optimizer.rule.OptimizeCollectWhereClauseAccess) DocReferences(io.crate.metadata.DocReferences) List(java.util.List) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) DataTypes(io.crate.types.DataTypes) SubQueryResults(io.crate.planner.operators.SubQueryResults) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) PartitionPropertiesAnalyzer(io.crate.analyze.PartitionPropertiesAnalyzer) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Assignment(io.crate.sql.tree.Assignment) COMPRESSION_SETTING(io.crate.analyze.CopyStatementSettings.COMPRESSION_SETTING) AnalyzedCopyTo(io.crate.analyze.AnalyzedCopyTo) PartitionUnknownException(io.crate.exceptions.PartitionUnknownException) ProjectionBuilder(io.crate.execution.dsl.projection.builder.ProjectionBuilder) MergeCountProjection(io.crate.execution.dsl.projection.MergeCountProjection) WhereClause(io.crate.analyze.WhereClause) NodeOperationTree(io.crate.execution.dsl.phases.NodeOperationTree) ColumnIdent(io.crate.metadata.ColumnIdent) Reference(io.crate.metadata.Reference) NodeOperationTreeGenerator(io.crate.execution.engine.NodeOperationTreeGenerator) Merge(io.crate.planner.Merge) RowConsumer(io.crate.data.RowConsumer) WriterProjection(io.crate.execution.dsl.projection.WriterProjection) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Literal(io.crate.expression.symbol.Literal) PlannerContext(io.crate.planner.PlannerContext) CopyStatementSettings.settingAsEnum(io.crate.analyze.CopyStatementSettings.settingAsEnum) Plan(io.crate.planner.Plan) Collections(java.util.Collections) DocTableInfo(io.crate.metadata.doc.DocTableInfo) GeneratedReference(io.crate.metadata.GeneratedReference) UnsupportedFeatureException(io.crate.exceptions.UnsupportedFeatureException) BoundCopyTo(io.crate.analyze.BoundCopyTo) Symbol(io.crate.expression.symbol.Symbol) GeneratedReference(io.crate.metadata.GeneratedReference) Reference(io.crate.metadata.Reference) ArrayList(java.util.ArrayList) WhereClause(io.crate.analyze.WhereClause) WriterProjection(io.crate.execution.dsl.projection.WriterProjection) ColumnIdent(io.crate.metadata.ColumnIdent) GenericPropertiesConverter.genericPropertiesToSettings(io.crate.analyze.GenericPropertiesConverter.genericPropertiesToSettings) Settings(org.elasticsearch.common.settings.Settings) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 32 with DocTableInfo

use of io.crate.metadata.doc.DocTableInfo in project crate by crate.

the class GeneratedColumnsTest method testSubscriptExpressionThatReturnsAnArray.

@Test
public void testSubscriptExpressionThatReturnsAnArray() throws Exception {
    SQLExecutor e = SQLExecutor.builder(clusterService).addTable("create table t (obj object as (arr array(integer)), arr as obj['arr'])").build();
    QueriedSelectRelation query = e.analyze("select obj, arr from t");
    DocTableInfo table = ((DocTableRelation) query.from().get(0)).tableInfo();
    GeneratedColumns<Doc> generatedColumns = new GeneratedColumns<>(new InputFactory(e.nodeCtx), CoordinatorTxnCtx.systemTransactionContext(), GeneratedColumns.Validation.NONE, new DocRefResolver(Collections.emptyList()), Collections.emptyList(), table.generatedColumns());
    BytesReference bytes = BytesReference.bytes(XContentFactory.jsonBuilder().startObject().startObject("obj").startArray("arr").value(10).value(20).endArray().endObject().endObject());
    generatedColumns.setNextRow(new Doc(1, table.concreteIndices()[0], "1", 1, 1, 1, XContentHelper.convertToMap(bytes, false, XContentType.JSON).v2(), bytes::utf8ToString));
    Map.Entry<Reference, Input<?>> generatedColumn = generatedColumns.generatedToInject().iterator().next();
    assertThat((List<Object>) generatedColumn.getValue().value(), contains(10, 20));
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) InputFactory(io.crate.expression.InputFactory) DocTableInfo(io.crate.metadata.doc.DocTableInfo) Reference(io.crate.metadata.Reference) BytesReference(org.elasticsearch.common.bytes.BytesReference) DocRefResolver(io.crate.expression.reference.DocRefResolver) Input(io.crate.data.Input) SQLExecutor(io.crate.testing.SQLExecutor) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Doc(io.crate.expression.reference.Doc) Map(java.util.Map) Test(org.junit.Test) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest)

Example 33 with DocTableInfo

use of io.crate.metadata.doc.DocTableInfo in project crate by crate.

the class UpdateSourceGenTest method testSetXBasedOnXAndPartitionedColumn.

@Test
public void testSetXBasedOnXAndPartitionedColumn() throws Exception {
    SQLExecutor e = SQLExecutor.builder(clusterService).addPartitionedTable("create table t (x int, p int) partitioned by (p)", new PartitionName(new RelationName("doc", "t"), Collections.singletonList("1")).asIndexName()).build();
    AnalyzedUpdateStatement update = e.analyze("update t set x = x + p");
    Assignments assignments = Assignments.convert(update.assignmentByTargetCol(), e.nodeCtx);
    DocTableInfo table = (DocTableInfo) update.table().tableInfo();
    UpdateSourceGen updateSourceGen = new UpdateSourceGen(txnCtx, e.nodeCtx, table, assignments.targetNames());
    Map<String, Object> source = singletonMap("x", 1);
    Map<String, Object> updatedSource = updateSourceGen.generateSource(new Doc(1, table.concreteIndices()[0], "1", 1, 1, 1, source, () -> {
        try {
            return Strings.toString(XContentFactory.jsonBuilder().map(source));
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }), assignments.sources(), new Object[0]);
    assertThat(updatedSource, is(Map.of("x", 2)));
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) Assignments(io.crate.expression.symbol.Assignments) IOException(java.io.IOException) PartitionName(io.crate.metadata.PartitionName) SQLExecutor(io.crate.testing.SQLExecutor) AnalyzedUpdateStatement(io.crate.analyze.AnalyzedUpdateStatement) RelationName(io.crate.metadata.RelationName) Doc(io.crate.expression.reference.Doc) Test(org.junit.Test) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest)

Example 34 with DocTableInfo

use of io.crate.metadata.doc.DocTableInfo in project crate by crate.

the class UpdateSourceGenTest method testNestedGeneratedColumnIsGeneratedValidateValueIfGivenByUser.

@Test
public void testNestedGeneratedColumnIsGeneratedValidateValueIfGivenByUser() throws Exception {
    SQLExecutor e = SQLExecutor.builder(clusterService).addTable("create table t (x int, obj object as (y as 'foo'))").build();
    AnalyzedUpdateStatement update = e.analyze("update t set x = 4, obj = {y='foo'}");
    Assignments assignments = Assignments.convert(update.assignmentByTargetCol(), e.nodeCtx);
    DocTableInfo table = (DocTableInfo) update.table().tableInfo();
    UpdateSourceGen updateSourceGen = new UpdateSourceGen(txnCtx, e.nodeCtx, table, assignments.targetNames());
    Map<String, Object> updatedSource = updateSourceGen.generateSource(new Doc(1, table.concreteIndices()[0], "1", 1, 1, 1, emptyMap(), () -> "{}"), assignments.sources(), new Object[0]);
    assertThat(updatedSource, is(Map.of("obj", Map.of("y", "foo"), "x", 4)));
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) SQLExecutor(io.crate.testing.SQLExecutor) AnalyzedUpdateStatement(io.crate.analyze.AnalyzedUpdateStatement) Assignments(io.crate.expression.symbol.Assignments) Doc(io.crate.expression.reference.Doc) Test(org.junit.Test) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest)

Example 35 with DocTableInfo

use of io.crate.metadata.doc.DocTableInfo in project crate by crate.

the class UpdateSourceGenTest method testGeneratedColumnUsingFunctionDependingOnActiveTransaction.

@Test
public void testGeneratedColumnUsingFunctionDependingOnActiveTransaction() throws Exception {
    SQLExecutor e = SQLExecutor.builder(clusterService).addTable("create table t (x int, gen as current_schema)").build();
    AnalyzedUpdateStatement update = e.analyze("update t set x = 1");
    Assignments assignments = Assignments.convert(update.assignmentByTargetCol(), e.nodeCtx);
    DocTableInfo table = (DocTableInfo) update.table().tableInfo();
    UpdateSourceGen sourceGen = new UpdateSourceGen(TransactionContext.of(DUMMY_SESSION_INFO), e.nodeCtx, table, assignments.targetNames());
    Map<String, Object> source = sourceGen.generateSource(new Doc(1, table.concreteIndices()[0], "1", 1, 1, 1, emptyMap(), () -> "{}"), assignments.sources(), new Object[0]);
    assertThat(source, is(Map.of("gen", "dummySchema", "x", 1)));
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) SQLExecutor(io.crate.testing.SQLExecutor) AnalyzedUpdateStatement(io.crate.analyze.AnalyzedUpdateStatement) Assignments(io.crate.expression.symbol.Assignments) Doc(io.crate.expression.reference.Doc) Test(org.junit.Test) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest)

Aggregations

DocTableInfo (io.crate.metadata.doc.DocTableInfo)127 Test (org.junit.Test)56 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)40 Symbol (io.crate.expression.symbol.Symbol)27 Reference (io.crate.metadata.Reference)27 SQLExecutor (io.crate.testing.SQLExecutor)25 RelationName (io.crate.metadata.RelationName)24 DocTableRelation (io.crate.analyze.relations.DocTableRelation)20 ColumnIdent (io.crate.metadata.ColumnIdent)20 TableInfo (io.crate.metadata.table.TableInfo)18 Assignments (io.crate.expression.symbol.Assignments)16 Row (io.crate.data.Row)14 PlannerContext (io.crate.planner.PlannerContext)13 Before (org.junit.Before)13 RowConsumer (io.crate.data.RowConsumer)12 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)12 PartitionName (io.crate.metadata.PartitionName)12 DependencyCarrier (io.crate.planner.DependencyCarrier)12 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12