Search in sources :

Example 1 with TypedValue

use of org.apache.calcite.avatica.remote.TypedValue in project calcite by apache.

the class CalciteConnectionImpl method enumerable.

public <T> Enumerable<T> enumerable(Meta.StatementHandle handle, CalcitePrepare.CalciteSignature<T> signature) throws SQLException {
    Map<String, Object> map = Maps.newLinkedHashMap();
    AvaticaStatement statement = lookupStatement(handle);
    final List<TypedValue> parameterValues = TROJAN.getParameterValues(statement);
    if (MetaImpl.checkParameterValueHasNull(parameterValues)) {
        throw new SQLException("exception while executing query: unbound parameter");
    }
    for (Ord<TypedValue> o : Ord.zip(parameterValues)) {
        map.put("?" + o.i, o.e.toLocal());
    }
    map.putAll(signature.internalParameters);
    final AtomicBoolean cancelFlag;
    try {
        cancelFlag = getCancelFlag(handle);
    } catch (NoSuchStatementException e) {
        throw new RuntimeException(e);
    }
    map.put(DataContext.Variable.CANCEL_FLAG.camelName, cancelFlag);
    final DataContext dataContext = createDataContext(map, signature.rootSchema);
    return signature.enumerable(dataContext);
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DataContext(org.apache.calcite.DataContext) SQLException(java.sql.SQLException) NoSuchStatementException(org.apache.calcite.avatica.NoSuchStatementException) AvaticaStatement(org.apache.calcite.avatica.AvaticaStatement) TypedValue(org.apache.calcite.avatica.remote.TypedValue)

Example 2 with TypedValue

use of org.apache.calcite.avatica.remote.TypedValue in project calcite-avatica by apache.

the class RemoteDriverTest method preparedStatementParameterCopies.

@Test
public void preparedStatementParameterCopies() throws Exception {
    // When implementing the JDBC batch APIs, it's important that we are copying the
    // TypedValues and caching them in the AvaticaPreparedStatement. Otherwise, when we submit
    // the batch, the parameter values for the last update added will be reflected in all previous
    // updates added to the batch.
    ConnectionSpec.getDatabaseLock().lock();
    try {
        final String tableName = AvaticaUtils.unique("PREPAREDSTATEMENT_VALUES");
        final Connection conn = getLocalConnection();
        try (Statement stmt = conn.createStatement()) {
            final String sql = "CREATE TABLE " + tableName + " (id varchar(1) not null, col1 varchar(1) not null)";
            assertFalse(stmt.execute(sql));
        }
        try (final PreparedStatement pstmt = conn.prepareStatement("INSERT INTO " + tableName + " values(?, ?)")) {
            pstmt.setString(1, "a");
            pstmt.setString(2, "b");
            @SuppressWarnings("resource") AvaticaPreparedStatement apstmt = (AvaticaPreparedStatement) pstmt;
            TypedValue[] slots = apstmt.slots;
            assertEquals("Unexpected number of values", 2, slots.length);
            List<TypedValue> valuesReference = apstmt.getParameterValues();
            assertEquals(2, valuesReference.size());
            assertEquals(slots[0], valuesReference.get(0));
            assertEquals(slots[1], valuesReference.get(1));
            List<TypedValue> copiedValues = apstmt.copyParameterValues();
            assertEquals(2, valuesReference.size());
            assertEquals(slots[0], copiedValues.get(0));
            assertEquals(slots[1], copiedValues.get(1));
            slots[0] = null;
            slots[1] = null;
            // Modifications to the array are reflected in the List from getParameterValues()
            assertNull(valuesReference.get(0));
            assertNull(valuesReference.get(1));
            // copyParameterValues() copied the underlying array, so updates to slots is not reflected
            assertNotNull(copiedValues.get(0));
            assertNotNull(copiedValues.get(1));
        }
    } finally {
        ConnectionSpec.getDatabaseLock().unlock();
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) StringContains.containsString(org.hamcrest.core.StringContains.containsString) TypedValue(org.apache.calcite.avatica.remote.TypedValue) Test(org.junit.Test)

Example 3 with TypedValue

use of org.apache.calcite.avatica.remote.TypedValue in project calcite-avatica by apache.

the class JdbcMeta method execute.

@Override
public ExecuteResult execute(StatementHandle h, List<TypedValue> parameterValues, int maxRowsInFirstFrame) throws NoSuchStatementException {
    try {
        if (MetaImpl.checkParameterValueHasNull(parameterValues)) {
            throw new SQLException("exception while executing query: unbound parameter");
        }
        final StatementInfo statementInfo = statementCache.getIfPresent(h.id);
        if (null == statementInfo) {
            throw new NoSuchStatementException(h);
        }
        final List<MetaResultSet> resultSets;
        final PreparedStatement preparedStatement = (PreparedStatement) statementInfo.statement;
        if (parameterValues != null) {
            for (int i = 0; i < parameterValues.size(); i++) {
                TypedValue o = parameterValues.get(i);
                preparedStatement.setObject(i + 1, o.toJdbc(calendar));
            }
        }
        if (preparedStatement.execute()) {
            final Signature signature2;
            if (preparedStatement.isWrapperFor(AvaticaPreparedStatement.class)) {
                signature2 = h.signature;
            } else {
                h.signature = signature(preparedStatement.getMetaData(), preparedStatement.getParameterMetaData(), h.signature.sql, Meta.StatementType.SELECT);
                signature2 = h.signature;
            }
            // Make sure we set this for subsequent fetch()'s to find the result set.
            statementInfo.setResultSet(preparedStatement.getResultSet());
            if (statementInfo.getResultSet() == null) {
                resultSets = Collections.<MetaResultSet>singletonList(JdbcResultSet.empty(h.connectionId, h.id, signature2));
            } else {
                resultSets = Collections.<MetaResultSet>singletonList(JdbcResultSet.create(h.connectionId, h.id, statementInfo.getResultSet(), maxRowsInFirstFrame, signature2));
            }
        } else {
            resultSets = Collections.<MetaResultSet>singletonList(JdbcResultSet.count(h.connectionId, h.id, preparedStatement.getUpdateCount()));
        }
        return new ExecuteResult(resultSets);
    } catch (SQLException e) {
        throw propagate(e);
    }
}
Also used : SQLException(java.sql.SQLException) NoSuchStatementException(org.apache.calcite.avatica.NoSuchStatementException) PreparedStatement(java.sql.PreparedStatement) AvaticaPreparedStatement(org.apache.calcite.avatica.AvaticaPreparedStatement) TypedValue(org.apache.calcite.avatica.remote.TypedValue)

Example 4 with TypedValue

use of org.apache.calcite.avatica.remote.TypedValue in project druid by druid-io.

the class SqlParameterizerShuttle method visit.

@Override
public SqlNode visit(SqlDynamicParam param) {
    try {
        if (plannerContext.getParameters().size() > param.getIndex()) {
            TypedValue paramBinding = plannerContext.getParameters().get(param.getIndex());
            if (paramBinding == null) {
                throw new IAE("Parameter at position[%s] is not bound", param.getIndex());
            }
            if (paramBinding.value == null) {
                return SqlLiteral.createNull(param.getParserPosition());
            }
            SqlTypeName typeName = SqlTypeName.getNameForJdbcType(paramBinding.type.typeId);
            if (SqlTypeName.APPROX_TYPES.contains(typeName)) {
                return SqlLiteral.createApproxNumeric(paramBinding.value.toString(), param.getParserPosition());
            }
            if (SqlTypeName.TIMESTAMP.equals(typeName) && paramBinding.value instanceof Long) {
                return SqlLiteral.createTimestamp(TimestampString.fromMillisSinceEpoch((Long) paramBinding.value), 0, param.getParserPosition());
            }
            return typeName.createLiteral(paramBinding.value, param.getParserPosition());
        } else {
            throw new IAE("Parameter at position[%s] is not bound", param.getIndex());
        }
    } catch (ClassCastException ignored) {
    // suppress
    }
    return param;
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) IAE(org.apache.druid.java.util.common.IAE) TypedValue(org.apache.calcite.avatica.remote.TypedValue)

Example 5 with TypedValue

use of org.apache.calcite.avatica.remote.TypedValue in project druid by druid-io.

the class PlannerContext method createDataContext.

public DataContext createDataContext(final JavaTypeFactory typeFactory, List<TypedValue> parameters) {
    class DruidDataContext implements DataContext {

        private final Map<String, Object> base_context = ImmutableMap.of(DataContext.Variable.UTC_TIMESTAMP.camelName, localNow.getMillis(), DataContext.Variable.CURRENT_TIMESTAMP.camelName, localNow.getMillis(), DataContext.Variable.LOCAL_TIMESTAMP.camelName, new Interval(new DateTime("1970-01-01T00:00:00.000", localNow.getZone()), localNow).toDurationMillis(), DataContext.Variable.TIME_ZONE.camelName, localNow.getZone().toTimeZone().clone());

        private final Map<String, Object> context;

        DruidDataContext() {
            ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
            builder.putAll(base_context);
            int i = 0;
            for (TypedValue parameter : parameters) {
                builder.put("?" + i, parameter.value);
                i++;
            }
            if (authenticationResult != null) {
                builder.put(DATA_CTX_AUTHENTICATION_RESULT, authenticationResult);
            }
            context = builder.build();
        }

        @Override
        public SchemaPlus getRootSchema() {
            throw new UnsupportedOperationException();
        }

        @Override
        public JavaTypeFactory getTypeFactory() {
            return typeFactory;
        }

        @Override
        public QueryProvider getQueryProvider() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Object get(final String name) {
            return context.get(name);
        }
    }
    return new DruidDataContext();
}
Also used : DataContext(org.apache.calcite.DataContext) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) DateTime(org.joda.time.DateTime) ImmutableMap(com.google.common.collect.ImmutableMap) Interval(org.joda.time.Interval) TypedValue(org.apache.calcite.avatica.remote.TypedValue)

Aggregations

TypedValue (org.apache.calcite.avatica.remote.TypedValue)10 Test (org.junit.Test)4 PreparedStatement (java.sql.PreparedStatement)3 SQLException (java.sql.SQLException)3 NoSuchStatementException (org.apache.calcite.avatica.NoSuchStatementException)3 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)2 DataContext (org.apache.calcite.DataContext)2 AvaticaPreparedStatement (org.apache.calcite.avatica.AvaticaPreparedStatement)2 SqlTypeName (org.apache.calcite.sql.type.SqlTypeName)2 ServiceEventBuilder (org.apache.druid.java.util.emitter.service.ServiceEventBuilder)2 DruidPlanner (org.apache.druid.sql.calcite.planner.DruidPlanner)2 PlannerContext (org.apache.druid.sql.calcite.planner.PlannerContext)2 PlannerResult (org.apache.druid.sql.calcite.planner.PlannerResult)2 PrepareResult (org.apache.druid.sql.calcite.planner.PrepareResult)2 ValidationResult (org.apache.druid.sql.calcite.planner.ValidationResult)2 SqlParameter (org.apache.druid.sql.http.SqlParameter)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 BigDecimal (java.math.BigDecimal)1 Connection (java.sql.Connection)1 Statement (java.sql.Statement)1