use of org.h2.engine.User in project ignite by apache.
the class DmlUtils method convert.
/**
* Convert value to column's expected type by means of H2.
*
* @param val Source value.
* @param desc Row descriptor.
* @param expCls Expected value class.
* @param type Expected column type to convert to.
* @return Converted object.
*/
@SuppressWarnings({ "ConstantConditions", "SuspiciousSystemArraycopy" })
public static Object convert(Object val, GridH2RowDescriptor desc, Class<?> expCls, int type, String columnName) {
if (val == null)
return null;
Class<?> currCls = val.getClass();
try {
// precise Date instance. Let's satisfy it.
if (val instanceof Date && currCls != Date.class && expCls == Date.class)
return new Date(((Date) val).getTime());
// User-given UUID is always serialized by H2 to byte array, so we have to deserialize manually
if (type == Value.UUID && currCls == byte[].class) {
return U.unmarshal(desc.context().marshaller(), (byte[]) val, U.resolveClassLoader(desc.context().gridConfig()));
}
if (val instanceof Timestamp && LocalDateTimeUtils.LOCAL_DATE_TIME == expCls)
return LocalDateTimeUtils.valueToLocalDateTime(ValueTimestamp.get((Timestamp) val));
if (val instanceof Date && LocalDateTimeUtils.LOCAL_DATE == expCls) {
return LocalDateTimeUtils.valueToLocalDate(ValueDate.fromDateValue(DateTimeUtils.dateValueFromDate(((Date) val).getTime())));
}
if (val instanceof Time && LocalDateTimeUtils.LOCAL_TIME == expCls)
return LocalDateTimeUtils.valueToLocalTime(ValueTime.get((Time) val));
// Still, we only can convert from Object[] to something more precise.
if (type == Value.ARRAY && val instanceof BinaryArray)
return val;
if (type == Value.ARRAY && currCls != expCls) {
if (currCls != Object[].class) {
throw new IgniteCheckedException("Unexpected array type - only conversion from Object[] " + "is assumed");
}
// Why would otherwise type be Value.ARRAY?
assert expCls.isArray();
Object[] curr = (Object[]) val;
Object newArr = Array.newInstance(expCls.getComponentType(), curr.length);
System.arraycopy(curr, 0, newArr, 0, curr.length);
return newArr;
}
Object res = H2Utils.convert(val, desc.indexing(), type);
// without query - let's handle this
if (res instanceof Date && res.getClass() != Date.class && expCls == Date.class)
return new Date(((Date) res).getTime());
return res;
} catch (Exception e) {
throw new IgniteSQLException("Value conversion failed [column=" + columnName + ", from=" + currCls.getName() + ", to=" + expCls.getName() + ']', IgniteQueryErrorCode.CONVERSION_FAILED, e);
}
}
use of org.h2.engine.User in project ignite by apache.
the class DmlAstUtils method selectForUpdate.
/**
* Generate SQL SELECT based on UPDATE's WHERE, LIMIT, etc.
*
* @param update Update statement.
* @return SELECT statement.
*/
public static GridSqlSelect selectForUpdate(GridSqlUpdate update) {
GridSqlSelect mapQry = new GridSqlSelect();
mapQry.from(update.target());
Set<GridSqlTable> tbls = new HashSet<>();
collectAllGridTablesInTarget(update.target(), tbls);
assert tbls.size() == 1 : "Failed to determine target table for UPDATE";
GridSqlTable tbl = tbls.iterator().next();
GridH2Table gridTbl = tbl.dataTable();
assert gridTbl != null : "Failed to determine target grid table for UPDATE";
Column h2KeyCol = gridTbl.getColumn(QueryUtils.KEY_COL);
Column h2ValCol = gridTbl.getColumn(QueryUtils.VAL_COL);
GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
valCol.resultType(GridSqlType.fromColumn(h2ValCol));
mapQry.addColumn(keyCol, true);
mapQry.addColumn(valCol, true);
for (GridSqlColumn c : update.cols()) {
String newColName = Parser.quoteIdentifier("_upd_" + c.columnName());
// We have to use aliases to cover cases when the user
// wants to update _val field directly (if it's a literal)
GridSqlAlias alias = new GridSqlAlias(newColName, elementOrDefault(update.set().get(c.columnName()), c), true);
alias.resultType(c.resultType());
mapQry.addColumn(alias, true);
}
GridSqlElement where = update.where();
// On no MVCC mode we cannot use lazy mode when UPDATE query contains index with updated columns
// and that index may be chosen to scan by WHERE condition
// because in this case any rows update may be updated several times.
// e.g. in the cases below we cannot use lazy mode:
//
// 1. CREATE INDEX idx on test(val)
// UPDATE test SET val = val + 1 WHERE val >= ?
//
// 2. CREATE INDEX idx on test(val0, val1)
// UPDATE test SET val1 = val1 + 1 WHERE val0 >= ?
mapQry.canBeLazy(!isIndexWithUpdateColumnsMayBeUsed(gridTbl, update.cols().stream().map(GridSqlColumn::column).collect(Collectors.toSet()), extractColumns(gridTbl, where)));
mapQry.where(where);
mapQry.limit(update.limit());
return mapQry;
}
use of org.h2.engine.User in project ignite by apache.
the class GridH2Table method removeChildrenAndResources.
/**
* {@inheritDoc}
*/
@Override
public void removeChildrenAndResources(Session ses) {
lock(true);
try {
super.removeChildrenAndResources(ses);
// Clear all user indexes registered in schema.
while (idxs.size() > sysIdxsCnt) {
Index idx = idxs.get(sysIdxsCnt);
if (idx.getName() != null && idx.getSchema().findIndex(ses, idx.getName()) == idx) {
// This call implicitly removes both idx and its proxy, if any, from idxs.
database.removeSchemaObject(ses, idx);
// We have to call destroy here if we are who has removed this index from the table.
destroyIndex(idx);
}
}
if (SysProperties.CHECK) {
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.INDEX)) {
Index idx = (Index) obj;
if (idx.getTable() == this)
DbException.throwInternalError("index not dropped: " + idx.getName());
}
}
database.removeMeta(ses, getId());
invalidate();
} finally {
unlock(true);
}
}
use of org.h2.engine.User in project ignite by apache.
the class H2TableDescriptor method createUserIndex.
/**
* Create user index.
*
* @param idxDesc Index descriptor.
* @param cacheVisitor Cache visitor.
* @return Index.
*/
public GridH2IndexBase createUserIndex(GridQueryIndexDescriptor idxDesc, @Nullable SchemaIndexCacheVisitor cacheVisitor) {
IndexColumn keyCol = tbl.indexColumn(QueryUtils.KEY_COL, SortOrder.ASCENDING);
IndexColumn affCol = tbl.getAffinityKeyColumn();
List<IndexColumn> cols = new ArrayList<>(idxDesc.fields().size() + 2);
for (String field : idxDesc.fields()) {
Column col = tbl.getColumn(field);
cols.add(tbl.indexColumn(col.getColumnId(), idxDesc.descending(field) ? SortOrder.DESCENDING : SortOrder.ASCENDING));
}
GridH2RowDescriptor desc = tbl.rowDescriptor();
if (idxDesc.type() == QueryIndexType.SORTED) {
List<IndexColumn> unwrappedKeyCols = extractKeyColumns(tbl, keyCol, affCol);
List<IndexColumn> colsWithUnwrappedKey = new ArrayList<>(cols);
H2Utils.addUniqueColumns(colsWithUnwrappedKey, unwrappedKeyCols);
cols = H2Utils.treeIndexColumns(desc, cols, keyCol, affCol);
return idx.createSortedIndex(idxDesc.name(), tbl, false, false, colsWithUnwrappedKey, cols, idxDesc.inlineSize(), cacheVisitor);
} else if (idxDesc.type() == QueryIndexType.GEOSPATIAL)
return H2Utils.createSpatialIndex(tbl, idxDesc.name(), cols);
throw new IllegalStateException("Index type: " + idxDesc.type());
}
use of org.h2.engine.User in project sonarqube by SonarSource.
the class EmbeddedDatabase method createDatabase.
private static void createDatabase(File dbHome, String user, String password) throws SQLException {
String url = format("jdbc:h2:%s/sonar;USER=%s;PASSWORD=%s%s", dbHome.getAbsolutePath(), user, password, IGNORED_KEYWORDS_OPTION);
DriverManager.registerDriver(new Driver());
DriverManager.getConnection(url).close();
}
Aggregations