Search in sources :

Example 1 with CheckConstraint

use of io.crate.sql.tree.CheckConstraint in project crate by crate.

the class AstBuilder method visitTableCheckConstraint.

@Override
public Node visitTableCheckConstraint(SqlBaseParser.TableCheckConstraintContext context) {
    SqlBaseParser.CheckConstraintContext ctx = context.checkConstraint();
    String name = ctx.CONSTRAINT() != null ? getIdentText(ctx.name) : null;
    Expression expression = (Expression) visit(ctx.expression);
    String expressionStr = ExpressionFormatter.formatStandaloneExpression(expression);
    return new CheckConstraint<>(name, null, expression, expressionStr);
}
Also used : SqlBaseParser(io.crate.sql.parser.antlr.v4.SqlBaseParser) SubscriptExpression(io.crate.sql.tree.SubscriptExpression) IfExpression(io.crate.sql.tree.IfExpression) NotExpression(io.crate.sql.tree.NotExpression) SearchedCaseExpression(io.crate.sql.tree.SearchedCaseExpression) LogicalBinaryExpression(io.crate.sql.tree.LogicalBinaryExpression) ArraySliceExpression(io.crate.sql.tree.ArraySliceExpression) ArraySubQueryExpression(io.crate.sql.tree.ArraySubQueryExpression) SimpleCaseExpression(io.crate.sql.tree.SimpleCaseExpression) SubqueryExpression(io.crate.sql.tree.SubqueryExpression) InListExpression(io.crate.sql.tree.InListExpression) ParameterExpression(io.crate.sql.tree.ParameterExpression) ArrayComparisonExpression(io.crate.sql.tree.ArrayComparisonExpression) Expression(io.crate.sql.tree.Expression) ComparisonExpression(io.crate.sql.tree.ComparisonExpression) ArithmeticExpression(io.crate.sql.tree.ArithmeticExpression) NegativeExpression(io.crate.sql.tree.NegativeExpression) BitString(io.crate.sql.tree.BitString) CheckConstraint(io.crate.sql.tree.CheckConstraint) DropCheckConstraint(io.crate.sql.tree.DropCheckConstraint)

Example 2 with CheckConstraint

use of io.crate.sql.tree.CheckConstraint in project crate by crate.

the class DocIndexMetadata method build.

public DocIndexMetadata build() {
    notNullColumns = getNotNullColumns();
    columnPolicy = getColumnPolicy();
    createColumnDefinitions();
    indices = createIndexDefinitions();
    references = new LinkedHashMap<>();
    DocSysColumns.forTable(ident, references::put);
    columns.sort(SORT_REFS_BY_POSTITON_THEN_NAME);
    nestedColumns.sort(SORT_REFS_BY_POSTITON_THEN_NAME);
    for (Reference ref : columns) {
        references.put(ref.column(), ref);
        for (Reference nestedColumn : nestedColumns) {
            if (nestedColumn.column().getRoot().equals(ref.column())) {
                references.put(nestedColumn.column(), nestedColumn);
            }
        }
    }
    // Order of the partitionedByColumns is important; Must be the same order as `partitionedBy` is in.
    partitionedByColumns = Lists2.map(partitionedBy, references::get);
    generatedColumnReferences = List.copyOf(generatedColumnReferencesBuilder);
    primaryKey = getPrimaryKey();
    routingCol = getRoutingCol();
    Collection<Reference> references = this.references.values();
    TableReferenceResolver tableReferenceResolver = new TableReferenceResolver(references, ident);
    CoordinatorTxnCtx txnCtx = CoordinatorTxnCtx.systemTransactionContext();
    ExpressionAnalyzer exprAnalyzer = new ExpressionAnalyzer(txnCtx, nodeCtx, ParamTypeHints.EMPTY, tableReferenceResolver, null);
    ExpressionAnalysisContext analysisCtx = new ExpressionAnalysisContext(txnCtx.sessionContext());
    ArrayList<CheckConstraint<Symbol>> checkConstraintsBuilder = null;
    Map<String, Object> metaMap = Maps.get(mappingMap, "_meta");
    if (metaMap != null) {
        Map<String, String> checkConstraintsMap = Maps.get(metaMap, "check_constraints");
        if (checkConstraintsMap != null) {
            checkConstraintsBuilder = new ArrayList<>();
            for (Map.Entry<String, String> entry : checkConstraintsMap.entrySet()) {
                String name = entry.getKey();
                String expressionStr = entry.getValue();
                Expression expr = SqlParser.createExpression(expressionStr);
                Symbol analyzedExpr = exprAnalyzer.convert(expr, analysisCtx);
                checkConstraintsBuilder.add(new CheckConstraint<>(name, null, analyzedExpr, expressionStr));
            }
        }
    }
    checkConstraints = checkConstraintsBuilder != null ? List.copyOf(checkConstraintsBuilder) : List.of();
    for (Reference reference : generatedColumnReferences) {
        GeneratedReference generatedReference = (GeneratedReference) reference;
        Expression expression = SqlParser.createExpression(generatedReference.formattedGeneratedExpression());
        generatedReference.generatedExpression(exprAnalyzer.convert(expression, analysisCtx));
        generatedReference.referencedReferences(List.copyOf(tableReferenceResolver.references()));
        tableReferenceResolver.references().clear();
    }
    return this;
}
Also used : CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) GeneratedReference(io.crate.metadata.GeneratedReference) GeneratedReference(io.crate.metadata.GeneratedReference) GeoReference(io.crate.metadata.GeoReference) IndexReference(io.crate.metadata.IndexReference) Reference(io.crate.metadata.Reference) Symbol(io.crate.expression.symbol.Symbol) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) Expression(io.crate.sql.tree.Expression) TableReferenceResolver(io.crate.analyze.expressions.TableReferenceResolver) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CheckConstraint(io.crate.sql.tree.CheckConstraint)

Example 3 with CheckConstraint

use of io.crate.sql.tree.CheckConstraint in project crate by crate.

the class CheckConstraints method validate.

/**
 * The method must be called on {@code T values}, e.g. source maps,
 * rows that already contain values of evaluated generated column
 * expressions.
 */
public void validate(T values) {
    for (int i = 0; i < expressions.size(); i++) {
        expressions.get(i).setNextRow(values);
    }
    for (int i = 0; i < inputs.size(); i++) {
        Object val = inputs.get(i).value();
        if (val == null) {
            throw new IllegalArgumentException("\"" + notNullColumns.get(i) + "\" must not be null");
        }
    }
    for (int i = 0; i < checkConstraints.size(); i++) {
        Tuple<? extends Input<?>, CheckConstraint<Symbol>> checkEntry = checkConstraints.get(i);
        Input<?> checkInput = checkEntry.v1();
        Object value = checkInput.value();
        if (value == null) {
            // CHECK constraints should not fail. Same for writing explicit `null` values.
            continue;
        }
        assert value instanceof Boolean : "expected a boolean value";
        if (!((Boolean) value).booleanValue()) {
            CheckConstraint<Symbol> chk = checkEntry.v2();
            throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Failed CONSTRAINT %s CHECK (%s) and values %s", chk.name(), chk.expressionStr(), values));
        }
    }
}
Also used : Symbol(io.crate.expression.symbol.Symbol) CheckConstraint(io.crate.sql.tree.CheckConstraint) CheckConstraint(io.crate.sql.tree.CheckConstraint)

Example 4 with CheckConstraint

use of io.crate.sql.tree.CheckConstraint in project crate by crate.

the class SchemasITest method testDocTable.

@Test
public void testDocTable() {
    execute("create table t1 (" + "id int primary key, " + "name string, " + "CONSTRAINT not_miguel CHECK (name != 'miguel'), " + "details object(dynamic) as (size byte, created timestamp with time zone)" + ") clustered into 10 shards with (number_of_replicas=1)");
    ensureYellow();
    DocTableInfo ti = schemas.getTableInfo(new RelationName(sqlExecutor.getCurrentSchema(), "t1"));
    assertThat(ti.ident().name(), is("t1"));
    assertThat(ti.columns().size(), is(3));
    assertThat(ti.primaryKey().size(), is(1));
    assertThat(ti.primaryKey().get(0), is(new ColumnIdent("id")));
    assertThat(ti.clusteredBy(), is(new ColumnIdent("id")));
    List<CheckConstraint<Symbol>> checkConstraints = ti.checkConstraints();
    assertEquals(1, checkConstraints.size());
    assertEquals(checkConstraints.get(0).name(), "not_miguel");
    assertThat(checkConstraints.get(0).expressionStr(), equalTo("\"name\" <> 'miguel'"));
    ClusterService clusterService = clusterService();
    Routing routing = ti.getRouting(clusterService.state(), routingProvider, WhereClause.MATCH_ALL, RoutingProvider.ShardSelection.ANY, SessionContext.systemSessionContext());
    Set<String> nodes = routing.nodes();
    // for the rare case
    assertThat(nodes.size(), isOneOf(1, 2));
    // where all shards are on 1 node
    int numShards = 0;
    for (Map.Entry<String, Map<String, IntIndexedContainer>> nodeEntry : routing.locations().entrySet()) {
        for (Map.Entry<String, IntIndexedContainer> indexEntry : nodeEntry.getValue().entrySet()) {
            assertThat(indexEntry.getKey(), is(getFqn("t1")));
            numShards += indexEntry.getValue().size();
        }
    }
    assertThat(numShards, is(10));
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) IntIndexedContainer(com.carrotsearch.hppc.IntIndexedContainer) CheckConstraint(io.crate.sql.tree.CheckConstraint) ClusterService(org.elasticsearch.cluster.service.ClusterService) Map(java.util.Map) CheckConstraint(io.crate.sql.tree.CheckConstraint) Test(org.junit.Test)

Example 5 with CheckConstraint

use of io.crate.sql.tree.CheckConstraint in project crate by crate.

the class DropCheckConstraintAnalyzer method analyze.

public AnalyzedAlterTableDropCheckConstraint analyze(Table<?> table, String name, CoordinatorTxnCtx txnCtx) {
    DocTableInfo tableInfo = (DocTableInfo) schemas.resolveTableInfo(table.getName(), Operation.ALTER, txnCtx.sessionContext().sessionUser(), txnCtx.sessionContext().searchPath());
    List<CheckConstraint<Symbol>> checkConstraints = tableInfo.checkConstraints();
    for (var checkConstraint : checkConstraints) {
        if (name.equals(checkConstraint.name())) {
            return new AnalyzedAlterTableDropCheckConstraint(tableInfo, name);
        }
    }
    throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot find a CHECK CONSTRAINT named [%s], available constraints are: %s", name, Lists2.map(checkConstraints, CheckConstraint::name)));
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) CheckConstraint(io.crate.sql.tree.CheckConstraint)

Aggregations

CheckConstraint (io.crate.sql.tree.CheckConstraint)7 Symbol (io.crate.expression.symbol.Symbol)3 Expression (io.crate.sql.tree.Expression)3 Map (java.util.Map)3 ExpressionAnalysisContext (io.crate.analyze.expressions.ExpressionAnalysisContext)2 ExpressionAnalyzer (io.crate.analyze.expressions.ExpressionAnalyzer)2 TableReferenceResolver (io.crate.analyze.expressions.TableReferenceResolver)2 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)2 DocTableInfo (io.crate.metadata.doc.DocTableInfo)2 LinkedHashMap (java.util.LinkedHashMap)2 Test (org.junit.Test)2 IntIndexedContainer (com.carrotsearch.hppc.IntIndexedContainer)1 FieldProvider (io.crate.analyze.relations.FieldProvider)1 GeneratedReference (io.crate.metadata.GeneratedReference)1 GeoReference (io.crate.metadata.GeoReference)1 IndexReference (io.crate.metadata.IndexReference)1 NodeContext (io.crate.metadata.NodeContext)1 Reference (io.crate.metadata.Reference)1 RelationName (io.crate.metadata.RelationName)1 EnsureNoMatchPredicate (io.crate.planner.operators.EnsureNoMatchPredicate)1