1 package com.quadcap.sql; 2 3 40 41 import java.io.Externalizable ; 42 import java.io.IOException ; 43 import java.io.ObjectInput ; 44 import java.io.ObjectOutput ; 45 46 import java.sql.SQLException ; 47 48 import com.quadcap.sql.types.Value; 49 import com.quadcap.sql.types.ValueBoolean; 50 import com.quadcap.sql.types.ValueUnknown; 51 52 57 public class CheckConstraint extends Constraint implements Externalizable { 58 Expression expression; 59 60 public CheckConstraint() {} 61 62 public CheckConstraint(String name, Expression expression) { 63 super(name); 64 this.expression = expression; 65 } 66 67 public void add(Session session) throws SQLException { 68 if (!table.isUnderConstruction()) { 69 Cursor c = table.getCursor(session, null, null); 70 if (c != null) { 71 try { 72 while (c.next()) { 73 checkValue(expression.getValue(session, c)); 74 } 75 } finally { 76 c.close(); 77 } 78 } 79 } 80 } 81 82 public void delete(Session session) {} 83 public void undoDelete(Session session) {} 84 85 public void applyInsert(Session session, Row row, long rowId, 86 Constraint activeIndex) 87 throws SQLException , IOException 88 { 89 } 90 91 public void applyDelete(Session session, Row row, long rowId, 92 Constraint activeIndex) 93 throws SQLException , IOException 94 { 95 } 96 97 public final void checkValue(Value val) throws SQLException { 98 if (!(val instanceof ValueBoolean)) { 99 if (val instanceof ValueUnknown) return; 100 throw new SQLException ("Bad check expression: " + expression + 101 ", value = " + val, "42000"); 102 } 103 if (!((ValueBoolean)val).isTrue()) { 104 throw new SQLException ("Check constraint violated: " + 105 expression, "23000"); 106 } 107 } 108 109 public void checkInsert(Session session, Row row) 110 throws SQLException , IOException 111 { 112 StaticCursor cursor = new StaticCursor(session, table, row); 113 cursor.next(); 114 checkValue(expression.getValue(session, cursor)); 115 } 116 117 public void checkUpdate(Session session, byte[] oldKey, Row row, 118 Row oldRow, long rowId, Constraint activeIndex) 119 throws SQLException , IOException 120 { 121 checkInsert(session, row); 122 } 123 124 public void checkDelete(Session session, Row row, long rowId) 125 throws SQLException , IOException 126 { 127 } 128 129 public void applyUpdate(Session session, byte[] oldKey, Row row, 130 Row oldRow, long rowId, Constraint activeIndex) 131 throws SQLException , IOException 132 { 133 } 134 135 public void readExternal(ObjectInput in) 136 throws IOException , ClassNotFoundException 137 { 138 super.readExternal(in); 139 expression = (Expression)in.readObject(); 140 } 141 142 public void writeExternal(ObjectOutput out) throws IOException { 143 super.writeExternal(out); 144 out.writeObject(expression); 145 } 146 } 147 | Popular Tags |