Search in sources :

Example 1 with DataType

use of io.crate.types.DataType in project crate by crate.

the class ParameterContext method getAsSymbol.

public io.crate.analyze.symbol.Literal getAsSymbol(int index) {
    try {
        Object value = parameters().get(index);
        DataType type = guessTypeSafe(value);
        // use type.value because some types need conversion (String to BytesRef, List to Array)
        return Literal.of(type, type.value(value));
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Tried to resolve a parameter but the arguments provided with the " + "SQLRequest don't contain a parameter at position %d", index), e);
    }
}
Also used : DataType(io.crate.types.DataType)

Example 2 with DataType

use of io.crate.types.DataType in project crate by crate.

the class QuerySpec method castOutputs.

/**
     * Tries to cast the outputs to the given types. Types might contain Null values, which indicates to skip that
     * position. The iterator needs to return exactly the same number of types as there are outputs.
     *
     * @param types an iterable providing the types
     * @return -1 if all casts where successfully applied or the position of the failed cast
     */
public int castOutputs(Iterator<DataType> types) {
    int i = 0;
    ListIterator<Symbol> outputsIt = outputs.listIterator();
    while (types.hasNext() && outputsIt.hasNext()) {
        DataType targetType = types.next();
        assert targetType != null : "targetType must not be null";
        Symbol output = outputsIt.next();
        DataType sourceType = output.valueType();
        if (!sourceType.equals(targetType)) {
            if (sourceType.isConvertableTo(targetType)) {
                Symbol castFunction = CastFunctionResolver.generateCastFunction(output, targetType, false);
                if (groupBy.isPresent()) {
                    Collections.replaceAll(groupBy.get(), output, castFunction);
                }
                if (orderBy.isPresent()) {
                    Collections.replaceAll(orderBy.get().orderBySymbols(), output, castFunction);
                }
                outputsIt.set(castFunction);
            } else if (!targetType.equals(DataTypes.UNDEFINED)) {
                return i;
            }
        }
        i++;
    }
    assert i == outputs.size() : "i must be equal to outputs.size()";
    return -1;
}
Also used : Symbol(io.crate.analyze.symbol.Symbol) DataType(io.crate.types.DataType)

Example 3 with DataType

use of io.crate.types.DataType in project crate by crate.

the class AnalyzedTableElements method processGeneratedExpression.

private void processGeneratedExpression(ExpressionAnalyzer expressionAnalyzer, SymbolPrinter symbolPrinter, AnalyzedColumnDefinition columnDefinition, ExpressionAnalysisContext expressionAnalysisContext) {
    // validate expression
    Symbol function = expressionAnalyzer.convert(columnDefinition.generatedExpression(), expressionAnalysisContext);
    String formattedExpression;
    DataType valueType = function.valueType();
    DataType definedType = columnDefinition.dataType() == null ? null : DataTypes.ofMappingNameSafe(columnDefinition.dataType());
    // check for optional defined type and add `cast` to expression if possible
    if (definedType != null && !definedType.equals(valueType)) {
        Preconditions.checkArgument(valueType.isConvertableTo(definedType), "generated expression value type '%s' not supported for conversion to '%s'", valueType, definedType.getName());
        Symbol castFunction = CastFunctionResolver.generateCastFunction(function, definedType, false);
        // no full qualified references here
        formattedExpression = symbolPrinter.print(castFunction, SymbolPrinter.Style.PARSEABLE_NOT_QUALIFIED);
    } else {
        columnDefinition.dataType(function.valueType().getName());
        // no full qualified references here
        formattedExpression = symbolPrinter.print(function, SymbolPrinter.Style.PARSEABLE_NOT_QUALIFIED);
    }
    columnDefinition.formattedGeneratedExpression(formattedExpression);
}
Also used : Symbol(io.crate.analyze.symbol.Symbol) DataType(io.crate.types.DataType)

Example 4 with DataType

use of io.crate.types.DataType in project crate by crate.

the class AnalyzedTableElements method changeToPartitionedByColumn.

void changeToPartitionedByColumn(ColumnIdent partitionedByIdent, boolean skipIfNotFound) {
    Preconditions.checkArgument(!partitionedByIdent.name().startsWith("_"), "Cannot use system columns in PARTITIONED BY clause");
    // need to call primaryKeys() before the partition column is removed from the columns list
    if (!primaryKeys().isEmpty() && !primaryKeys().contains(partitionedByIdent.fqn())) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot use non primary key column '%s' in PARTITIONED BY clause if primary key is set on table", partitionedByIdent.sqlFqn()));
    }
    AnalyzedColumnDefinition columnDefinition = columnDefinitionByIdent(partitionedByIdent);
    if (columnDefinition == null) {
        if (skipIfNotFound) {
            return;
        }
        throw new ColumnUnknownException(partitionedByIdent.sqlFqn());
    }
    DataType columnType = DataTypes.ofMappingNameSafe(columnDefinition.dataType());
    if (!DataTypes.isPrimitive(columnType)) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot use column %s of type %s in PARTITIONED BY clause", columnDefinition.ident().sqlFqn(), columnDefinition.dataType()));
    }
    if (columnDefinition.isArrayOrInArray()) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot use array column %s in PARTITIONED BY clause", columnDefinition.ident().sqlFqn()));
    }
    if (columnDefinition.indexConstraint().equals("analyzed")) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot use column %s with fulltext index in PARTITIONED BY clause", columnDefinition.ident().sqlFqn()));
    }
    columnIdents.remove(columnDefinition.ident());
    columnDefinition.indexConstraint(Reference.IndexType.NO.toString());
    partitionedByColumns.add(columnDefinition);
}
Also used : ColumnUnknownException(io.crate.exceptions.ColumnUnknownException) DataType(io.crate.types.DataType)

Example 5 with DataType

use of io.crate.types.DataType in project crate by crate.

the class LuceneQueryBuilderTest method testWhereRefEqNullWithDifferentTypes.

@Test
public void testWhereRefEqNullWithDifferentTypes() throws Exception {
    for (DataType type : DataTypes.PRIMITIVE_TYPES) {
        DocTableInfo tableInfo = TestingTableInfo.builder(new TableIdent(null, "test_primitive"), null).add("x", type).build();
        TableRelation tableRelation = new TableRelation(tableInfo);
        Map<QualifiedName, AnalyzedRelation> tableSources = ImmutableMap.of(new QualifiedName(tableInfo.ident().name()), tableRelation);
        SqlExpressions sqlExpressions = new SqlExpressions(tableSources, tableRelation, new Object[] { null }, SessionContext.SYSTEM_SESSION);
        Query query = convert(new WhereClause(sqlExpressions.normalize(sqlExpressions.asSymbol("x = ?"))));
        // must always become a MatchNoDocsQuery (empty BooleanQuery)
        // string: term query with null would cause NPE
        // int/numeric: rangeQuery from null to null would match all
        // bool:  term would match false too because of the condition in the eq query builder
        assertThat(query, instanceOf(BooleanQuery.class));
        assertThat(((BooleanQuery) query).clauses().size(), is(0));
    }
}
Also used : DocTableInfo(io.crate.metadata.doc.DocTableInfo) TermsQuery(org.apache.lucene.queries.TermsQuery) CrateRegexQuery(io.crate.lucene.match.CrateRegexQuery) IntersectsPrefixTreeQuery(org.apache.lucene.spatial.prefix.IntersectsPrefixTreeQuery) WithinPrefixTreeQuery(org.apache.lucene.spatial.prefix.WithinPrefixTreeQuery) QualifiedName(io.crate.sql.tree.QualifiedName) WhereClause(io.crate.analyze.WhereClause) DataType(io.crate.types.DataType) TableIdent(io.crate.metadata.TableIdent) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) SqlExpressions(io.crate.testing.SqlExpressions) TableRelation(io.crate.analyze.relations.TableRelation) Test(org.junit.Test) CrateUnitTest(io.crate.test.integration.CrateUnitTest)

Aggregations

DataType (io.crate.types.DataType)95 ArrayType (io.crate.types.ArrayType)35 Test (org.junit.Test)33 ArrayList (java.util.ArrayList)17 Map (java.util.Map)17 CrateUnitTest (io.crate.test.integration.CrateUnitTest)14 List (java.util.List)12 Symbol (io.crate.expression.symbol.Symbol)11 Literal (io.crate.expression.symbol.Literal)9 ColumnIdent (io.crate.metadata.ColumnIdent)9 HashMap (java.util.HashMap)9 FunctionIdent (io.crate.metadata.FunctionIdent)8 NodeContext (io.crate.metadata.NodeContext)8 Reference (io.crate.metadata.Reference)8 Row (io.crate.data.Row)7 Symbols (io.crate.expression.symbol.Symbols)7 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)7 Locale (java.util.Locale)7 Lists2 (io.crate.common.collections.Lists2)6 FunctionInfo (io.crate.metadata.FunctionInfo)6