blob: a8e88056a347f709fd37d11128100965bcfb7321 [file] [log] [blame]
dan1da40a32009-09-19 17:00:31 +00001/*
2**
3** The author disclaims copyright to this source code. In place of
4** a legal notice, here is a blessing:
5**
6** May you do good and not evil.
7** May you find forgiveness for yourself and forgive others.
8** May you share freely, never taking more than you give.
9**
10*************************************************************************
11** This file contains code used by the compiler to add foreign key
12** support to compiled SQL statements.
13*/
14#include "sqliteInt.h"
15
16#ifndef SQLITE_OMIT_FOREIGN_KEY
dan75cbd982009-09-21 16:06:03 +000017#ifndef SQLITE_OMIT_TRIGGER
dan1da40a32009-09-19 17:00:31 +000018
19/*
20** Deferred and Immediate FKs
21** --------------------------
22**
23** Foreign keys in SQLite come in two flavours: deferred and immediate.
dan8a2fff72009-09-23 18:07:22 +000024** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
25** is returned and the current statement transaction rolled back. If a
dan1da40a32009-09-19 17:00:31 +000026** deferred foreign key constraint is violated, no action is taken
27** immediately. However if the application attempts to commit the
28** transaction before fixing the constraint violation, the attempt fails.
29**
30** Deferred constraints are implemented using a simple counter associated
31** with the database handle. The counter is set to zero each time a
32** database transaction is opened. Each time a statement is executed
33** that causes a foreign key violation, the counter is incremented. Each
34** time a statement is executed that removes an existing violation from
35** the database, the counter is decremented. When the transaction is
36** committed, the commit fails if the current value of the counter is
37** greater than zero. This scheme has two big drawbacks:
38**
39** * When a commit fails due to a deferred foreign key constraint,
40** there is no way to tell which foreign constraint is not satisfied,
41** or which row it is not satisfied for.
42**
43** * If the database contains foreign key violations when the
44** transaction is opened, this may cause the mechanism to malfunction.
45**
46** Despite these problems, this approach is adopted as it seems simpler
47** than the alternatives.
48**
49** INSERT operations:
50**
dan8099ce62009-09-23 08:43:35 +000051** I.1) For each FK for which the table is the child table, search
dan8a2fff72009-09-23 18:07:22 +000052** the parent table for a match. If none is found increment the
53** constraint counter.
dan1da40a32009-09-19 17:00:31 +000054**
dan8a2fff72009-09-23 18:07:22 +000055** I.2) For each FK for which the table is the parent table,
dan8099ce62009-09-23 08:43:35 +000056** search the child table for rows that correspond to the new
57** row in the parent table. Decrement the counter for each row
dan1da40a32009-09-19 17:00:31 +000058** found (as the constraint is now satisfied).
59**
60** DELETE operations:
61**
dan8a2fff72009-09-23 18:07:22 +000062** D.1) For each FK for which the table is the child table,
dan8099ce62009-09-23 08:43:35 +000063** search the parent table for a row that corresponds to the
64** deleted row in the child table. If such a row is not found,
dan1da40a32009-09-19 17:00:31 +000065** decrement the counter.
66**
dan8099ce62009-09-23 08:43:35 +000067** D.2) For each FK for which the table is the parent table, search
68** the child table for rows that correspond to the deleted row
dan8a2fff72009-09-23 18:07:22 +000069** in the parent table. For each found increment the counter.
dan1da40a32009-09-19 17:00:31 +000070**
71** UPDATE operations:
72**
73** An UPDATE command requires that all 4 steps above are taken, but only
74** for FK constraints for which the affected columns are actually
75** modified (values must be compared at runtime).
76**
77** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
78** This simplifies the implementation a bit.
79**
80** For the purposes of immediate FK constraints, the OR REPLACE conflict
81** resolution is considered to delete rows before the new row is inserted.
82** If a delete caused by OR REPLACE violates an FK constraint, an exception
83** is thrown, even if the FK constraint would be satisfied after the new
84** row is inserted.
85**
danbd747832009-09-25 12:00:01 +000086** Immediate constraints are usually handled similarly. The only difference
87** is that the counter used is stored as part of each individual statement
88** object (struct Vdbe). If, after the statement has run, its immediate
89** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
90** and the statement transaction is rolled back. An exception is an INSERT
91** statement that inserts a single row only (no triggers). In this case,
92** instead of using a counter, an exception is thrown immediately if the
93** INSERT violates a foreign key constraint. This is necessary as such
94** an INSERT does not open a statement transaction.
95**
dan1da40a32009-09-19 17:00:31 +000096** TODO: How should dropping a table be handled? How should renaming a
97** table be handled?
dan8099ce62009-09-23 08:43:35 +000098**
99**
dan1da40a32009-09-19 17:00:31 +0000100** Query API Notes
101** ---------------
102**
103** Before coding an UPDATE or DELETE row operation, the code-generator
104** for those two operations needs to know whether or not the operation
105** requires any FK processing and, if so, which columns of the original
106** row are required by the FK processing VDBE code (i.e. if FKs were
107** implemented using triggers, which of the old.* columns would be
108** accessed). No information is required by the code-generator before
dan8099ce62009-09-23 08:43:35 +0000109** coding an INSERT operation. The functions used by the UPDATE/DELETE
110** generation code to query for this information are:
dan1da40a32009-09-19 17:00:31 +0000111**
dan8099ce62009-09-23 08:43:35 +0000112** sqlite3FkRequired() - Test to see if FK processing is required.
113** sqlite3FkOldmask() - Query for the set of required old.* columns.
114**
115**
116** Externally accessible module functions
117** --------------------------------------
118**
119** sqlite3FkCheck() - Check for foreign key violations.
120** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
121** sqlite3FkDelete() - Delete an FKey structure.
dan1da40a32009-09-19 17:00:31 +0000122*/
123
124/*
125** VDBE Calling Convention
126** -----------------------
127**
128** Example:
129**
130** For the following INSERT statement:
131**
132** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
133** INSERT INTO t1 VALUES(1, 2, 3.1);
134**
135** Register (x): 2 (type integer)
136** Register (x+1): 1 (type integer)
137** Register (x+2): NULL (type NULL)
138** Register (x+3): 3.1 (type real)
139*/
140
141/*
dan8099ce62009-09-23 08:43:35 +0000142** A foreign key constraint requires that the key columns in the parent
dan1da40a32009-09-19 17:00:31 +0000143** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
dan8099ce62009-09-23 08:43:35 +0000144** Given that pParent is the parent table for foreign key constraint pFKey,
145** search the schema a unique index on the parent key columns.
dan1da40a32009-09-19 17:00:31 +0000146**
dan8099ce62009-09-23 08:43:35 +0000147** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
148** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
149** is set to point to the unique index.
150**
151** If the parent key consists of a single column (the foreign key constraint
152** is not a composite foreign key), output variable *paiCol is set to NULL.
153** Otherwise, it is set to point to an allocated array of size N, where
154** N is the number of columns in the parent key. The first element of the
155** array is the index of the child table column that is mapped by the FK
156** constraint to the parent table column stored in the left-most column
157** of index *ppIdx. The second element of the array is the index of the
158** child table column that corresponds to the second left-most column of
159** *ppIdx, and so on.
160**
161** If the required index cannot be found, either because:
162**
163** 1) The named parent key columns do not exist, or
164**
165** 2) The named parent key columns do exist, but are not subject to a
166** UNIQUE or PRIMARY KEY constraint, or
167**
168** 3) No parent key columns were provided explicitly as part of the
169** foreign key definition, and the parent table does not have a
170** PRIMARY KEY, or
171**
172** 4) No parent key columns were provided explicitly as part of the
173** foreign key definition, and the PRIMARY KEY of the parent table
174** consists of a a different number of columns to the child key in
175** the child table.
176**
177** then non-zero is returned, and a "foreign key mismatch" error loaded
178** into pParse. If an OOM error occurs, non-zero is returned and the
179** pParse->db->mallocFailed flag is set.
dan1da40a32009-09-19 17:00:31 +0000180*/
181static int locateFkeyIndex(
182 Parse *pParse, /* Parse context to store any error in */
dan8099ce62009-09-23 08:43:35 +0000183 Table *pParent, /* Parent table of FK constraint pFKey */
dan1da40a32009-09-19 17:00:31 +0000184 FKey *pFKey, /* Foreign key to find index for */
dan8099ce62009-09-23 08:43:35 +0000185 Index **ppIdx, /* OUT: Unique index on parent table */
dan1da40a32009-09-19 17:00:31 +0000186 int **paiCol /* OUT: Map of index columns in pFKey */
187){
dan8099ce62009-09-23 08:43:35 +0000188 Index *pIdx = 0; /* Value to return via *ppIdx */
189 int *aiCol = 0; /* Value to return via *paiCol */
190 int nCol = pFKey->nCol; /* Number of columns in parent key */
191 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
dan1da40a32009-09-19 17:00:31 +0000192
193 /* The caller is responsible for zeroing output parameters. */
194 assert( ppIdx && *ppIdx==0 );
195 assert( !paiCol || *paiCol==0 );
196
197 /* If this is a non-composite (single column) foreign key, check if it
dan8099ce62009-09-23 08:43:35 +0000198 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
dan1da40a32009-09-19 17:00:31 +0000199 ** and *paiCol set to zero and return early.
200 **
201 ** Otherwise, for a composite foreign key (more than one column), allocate
202 ** space for the aiCol array (returned via output parameter *paiCol).
203 ** Non-composite foreign keys do not require the aiCol array.
204 */
205 if( nCol==1 ){
206 /* The FK maps to the IPK if any of the following are true:
207 **
dand981d442009-09-23 13:59:17 +0000208 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
209 ** mapped to the primary key of table pParent, or
210 ** 2) The FK is explicitly mapped to a column declared as INTEGER
dan1da40a32009-09-19 17:00:31 +0000211 ** PRIMARY KEY.
212 */
dan8099ce62009-09-23 08:43:35 +0000213 if( pParent->iPKey>=0 ){
214 if( !zKey ) return 0;
215 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
dan1da40a32009-09-19 17:00:31 +0000216 }
217 }else if( paiCol ){
218 assert( nCol>1 );
219 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
220 if( !aiCol ) return 1;
221 *paiCol = aiCol;
222 }
223
dan8099ce62009-09-23 08:43:35 +0000224 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
dan1da40a32009-09-19 17:00:31 +0000225 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
226 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
227 ** of columns. If each indexed column corresponds to a foreign key
228 ** column of pFKey, then this index is a winner. */
229
dan8099ce62009-09-23 08:43:35 +0000230 if( zKey==0 ){
231 /* If zKey is NULL, then this foreign key is implicitly mapped to
232 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
dan1da40a32009-09-19 17:00:31 +0000233 ** identified by the test (Index.autoIndex==2). */
234 if( pIdx->autoIndex==2 ){
dan8a2fff72009-09-23 18:07:22 +0000235 if( aiCol ){
236 int i;
237 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
238 }
dan1da40a32009-09-19 17:00:31 +0000239 break;
240 }
241 }else{
dan8099ce62009-09-23 08:43:35 +0000242 /* If zKey is non-NULL, then this foreign key was declared to
243 ** map to an explicit list of columns in table pParent. Check if this
dan9707c7b2009-09-29 15:41:57 +0000244 ** index matches those columns. Also, check that the index uses
245 ** the default collation sequences for each column. */
dan1da40a32009-09-19 17:00:31 +0000246 int i, j;
247 for(i=0; i<nCol; i++){
dan9707c7b2009-09-29 15:41:57 +0000248 int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
249 char *zDfltColl; /* Def. collation for column */
250 char *zIdxCol; /* Name of indexed column */
251
252 /* If the index uses a collation sequence that is different from
253 ** the default collation sequence for the column, this index is
254 ** unusable. Bail out early in this case. */
255 zDfltColl = pParent->aCol[iCol].zColl;
256 if( !zDfltColl ){
257 zDfltColl = "BINARY";
258 }
259 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
260
261 zIdxCol = pParent->aCol[iCol].zName;
dan1da40a32009-09-19 17:00:31 +0000262 for(j=0; j<nCol; j++){
263 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
264 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
265 break;
266 }
267 }
268 if( j==nCol ) break;
269 }
270 if( i==nCol ) break; /* pIdx is usable */
271 }
272 }
273 }
274
275 if( pParse && !pIdx ){
danf0662562009-09-28 18:52:11 +0000276 if( !pParse->disableTriggers ){
277 sqlite3ErrorMsg(pParse, "foreign key mismatch");
278 }
dan1da40a32009-09-19 17:00:31 +0000279 sqlite3DbFree(pParse->db, aiCol);
280 return 1;
281 }
282
283 *ppIdx = pIdx;
284 return 0;
285}
286
dan8099ce62009-09-23 08:43:35 +0000287/*
danbd747832009-09-25 12:00:01 +0000288** This function is called when a row is inserted into or deleted from the
289** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
290** on the child table of pFKey, this function is invoked twice for each row
dan8099ce62009-09-23 08:43:35 +0000291** affected - once to "delete" the old row, and then again to "insert" the
292** new row.
293**
294** Each time it is called, this function generates VDBE code to locate the
295** row in the parent table that corresponds to the row being inserted into
296** or deleted from the child table. If the parent row can be found, no
297** special action is taken. Otherwise, if the parent row can *not* be
298** found in the parent table:
299**
300** Operation | FK type | Action taken
301** --------------------------------------------------------------------------
danbd747832009-09-25 12:00:01 +0000302** INSERT immediate Increment the "immediate constraint counter".
303**
304** DELETE immediate Decrement the "immediate constraint counter".
dan8099ce62009-09-23 08:43:35 +0000305**
306** INSERT deferred Increment the "deferred constraint counter".
307**
308** DELETE deferred Decrement the "deferred constraint counter".
309**
danbd747832009-09-25 12:00:01 +0000310** These operations are identified in the comment at the top of this file
311** (fkey.c) as "I.1" and "D.1".
dan8099ce62009-09-23 08:43:35 +0000312*/
313static void fkLookupParent(
dan1da40a32009-09-19 17:00:31 +0000314 Parse *pParse, /* Parse context */
315 int iDb, /* Index of database housing pTab */
dan8099ce62009-09-23 08:43:35 +0000316 Table *pTab, /* Parent table of FK pFKey */
317 Index *pIdx, /* Unique index on parent key columns in pTab */
318 FKey *pFKey, /* Foreign key constraint */
319 int *aiCol, /* Map from parent key columns to child table columns */
320 int regData, /* Address of array containing child table row */
dan32b09f22009-09-23 17:29:59 +0000321 int nIncr /* Increment constraint counter by this */
dan1da40a32009-09-19 17:00:31 +0000322){
dan8099ce62009-09-23 08:43:35 +0000323 int i; /* Iterator variable */
324 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
325 int iCur = pParse->nTab - 1; /* Cursor number to use */
326 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
dan1da40a32009-09-19 17:00:31 +0000327
dan0ff297e2009-09-25 17:03:14 +0000328 /* If nIncr is less than zero, then check at runtime if there are any
329 ** outstanding constraints to resolve. If there are not, there is no need
330 ** to check if deleting this row resolves any outstanding violations.
331 **
332 ** Check if any of the key columns in the child table row are NULL. If
333 ** any are, then the constraint is considered satisfied. No need to
334 ** search for a matching row in the parent table. */
335 if( nIncr<0 ){
336 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
337 }
dan1da40a32009-09-19 17:00:31 +0000338 for(i=0; i<pFKey->nCol; i++){
dan36062642009-09-21 18:56:23 +0000339 int iReg = aiCol[i] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000340 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
341 }
342
343 if( pIdx==0 ){
dan8099ce62009-09-23 08:43:35 +0000344 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
345 ** column of the parent table (table pTab). */
dan9277efa2009-09-28 11:54:21 +0000346 int iMustBeInt; /* Address of MustBeInt instruction */
dan140026b2009-09-24 18:19:41 +0000347 int regTemp = sqlite3GetTempReg(pParse);
348
349 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
350 ** apply the affinity of the parent key). If this fails, then there
351 ** is no matching parent key. Before using MustBeInt, make a copy of
352 ** the value. Otherwise, the value inserted into the child key column
353 ** will have INTEGER affinity applied to it, which may not be correct. */
354 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
dan9277efa2009-09-28 11:54:21 +0000355 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
356
357 /* If the parent table is the same as the child table, and we are about
358 ** to increment the constraint-counter (i.e. this is an INSERT operation),
359 ** then check if the row being inserted matches itself. If so, do not
360 ** increment the constraint-counter. */
361 if( pTab==pFKey->pFrom && nIncr==1 ){
362 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
363 }
364
dan1da40a32009-09-19 17:00:31 +0000365 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
dan140026b2009-09-24 18:19:41 +0000366 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
dan1da40a32009-09-19 17:00:31 +0000367 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
368 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
dan9277efa2009-09-28 11:54:21 +0000369 sqlite3VdbeJumpHere(v, iMustBeInt);
dan140026b2009-09-24 18:19:41 +0000370 sqlite3ReleaseTempReg(pParse, regTemp);
dan1da40a32009-09-19 17:00:31 +0000371 }else{
dan140026b2009-09-24 18:19:41 +0000372 int nCol = pFKey->nCol;
373 int regTemp = sqlite3GetTempRange(pParse, nCol);
dan1da40a32009-09-19 17:00:31 +0000374 int regRec = sqlite3GetTempReg(pParse);
375 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
376
377 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
378 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
dan9277efa2009-09-28 11:54:21 +0000379 for(i=0; i<nCol; i++){
dan140026b2009-09-24 18:19:41 +0000380 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
dan1da40a32009-09-19 17:00:31 +0000381 }
dan9277efa2009-09-28 11:54:21 +0000382
383 /* If the parent table is the same as the child table, and we are about
384 ** to increment the constraint-counter (i.e. this is an INSERT operation),
385 ** then check if the row being inserted matches itself. If so, do not
386 ** increment the constraint-counter. */
387 if( pTab==pFKey->pFrom && nIncr==1 ){
388 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
389 for(i=0; i<nCol; i++){
390 int iChild = aiCol[i]+1+regData;
391 int iParent = pIdx->aiColumn[i]+1+regData;
392 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
393 }
394 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
395 }
396
dan140026b2009-09-24 18:19:41 +0000397 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
398 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
dan1da40a32009-09-19 17:00:31 +0000399 sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
dan9277efa2009-09-28 11:54:21 +0000400
dan1da40a32009-09-19 17:00:31 +0000401 sqlite3ReleaseTempReg(pParse, regRec);
dan140026b2009-09-24 18:19:41 +0000402 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
dan1da40a32009-09-19 17:00:31 +0000403 }
404
dan32b09f22009-09-23 17:29:59 +0000405 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
406 /* Special case: If this is an INSERT statement that will insert exactly
407 ** one row into the table, raise a constraint immediately instead of
408 ** incrementing a counter. This is necessary as the VM code is being
409 ** generated for will not open a statement transaction. */
410 assert( nIncr==1 );
dan1da40a32009-09-19 17:00:31 +0000411 sqlite3HaltConstraint(
412 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
413 );
dan32b09f22009-09-23 17:29:59 +0000414 }else{
415 if( nIncr>0 && pFKey->isDeferred==0 ){
416 sqlite3ParseToplevel(pParse)->mayAbort = 1;
417 }
dan0ff297e2009-09-25 17:03:14 +0000418 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
dan1da40a32009-09-19 17:00:31 +0000419 }
420
421 sqlite3VdbeResolveLabel(v, iOk);
422}
423
dan8099ce62009-09-23 08:43:35 +0000424/*
425** This function is called to generate code executed when a row is deleted
426** from the parent table of foreign key constraint pFKey and, if pFKey is
427** deferred, when a row is inserted into the same table. When generating
428** code for an SQL UPDATE operation, this function may be called twice -
429** once to "delete" the old row and once to "insert" the new row.
430**
431** The code generated by this function scans through the rows in the child
432** table that correspond to the parent table row being deleted or inserted.
433** For each child row found, one of the following actions is taken:
434**
435** Operation | FK type | Action taken
436** --------------------------------------------------------------------------
danbd747832009-09-25 12:00:01 +0000437** DELETE immediate Increment the "immediate constraint counter".
438** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
439** throw a "foreign key constraint failed" exception.
440**
441** INSERT immediate Decrement the "immediate constraint counter".
dan8099ce62009-09-23 08:43:35 +0000442**
443** DELETE deferred Increment the "deferred constraint counter".
444** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
445** throw a "foreign key constraint failed" exception.
446**
447** INSERT deferred Decrement the "deferred constraint counter".
448**
danbd747832009-09-25 12:00:01 +0000449** These operations are identified in the comment at the top of this file
450** (fkey.c) as "I.2" and "D.2".
dan8099ce62009-09-23 08:43:35 +0000451*/
452static void fkScanChildren(
dan1da40a32009-09-19 17:00:31 +0000453 Parse *pParse, /* Parse context */
454 SrcList *pSrc, /* SrcList containing the table to scan */
dan9277efa2009-09-28 11:54:21 +0000455 Table *pTab,
dan1da40a32009-09-19 17:00:31 +0000456 Index *pIdx, /* Foreign key index */
457 FKey *pFKey, /* Foreign key relationship */
dan8099ce62009-09-23 08:43:35 +0000458 int *aiCol, /* Map from pIdx cols to child table cols */
dan1da40a32009-09-19 17:00:31 +0000459 int regData, /* Referenced table data starts here */
460 int nIncr /* Amount to increment deferred counter by */
461){
462 sqlite3 *db = pParse->db; /* Database handle */
463 int i; /* Iterator variable */
464 Expr *pWhere = 0; /* WHERE clause to scan with */
465 NameContext sNameContext; /* Context used to resolve WHERE clause */
466 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
dan0ff297e2009-09-25 17:03:14 +0000467 int iFkIfZero = 0; /* Address of OP_FkIfZero */
468 Vdbe *v = sqlite3GetVdbe(pParse);
469
dan9277efa2009-09-28 11:54:21 +0000470 assert( !pIdx || pIdx->pTable==pTab );
471
dan0ff297e2009-09-25 17:03:14 +0000472 if( nIncr<0 ){
473 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
474 }
dan1da40a32009-09-19 17:00:31 +0000475
danbd747832009-09-25 12:00:01 +0000476 /* Create an Expr object representing an SQL expression like:
477 **
478 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
479 **
480 ** The collation sequence used for the comparison should be that of
481 ** the parent key columns. The affinity of the parent key column should
482 ** be applied to each child key value before the comparison takes place.
483 */
dan1da40a32009-09-19 17:00:31 +0000484 for(i=0; i<pFKey->nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000485 Expr *pLeft; /* Value from parent table row */
486 Expr *pRight; /* Column ref to child table */
dan1da40a32009-09-19 17:00:31 +0000487 Expr *pEq; /* Expression (pLeft = pRight) */
dan8099ce62009-09-23 08:43:35 +0000488 int iCol; /* Index of column in child table */
489 const char *zCol; /* Name of column in child table */
dan1da40a32009-09-19 17:00:31 +0000490
491 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
492 if( pLeft ){
danbd747832009-09-25 12:00:01 +0000493 /* Set the collation sequence and affinity of the LHS of each TK_EQ
494 ** expression to the parent key column defaults. */
dan140026b2009-09-24 18:19:41 +0000495 if( pIdx ){
496 int iCol = pIdx->aiColumn[i];
497 Column *pCol = &pIdx->pTable->aCol[iCol];
498 pLeft->iTable = regData+iCol+1;
499 pLeft->affinity = pCol->affinity;
500 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
501 }else{
502 pLeft->iTable = regData;
503 pLeft->affinity = SQLITE_AFF_INTEGER;
504 }
dan1da40a32009-09-19 17:00:31 +0000505 }
506 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000507 assert( iCol>=0 );
508 zCol = pFKey->pFrom->aCol[iCol].zName;
dan1da40a32009-09-19 17:00:31 +0000509 pRight = sqlite3Expr(db, TK_ID, zCol);
510 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
511 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
512 }
513
dan9277efa2009-09-28 11:54:21 +0000514 /* If the child table is the same as the parent table, and this scan
515 ** is taking place as part of a DELETE operation (operation D.2), omit the
516 ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
517 ** clause, where $rowid is the rowid of the row being deleted. */
518 if( pTab==pFKey->pFrom && nIncr>0 ){
519 Expr *pEq; /* Expression (pLeft = pRight) */
520 Expr *pLeft; /* Value from parent table row */
521 Expr *pRight; /* Column ref to child table */
522 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
523 pRight = sqlite3Expr(db, TK_COLUMN, 0);
524 if( pLeft && pRight ){
525 pLeft->iTable = regData;
526 pLeft->affinity = SQLITE_AFF_INTEGER;
527 pRight->iTable = pSrc->a[0].iCursor;
528 pRight->iColumn = -1;
529 }
530 pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
531 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
532 }
533
dan1da40a32009-09-19 17:00:31 +0000534 /* Resolve the references in the WHERE clause. */
535 memset(&sNameContext, 0, sizeof(NameContext));
536 sNameContext.pSrcList = pSrc;
537 sNameContext.pParse = pParse;
538 sqlite3ResolveExprNames(&sNameContext, pWhere);
539
540 /* Create VDBE to loop through the entries in pSrc that match the WHERE
541 ** clause. If the constraint is not deferred, throw an exception for
542 ** each row found. Otherwise, for deferred constraints, increment the
543 ** deferred constraint counter by nIncr for each row selected. */
544 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
dan32b09f22009-09-23 17:29:59 +0000545 if( nIncr==0 ){
danbd747832009-09-25 12:00:01 +0000546 /* Special case: A RESTRICT Action. Throw an error immediately if one
547 ** of these is encountered. */
dan1da40a32009-09-19 17:00:31 +0000548 sqlite3HaltConstraint(
549 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
550 );
dan32b09f22009-09-23 17:29:59 +0000551 }else{
552 if( nIncr>0 && pFKey->isDeferred==0 ){
553 sqlite3ParseToplevel(pParse)->mayAbort = 1;
554 }
dan0ff297e2009-09-25 17:03:14 +0000555 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
dan1da40a32009-09-19 17:00:31 +0000556 }
danf59c5ca2009-09-22 16:55:38 +0000557 if( pWInfo ){
558 sqlite3WhereEnd(pWInfo);
559 }
dan1da40a32009-09-19 17:00:31 +0000560
561 /* Clean up the WHERE clause constructed above. */
562 sqlite3ExprDelete(db, pWhere);
dan0ff297e2009-09-25 17:03:14 +0000563 if( iFkIfZero ){
564 sqlite3VdbeJumpHere(v, iFkIfZero);
565 }
dan1da40a32009-09-19 17:00:31 +0000566}
567
568/*
569** This function returns a pointer to the head of a linked list of FK
dan8099ce62009-09-23 08:43:35 +0000570** constraints for which table pTab is the parent table. For example,
dan1da40a32009-09-19 17:00:31 +0000571** given the following schema:
572**
573** CREATE TABLE t1(a PRIMARY KEY);
574** CREATE TABLE t2(b REFERENCES t1(a);
575**
576** Calling this function with table "t1" as an argument returns a pointer
577** to the FKey structure representing the foreign key constraint on table
578** "t2". Calling this function with "t2" as the argument would return a
dan8099ce62009-09-23 08:43:35 +0000579** NULL pointer (as there are no FK constraints for which t2 is the parent
580** table).
dan1da40a32009-09-19 17:00:31 +0000581*/
dan432cc5b2009-09-26 17:51:48 +0000582FKey *sqlite3FkReferences(Table *pTab){
dan1da40a32009-09-19 17:00:31 +0000583 int nName = sqlite3Strlen30(pTab->zName);
584 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
585}
586
dan8099ce62009-09-23 08:43:35 +0000587/*
588** The second argument is a Trigger structure allocated by the
589** fkActionTrigger() routine. This function deletes the Trigger structure
590** and all of its sub-components.
591**
592** The Trigger structure or any of its sub-components may be allocated from
593** the lookaside buffer belonging to database handle dbMem.
594*/
dan75cbd982009-09-21 16:06:03 +0000595static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
596 if( p ){
597 TriggerStep *pStep = p->step_list;
598 sqlite3ExprDelete(dbMem, pStep->pWhere);
599 sqlite3ExprListDelete(dbMem, pStep->pExprList);
dan9277efa2009-09-28 11:54:21 +0000600 sqlite3SelectDelete(dbMem, pStep->pSelect);
drh788536b2009-09-23 03:01:58 +0000601 sqlite3ExprDelete(dbMem, p->pWhen);
dan75cbd982009-09-21 16:06:03 +0000602 sqlite3DbFree(dbMem, p);
603 }
604}
605
dan8099ce62009-09-23 08:43:35 +0000606/*
dand66c8302009-09-28 14:49:01 +0000607** This function is called to generate code that runs when table pTab is
608** being dropped from the database. The SrcList passed as the second argument
609** to this function contains a single entry guaranteed to resolve to
610** table pTab.
611**
612** Normally, no code is required. However, if either
613**
614** (a) The table is the parent table of a FK constraint, or
615** (b) The table is the child table of a deferred FK constraint and it is
616** determined at runtime that there are outstanding deferred FK
617** constraint violations in the database,
618**
619** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
620** the table from the database. Triggers are disabled while running this
621** DELETE, but foreign key actions are not.
622*/
623void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
624 sqlite3 *db = pParse->db;
625 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
626 int iSkip = 0;
627 Vdbe *v = sqlite3GetVdbe(pParse);
628
629 assert( v ); /* VDBE has already been allocated */
630 if( sqlite3FkReferences(pTab)==0 ){
631 /* Search for a deferred foreign key constraint for which this table
632 ** is the child table. If one cannot be found, return without
633 ** generating any VDBE code. If one can be found, then jump over
634 ** the entire DELETE if there are no outstanding deferred constraints
635 ** when this statement is run. */
636 FKey *p;
637 for(p=pTab->pFKey; p; p=p->pNextFrom){
638 if( p->isDeferred ) break;
639 }
640 if( !p ) return;
641 iSkip = sqlite3VdbeMakeLabel(v);
642 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
643 }
644
645 pParse->disableTriggers = 1;
646 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
647 pParse->disableTriggers = 0;
648
649 /* If the DELETE has generated immediate foreign key constraint
650 ** violations, halt the VDBE and return an error at this point, before
651 ** any modifications to the schema are made. This is because statement
652 ** transactions are not able to rollback schema changes. */
653 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
654 sqlite3HaltConstraint(
655 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
656 );
657
658 if( iSkip ){
659 sqlite3VdbeResolveLabel(v, iSkip);
660 }
661 }
662}
663
664/*
dan8099ce62009-09-23 08:43:35 +0000665** This function is called when inserting, deleting or updating a row of
666** table pTab to generate VDBE code to perform foreign key constraint
667** processing for the operation.
668**
669** For a DELETE operation, parameter regOld is passed the index of the
670** first register in an array of (pTab->nCol+1) registers containing the
671** rowid of the row being deleted, followed by each of the column values
672** of the row being deleted, from left to right. Parameter regNew is passed
673** zero in this case.
674**
dan8099ce62009-09-23 08:43:35 +0000675** For an INSERT operation, regOld is passed zero and regNew is passed the
676** first register of an array of (pTab->nCol+1) registers containing the new
677** row data.
678**
dan9277efa2009-09-28 11:54:21 +0000679** For an UPDATE operation, this function is called twice. Once before
680** the original record is deleted from the table using the calling convention
681** described for DELETE. Then again after the original record is deleted
682** but before the new record is inserted using the INSERT convention. In
683** both cases parameter pChanges is passed the list of columns being
684** updated by the statement.
dan8099ce62009-09-23 08:43:35 +0000685*/
dan1da40a32009-09-19 17:00:31 +0000686void sqlite3FkCheck(
687 Parse *pParse, /* Parse context */
688 Table *pTab, /* Row is being deleted from this table */
689 ExprList *pChanges, /* Changed columns if this is an UPDATE */
690 int regOld, /* Previous row data is stored here */
691 int regNew /* New row data is stored here */
692){
693 sqlite3 *db = pParse->db; /* Database handle */
694 Vdbe *v; /* VM to write code to */
695 FKey *pFKey; /* Used to iterate through FKs */
696 int iDb; /* Index of database containing pTab */
697 const char *zDb; /* Name of database containing pTab */
danf0662562009-09-28 18:52:11 +0000698 int isIgnoreErrors = pParse->disableTriggers;
dan1da40a32009-09-19 17:00:31 +0000699
dan792e9202009-09-29 11:28:51 +0000700 /* Exactly one of regOld and regNew should be non-zero. */
701 assert( (regOld==0)!=(regNew==0) );
dan1da40a32009-09-19 17:00:31 +0000702
703 /* If foreign-keys are disabled, this function is a no-op. */
704 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
705
706 v = sqlite3GetVdbe(pParse);
707 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
708 zDb = db->aDb[iDb].zName;
709
dan8099ce62009-09-23 08:43:35 +0000710 /* Loop through all the foreign key constraints for which pTab is the
711 ** child table (the table that the foreign key definition is part of). */
dan1da40a32009-09-19 17:00:31 +0000712 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan8099ce62009-09-23 08:43:35 +0000713 Table *pTo; /* Parent table of foreign key pFKey */
dan1da40a32009-09-19 17:00:31 +0000714 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000715 int *aiFree = 0;
716 int *aiCol;
717 int iCol;
718 int i;
dan1da40a32009-09-19 17:00:31 +0000719
dan8099ce62009-09-23 08:43:35 +0000720 /* Find the parent table of this foreign key. Also find a unique index
721 ** on the parent key columns in the parent table. If either of these
722 ** schema items cannot be located, set an error in pParse and return
723 ** early. */
danf0662562009-09-28 18:52:11 +0000724 if( pParse->disableTriggers ){
725 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
726 }else{
727 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
728 }
729 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
730 if( !isIgnoreErrors || db->mallocFailed ) return;
731 continue;
732 }
dan36062642009-09-21 18:56:23 +0000733 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000734
735 /* If the key does not overlap with the pChanges list, skip this FK. */
736 if( pChanges ){
737 /* TODO */
738 }
739
dan36062642009-09-21 18:56:23 +0000740 if( aiFree ){
741 aiCol = aiFree;
742 }else{
743 iCol = pFKey->aCol[0].iFrom;
744 aiCol = &iCol;
745 }
746 for(i=0; i<pFKey->nCol; i++){
747 if( aiCol[i]==pTab->iPKey ){
748 aiCol[i] = -1;
749 }
750 }
751
dan8099ce62009-09-23 08:43:35 +0000752 /* Take a shared-cache advisory read-lock on the parent table. Allocate
753 ** a cursor to use to search the unique index on the parent key columns
754 ** in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000755 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
756 pParse->nTab++;
757
dan32b09f22009-09-23 17:29:59 +0000758 if( regOld!=0 ){
759 /* A row is being removed from the child table. Search for the parent.
760 ** If the parent does not exist, removing the child row resolves an
761 ** outstanding foreign key constraint violation. */
dan8099ce62009-09-23 08:43:35 +0000762 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
dan1da40a32009-09-19 17:00:31 +0000763 }
764 if( regNew!=0 ){
dan32b09f22009-09-23 17:29:59 +0000765 /* A row is being added to the child table. If a parent row cannot
766 ** be found, adding the child row has violated the FK constraint. */
dan8099ce62009-09-23 08:43:35 +0000767 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
dan1da40a32009-09-19 17:00:31 +0000768 }
769
dan36062642009-09-21 18:56:23 +0000770 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000771 }
772
773 /* Loop through all the foreign key constraints that refer to this table */
dan432cc5b2009-09-26 17:51:48 +0000774 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
dan1da40a32009-09-19 17:00:31 +0000775 Index *pIdx = 0; /* Foreign key index for pFKey */
776 SrcList *pSrc;
777 int *aiCol = 0;
778
dan32b09f22009-09-23 17:29:59 +0000779 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
780 assert( regOld==0 && regNew!=0 );
781 /* Inserting a single row into a parent table cannot cause an immediate
782 ** foreign key violation. So do nothing in this case. */
danf0662562009-09-28 18:52:11 +0000783 continue;
dan1da40a32009-09-19 17:00:31 +0000784 }
785
danf0662562009-09-28 18:52:11 +0000786 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
787 if( !isIgnoreErrors || db->mallocFailed ) return;
788 continue;
789 }
dan1da40a32009-09-19 17:00:31 +0000790 assert( aiCol || pFKey->nCol==1 );
791
dan8099ce62009-09-23 08:43:35 +0000792 /* Check if this update statement has modified any of the child key
793 ** columns for this foreign key constraint. If it has not, there is
794 ** no need to search the child table for rows in violation. This is
dan1da40a32009-09-19 17:00:31 +0000795 ** just an optimization. Things would work fine without this check. */
796 if( pChanges ){
797 /* TODO */
798 }
799
800 /* Create a SrcList structure containing a single table (the table
801 ** the foreign key that refers to this table is attached to). This
802 ** is required for the sqlite3WhereXXX() interface. */
803 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000804 if( pSrc ){
805 pSrc->a->pTab = pFKey->pFrom;
806 pSrc->a->pTab->nRef++;
807 pSrc->a->iCursor = pParse->nTab++;
808
dan32b09f22009-09-23 17:29:59 +0000809 if( regNew!=0 ){
dan9277efa2009-09-28 11:54:21 +0000810 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
danf59c5ca2009-09-22 16:55:38 +0000811 }
812 if( regOld!=0 ){
813 /* If there is a RESTRICT action configured for the current operation
dan8099ce62009-09-23 08:43:35 +0000814 ** on the parent table of this FK, then throw an exception
danf59c5ca2009-09-22 16:55:38 +0000815 ** immediately if the FK constraint is violated, even if this is a
816 ** deferred trigger. That's what RESTRICT means. To defer checking
817 ** the constraint, the FK should specify NO ACTION (represented
818 ** using OE_None). NO ACTION is the default. */
dan9277efa2009-09-28 11:54:21 +0000819 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
danf59c5ca2009-09-22 16:55:38 +0000820 }
821
danf59c5ca2009-09-22 16:55:38 +0000822 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000823 }
dan1da40a32009-09-19 17:00:31 +0000824 sqlite3DbFree(db, aiCol);
825 }
826}
827
828#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
829
830/*
831** This function is called before generating code to update or delete a
832** row contained in table pTab. If the operation is an update, then
833** pChanges is a pointer to the list of columns to modify. If this is a
834** delete, then pChanges is NULL.
835*/
836u32 sqlite3FkOldmask(
837 Parse *pParse, /* Parse context */
838 Table *pTab, /* Table being modified */
839 ExprList *pChanges /* Non-NULL for UPDATE operations */
840){
841 u32 mask = 0;
842 if( pParse->db->flags&SQLITE_ForeignKeys ){
843 FKey *p;
844 int i;
845 for(p=pTab->pFKey; p; p=p->pNextFrom){
dan32b09f22009-09-23 17:29:59 +0000846 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
dan1da40a32009-09-19 17:00:31 +0000847 }
dan432cc5b2009-09-26 17:51:48 +0000848 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
dan1da40a32009-09-19 17:00:31 +0000849 Index *pIdx = 0;
danf0662562009-09-28 18:52:11 +0000850 locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
dan1da40a32009-09-19 17:00:31 +0000851 if( pIdx ){
852 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
853 }
854 }
855 }
856 return mask;
857}
858
859/*
860** This function is called before generating code to update or delete a
861** row contained in table pTab. If the operation is an update, then
862** pChanges is a pointer to the list of columns to modify. If this is a
863** delete, then pChanges is NULL.
864**
865** If any foreign key processing will be required, this function returns
866** true. If there is no foreign key related processing, this function
867** returns false.
868*/
869int sqlite3FkRequired(
870 Parse *pParse, /* Parse context */
871 Table *pTab, /* Table being modified */
872 ExprList *pChanges /* Non-NULL for UPDATE operations */
873){
874 if( pParse->db->flags&SQLITE_ForeignKeys ){
dan432cc5b2009-09-26 17:51:48 +0000875 if( sqlite3FkReferences(pTab) || pTab->pFKey ) return 1;
dan1da40a32009-09-19 17:00:31 +0000876 }
877 return 0;
878}
879
dan8099ce62009-09-23 08:43:35 +0000880/*
881** This function is called when an UPDATE or DELETE operation is being
882** compiled on table pTab, which is the parent table of foreign-key pFKey.
883** If the current operation is an UPDATE, then the pChanges parameter is
884** passed a pointer to the list of columns being modified. If it is a
885** DELETE, pChanges is passed a NULL pointer.
886**
887** It returns a pointer to a Trigger structure containing a trigger
888** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
889** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
890** returned (these actions require no special handling by the triggers
891** sub-system, code for them is created by fkScanChildren()).
892**
893** For example, if pFKey is the foreign key and pTab is table "p" in
894** the following schema:
895**
896** CREATE TABLE p(pk PRIMARY KEY);
897** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
898**
899** then the returned trigger structure is equivalent to:
900**
901** CREATE TRIGGER ... DELETE ON p BEGIN
902** DELETE FROM c WHERE ck = old.pk;
903** END;
904**
905** The returned pointer is cached as part of the foreign key object. It
906** is eventually freed along with the rest of the foreign key object by
907** sqlite3FkDelete().
908*/
dan1da40a32009-09-19 17:00:31 +0000909static Trigger *fkActionTrigger(
dan8099ce62009-09-23 08:43:35 +0000910 Parse *pParse, /* Parse context */
dan1da40a32009-09-19 17:00:31 +0000911 Table *pTab, /* Table being updated or deleted from */
912 FKey *pFKey, /* Foreign key to get action for */
913 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
914){
915 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000916 int action; /* One of OE_None, OE_Cascade etc. */
917 Trigger *pTrigger; /* Trigger definition to return */
dan8099ce62009-09-23 08:43:35 +0000918 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
dan1da40a32009-09-19 17:00:31 +0000919
dan8099ce62009-09-23 08:43:35 +0000920 action = pFKey->aAction[iAction];
921 pTrigger = pFKey->apTrigger[iAction];
dan1da40a32009-09-19 17:00:31 +0000922
dan9277efa2009-09-28 11:54:21 +0000923 if( action!=OE_None && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000924 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan8099ce62009-09-23 08:43:35 +0000925 char const *zFrom; /* Name of child table */
dan1da40a32009-09-19 17:00:31 +0000926 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000927 Index *pIdx = 0; /* Parent key index for this FK */
928 int *aiCol = 0; /* child table cols -> parent key cols */
929 TriggerStep *pStep; /* First (only) step of trigger program */
930 Expr *pWhere = 0; /* WHERE clause of trigger step */
931 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
dan9277efa2009-09-28 11:54:21 +0000932 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
dan29c7f9c2009-09-22 15:53:47 +0000933 int i; /* Iterator variable */
drh788536b2009-09-23 03:01:58 +0000934 Expr *pWhen = 0; /* WHEN clause for the trigger */
dan1da40a32009-09-19 17:00:31 +0000935
936 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
937 assert( aiCol || pFKey->nCol==1 );
938
dan1da40a32009-09-19 17:00:31 +0000939 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000940 Token tOld = { "old", 3 }; /* Literal "old" token */
941 Token tNew = { "new", 3 }; /* Literal "new" token */
dan8099ce62009-09-23 08:43:35 +0000942 Token tFromCol; /* Name of column in child table */
943 Token tToCol; /* Name of column in parent table */
944 int iFromCol; /* Idx of column in child table */
dan29c7f9c2009-09-22 15:53:47 +0000945 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000946
947 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000948 assert( iFromCol>=0 );
dan1da40a32009-09-19 17:00:31 +0000949 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
dana8f0bf62009-09-23 12:06:52 +0000950 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
dan1da40a32009-09-19 17:00:31 +0000951
952 tToCol.n = sqlite3Strlen30(tToCol.z);
953 tFromCol.n = sqlite3Strlen30(tFromCol.z);
954
955 /* Create the expression "zFromCol = OLD.zToCol" */
956 pEq = sqlite3PExpr(pParse, TK_EQ,
957 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
958 sqlite3PExpr(pParse, TK_DOT,
959 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
960 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
961 , 0)
962 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000963 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000964
drh788536b2009-09-23 03:01:58 +0000965 /* For ON UPDATE, construct the next term of the WHEN clause.
966 ** The final WHEN clause will be like this:
967 **
968 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
969 */
970 if( pChanges ){
971 pEq = sqlite3PExpr(pParse, TK_IS,
972 sqlite3PExpr(pParse, TK_DOT,
973 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
974 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
975 0),
976 sqlite3PExpr(pParse, TK_DOT,
977 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
978 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
979 0),
980 0);
981 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
982 }
983
dan9277efa2009-09-28 11:54:21 +0000984 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
dan1da40a32009-09-19 17:00:31 +0000985 Expr *pNew;
986 if( action==OE_Cascade ){
987 pNew = sqlite3PExpr(pParse, TK_DOT,
988 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
989 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
990 , 0);
991 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000992 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000993 if( pDflt ){
994 pNew = sqlite3ExprDup(db, pDflt, 0);
995 }else{
996 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
997 }
998 }else{
999 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
1000 }
1001 pList = sqlite3ExprListAppend(pParse, pList, pNew);
1002 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
1003 }
1004 }
dan29c7f9c2009-09-22 15:53:47 +00001005 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +00001006
dan9277efa2009-09-28 11:54:21 +00001007 zFrom = pFKey->pFrom->zName;
1008 nFrom = sqlite3Strlen30(zFrom);
1009
1010 if( action==OE_Restrict ){
1011 Token tFrom;
1012 Expr *pRaise;
1013
1014 tFrom.z = zFrom;
1015 tFrom.n = nFrom;
1016 pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
1017 if( pRaise ){
1018 pRaise->affinity = OE_Abort;
1019 }
1020 pSelect = sqlite3SelectNew(pParse,
1021 sqlite3ExprListAppend(pParse, 0, pRaise),
1022 sqlite3SrcListAppend(db, 0, &tFrom, 0),
1023 pWhere,
1024 0, 0, 0, 0, 0, 0
1025 );
1026 pWhere = 0;
1027 }
1028
drh1f638ce2009-09-24 13:48:10 +00001029 /* In the current implementation, pTab->dbMem==0 for all tables except
1030 ** for temporary tables used to describe subqueries. And temporary
1031 ** tables do not have foreign key constraints. Hence, pTab->dbMem
1032 ** should always be 0 there.
1033 */
dan29c7f9c2009-09-22 15:53:47 +00001034 enableLookaside = db->lookaside.bEnabled;
drh46803c32009-09-24 14:27:33 +00001035 db->lookaside.bEnabled = 0;
dan29c7f9c2009-09-22 15:53:47 +00001036
dan29c7f9c2009-09-22 15:53:47 +00001037 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
1038 sizeof(Trigger) + /* struct Trigger */
1039 sizeof(TriggerStep) + /* Single step in trigger program */
1040 nFrom + 1 /* Space for pStep->target.z */
1041 );
1042 if( pTrigger ){
1043 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
1044 pStep->target.z = (char *)&pStep[1];
1045 pStep->target.n = nFrom;
1046 memcpy((char *)pStep->target.z, zFrom, nFrom);
1047
1048 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
1049 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
dan9277efa2009-09-28 11:54:21 +00001050 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh788536b2009-09-23 03:01:58 +00001051 if( pWhen ){
1052 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
1053 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
1054 }
dan29c7f9c2009-09-22 15:53:47 +00001055 }
1056
1057 /* Re-enable the lookaside buffer, if it was disabled earlier. */
1058 db->lookaside.bEnabled = enableLookaside;
1059
drh788536b2009-09-23 03:01:58 +00001060 sqlite3ExprDelete(db, pWhere);
1061 sqlite3ExprDelete(db, pWhen);
1062 sqlite3ExprListDelete(db, pList);
dan9277efa2009-09-28 11:54:21 +00001063 sqlite3SelectDelete(db, pSelect);
dan29c7f9c2009-09-22 15:53:47 +00001064 if( db->mallocFailed==1 ){
1065 fkTriggerDelete(db, pTrigger);
1066 return 0;
1067 }
dan1da40a32009-09-19 17:00:31 +00001068
dan9277efa2009-09-28 11:54:21 +00001069 switch( action ){
1070 case OE_Restrict:
1071 pStep->op = TK_SELECT;
1072 break;
1073 case OE_Cascade:
1074 if( !pChanges ){
1075 pStep->op = TK_DELETE;
1076 break;
1077 }
1078 default:
1079 pStep->op = TK_UPDATE;
1080 }
dan1da40a32009-09-19 17:00:31 +00001081 pStep->pTrig = pTrigger;
1082 pTrigger->pSchema = pTab->pSchema;
1083 pTrigger->pTabSchema = pTab->pSchema;
dan8099ce62009-09-23 08:43:35 +00001084 pFKey->apTrigger[iAction] = pTrigger;
1085 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
dan1da40a32009-09-19 17:00:31 +00001086 }
1087
1088 return pTrigger;
1089}
1090
dan1da40a32009-09-19 17:00:31 +00001091/*
1092** This function is called when deleting or updating a row to implement
1093** any required CASCADE, SET NULL or SET DEFAULT actions.
1094*/
1095void sqlite3FkActions(
1096 Parse *pParse, /* Parse context */
1097 Table *pTab, /* Table being updated or deleted from */
1098 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
1099 int regOld /* Address of array containing old row */
1100){
1101 /* If foreign-key support is enabled, iterate through all FKs that
1102 ** refer to table pTab. If there is an action associated with the FK
1103 ** for this operation (either update or delete), invoke the associated
1104 ** trigger sub-program. */
1105 if( pParse->db->flags&SQLITE_ForeignKeys ){
1106 FKey *pFKey; /* Iterator variable */
dan432cc5b2009-09-26 17:51:48 +00001107 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
dan1da40a32009-09-19 17:00:31 +00001108 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
1109 if( pAction ){
1110 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
1111 }
1112 }
1113 }
1114}
1115
dan75cbd982009-09-21 16:06:03 +00001116#endif /* ifndef SQLITE_OMIT_TRIGGER */
1117
dan1da40a32009-09-19 17:00:31 +00001118/*
1119** Free all memory associated with foreign key definitions attached to
1120** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
1121** hash table.
1122*/
1123void sqlite3FkDelete(Table *pTab){
1124 FKey *pFKey; /* Iterator variable */
1125 FKey *pNext; /* Copy of pFKey->pNextFrom */
1126
1127 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
1128
1129 /* Remove the FK from the fkeyHash hash table. */
1130 if( pFKey->pPrevTo ){
1131 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
1132 }else{
1133 void *data = (void *)pFKey->pNextTo;
1134 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
1135 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
1136 }
1137 if( pFKey->pNextTo ){
1138 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
1139 }
1140
1141 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +00001142#ifndef SQLITE_OMIT_TRIGGER
dan8099ce62009-09-23 08:43:35 +00001143 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
1144 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
dan75cbd982009-09-21 16:06:03 +00001145#endif
dan1da40a32009-09-19 17:00:31 +00001146
1147 /* Delete the memory allocated for the FK structure. */
1148 pNext = pFKey->pNextFrom;
1149 sqlite3DbFree(pTab->dbMem, pFKey);
1150 }
1151}
dan75cbd982009-09-21 16:06:03 +00001152#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */