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;
}
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());
}
}
};
}
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;
}
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();
}
}
}
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 + "]");
}
Aggregations