1 5 package org.h2.command.dml; 6 7 import java.sql.SQLException ; 8 9 import org.h2.command.Prepared; 10 import org.h2.engine.Right; 11 import org.h2.engine.Session; 12 import org.h2.expression.Expression; 13 import org.h2.result.Row; 14 import org.h2.store.UndoLogRecord; 15 import org.h2.table.PlanItem; 16 import org.h2.table.Table; 17 import org.h2.table.TableFilter; 18 import org.h2.util.ObjectArray; 19 import org.h2.util.StringUtils; 20 21 24 public class Delete extends Prepared { 25 26 private Expression condition; 27 private TableFilter tableFilter; 28 29 public Delete(Session session) { 30 super(session); 31 } 32 33 public void setTableFilter(TableFilter tableFilter) { 34 this.tableFilter = tableFilter; 35 } 36 37 public void setCondition(Expression condition) { 38 this.condition = condition; 39 } 40 41 public int update() throws SQLException { 42 tableFilter.startQuery(); 43 tableFilter.reset(); 44 Table table = tableFilter.getTable(); 45 session.getUser().checkRight(table, Right.DELETE); 46 table.fireBefore(session); 47 table.lock(session, true); 48 ObjectArray rows = new ObjectArray(); 49 setCurrentRowNumber(0); 50 while (tableFilter.next()) { 51 checkCancelled(); 52 setCurrentRowNumber(rows.size()+1); 53 if (condition == null || Boolean.TRUE.equals(condition.getBooleanValue(session))) { 54 Row row = tableFilter.get(); 55 rows.add(row); 56 } 57 } 58 if(table.fireRow()) { 59 for (int i = 0; i < rows.size(); i++) { 60 checkCancelled(); 61 Row row = (Row) rows.get(i); 62 table.fireBeforeRow(session, row, null); 63 } 64 } 65 for (int i = 0; i < rows.size(); i++) { 66 checkCancelled(); 67 Row row = (Row) rows.get(i); 68 table.removeRow(session, row); 69 session.log(new UndoLogRecord(table, UndoLogRecord.DELETE, row)); 70 } 71 if(table.fireRow()) { 72 for (int i = 0; i < rows.size(); i++) { 73 checkCancelled(); 74 Row row = (Row) rows.get(i); 75 table.fireAfterRow(session, row, null); 76 } 77 } 78 table.fireAfter(session); 79 return rows.size(); 80 } 81 82 public String getPlan() { 83 StringBuffer buff = new StringBuffer (); 84 buff.append("DELETE FROM "); 85 buff.append(tableFilter.getPlanSQL(false)); 86 if(condition != null) { 87 buff.append("\nWHERE " + StringUtils.unEnclose(condition.getSQL())); 88 } 89 return buff.toString(); 90 } 91 92 public void prepare() throws SQLException { 93 if (condition != null) { 94 condition.mapColumns(tableFilter, 0); 95 condition = condition.optimize(session); 96 condition.createIndexConditions(tableFilter); 97 } 98 PlanItem item = tableFilter.getBestPlanItem(session); 99 tableFilter.setPlanItem(item); 100 tableFilter.prepare(); 101 } 102 103 public boolean isTransactional() { 104 return true; 105 } 106 107 } 108 | Popular Tags |