KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > quadcap > sql > Constraint


1 package com.quadcap.sql;
2
3 /* Copyright 1999 - 2003 Quadcap Software. All rights reserved.
4  *
5  * This software is distributed under the Quadcap Free Software License.
6  * This software may be used or modified for any purpose, personal or
7  * commercial. Open Source redistributions are permitted. Commercial
8  * redistribution of larger works derived from, or works which bundle
9  * this software requires a "Commercial Redistribution License"; see
10  * http://www.quadcap.com/purchase.
11  *
12  * Redistributions qualify as "Open Source" under one of the following terms:
13  *
14  * Redistributions are made at no charge beyond the reasonable cost of
15  * materials and delivery.
16  *
17  * Redistributions are accompanied by a copy of the Source Code or by an
18  * irrevocable offer to provide a copy of the Source Code for up to three
19  * years at the cost of materials and delivery. Such redistributions
20  * must allow further use, modification, and redistribution of the Source
21  * Code under substantially the same terms as this license.
22  *
23  * Redistributions of source code must retain the copyright notices as they
24  * appear in each source code file, these license terms, and the
25  * disclaimer/limitation of liability set forth as paragraph 6 below.
26  *
27  * Redistributions in binary form must reproduce this Copyright Notice,
28  * these license terms, and the disclaimer/limitation of liability set
29  * forth as paragraph 6 below, in the documentation and/or other materials
30  * provided with the distribution.
31  *
32  * The Software is provided on an "AS IS" basis. No warranty is
33  * provided that the Software is free of defects, or fit for a
34  * particular purpose.
35  *
36  * Limitation of Liability. Quadcap Software shall not be liable
37  * for any damages suffered by the Licensee or any third party resulting
38  * from use of the Software.
39  */

40
41 import java.io.Externalizable JavaDoc;
42 import java.io.IOException JavaDoc;
43 import java.io.ObjectInput JavaDoc;
44 import java.io.ObjectOutput JavaDoc;
45
46 import java.util.Vector JavaDoc;
47
48 import java.sql.SQLException JavaDoc;
49
50 import com.quadcap.sql.index.Btree;
51
52 import com.quadcap.util.Debug;
53
54 /**
55  * A constraint is a condition which must be satisfied relative to
56  * the rows of a table. Constraint checking hooks are available for
57  * both before and after table-modifying operations.
58  *
59  * @author Stan Bailes
60  */

61 public abstract class Constraint implements Externalizable JavaDoc {
62     transient Table table;
63     transient int[] columns;
64     Vector JavaDoc colNames = new Vector JavaDoc();
65     String JavaDoc name = null;
66     int spec = 0;
67
68     // bits 0..1 of the constraint
69
public static final int FULL = (1 << 0);
70     public static final int PARTIAL = (1 << 1);
71
72     // two actions bits for update and delete
73
public static final int NOACTION = 0;
74     public static final int CASCADE = 1;
75     public static final int SETNULL = 2;
76     public static final int SETDEFAULT = 3;
77
78     // bits 2..3 (action)
79
public static final int UPDATE = 2;
80     // bits 4..5 (action)
81
public static final int DELETE = 4;
82
83     // bit 6
84
public static final int DEFERRABLE = (1 << 6);
85     // bit 7
86
public static final int INIT_DEFERRED = (1 << 7);
87     // bit 8
88
public static final int GLOBAL = (1 << 8);
89
90     /**
91      * Default constructor
92      */

93     public Constraint() {}
94
95     /**
96      * Construct a named constraint
97      */

98     public Constraint(String JavaDoc name) {
99     this.name = name;
100     }
101
102     /**
103      * Construct a named constraint with a list of columns
104      */

105     public Constraint(String JavaDoc name, Vector JavaDoc colNames) {
106     this.name = name;
107     this.colNames = colNames;
108     }
109
110     /**
111      * Return the constraint's name
112      */

113     public String JavaDoc getName() {
114     return name;
115     }
116
117     /**
118      * Set the constraint's name
119      */

120     public void setName(String JavaDoc name) {
121     this.name = name;
122     }
123
124     /**
125      * Get the referential action for the specified operation (UPD OR DEL)
126      */

127     public int getRefAction(int opType) {
128     return (spec >> opType) & 0x3;
129     }
130
131     /**
132      * String names for Various referential actions
133      */

134     static String JavaDoc[] refActions = { "NO ACTION", "CASCADE", "SET NULL",
135                                    "SET DEFAULT" };
136
137     /**
138      * Return the referential action for the specified operation
139      */

140     public String JavaDoc getRefActionString(int opType) {
141         return refActions[getRefAction(opType)];
142     }
143
144     /**
145      * Set the 'global' flag
146      */

147     public void setGlobal(boolean g) {
148         if (g) {
149             spec |= GLOBAL;
150         } else {
151             spec &= ~GLOBAL;
152         }
153     }
154
155     /**
156      * Get the 'global' flag
157      */

158     public boolean isGlobal() { return (spec & GLOBAL) != 0; }
159
160     /**---INSERT
161      * Called before a row is INSERTED, with an opportunity to signal
162      * a constraint violation if one can be detected.
163      */

164     abstract public void checkInsert(Session session, Row row)
165     throws SQLException JavaDoc, IOException JavaDoc
166     ;
167
168     /**
169      * Called after the specified row has been inserted, with the resulting
170      * row ID, and with the active index. Constraints which maintain state
171      * (such as an index) would extend this class and implement this
172      * method to update the index
173      */

174     abstract public void applyInsert(Session session, Row row, long rowId,
175                      Constraint activeIndex)
176     throws SQLException JavaDoc, IOException JavaDoc
177     ;
178
179     /**----DELETE
180      * Called before a row is DELETED, with an opportunity to signal a
181      * constraint violation if one can be detected.
182      */

183     abstract public void checkDelete(Session session, Row row, long rowId)
184     throws SQLException JavaDoc, IOException JavaDoc
185     ;
186
187     /**
188      * Called after a row has been deleted, with the old row and row ID.
189      * Constraints which maintain state (such as an index) would extend
190      * this class and implement this method to update the index.
191      */

192     abstract public void applyDelete(Session session, Row row, long rowId,
193                      Constraint activeIndex)
194     throws SQLException JavaDoc, IOException JavaDoc
195     ;
196
197     /**----UPDATE
198      * Called before a row is UPDATED, with an opportunity to signal a
199      * constraint violation if one can be detected.
200      *
201      * Because the oldRow may be 'lazy', it's important to instantiate
202      * whatever items are going to be needed later by applyUpdate *now*,
203      * otherwise, apply may get the 'new' versions of those items, because
204      * the underlying byte stream is modified by the time applyUpdate
205      * gets called.
206      */

207     abstract public void checkUpdate(Session session, byte[] oldKey, Row row,
208                      Row oldRow, long rowId,
209                                      Constraint activeIndex)
210     throws SQLException JavaDoc, IOException JavaDoc
211     ;
212
213     /**
214      * Called after a row has been updated, with the old row, old key,
215      * new row and row ID.
216      * Constraints which maintain state (such as an index) would extend
217      * this class and implement this method to update the index.
218      */

219     abstract public void applyUpdate(Session session, byte[] oldKey, Row row,
220                      Row oldRow, long rowId,
221                      Constraint activeIndex)
222     throws SQLException JavaDoc, IOException JavaDoc
223     ;
224
225     /**
226      * Called when the constraint itself is being removed. Constraints which
227      * allocate resources of any kind should release them here since they
228      * are about to be discarded and gc'ed.
229      */

230     abstract public void delete(Session session)
231     throws SQLException JavaDoc, IOException JavaDoc
232     ;
233
234     /**
235      * Called when the constraint is added. Constraints which maintain
236      * state (e.g., indexes) can build their initial data structures (or
237      * whatever it is that they do at this time)
238      */

239     abstract public void add(Session session)
240     throws SQLException JavaDoc, IOException JavaDoc;
241
242     /**
243      * Called to undo a constraint-add operation.
244      */

245     public void undoAdd(Session session)
246     throws SQLException JavaDoc, IOException JavaDoc {
247         delete(session);
248     }
249
250
251     /**
252      * Called to undo a constraint-add operation.
253      */

254     public void undoDelete(Session session)
255     throws SQLException JavaDoc, IOException JavaDoc
256     {
257         add(session);
258     }
259
260
261     /**
262      * Set the deferrable flags
263      */

264     public void setDeferrable(int def) {
265     this.spec |= def;
266     }
267     
268     /**
269      * Set the referential integrity flags
270      */

271     public void setRefSpec(int ref) {
272     this.spec |= ref;
273     }
274
275     /**
276      * Set the contstraint's table
277      */

278     public void setTable(Table table) throws SQLException JavaDoc {
279     this.table = table;
280         this.columns = null;
281         getColumns();
282     }
283
284     /**
285      * Get the constraint's table
286      */

287     public Table getTable() { return this.table; }
288
289     /**
290      * Return the referential integrity and deferrability flags
291      */

292     public int getSpec() {
293     return spec;
294     }
295
296     /**
297      * Convenience method for setting single column constraints.
298      */

299     public void setColumn(Column column) {
300         if (colNames.size() != 0) {
301             colNames = new Vector JavaDoc();
302         }
303         colNames.add(column.getName());
304         this.columns = null;
305     }
306
307     /**
308      * For the simple, single column constraint, the constraint's column
309      *
310      * @exception SQLException if called for a multi-column constraint.
311      */

312     public Column getColumn() throws SQLException JavaDoc {
313     getColumns();
314     if (columns.length < 1) throw new SQLException JavaDoc("No column", "Q0000");
315     if (columns.length > 1)
316         throw new SQLException JavaDoc("Not a single column constraint: " + this,
317                    "Q0000");
318     return table.getColumn(columns[0]);
319     }
320
321     /**
322      * Return the number of columns described by the constraint.
323      */

324     public int getColumnCount() {
325     return colNames.size();
326     }
327
328     /**
329      * Zero based!!!!
330      */

331     public Column getColumn(int c) throws SQLException JavaDoc {
332         return table.getColumn(columns[c]);
333     }
334
335     /**
336      * Read me from a stream
337      */

338     public void readExternal(ObjectInput JavaDoc in)
339     throws IOException JavaDoc, ClassNotFoundException JavaDoc
340     {
341     spec = in.readInt();
342     name = (String JavaDoc)in.readObject();
343         colNames = (Vector JavaDoc)in.readObject();
344     columns = null;
345     }
346
347     /**
348      * Write me to a stream
349      */

350     public void writeExternal(ObjectOutput JavaDoc out) throws IOException JavaDoc {
351     out.writeInt(spec);
352     out.writeObject(name);
353         out.writeObject(colNames);
354     }
355
356     /**
357      * Return the integer indexes in the table's column list of the
358      * columns in this constraint. We return a copy of our internal
359      * array, for speed, and trust the caller to not mess with the
360      * array...
361      */

362     public int[] getColumns() throws SQLException JavaDoc {
363     if (columns == null) {
364             columns = table.mapColumns(colNames);
365     }
366     return columns;
367     }
368
369     /**
370      * Reset any mapped columns (e.g. in case a column is added or deleted)
371      */

372     public void resetColumns() throws SQLException JavaDoc {
373         columns = null;
374     }
375     
376     /**
377      * Return a vector containing all of the column names
378      */

379     public Vector JavaDoc getColumnNames() throws SQLException JavaDoc {
380     return colNames;
381     }
382
383     /**
384      * Funny, but a lot of constraints have indexes. For the ones that
385      * do, this can be a nifty little function.
386      */

387     public Btree getIndex(Database db) throws IOException JavaDoc {
388     return null;
389     }
390
391     /**
392      * Higher priority (larger numbers) execute first.
393      */

394     public int getPriority() { return 3; }
395
396     /**
397      * Is this constraint 'deferred'?
398      */

399     public boolean isDeferred() {
400         return false; // only foreign key constraints are deferrable...
401
}
402
403     /**
404      * Return a displayable representation for debugging
405      */

406     public String JavaDoc toString() {
407     StringBuffer JavaDoc sb = new StringBuffer JavaDoc("Constraint ");
408     sb.append(name);
409     sb.append(": ");
410     if (table == null) {
411         sb.append("<null table>");
412     } else {
413         sb.append(table.getName());
414     }
415     sb.append("(");
416     if (colNames != null) {
417         for (int i = 0; i < colNames.size(); i++) {
418         if (i > 0) sb.append(',');
419         sb.append(colNames.elementAt(i).toString());
420         }
421     }
422     sb.append(")");
423         if ((spec & FULL) != 0) sb.append(" FULL");
424         if ((spec & PARTIAL) != 0) sb.append(" PARTIAL");
425
426         if (getRefAction(UPDATE) != NOACTION) {
427             sb.append(" ON UPDATE ");
428             sb.append(getRefActionString(UPDATE));
429         }
430         if (getRefAction(DELETE) != NOACTION) {
431             sb.append(" ON DELETE ");
432             sb.append(getRefActionString(DELETE));
433         }
434         if ((spec & DEFERRABLE) != 0) sb.append(" DEFERRABLE");
435         if ((spec & INIT_DEFERRED) != 0) sb.append(" INITIALLY DEFERRED");
436         
437     return sb.toString();
438     }
439 }
440
Popular Tags