use of org.apache.ignite.internal.processors.cache.QueryCursorImpl in project ignite by apache.
the class JdbcRequestHandler method executeQuery.
/**
* {@link JdbcQueryExecuteRequest} command handler.
*
* @param req Execute query request.
* @return Response.
*/
@SuppressWarnings("unchecked")
private JdbcResponse executeQuery(JdbcQueryExecuteRequest req) {
int cursorCnt = qryCursors.size();
if (maxCursors > 0 && cursorCnt >= maxCursors)
return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Too many open cursors (either close other " + "open cursors or increase the limit through " + "ClientConnectorConfiguration.maxOpenCursorsPerConnection) [maximum=" + maxCursors + ", current=" + cursorCnt + ']');
long qryId = QRY_ID_GEN.getAndIncrement();
assert !cliCtx.isStream();
try {
String sql = req.sqlQuery();
SqlFieldsQuery qry;
switch(req.expectedStatementType()) {
case ANY_STATEMENT_TYPE:
qry = new SqlFieldsQuery(sql);
break;
case SELECT_STATEMENT_TYPE:
qry = new SqlFieldsQueryEx(sql, true);
break;
default:
assert req.expectedStatementType() == JdbcStatementType.UPDATE_STMT_TYPE;
qry = new SqlFieldsQueryEx(sql, false);
if (cliCtx.isSkipReducerOnUpdate())
((SqlFieldsQueryEx) qry).setSkipReducerOnUpdate(true);
}
qry.setArgs(req.arguments());
qry.setDistributedJoins(cliCtx.isDistributedJoins());
qry.setEnforceJoinOrder(cliCtx.isEnforceJoinOrder());
qry.setCollocated(cliCtx.isCollocated());
qry.setReplicatedOnly(cliCtx.isReplicatedOnly());
qry.setLazy(cliCtx.isLazy());
if (req.pageSize() <= 0)
return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Invalid fetch size: " + req.pageSize());
qry.setPageSize(req.pageSize());
String schemaName = req.schemaName();
if (F.isEmpty(schemaName))
schemaName = QueryUtils.DFLT_SCHEMA;
qry.setSchema(schemaName);
List<FieldsQueryCursor<List<?>>> results = ctx.query().querySqlFields(null, qry, cliCtx, true, protocolVer.compareTo(VER_2_3_0) < 0);
FieldsQueryCursor<List<?>> fieldsCur = results.get(0);
if (fieldsCur instanceof BulkLoadContextCursor) {
BulkLoadContextCursor blCur = (BulkLoadContextCursor) fieldsCur;
BulkLoadProcessor blProcessor = blCur.bulkLoadProcessor();
BulkLoadAckClientParameters clientParams = blCur.clientParams();
bulkLoadRequests.put(qryId, new JdbcBulkLoadProcessor(blProcessor));
return new JdbcResponse(new JdbcBulkLoadAckResult(qryId, clientParams));
}
if (results.size() == 1) {
JdbcQueryCursor cur = new JdbcQueryCursor(qryId, req.pageSize(), req.maxRows(), (QueryCursorImpl) fieldsCur);
JdbcQueryExecuteResult res;
if (cur.isQuery())
res = new JdbcQueryExecuteResult(qryId, cur.fetchRows(), !cur.hasNext());
else {
List<List<Object>> items = cur.fetchRows();
assert items != null && items.size() == 1 && items.get(0).size() == 1 && items.get(0).get(0) instanceof Long : "Invalid result set for not-SELECT query. [qry=" + sql + ", res=" + S.toString(List.class, items) + ']';
res = new JdbcQueryExecuteResult(qryId, (Long) items.get(0).get(0));
}
if (res.last() && (!res.isQuery() || autoCloseCursors))
cur.close();
else
qryCursors.put(qryId, cur);
return new JdbcResponse(res);
} else {
List<JdbcResultInfo> jdbcResults = new ArrayList<>(results.size());
List<List<Object>> items = null;
boolean last = true;
for (FieldsQueryCursor<List<?>> c : results) {
QueryCursorImpl qryCur = (QueryCursorImpl) c;
JdbcResultInfo jdbcRes;
if (qryCur.isQuery()) {
jdbcRes = new JdbcResultInfo(true, -1, qryId);
JdbcQueryCursor cur = new JdbcQueryCursor(qryId, req.pageSize(), req.maxRows(), qryCur);
qryCursors.put(qryId, cur);
qryId = QRY_ID_GEN.getAndIncrement();
if (items == null) {
items = cur.fetchRows();
last = cur.hasNext();
}
} else
jdbcRes = new JdbcResultInfo(false, (Long) ((List<?>) qryCur.getAll().get(0)).get(0), -1);
jdbcResults.add(jdbcRes);
}
return new JdbcResponse(new JdbcQueryExecuteMultipleStatementsResult(jdbcResults, items, last));
}
} catch (Exception e) {
qryCursors.remove(qryId);
U.error(log, "Failed to execute SQL query [reqId=" + req.requestId() + ", req=" + req + ']', e);
return exceptionToResult(e);
}
}
use of org.apache.ignite.internal.processors.cache.QueryCursorImpl in project ignite by apache.
the class DdlStatementsProcessor method runDdlStatement.
/**
* Execute DDL statement.
*
* @param sql SQL.
* @param prepared Prepared.
* @return Cursor on query results.
* @throws IgniteCheckedException On error.
*/
@SuppressWarnings({ "unchecked", "ThrowableResultOfMethodCallIgnored" })
public FieldsQueryCursor<List<?>> runDdlStatement(String sql, Prepared prepared) throws IgniteCheckedException {
IgniteInternalFuture fut = null;
try {
GridSqlStatement stmt0 = new GridSqlQueryParser(false).parse(prepared);
if (stmt0 instanceof GridSqlCreateIndex) {
GridSqlCreateIndex cmd = (GridSqlCreateIndex) stmt0;
GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
if (tbl == null)
throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
assert tbl.rowDescriptor() != null;
isDdlSupported(tbl);
QueryIndex newIdx = new QueryIndex();
newIdx.setName(cmd.index().getName());
newIdx.setIndexType(cmd.index().getIndexType());
LinkedHashMap<String, Boolean> flds = new LinkedHashMap<>();
// Let's replace H2's table and property names by those operated by GridQueryProcessor.
GridQueryTypeDescriptor typeDesc = tbl.rowDescriptor().type();
for (Map.Entry<String, Boolean> e : cmd.index().getFields().entrySet()) {
GridQueryProperty prop = typeDesc.property(e.getKey());
if (prop == null)
throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_NOT_FOUND, e.getKey());
flds.put(prop.name(), e.getValue());
}
newIdx.setFields(flds);
fut = ctx.query().dynamicIndexCreate(tbl.cacheName(), cmd.schemaName(), typeDesc.tableName(), newIdx, cmd.ifNotExists(), 0);
} else if (stmt0 instanceof GridSqlDropIndex) {
GridSqlDropIndex cmd = (GridSqlDropIndex) stmt0;
GridH2Table tbl = idx.dataTableForIndex(cmd.schemaName(), cmd.indexName());
if (tbl != null) {
isDdlSupported(tbl);
fut = ctx.query().dynamicIndexDrop(tbl.cacheName(), cmd.schemaName(), cmd.indexName(), cmd.ifExists());
} else {
if (cmd.ifExists())
fut = new GridFinishedFuture();
else
throw new SchemaOperationException(SchemaOperationException.CODE_INDEX_NOT_FOUND, cmd.indexName());
}
} else if (stmt0 instanceof GridSqlCreateTable) {
GridSqlCreateTable cmd = (GridSqlCreateTable) stmt0;
if (!F.eq(QueryUtils.DFLT_SCHEMA, cmd.schemaName()))
throw new SchemaOperationException("CREATE TABLE can only be executed on " + QueryUtils.DFLT_SCHEMA + " schema.");
GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
if (tbl != null) {
if (!cmd.ifNotExists())
throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_EXISTS, cmd.tableName());
} else {
QueryEntity e = toQueryEntity(cmd);
CacheConfiguration<?, ?> ccfg = new CacheConfiguration<>(cmd.tableName());
ccfg.setQueryEntities(Collections.singleton(e));
ccfg.setSqlSchema(cmd.schemaName());
SchemaOperationException err = QueryUtils.checkQueryEntityConflicts(ccfg, ctx.cache().cacheDescriptors().values());
if (err != null)
throw err;
ctx.query().dynamicTableCreate(cmd.schemaName(), e, cmd.templateName(), cmd.cacheName(), cmd.cacheGroup(), cmd.dataRegionName(), cmd.affinityKey(), cmd.atomicityMode(), cmd.writeSynchronizationMode(), cmd.backups(), cmd.ifNotExists());
}
} else if (stmt0 instanceof GridSqlDropTable) {
GridSqlDropTable cmd = (GridSqlDropTable) stmt0;
if (!F.eq(QueryUtils.DFLT_SCHEMA, cmd.schemaName()))
throw new SchemaOperationException("DROP TABLE can only be executed on " + QueryUtils.DFLT_SCHEMA + " schema.");
GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
if (tbl == null && cmd.ifExists()) {
ctx.cache().createMissingQueryCaches();
tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
}
if (tbl == null) {
if (!cmd.ifExists())
throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
} else
ctx.query().dynamicTableDrop(tbl.cacheName(), cmd.tableName(), cmd.ifExists());
} else if (stmt0 instanceof GridSqlAlterTableAddColumn) {
GridSqlAlterTableAddColumn cmd = (GridSqlAlterTableAddColumn) stmt0;
GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
if (tbl == null && cmd.ifTableExists()) {
ctx.cache().createMissingQueryCaches();
tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
}
if (tbl == null) {
if (!cmd.ifTableExists())
throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
} else {
if (QueryUtils.isSqlType(tbl.rowDescriptor().type().valueClass()))
throw new SchemaOperationException("Cannot add column(s) because table was created " + "with " + PARAM_WRAP_VALUE + "=false option.");
List<QueryField> cols = new ArrayList<>(cmd.columns().length);
boolean allFieldsNullable = true;
for (GridSqlColumn col : cmd.columns()) {
if (tbl.doesColumnExist(col.columnName())) {
if ((!cmd.ifNotExists() || cmd.columns().length != 1)) {
throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_EXISTS, col.columnName());
} else {
cols = null;
break;
}
}
QueryField field = new QueryField(col.columnName(), DataType.getTypeClassName(col.column().getType()), col.column().isNullable(), col.defaultValue());
cols.add(field);
allFieldsNullable &= field.isNullable();
}
if (cols != null) {
assert tbl.rowDescriptor() != null;
if (!allFieldsNullable)
QueryUtils.checkNotNullAllowed(tbl.cache().config());
fut = ctx.query().dynamicColumnAdd(tbl.cacheName(), cmd.schemaName(), tbl.rowDescriptor().type().tableName(), cols, cmd.ifTableExists(), cmd.ifNotExists());
}
}
} else if (stmt0 instanceof GridSqlAlterTableDropColumn) {
GridSqlAlterTableDropColumn cmd = (GridSqlAlterTableDropColumn) stmt0;
GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
if (tbl == null && cmd.ifTableExists()) {
ctx.cache().createMissingQueryCaches();
tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
}
if (tbl == null) {
if (!cmd.ifTableExists())
throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
} else {
assert tbl.rowDescriptor() != null;
if (QueryUtils.isSqlType(tbl.rowDescriptor().type().valueClass()))
throw new SchemaOperationException("Cannot drop column(s) because table was created " + "with " + PARAM_WRAP_VALUE + "=false option.");
List<String> cols = new ArrayList<>(cmd.columns().length);
GridQueryTypeDescriptor type = tbl.rowDescriptor().type();
for (String colName : cmd.columns()) {
if (!tbl.doesColumnExist(colName)) {
if ((!cmd.ifExists() || cmd.columns().length != 1)) {
throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_NOT_FOUND, colName);
} else {
cols = null;
break;
}
}
SchemaOperationException err = QueryUtils.validateDropColumn(type, colName);
if (err != null)
throw err;
cols.add(colName);
}
if (cols != null) {
fut = ctx.query().dynamicColumnRemove(tbl.cacheName(), cmd.schemaName(), type.tableName(), cols, cmd.ifTableExists(), cmd.ifExists());
}
}
} else
throw new IgniteSQLException("Unsupported DDL operation: " + sql, IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
if (fut != null)
fut.get();
QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>) new QueryCursorImpl(Collections.singletonList(Collections.singletonList(0L)), null, false);
resCur.fieldsMeta(UPDATE_RESULT_META);
return resCur;
} catch (SchemaOperationException e) {
U.error(null, "DDL operation failure", e);
throw convert(e);
} catch (IgniteSQLException e) {
throw e;
} catch (Exception e) {
throw new IgniteSQLException(e.getMessage(), e);
}
}
use of org.apache.ignite.internal.processors.cache.QueryCursorImpl in project ignite by apache.
the class H2Utils method zeroCursor.
/**
* @return Single-column, single-row cursor with 0 as number of updated records.
*/
@SuppressWarnings("unchecked")
public static QueryCursorImpl<List<?>> zeroCursor() {
QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>) new QueryCursorImpl(Collections.singletonList(Collections.singletonList(0L)), null, false);
resCur.fieldsMeta(UPDATE_RESULT_META);
return resCur;
}
use of org.apache.ignite.internal.processors.cache.QueryCursorImpl in project ignite by apache.
the class MultipleStatementsSqlQuerySelfTest method testQuery.
/**
* Test query without caches.
*
* @throws Exception If failed.
*/
public void testQuery() throws Exception {
GridQueryProcessor qryProc = node.context().query();
SqlFieldsQuery qry = new SqlFieldsQuery("create table test(ID int primary key, NAME varchar(20)); " + "insert into test (ID, NAME) values (1, 'name_1');" + "insert into test (ID, NAME) values (2, 'name_2'), (3, 'name_3');" + "select * from test;").setSchema("PUBLIC");
List<FieldsQueryCursor<List<?>>> res = qryProc.querySqlFields(qry, true, false);
assert res.size() == 4 : "Unexpected cursors count: " + res.size();
assert !((QueryCursorImpl) res.get(0)).isQuery() : "Results of DDL statement is expected ";
List<List<?>> rows = res.get(1).getAll();
assert !((QueryCursorImpl) res.get(1)).isQuery() : "Results of DDL statement is expected ";
assert Long.valueOf(1).equals(rows.get(0).get(0)) : "1 row must be updated. [actual=" + rows.get(0).get(0) + ']';
rows = res.get(2).getAll();
assert !((QueryCursorImpl) res.get(2)).isQuery() : "Results of DML statement is expected ";
assert Long.valueOf(2).equals(rows.get(0).get(0)) : "2 row must be updated";
rows = res.get(3).getAll();
assert ((QueryCursorImpl) res.get(3)).isQuery() : "Results of SELECT statement is expected ";
assert rows.size() == 3 : "Invalid rows count: " + rows.size();
for (int i = 0; i < rows.size(); ++i) {
assert Integer.valueOf(1).equals(rows.get(i).get(0)) || Integer.valueOf(2).equals(rows.get(i).get(0)) || Integer.valueOf(3).equals(rows.get(i).get(0)) : "Invalid ID: " + rows.get(i).get(0);
}
}
use of org.apache.ignite.internal.processors.cache.QueryCursorImpl in project ignite by apache.
the class MultipleStatementsSqlQuerySelfTest method testQueryWithParameters.
/**
* Test query without caches.
*
* @throws Exception If failed.
*/
public void testQueryWithParameters() throws Exception {
GridQueryProcessor qryProc = node.context().query();
SqlFieldsQuery qry = new SqlFieldsQuery("create table test(ID int primary key, NAME varchar(20)); " + "insert into test (ID, NAME) values (?, ?);" + "insert into test (ID, NAME) values (?, ?), (?, ?);" + "select * from test;").setSchema("PUBLIC").setArgs(1, "name_1", 2, "name2", 3, "name_3");
List<FieldsQueryCursor<List<?>>> res = qryProc.querySqlFields(qry, true, false);
assert res.size() == 4 : "Unexpected cursors count: " + res.size();
assert !((QueryCursorImpl) res.get(0)).isQuery() : "Results of DDL statement is expected ";
List<List<?>> rows = res.get(1).getAll();
assert !((QueryCursorImpl) res.get(1)).isQuery() : "Results of DDL statement is expected ";
assert Long.valueOf(1).equals(rows.get(0).get(0)) : "1 row must be updated. [actual=" + rows.get(0).get(0) + ']';
rows = res.get(2).getAll();
assert !((QueryCursorImpl) res.get(2)).isQuery() : "Results of DML statement is expected ";
assert Long.valueOf(2).equals(rows.get(0).get(0)) : "2 row must be updated";
rows = res.get(3).getAll();
assert ((QueryCursorImpl) res.get(3)).isQuery() : "Results of SELECT statement is expected ";
assert rows.size() == 3 : "Invalid rows count: " + rows.size();
for (int i = 0; i < rows.size(); ++i) {
assert Integer.valueOf(1).equals(rows.get(i).get(0)) || Integer.valueOf(2).equals(rows.get(i).get(0)) || Integer.valueOf(3).equals(rows.get(i).get(0)) : "Invalid ID: " + rows.get(i).get(0);
}
}
Aggregations