Search in sources :

Example 76 with IgniteCheckedException

use of org.apache.ignite.IgniteCheckedException in project ignite by apache.

the class IgniteH2Indexing method generateQuery.

/**
 * Prepares statement for query.
 *
 * @param qry Query string.
 * @param tableAlias table alias.
 * @param tbl Table to use.
 * @return Prepared statement.
 * @throws IgniteCheckedException In case of error.
 */
private String generateQuery(String qry, String tableAlias, H2TableDescriptor tbl) throws IgniteCheckedException {
    assert tbl != null;
    final String qry0 = qry;
    String t = tbl.fullTableName();
    String from = " ";
    qry = qry.trim();
    String upper = qry.toUpperCase();
    if (upper.startsWith("SELECT")) {
        qry = qry.substring(6).trim();
        final int star = qry.indexOf('*');
        if (star == 0)
            qry = qry.substring(1).trim();
        else if (star > 0) {
            if (F.eq('.', qry.charAt(star - 1))) {
                t = qry.substring(0, star - 1);
                qry = qry.substring(star + 1).trim();
            } else
                throw new IgniteCheckedException("Invalid query (missing alias before asterisk): " + qry0);
        } else
            throw new IgniteCheckedException("Only queries starting with 'SELECT *' and 'SELECT alias.*' " + "are supported (rewrite your query or use SqlFieldsQuery instead): " + qry0);
        upper = qry.toUpperCase();
    }
    if (!upper.startsWith("FROM"))
        from = " FROM " + t + (tableAlias != null ? " as " + tableAlias : "") + (upper.startsWith("WHERE") || upper.startsWith("ORDER") || upper.startsWith("LIMIT") ? " " : " WHERE ");
    if (tableAlias != null)
        t = tableAlias;
    qry = "SELECT " + t + "." + KEY_FIELD_NAME + ", " + t + "." + VAL_FIELD_NAME + from + qry;
    return qry;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSystemProperties.getString(org.apache.ignite.IgniteSystemProperties.getString)

Example 77 with IgniteCheckedException

use of org.apache.ignite.IgniteCheckedException in project ignite by apache.

the class IgniteH2Indexing method queryLocalSqlFields.

/**
 * Queries individual fields (generally used by JDBC drivers).
 *
 * @param schemaName Schema name.
 * @param qry Query.
 * @param params Query parameters.
 * @param filter Cache name and key filter.
 * @param enforceJoinOrder Enforce join order of tables in the query.
 * @param timeout Query timeout in milliseconds.
 * @param cancel Query cancel.
 * @return Query result.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("unchecked")
GridQueryFieldsResult queryLocalSqlFields(final String schemaName, final String qry, @Nullable final Collection<Object> params, final IndexingQueryFilter filter, boolean enforceJoinOrder, final int timeout, final GridQueryCancel cancel) throws IgniteCheckedException {
    final Connection conn = connectionForSchema(schemaName);
    H2Utils.setupConnection(conn, false, enforceJoinOrder);
    final PreparedStatement stmt = preparedStatementWithParams(conn, qry, params, true);
    if (GridSqlQueryParser.checkMultipleStatements(stmt))
        throw new IgniteSQLException("Multiple statements queries are not supported for local queries");
    Prepared p = GridSqlQueryParser.prepared(stmt);
    if (DmlStatementsProcessor.isDmlStatement(p)) {
        SqlFieldsQuery fldsQry = new SqlFieldsQuery(qry);
        if (params != null)
            fldsQry.setArgs(params.toArray());
        fldsQry.setEnforceJoinOrder(enforceJoinOrder);
        fldsQry.setTimeout(timeout, TimeUnit.MILLISECONDS);
        return dmlProc.updateSqlFieldsLocal(schemaName, conn, p, fldsQry, filter, cancel);
    } else if (DdlStatementsProcessor.isDdlStatement(p))
        throw new IgniteSQLException("DDL statements are supported for the whole cluster only", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    List<GridQueryFieldMetadata> meta;
    try {
        meta = H2Utils.meta(stmt.getMetaData());
    } catch (SQLException e) {
        throw new IgniteCheckedException("Cannot prepare query metadata", e);
    }
    final GridH2QueryContext ctx = new GridH2QueryContext(nodeId, nodeId, 0, LOCAL).filter(filter).distributedJoinMode(OFF);
    return new GridQueryFieldsResultAdapter(meta, null) {

        @Override
        public GridCloseableIterator<List<?>> iterator() throws IgniteCheckedException {
            assert GridH2QueryContext.get() == null;
            GridH2QueryContext.set(ctx);
            GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL_FIELDS, schemaName, U.currentTimeMillis(), cancel, true);
            runs.putIfAbsent(run.id(), run);
            try {
                ResultSet rs = executeSqlQueryWithTimer(stmt, conn, qry, params, timeout, cancel);
                return new H2FieldsIterator(rs);
            } finally {
                GridH2QueryContext.clearThreadLocal();
                runs.remove(run.id());
            }
        }
    };
}
Also used : GridQueryFieldsResultAdapter(org.apache.ignite.internal.processors.query.GridQueryFieldsResultAdapter) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Connection(java.sql.Connection) Prepared(org.h2.command.Prepared) GridRunningQueryInfo(org.apache.ignite.internal.processors.query.GridRunningQueryInfo) GridQueryFieldMetadata(org.apache.ignite.internal.processors.query.GridQueryFieldMetadata) PreparedStatement(java.sql.PreparedStatement) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) GridH2QueryContext(org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext)

Example 78 with IgniteCheckedException

use of org.apache.ignite.IgniteCheckedException in project ignite by apache.

the class IgniteH2Indexing method preparedStatementWithParams.

/**
 * Prepares sql statement.
 *
 * @param conn Connection.
 * @param sql Sql.
 * @param params Params.
 * @param useStmtCache If {@code true} use stmt cache.
 * @return Prepared statement with set parameters.
 * @throws IgniteCheckedException If failed.
 */
private PreparedStatement preparedStatementWithParams(Connection conn, String sql, Collection<Object> params, boolean useStmtCache) throws IgniteCheckedException {
    final PreparedStatement stmt;
    try {
        stmt = prepareStatement(conn, sql, useStmtCache);
    } catch (SQLException e) {
        throw new IgniteCheckedException("Failed to parse SQL query: " + sql, e);
    }
    bindParameters(stmt, params);
    return stmt;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) PreparedStatement(java.sql.PreparedStatement)

Example 79 with IgniteCheckedException

use of org.apache.ignite.IgniteCheckedException in project ignite by apache.

the class IgniteH2Indexing method unregisterCache.

/**
 * {@inheritDoc}
 */
@Override
public void unregisterCache(GridCacheContext cctx, boolean rmvIdx) {
    rowCache.onCacheUnregistered(cctx);
    String cacheName = cctx.name();
    String schemaName = schema(cacheName);
    H2Schema schema = schemas.get(schemaName);
    if (schema != null) {
        mapQryExec.onCacheStop(cacheName);
        dmlProc.onCacheStop(cacheName);
        // Remove this mapping only after callback to DML proc - it needs that mapping internally
        cacheName2schema.remove(cacheName);
        // Drop tables.
        Collection<H2TableDescriptor> rmvTbls = new HashSet<>();
        for (H2TableDescriptor tbl : schema.tables()) {
            if (F.eq(tbl.cache().name(), cacheName)) {
                try {
                    tbl.table().setRemoveIndexOnDestroy(rmvIdx);
                    dropTable(tbl);
                } catch (IgniteCheckedException e) {
                    U.error(log, "Failed to drop table on cache stop (will ignore): " + tbl.fullTableName(), e);
                }
                schema.drop(tbl);
                rmvTbls.add(tbl);
            }
        }
        if (!isDefaultSchema(schemaName)) {
            synchronized (schemaMux) {
                if (schema.decrementUsageCount() == 0) {
                    schemas.remove(schemaName);
                    try {
                        dropSchema(schemaName);
                    } catch (IgniteCheckedException e) {
                        U.error(log, "Failed to drop schema on cache stop (will ignore): " + cacheName, e);
                    }
                }
            }
        }
        stmtCache.clear();
        for (H2TableDescriptor tbl : rmvTbls) {
            for (Index idx : tbl.table().getIndexes()) idx.close(null);
        }
        int cacheId = CU.cacheId(cacheName);
        for (Iterator<Map.Entry<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery>> it = twoStepCache.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery> e = it.next();
            GridCacheTwoStepQuery qry = e.getValue().query();
            if (!F.isEmpty(qry.cacheIds()) && qry.cacheIds().contains(cacheId))
                it.remove();
        }
    }
}
Also used : GridCacheTwoStepQuery(org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery) Index(org.h2.index.Index) H2TreeIndex(org.apache.ignite.internal.processors.query.h2.database.H2TreeIndex) IgniteSystemProperties.getString(org.apache.ignite.IgniteSystemProperties.getString) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GridBoundedConcurrentLinkedHashMap(org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 80 with IgniteCheckedException

use of org.apache.ignite.IgniteCheckedException in project ignite by apache.

the class GridH2RowDescriptor method wrap.

/**
 * Wraps object to respective {@link Value}.
 *
 * @param obj Object.
 * @param type Value type.
 * @return Value.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("ConstantConditions")
public Value wrap(Object obj, int type) throws IgniteCheckedException {
    assert obj != null;
    if (obj instanceof CacheObject) {
        // Handle cache object.
        CacheObject co = (CacheObject) obj;
        if (type == Value.JAVA_OBJECT)
            return new GridH2ValueCacheObject(co, idx.objectContext());
        obj = co.value(idx.objectContext(), false);
    }
    switch(type) {
        case Value.BOOLEAN:
            return ValueBoolean.get((Boolean) obj);
        case Value.BYTE:
            return ValueByte.get((Byte) obj);
        case Value.SHORT:
            return ValueShort.get((Short) obj);
        case Value.INT:
            return ValueInt.get((Integer) obj);
        case Value.FLOAT:
            return ValueFloat.get((Float) obj);
        case Value.LONG:
            return ValueLong.get((Long) obj);
        case Value.DOUBLE:
            return ValueDouble.get((Double) obj);
        case Value.UUID:
            UUID uuid = (UUID) obj;
            return ValueUuid.get(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
        case Value.DATE:
            if (LocalDateTimeUtils.isLocalDate(obj.getClass()))
                return LocalDateTimeUtils.localDateToDateValue(obj);
            return ValueDate.get((Date) obj);
        case Value.TIME:
            if (LocalDateTimeUtils.isLocalTime(obj.getClass()))
                return LocalDateTimeUtils.localTimeToTimeValue(obj);
            return ValueTime.get((Time) obj);
        case Value.TIMESTAMP:
            if (obj instanceof java.util.Date && !(obj instanceof Timestamp))
                obj = new Timestamp(((java.util.Date) obj).getTime());
            if (LocalDateTimeUtils.isLocalDateTime(obj.getClass()))
                return LocalDateTimeUtils.localDateTimeToValue(obj);
            return ValueTimestamp.get((Timestamp) obj);
        case Value.DECIMAL:
            return ValueDecimal.get((BigDecimal) obj);
        case Value.STRING:
            return ValueString.get(obj.toString());
        case Value.BYTES:
            return ValueBytes.get((byte[]) obj);
        case Value.JAVA_OBJECT:
            return ValueJavaObject.getNoCopy(obj, null, null);
        case Value.ARRAY:
            Object[] arr = (Object[]) obj;
            Value[] valArr = new Value[arr.length];
            for (int i = 0; i < arr.length; i++) {
                Object o = arr[i];
                valArr[i] = o == null ? ValueNull.INSTANCE : wrap(o, DataType.getTypeFromClass(o.getClass()));
            }
            return ValueArray.get(valArr);
        case Value.GEOMETRY:
            return ValueGeometry.getFromGeometry(obj);
    }
    throw new IgniteCheckedException("Failed to wrap value[type=" + type + ", value=" + obj + "]");
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Value(org.h2.value.Value) ValueJavaObject(org.h2.value.ValueJavaObject) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) UUID(java.util.UUID) Timestamp(java.sql.Timestamp) ValueTimestamp(org.h2.value.ValueTimestamp)

Aggregations

IgniteCheckedException (org.apache.ignite.IgniteCheckedException)1568 IgniteException (org.apache.ignite.IgniteException)388 ArrayList (java.util.ArrayList)237 IOException (java.io.IOException)226 ClusterNode (org.apache.ignite.cluster.ClusterNode)215 Map (java.util.Map)181 UUID (java.util.UUID)163 HashMap (java.util.HashMap)160 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)150 Test (org.junit.Test)143 List (java.util.List)139 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)138 Nullable (org.jetbrains.annotations.Nullable)134 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)118 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)109 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)105 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)104 Collection (java.util.Collection)97 HashSet (java.util.HashSet)97 Ignite (org.apache.ignite.Ignite)96