Search in sources :

Example 46 with User

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);
    }
}
Also used : BinaryArray(org.apache.ignite.internal.binary.BinaryArray) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Time(java.sql.Time) ValueTime(org.h2.value.ValueTime) Timestamp(java.sql.Timestamp) ValueTimestamp(org.h2.value.ValueTimestamp) Date(java.util.Date) ValueDate(org.h2.value.ValueDate) BatchUpdateException(java.sql.BatchUpdateException) IgniteQueryErrorCode.createJdbcSqlException(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode.createJdbcSqlException) SQLException(java.sql.SQLException) TransactionDuplicateKeyException(org.apache.ignite.transactions.TransactionDuplicateKeyException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 47 with User

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;
}
Also used : GridSqlAlias(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) Column(org.h2.table.Column) GridSqlTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridSqlElement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement) ValueString(org.h2.value.ValueString) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect) HashSet(java.util.HashSet)

Example 48 with User

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);
    }
}
Also used : SchemaObject(org.h2.schema.SchemaObject) Index(org.h2.index.Index) H2TreeIndex(org.apache.ignite.internal.processors.query.h2.database.H2TreeIndex) SpatialIndex(org.h2.index.SpatialIndex)

Example 49 with User

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());
}
Also used : GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) IndexColumn(org.h2.table.IndexColumn) ArrayList(java.util.ArrayList) IndexColumn(org.h2.table.IndexColumn)

Example 50 with User

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();
}
Also used : Driver(org.h2.Driver)

Aggregations

Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)21 PreparedStatement (java.sql.PreparedStatement)17 Statement (java.sql.Statement)17 ResultSet (java.sql.ResultSet)16 Server (org.h2.tools.Server)15 DbException (org.h2.message.DbException)14 Column (org.h2.table.Column)12 ValueString (org.h2.value.ValueString)12 Properties (java.util.Properties)10 Database (org.h2.engine.Database)10 Schema (org.h2.schema.Schema)8 IOException (java.io.IOException)7 User (org.h2.engine.User)7 JdbcDataSource (org.h2.jdbcx.JdbcDataSource)7 SimpleResultSet (org.h2.tools.SimpleResultSet)7 Value (org.h2.value.Value)7 PrintStream (java.io.PrintStream)6 Timestamp (java.sql.Timestamp)6 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)6