use of org.h2.constraint.Constraint.Type in project ignite by apache.
the class H2RowDescriptor method wrap.
/** {@inheritDoc} */
@SuppressWarnings("ConstantConditions")
@Override
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:
return ValueDate.get((Date) obj);
case Value.TIME:
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());
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 + "]");
}
use of org.h2.constraint.Constraint.Type in project ignite by apache.
the class IgniteH2Indexing method queryDistributedSqlFields.
/** {@inheritDoc} */
@Override
public FieldsQueryCursor<List<?>> queryDistributedSqlFields(String schemaName, SqlFieldsQuery qry, boolean keepBinary, GridQueryCancel cancel, @Nullable Integer mainCacheId) {
final String sqlQry = qry.getSql();
Connection c = connectionForSchema(schemaName);
final boolean enforceJoinOrder = qry.isEnforceJoinOrder();
final boolean distributedJoins = qry.isDistributedJoins();
final boolean grpByCollocated = qry.isCollocated();
final DistributedJoinMode distributedJoinMode = distributedJoinMode(qry.isLocal(), distributedJoins);
GridCacheTwoStepQuery twoStepQry = null;
List<GridQueryFieldMetadata> meta;
final H2TwoStepCachedQueryKey cachedQryKey = new H2TwoStepCachedQueryKey(schemaName, sqlQry, grpByCollocated, distributedJoins, enforceJoinOrder, qry.isLocal());
H2TwoStepCachedQuery cachedQry = twoStepCache.get(cachedQryKey);
if (cachedQry != null) {
twoStepQry = cachedQry.query().copy();
meta = cachedQry.meta();
} else {
final UUID locNodeId = ctx.localNodeId();
// Here we will just parse the statement, no need to optimize it at all.
H2Utils.setupConnection(c, /*distributedJoins*/
false, /*enforceJoinOrder*/
true);
GridH2QueryContext.set(new GridH2QueryContext(locNodeId, locNodeId, 0, PREPARE).distributedJoinMode(distributedJoinMode));
PreparedStatement stmt = null;
Prepared prepared;
boolean cachesCreated = false;
try {
try {
while (true) {
try {
// Do not cache this statement because the whole query object will be cached later on.
stmt = prepareStatement(c, sqlQry, false);
break;
} catch (SQLException e) {
if (!cachesCreated && (e.getErrorCode() == ErrorCode.SCHEMA_NOT_FOUND_1 || e.getErrorCode() == ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1 || e.getErrorCode() == ErrorCode.INDEX_NOT_FOUND_1)) {
try {
ctx.cache().createMissingQueryCaches();
} catch (IgniteCheckedException ignored) {
throw new CacheException("Failed to create missing caches.", e);
}
cachesCreated = true;
} else
throw new IgniteSQLException("Failed to parse query: " + sqlQry, IgniteQueryErrorCode.PARSING, e);
}
}
prepared = GridSqlQueryParser.prepared(stmt);
if (qry instanceof JdbcSqlFieldsQuery && ((JdbcSqlFieldsQuery) qry).isQuery() != prepared.isQuery())
throw new IgniteSQLException("Given statement type does not match that declared by JDBC driver", IgniteQueryErrorCode.STMT_TYPE_MISMATCH);
if (prepared.isQuery()) {
bindParameters(stmt, F.asList(qry.getArgs()));
twoStepQry = GridSqlQuerySplitter.split((JdbcPreparedStatement) stmt, qry.getArgs(), grpByCollocated, distributedJoins, enforceJoinOrder, this);
assert twoStepQry != null;
}
} finally {
GridH2QueryContext.clearThreadLocal();
}
// It is a DML statement if we did not create a twoStepQuery.
if (twoStepQry == null) {
if (DmlStatementsProcessor.isDmlStatement(prepared)) {
try {
return dmlProc.updateSqlFieldsDistributed(schemaName, stmt, qry, cancel);
} catch (IgniteCheckedException e) {
throw new IgniteSQLException("Failed to execute DML statement [stmt=" + sqlQry + ", params=" + Arrays.deepToString(qry.getArgs()) + "]", e);
}
}
if (DdlStatementsProcessor.isDdlStatement(prepared)) {
try {
return ddlProc.runDdlStatement(sqlQry, stmt);
} catch (IgniteCheckedException e) {
throw new IgniteSQLException("Failed to execute DDL statement [stmt=" + sqlQry + ']', e);
}
}
}
LinkedHashSet<Integer> caches0 = new LinkedHashSet<>();
assert twoStepQry != null;
int tblCnt = twoStepQry.tablesCount();
if (mainCacheId != null)
caches0.add(mainCacheId);
if (tblCnt > 0) {
for (QueryTable tblKey : twoStepQry.tables()) {
GridH2Table tbl = dataTable(tblKey);
int cacheId = CU.cacheId(tbl.cacheName());
caches0.add(cacheId);
}
}
if (caches0.isEmpty())
twoStepQry.local(true);
else {
//Prohibit usage indices with different numbers of segments in same query.
List<Integer> cacheIds = new ArrayList<>(caches0);
checkCacheIndexSegmentation(cacheIds);
twoStepQry.cacheIds(cacheIds);
twoStepQry.local(qry.isLocal());
}
meta = H2Utils.meta(stmt.getMetaData());
} catch (IgniteCheckedException e) {
throw new CacheException("Failed to bind parameters: [qry=" + sqlQry + ", params=" + Arrays.deepToString(qry.getArgs()) + "]", e);
} catch (SQLException e) {
throw new IgniteSQLException(e);
} finally {
U.close(stmt, log);
}
}
if (log.isDebugEnabled())
log.debug("Parsed query: `" + sqlQry + "` into two step query: " + twoStepQry);
twoStepQry.pageSize(qry.getPageSize());
if (cancel == null)
cancel = new GridQueryCancel();
int[] partitions = qry.getPartitions();
if (partitions == null && twoStepQry.derivedPartitions() != null) {
try {
partitions = calculateQueryPartitions(twoStepQry.derivedPartitions(), qry.getArgs());
} catch (IgniteCheckedException e) {
throw new CacheException("Failed to calculate derived partitions: [qry=" + sqlQry + ", params=" + Arrays.deepToString(qry.getArgs()) + "]", e);
}
}
QueryCursorImpl<List<?>> cursor = new QueryCursorImpl<>(runQueryTwoStep(schemaName, twoStepQry, keepBinary, enforceJoinOrder, qry.getTimeout(), cancel, qry.getArgs(), partitions), cancel);
cursor.fieldsMeta(meta);
if (cachedQry == null && !twoStepQry.explain()) {
cachedQry = new H2TwoStepCachedQuery(meta, twoStepQry.copy());
twoStepCache.putIfAbsent(cachedQryKey, cachedQry);
}
return cursor;
}
use of org.h2.constraint.Constraint.Type 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.constraint.Constraint.Type in project ignite by apache.
the class InlineIndexHelper method compareAsString.
/**
* @param pageAddr Page address.
* @param off Offset.
* @param v Value to compare.
* @param ignoreCase {@code True} if a case-insensitive comparison should be used.
* @return Compare result ({@code -2} means we can't compare).
*/
private int compareAsString(long pageAddr, int off, Value v, boolean ignoreCase) {
String s = v.getString();
int len1 = PageUtils.getShort(pageAddr, off + 1) & 0x7FFF;
int len2 = s.length();
int c, c2, c3, c4, cntr1 = 0, cntr2 = 0;
char v1, v2;
// Skip length and type byte.
long addr = pageAddr + off + 3;
// Try reading ASCII.
while (cntr1 < len1 && cntr2 < len2) {
c = (int) GridUnsafe.getByte(addr) & 0xFF;
if (c > 127)
break;
cntr1++;
addr++;
v1 = (char) c;
v2 = s.charAt(cntr2++);
if (ignoreCase) {
v1 = Character.toUpperCase(v1);
v2 = Character.toUpperCase(v2);
}
if (v1 != v2)
return fixSort(Integer.signum(v1 - v2), sortType());
}
// read other
while (cntr1 < len1 && cntr2 < len2) {
c = (int) GridUnsafe.getByte(addr++) & 0xFF;
switch(c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
/* 0xxxxxxx*/
cntr1++;
v1 = (char) c;
break;
case 12:
case 13:
/* 110x xxxx 10xx xxxx*/
cntr1 += 2;
if (cntr1 > len1)
throw new IllegalStateException("Malformed input (partial character at the end).");
c2 = (int) GridUnsafe.getByte(addr++) & 0xFF;
if ((c2 & 0xC0) != 0x80)
throw new IllegalStateException("Malformed input around byte: " + (cntr1 - 2));
c = c & 0x1F;
c = (c << 6) | (c2 & 0x3F);
v1 = (char) c;
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
cntr1 += 3;
if (cntr1 > len1)
throw new IllegalStateException("Malformed input (partial character at the end).");
c2 = (int) GridUnsafe.getByte(addr++) & 0xFF;
c3 = (int) GridUnsafe.getByte(addr++) & 0xFF;
if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80))
throw new IllegalStateException("Malformed input around byte: " + (cntr1 - 3));
c = c & 0x0F;
c = (c << 6) | (c2 & 0x3F);
c = (c << 6) | (c3 & 0x3F);
v1 = (char) c;
break;
case 15:
/* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
cntr1 += 4;
if (cntr1 > len1)
throw new IllegalStateException("Malformed input (partial character at the end).");
c2 = (int) GridUnsafe.getByte(addr++) & 0xFF;
c3 = (int) GridUnsafe.getByte(addr++) & 0xFF;
c4 = (int) GridUnsafe.getByte(addr++) & 0xFF;
if (((c & 0xF8) != 0xf0) || ((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80) || ((c4 & 0xC0) != 0x80))
throw new IllegalStateException("Malformed input around byte: " + (cntr1 - 4));
c = c & 0x07;
c = (c << 6) | (c2 & 0x3F);
c = (c << 6) | (c3 & 0x3F);
c = (c << 6) | (c4 & 0x3F);
// Subtract 0x010000, c is now 0..fffff (20 bits)
c = c - 0x010000;
// height surrogate
v1 = (char) (0xD800 + ((c >> 10) & 0x7FF));
v2 = s.charAt(cntr2++);
if (v1 != v2)
return fixSort(Integer.signum(v1 - v2), sortType());
if (cntr2 == len2)
// Finish comparison here.
return fixSort(1, sortType());
// Low surrogate.
v1 = (char) (0xDC00 + (c & 0x3FF));
v2 = s.charAt(cntr2++);
if (v1 != v2)
return fixSort(Integer.signum(v1 - v2), sortType());
continue;
default:
/* 10xx xxxx */
throw new IllegalStateException("Malformed input around byte: " + cntr1);
}
v2 = s.charAt(cntr2++);
if (ignoreCase) {
v1 = Character.toUpperCase(v1);
v2 = Character.toUpperCase(v2);
}
if (v1 != v2)
return fixSort(Integer.signum(v1 - v2), sortType());
}
int res = cntr1 == len1 && cntr2 == len2 ? 0 : cntr1 == len1 ? -1 : 1;
if (isValueFull(pageAddr, off))
return fixSort(res, sortType());
if (res >= 0)
// b) Even truncated current value is longer, so that it's bigger.
return fixSort(1, sortType());
return -2;
}
use of org.h2.constraint.Constraint.Type in project ignite by apache.
the class GridH2CollocationModel method childFilters.
/**
* @param childFilters New child filters.
* @return {@code true} If child filters were updated.
*/
private boolean childFilters(TableFilter[] childFilters) {
assert childFilters != null;
assert view;
Select select = childFilters[0].getSelect();
assert this.select == null || this.select == select;
if (this.select == null) {
this.select = select;
assert this.childFilters == null;
} else if (Arrays.equals(this.childFilters, childFilters))
return false;
if (this.childFilters == null) {
// We have to clone because H2 reuses array and reorders elements.
this.childFilters = childFilters.clone();
children = new GridH2CollocationModel[childFilters.length];
} else {
assert this.childFilters.length == childFilters.length;
// We have to copy because H2 reuses array and reorders elements.
System.arraycopy(childFilters, 0, this.childFilters, 0, childFilters.length);
Arrays.fill(children, null);
}
// Reset results.
type = null;
multiplier = 0;
return true;
}
Aggregations