1 5 package org.h2.constraint; 6 7 import java.sql.SQLException ; 8 9 import org.h2.engine.Session; 10 import org.h2.expression.Expression; 11 import org.h2.index.Index; 12 import org.h2.message.Message; 13 import org.h2.result.Row; 14 import org.h2.schema.Schema; 15 import org.h2.table.Column; 16 import org.h2.table.Table; 17 import org.h2.table.TableFilter; 18 import org.h2.util.StringUtils; 19 20 23 24 public class ConstraintCheck extends Constraint { 25 26 private TableFilter filter; 27 private Expression expr; 28 29 public ConstraintCheck(Schema schema, int id, String name, Table table) { 30 super(schema, id, name, table); 31 } 32 33 public String getConstraintType() { 34 return Constraint.CHECK; 35 } 36 37 public void setTableFilter(TableFilter filter) { 38 this.filter = filter; 39 } 40 41 public void setExpression(Expression expr) { 42 this.expr = expr; 43 } 44 45 public String getCreateSQLForCopy(Table table, String quotedName) { 46 StringBuffer buff = new StringBuffer (); 47 buff.append("ALTER TABLE "); 48 buff.append(table.getSQL()); 49 buff.append(" ADD CONSTRAINT "); 50 buff.append(quotedName); 51 if(comment != null) { 52 buff.append(" COMMENT "); 53 buff.append(StringUtils.quoteStringSQL(comment)); 54 } 55 buff.append(" CHECK"); 56 buff.append(StringUtils.enclose(expr.getSQL())); 57 return buff.toString(); 58 } 59 60 public String getShortDescription() { 61 StringBuffer buff = new StringBuffer (); 62 buff.append(getName()); 63 buff.append(": "); 64 buff.append(expr.getSQL()); 65 return buff.toString(); 66 } 67 68 public String getCreateSQLWithoutIndexes() { 69 return getCreateSQL(); 70 } 71 72 public String getCreateSQL() { 73 return getCreateSQLForCopy(table, getSQL()); 74 } 75 76 public void removeChildrenAndResources(Session session) { 77 table.removeConstraint(this); 78 filter = null; 79 expr = null; 80 table = null; 81 invalidate(); 82 } 83 84 public void checkRow(Session session, Table t, Row oldRow, Row newRow) throws SQLException { 85 if(newRow == null) { 86 return; 87 } 88 filter.set(newRow); 89 if(Boolean.FALSE.equals(expr.getValue(session).getBoolean())) { 91 throw Message.getSQLException(Message.CHECK_CONSTRAINT_VIOLATED_1, getShortDescription()); 92 } 93 } 94 95 public boolean usesIndex(Index index) { 96 return false; 97 } 98 99 public boolean containsColumn(Column col) { 100 String s = col.getSQL(); 102 String sql = getCreateSQL(); 103 return sql.indexOf(s) >= 0; 104 } 105 106 public Expression getExpression() { 107 return expr; 108 } 109 110 public boolean isBefore() { 111 return true; 112 } 113 114 } 115 | Popular Tags |