Search in sources :

Example 56 with Delete

use of org.h2.command.dml.Delete in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method dropIndex.

/**
 * Drop the fulltext index for a table
 *
 * @param   conn                SQL connection
 * @param   schema              Schema name
 * @param   table               Table name
 * @throws  SQLException        Unable to drop fulltext index
 */
public static void dropIndex(Connection conn, String schema, String table) throws SQLException {
    String upperSchema = schema.toUpperCase();
    String upperTable = table.toUpperCase();
    boolean reindex = false;
    // 
    try (Statement qstmt = conn.createStatement();
        Statement stmt = conn.createStatement()) {
        try (ResultSet rs = qstmt.executeQuery(String.format("SELECT COLUMNS FROM FTL.INDEXES WHERE SCHEMA = '%s' AND TABLE = '%s'", upperSchema, upperTable))) {
            if (rs.next()) {
                stmt.execute("DROP TRIGGER IF EXISTS FTL_" + upperTable);
                stmt.execute(String.format("DELETE FROM FTL.INDEXES WHERE SCHEMA = '%s' AND TABLE = '%s'", upperSchema, upperTable));
                reindex = true;
            }
        }
    }
    // 
    if (reindex) {
        reindex(conn);
    }
}
Also used : Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 57 with Delete

use of org.h2.command.dml.Delete in project ignite by apache.

the class UpdatePlanBuilder method planForUpdate.

/**
 * Prepare update plan for UPDATE or DELETE.
 *
 * @param stmt UPDATE or DELETE statement.
 * @param loc Local query flag.
 * @param idx Indexing.
 * @param conn Connection.
 * @param fieldsQuery Original query.
 * @param errKeysPos index to inject param for re-run keys at. Null if it's not a re-run plan.
 * @return Update plan.
 * @throws IgniteCheckedException if failed.
 */
private static UpdatePlan planForUpdate(GridSqlStatement stmt, boolean loc, IgniteH2Indexing idx, @Nullable Connection conn, @Nullable SqlFieldsQuery fieldsQuery, @Nullable Integer errKeysPos) throws IgniteCheckedException {
    GridSqlElement target;
    FastUpdate fastUpdate;
    UpdateMode mode;
    if (stmt instanceof GridSqlUpdate) {
        // Let's verify that user is not trying to mess with key's columns directly
        verifyUpdateColumns(stmt);
        GridSqlUpdate update = (GridSqlUpdate) stmt;
        target = update.target();
        fastUpdate = DmlAstUtils.getFastUpdateArgs(update);
        mode = UpdateMode.UPDATE;
    } else if (stmt instanceof GridSqlDelete) {
        GridSqlDelete del = (GridSqlDelete) stmt;
        target = del.from();
        fastUpdate = DmlAstUtils.getFastDeleteArgs(del);
        mode = UpdateMode.DELETE;
    } else
        throw new IgniteSQLException("Unexpected DML operation [cls=" + stmt.getClass().getName() + ']', IgniteQueryErrorCode.UNEXPECTED_OPERATION);
    GridSqlTable tbl = DmlAstUtils.gridTableForElement(target);
    GridH2Table h2Tbl = tbl.dataTable();
    GridH2RowDescriptor desc = h2Tbl.rowDescriptor();
    if (desc == null)
        throw new IgniteSQLException("Row descriptor undefined for table '" + h2Tbl.getName() + "'", IgniteQueryErrorCode.NULL_TABLE_DESCRIPTOR);
    if (fastUpdate != null) {
        return new UpdatePlan(mode, h2Tbl, null, fastUpdate, null);
    } else {
        GridSqlSelect sel;
        if (stmt instanceof GridSqlUpdate) {
            List<GridSqlColumn> updatedCols = ((GridSqlUpdate) stmt).cols();
            int valColIdx = -1;
            String[] colNames = new String[updatedCols.size()];
            int[] colTypes = new int[updatedCols.size()];
            for (int i = 0; i < updatedCols.size(); i++) {
                colNames[i] = updatedCols.get(i).columnName();
                colTypes[i] = updatedCols.get(i).resultType().type();
                Column col = updatedCols.get(i).column();
                if (desc.isValueColumn(col.getColumnId()))
                    valColIdx = i;
            }
            boolean hasNewVal = (valColIdx != -1);
            // Statement updates distinct properties if it does not have _val in updated columns list
            // or if its list of updated columns includes only _val, i.e. is single element.
            boolean hasProps = !hasNewVal || updatedCols.size() > 1;
            // Index of new _val in results of SELECT
            if (hasNewVal)
                valColIdx += 2;
            int newValColIdx = (hasNewVal ? valColIdx : 1);
            KeyValueSupplier valSupplier = createSupplier(desc.context(), desc.type(), newValColIdx, hasProps, false, true);
            sel = DmlAstUtils.selectForUpdate((GridSqlUpdate) stmt, errKeysPos);
            String selectSql = sel.getSQL();
            DmlDistributedPlanInfo distributed = F.isEmpty(selectSql) ? null : checkPlanCanBeDistributed(idx, conn, fieldsQuery, loc, selectSql, tbl.dataTable().cacheName());
            return new UpdatePlan(UpdateMode.UPDATE, h2Tbl, colNames, colTypes, null, valSupplier, -1, valColIdx, selectSql, false, null, 0, null, distributed);
        } else {
            sel = DmlAstUtils.selectForDelete((GridSqlDelete) stmt, errKeysPos);
            String selectSql = sel.getSQL();
            DmlDistributedPlanInfo distributed = F.isEmpty(selectSql) ? null : checkPlanCanBeDistributed(idx, conn, fieldsQuery, loc, selectSql, tbl.dataTable().cacheName());
            return new UpdatePlan(UpdateMode.DELETE, h2Tbl, selectSql, null, distributed);
        }
    }
}
Also used : GridSqlDelete(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDelete) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) 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) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridSqlElement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement) GridSqlUpdate(org.apache.ignite.internal.processors.query.h2.sql.GridSqlUpdate)

Example 58 with Delete

use of org.h2.command.dml.Delete in project ignite by apache.

the class GridSqlDelete method getSQL.

/**
 * {@inheritDoc}
 */
@Override
public String getSQL() {
    StatementBuilder buff = new StatementBuilder(explain() ? "EXPLAIN " : "");
    buff.append("DELETE").append("\nFROM ").append(from.getSQL());
    if (where != null)
        buff.append("\nWHERE ").append(StringUtils.unEnclose(where.getSQL()));
    if (limit != null)
        buff.append("\nLIMIT (").append(StringUtils.unEnclose(limit.getSQL())).append(')');
    return buff.toString();
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Example 59 with Delete

use of org.h2.command.dml.Delete in project h2database by h2database.

the class ConstraintReferential method buildDeleteSQL.

private void buildDeleteSQL() {
    if (deleteAction == ConstraintActionType.RESTRICT) {
        return;
    }
    StatementBuilder buff = new StatementBuilder();
    if (deleteAction == ConstraintActionType.CASCADE) {
        buff.append("DELETE FROM ").append(table.getSQL());
    } else {
        appendUpdate(buff);
    }
    appendWhere(buff);
    deleteSQL = buff.toString();
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Example 60 with Delete

use of org.h2.command.dml.Delete in project h2database by h2database.

the class Recover method writeSchema.

private void writeSchema(PrintWriter writer) {
    writer.println("---- Schema ----");
    Collections.sort(schema);
    for (MetaRecord m : schema) {
        if (!isSchemaObjectTypeDelayed(m)) {
            // create, but not referential integrity constraints and so on
            // because they could fail on duplicate keys
            String sql = m.getSQL();
            writer.println(sql + ";");
        }
    }
    // first, copy the lob storage (if there is any)
    // must occur before copying data,
    // otherwise the lob storage may be overwritten
    boolean deleteLobs = false;
    for (Map.Entry<Integer, String> entry : tableMap.entrySet()) {
        Integer objectId = entry.getKey();
        String name = entry.getValue();
        if (objectIdSet.contains(objectId)) {
            if (name.startsWith("INFORMATION_SCHEMA.LOB")) {
                setStorage(objectId);
                writer.println("DELETE FROM " + name + ";");
                writer.println("INSERT INTO " + name + " SELECT * FROM " + storageName + ";");
                if (name.startsWith("INFORMATION_SCHEMA.LOBS")) {
                    writer.println("UPDATE " + name + " SET TABLE = " + LobStorageFrontend.TABLE_TEMP + ";");
                    deleteLobs = true;
                }
            }
        }
    }
    for (Map.Entry<Integer, String> entry : tableMap.entrySet()) {
        Integer objectId = entry.getKey();
        String name = entry.getValue();
        if (objectIdSet.contains(objectId)) {
            setStorage(objectId);
            if (name.startsWith("INFORMATION_SCHEMA.LOB")) {
                continue;
            }
            writer.println("INSERT INTO " + name + " SELECT * FROM " + storageName + ";");
        }
    }
    for (Integer objectId : objectIdSet) {
        setStorage(objectId);
        writer.println("DROP TABLE " + storageName + ";");
    }
    writer.println("DROP ALIAS READ_BLOB;");
    writer.println("DROP ALIAS READ_CLOB;");
    writer.println("DROP ALIAS READ_BLOB_DB;");
    writer.println("DROP ALIAS READ_CLOB_DB;");
    if (deleteLobs) {
        writer.println("DELETE FROM INFORMATION_SCHEMA.LOBS WHERE TABLE = " + LobStorageFrontend.TABLE_TEMP + ";");
    }
    for (MetaRecord m : schema) {
        if (isSchemaObjectTypeDelayed(m)) {
            String sql = m.getSQL();
            writer.println(sql + ";");
        }
    }
}
Also used : MetaRecord(org.h2.engine.MetaRecord) TransactionMap(org.h2.mvstore.db.TransactionStore.TransactionMap) MVMap(org.h2.mvstore.MVMap) Map(java.util.Map) LobStorageMap(org.h2.store.LobStorageMap) HashMap(java.util.HashMap)

Aggregations

Connection (java.sql.Connection)40 PreparedStatement (java.sql.PreparedStatement)39 Statement (java.sql.Statement)38 ResultSet (java.sql.ResultSet)36 JdbcConnection (org.h2.jdbc.JdbcConnection)25 SQLException (java.sql.SQLException)17 SimpleResultSet (org.h2.tools.SimpleResultSet)14 Savepoint (java.sql.Savepoint)13 StatementBuilder (org.h2.util.StatementBuilder)9 DbException (org.h2.message.DbException)8 Column (org.h2.table.Column)8 ValueString (org.h2.value.ValueString)7 Random (java.util.Random)6 Expression (org.h2.expression.Expression)5 ValueExpression (org.h2.expression.ValueExpression)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ArrayList (java.util.ArrayList)4 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)4 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)4 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)4