use of org.h2.expression.Operation in project ignite by apache.
the class DdlStatementsProcessor method runDdlStatement.
/**
* Execute DDL statement.
*
* @param sql SQL.
* @param stmt H2 statement to parse and execute.
*/
@SuppressWarnings("unchecked")
public FieldsQueryCursor<List<?>> runDdlStatement(String sql, PreparedStatement stmt) throws IgniteCheckedException {
assert stmt instanceof JdbcPreparedStatement;
IgniteInternalFuture fut = null;
try {
GridSqlStatement stmt0 = new GridSqlQueryParser(false).parse(GridSqlQueryParser.prepared(stmt));
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;
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());
} else if (stmt0 instanceof GridSqlDropIndex) {
GridSqlDropIndex cmd = (GridSqlDropIndex) stmt0;
GridH2Table tbl = idx.dataTableForIndex(cmd.schemaName(), cmd.indexName());
if (tbl != null) {
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 {
ctx.query().dynamicTableCreate(cmd.schemaName(), toQueryEntity(cmd), cmd.templateName(), cmd.atomicityMode(), 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) {
if (!cmd.ifExists())
throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
} else
ctx.query().dynamicTableDrop(tbl.cacheName(), cmd.tableName(), 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) {
throw convert(e);
} catch (IgniteSQLException e) {
throw e;
} catch (Exception e) {
throw new IgniteSQLException("Unexpected DLL operation failure: " + e.getMessage(), e);
}
}
use of org.h2.expression.Operation in project ignite by apache.
the class GridH2Table method doUpdate.
/**
* For testing only.
*
* @param row Row.
* @param del If given row should be deleted from table.
* @return {@code True} if operation succeeded.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("LockAcquiredButNotSafelyReleased")
boolean doUpdate(final GridH2Row row, boolean del) throws IgniteCheckedException {
// Here we assume that each key can't be updated concurrently and case when different indexes
// getting updated from different threads with different rows with the same key is impossible.
GridUnsafeMemory mem = desc == null ? null : desc.memory();
lock(false);
if (mem != null)
desc.guard().begin();
try {
ensureNotDestroyed();
GridH2IndexBase pk = pk();
if (!del) {
assert rowFactory == null || row.link != 0 : row;
// Put to PK.
GridH2Row old = pk.put(row);
if (old == null)
size.increment();
int len = idxs.size();
int i = pkIndexPos;
// Start from 3 because 0 - Scan (don't need to update), 1 - PK hash (already updated), 2 - PK (already updated).
while (++i < len) {
if (!(idxs.get(i) instanceof GridH2IndexBase))
continue;
GridH2IndexBase idx = index(i);
addToIndex(idx, pk, row, old, false);
}
for (GridH2IndexBase idx : tmpIdxs.values()) addToIndex(idx, pk, row, old, true);
} else {
// index(1) is PK, get full row from there (search row here contains only key but no other columns).
GridH2Row old = pk.remove(row);
if (old != null) {
// Start from 3 because 0 - Scan (don't need to update), 1 - PK hash (already updated), 2 - PK (already updated).
for (int i = pkIndexPos + 1, len = idxs.size(); i < len; i++) {
if (!(idxs.get(i) instanceof GridH2IndexBase))
continue;
Row res = index(i).remove(old);
assert eq(pk, res, old) : "\n" + old + "\n" + res + "\n" + i + " -> " + index(i).getName();
}
for (GridH2IndexBase idx : tmpIdxs.values()) idx.remove(old);
size.decrement();
} else
return false;
}
// The snapshot is not actual after update.
if (actualSnapshot != null)
actualSnapshot.set(pk.segmentForRow(row), null);
return true;
} finally {
unlock(false);
if (mem != null)
desc.guard().end();
}
}
use of org.h2.expression.Operation in project ignite by apache.
the class GridSqlQuerySplitter method extractPartitionFromEquality.
/**
* Analyses the equality operation and extracts the partition if possible
*
* @param op AST equality operation.
* @param ctx Kernal Context.
* @return partition info, or {@code null} if none identified
*/
private static CacheQueryPartitionInfo extractPartitionFromEquality(GridSqlOperation op, GridKernalContext ctx) throws IgniteCheckedException {
assert op.operationType() == GridSqlOperationType.EQUAL;
GridSqlElement left = op.child(0);
GridSqlElement right = op.child(1);
if (!(left instanceof GridSqlColumn))
return null;
if (!(right instanceof GridSqlConst) && !(right instanceof GridSqlParameter))
return null;
GridSqlColumn column = (GridSqlColumn) left;
assert column.column().getTable() instanceof GridH2Table;
GridH2Table tbl = (GridH2Table) column.column().getTable();
GridH2RowDescriptor desc = tbl.rowDescriptor();
IndexColumn affKeyCol = tbl.getAffinityKeyColumn();
int colId = column.column().getColumnId();
if ((affKeyCol == null || colId != affKeyCol.column.getColumnId()) && !desc.isKeyColumn(colId))
return null;
if (right instanceof GridSqlConst) {
GridSqlConst constant = (GridSqlConst) right;
return new CacheQueryPartitionInfo(ctx.affinity().partition(tbl.cacheName(), constant.value().getObject()), null, null, -1, -1);
}
GridSqlParameter param = (GridSqlParameter) right;
return new CacheQueryPartitionInfo(-1, tbl.cacheName(), tbl.getName(), column.column().getType(), param.index());
}
use of org.h2.expression.Operation in project ignite by apache.
the class IgniteH2Indexing method doRunPrepared.
/**
* Execute an all-ready {@link SqlFieldsQuery}.
* @param schemaName Schema name.
* @param prepared H2 command.
* @param qry Fields query with flags.
* @param twoStepQry Two-step query if this query must be executed in a distributed way.
* @param meta Metadata for {@code twoStepQry}.
* @param keepBinary Whether binary objects must not be deserialized automatically.
* @param cancel Query cancel state holder. @return Query result.
*/
private List<? extends FieldsQueryCursor<List<?>>> doRunPrepared(String schemaName, Prepared prepared, SqlFieldsQuery qry, GridCacheTwoStepQuery twoStepQry, List<GridQueryFieldMetadata> meta, boolean keepBinary, GridQueryCancel cancel) {
String sqlQry = qry.getSql();
boolean loc = qry.isLocal();
IndexingQueryFilter filter = (loc ? backupFilter(null, qry.getPartitions()) : null);
if (!prepared.isQuery()) {
if (DmlStatementsProcessor.isDmlStatement(prepared)) {
try {
Connection conn = connectionForSchema(schemaName);
if (!loc)
return dmlProc.updateSqlFieldsDistributed(schemaName, conn, prepared, qry, cancel);
else {
final GridQueryFieldsResult updRes = dmlProc.updateSqlFieldsLocal(schemaName, conn, prepared, qry, filter, cancel);
return Collections.singletonList(new QueryCursorImpl<>(new Iterable<List<?>>() {
@Override
public Iterator<List<?>> iterator() {
try {
return new GridQueryCacheObjectsIterator(updRes.iterator(), objectContext(), true);
} catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
}, cancel));
}
} catch (IgniteCheckedException e) {
throw new IgniteSQLException("Failed to execute DML statement [stmt=" + sqlQry + ", params=" + Arrays.deepToString(qry.getArgs()) + "]", e);
}
}
if (DdlStatementsProcessor.isDdlStatement(prepared)) {
if (loc)
throw new IgniteSQLException("DDL statements are not supported for LOCAL caches", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
try {
return Collections.singletonList(ddlProc.runDdlStatement(sqlQry, prepared));
} catch (IgniteCheckedException e) {
throw new IgniteSQLException("Failed to execute DDL statement [stmt=" + sqlQry + ']', e);
}
}
if (prepared instanceof NoOperation) {
QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>) new QueryCursorImpl(Collections.singletonList(Collections.singletonList(0L)), null, false);
resCur.fieldsMeta(UPDATE_RESULT_META);
return Collections.singletonList(resCur);
}
throw new IgniteSQLException("Unsupported DDL/DML operation: " + prepared.getClass().getName());
}
if (twoStepQry != null) {
if (log.isDebugEnabled())
log.debug("Parsed query: `" + sqlQry + "` into two step query: " + twoStepQry);
checkQueryType(qry, true);
return Collections.singletonList(doRunDistributedQuery(schemaName, qry, twoStepQry, meta, keepBinary, cancel));
}
// We've encountered a local query, let's just run it.
try {
return Collections.singletonList(queryLocalSqlFields(schemaName, qry, keepBinary, filter, cancel));
} catch (IgniteCheckedException e) {
throw new IgniteSQLException("Failed to execute local statement [stmt=" + sqlQry + ", params=" + Arrays.deepToString(qry.getArgs()) + "]", e);
}
}
use of org.h2.expression.Operation in project h2database by h2database.
the class Parser method readConcat.
private Expression readConcat() {
Expression r = readSum();
while (true) {
if (readIf("||")) {
r = new Operation(OpType.CONCAT, r, readSum());
} else if (readIf("~")) {
if (readIf("*")) {
Function function = Function.getFunction(database, "CAST");
function.setDataType(new Column("X", Value.STRING_IGNORECASE));
function.setParameter(0, r);
r = function;
}
r = new CompareLike(database, r, readSum(), null, true);
} else if (readIf("!~")) {
if (readIf("*")) {
Function function = Function.getFunction(database, "CAST");
function.setDataType(new Column("X", Value.STRING_IGNORECASE));
function.setParameter(0, r);
r = function;
}
r = new ConditionNot(new CompareLike(database, r, readSum(), null, true));
} else {
return r;
}
}
}
Aggregations