blob: f81c6a8e238ae2331d6be288c23ace869483bca0 [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**
86** TODO: How should dropping a table be handled? How should renaming a
87** table be handled?
dan8099ce62009-09-23 08:43:35 +000088**
89**
dan1da40a32009-09-19 17:00:31 +000090** Query API Notes
91** ---------------
92**
93** Before coding an UPDATE or DELETE row operation, the code-generator
94** for those two operations needs to know whether or not the operation
95** requires any FK processing and, if so, which columns of the original
96** row are required by the FK processing VDBE code (i.e. if FKs were
97** implemented using triggers, which of the old.* columns would be
98** accessed). No information is required by the code-generator before
dan8099ce62009-09-23 08:43:35 +000099** coding an INSERT operation. The functions used by the UPDATE/DELETE
100** generation code to query for this information are:
dan1da40a32009-09-19 17:00:31 +0000101**
dan8099ce62009-09-23 08:43:35 +0000102** sqlite3FkRequired() - Test to see if FK processing is required.
103** sqlite3FkOldmask() - Query for the set of required old.* columns.
104**
105**
106** Externally accessible module functions
107** --------------------------------------
108**
109** sqlite3FkCheck() - Check for foreign key violations.
110** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
111** sqlite3FkDelete() - Delete an FKey structure.
dan1da40a32009-09-19 17:00:31 +0000112*/
113
114/*
115** VDBE Calling Convention
116** -----------------------
117**
118** Example:
119**
120** For the following INSERT statement:
121**
122** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
123** INSERT INTO t1 VALUES(1, 2, 3.1);
124**
125** Register (x): 2 (type integer)
126** Register (x+1): 1 (type integer)
127** Register (x+2): NULL (type NULL)
128** Register (x+3): 3.1 (type real)
129*/
130
131/*
dan8099ce62009-09-23 08:43:35 +0000132** A foreign key constraint requires that the key columns in the parent
dan1da40a32009-09-19 17:00:31 +0000133** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
dan8099ce62009-09-23 08:43:35 +0000134** Given that pParent is the parent table for foreign key constraint pFKey,
135** search the schema a unique index on the parent key columns.
dan1da40a32009-09-19 17:00:31 +0000136**
dan8099ce62009-09-23 08:43:35 +0000137** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
138** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
139** is set to point to the unique index.
140**
141** If the parent key consists of a single column (the foreign key constraint
142** is not a composite foreign key), output variable *paiCol is set to NULL.
143** Otherwise, it is set to point to an allocated array of size N, where
144** N is the number of columns in the parent key. The first element of the
145** array is the index of the child table column that is mapped by the FK
146** constraint to the parent table column stored in the left-most column
147** of index *ppIdx. The second element of the array is the index of the
148** child table column that corresponds to the second left-most column of
149** *ppIdx, and so on.
150**
151** If the required index cannot be found, either because:
152**
153** 1) The named parent key columns do not exist, or
154**
155** 2) The named parent key columns do exist, but are not subject to a
156** UNIQUE or PRIMARY KEY constraint, or
157**
158** 3) No parent key columns were provided explicitly as part of the
159** foreign key definition, and the parent table does not have a
160** PRIMARY KEY, or
161**
162** 4) No parent key columns were provided explicitly as part of the
163** foreign key definition, and the PRIMARY KEY of the parent table
164** consists of a a different number of columns to the child key in
165** the child table.
166**
167** then non-zero is returned, and a "foreign key mismatch" error loaded
168** into pParse. If an OOM error occurs, non-zero is returned and the
169** pParse->db->mallocFailed flag is set.
dan1da40a32009-09-19 17:00:31 +0000170*/
171static int locateFkeyIndex(
172 Parse *pParse, /* Parse context to store any error in */
dan8099ce62009-09-23 08:43:35 +0000173 Table *pParent, /* Parent table of FK constraint pFKey */
dan1da40a32009-09-19 17:00:31 +0000174 FKey *pFKey, /* Foreign key to find index for */
dan8099ce62009-09-23 08:43:35 +0000175 Index **ppIdx, /* OUT: Unique index on parent table */
dan1da40a32009-09-19 17:00:31 +0000176 int **paiCol /* OUT: Map of index columns in pFKey */
177){
dan8099ce62009-09-23 08:43:35 +0000178 Index *pIdx = 0; /* Value to return via *ppIdx */
179 int *aiCol = 0; /* Value to return via *paiCol */
180 int nCol = pFKey->nCol; /* Number of columns in parent key */
181 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
dan1da40a32009-09-19 17:00:31 +0000182
183 /* The caller is responsible for zeroing output parameters. */
184 assert( ppIdx && *ppIdx==0 );
185 assert( !paiCol || *paiCol==0 );
186
187 /* If this is a non-composite (single column) foreign key, check if it
dan8099ce62009-09-23 08:43:35 +0000188 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
dan1da40a32009-09-19 17:00:31 +0000189 ** and *paiCol set to zero and return early.
190 **
191 ** Otherwise, for a composite foreign key (more than one column), allocate
192 ** space for the aiCol array (returned via output parameter *paiCol).
193 ** Non-composite foreign keys do not require the aiCol array.
194 */
195 if( nCol==1 ){
196 /* The FK maps to the IPK if any of the following are true:
197 **
dand981d442009-09-23 13:59:17 +0000198 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
199 ** mapped to the primary key of table pParent, or
200 ** 2) The FK is explicitly mapped to a column declared as INTEGER
dan1da40a32009-09-19 17:00:31 +0000201 ** PRIMARY KEY.
202 */
dan8099ce62009-09-23 08:43:35 +0000203 if( pParent->iPKey>=0 ){
204 if( !zKey ) return 0;
205 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
dan1da40a32009-09-19 17:00:31 +0000206 }
207 }else if( paiCol ){
208 assert( nCol>1 );
209 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
210 if( !aiCol ) return 1;
211 *paiCol = aiCol;
212 }
213
dan8099ce62009-09-23 08:43:35 +0000214 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
dan1da40a32009-09-19 17:00:31 +0000215 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
216 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
217 ** of columns. If each indexed column corresponds to a foreign key
218 ** column of pFKey, then this index is a winner. */
219
dan8099ce62009-09-23 08:43:35 +0000220 if( zKey==0 ){
221 /* If zKey is NULL, then this foreign key is implicitly mapped to
222 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
dan1da40a32009-09-19 17:00:31 +0000223 ** identified by the test (Index.autoIndex==2). */
224 if( pIdx->autoIndex==2 ){
dan8a2fff72009-09-23 18:07:22 +0000225 if( aiCol ){
226 int i;
227 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
228 }
dan1da40a32009-09-19 17:00:31 +0000229 break;
230 }
231 }else{
dan8099ce62009-09-23 08:43:35 +0000232 /* If zKey is non-NULL, then this foreign key was declared to
233 ** map to an explicit list of columns in table pParent. Check if this
dan1da40a32009-09-19 17:00:31 +0000234 ** index matches those columns. */
235 int i, j;
236 for(i=0; i<nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000237 char *zIdxCol = pParent->aCol[pIdx->aiColumn[i]].zName;
dan1da40a32009-09-19 17:00:31 +0000238 for(j=0; j<nCol; j++){
239 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
240 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
241 break;
242 }
243 }
244 if( j==nCol ) break;
245 }
246 if( i==nCol ) break; /* pIdx is usable */
247 }
248 }
249 }
250
251 if( pParse && !pIdx ){
252 sqlite3ErrorMsg(pParse, "foreign key mismatch");
253 sqlite3DbFree(pParse->db, aiCol);
254 return 1;
255 }
256
257 *ppIdx = pIdx;
258 return 0;
259}
260
dan8099ce62009-09-23 08:43:35 +0000261/*
262** This function is called when a row is inserted into the child table of
263** foreign key constraint pFKey and, if pFKey is deferred, when a row is
264** deleted from the child table of pFKey. If an SQL UPDATE is executed on
265** the child table of pFKey, this function is invoked twice for each row
266** affected - once to "delete" the old row, and then again to "insert" the
267** new row.
268**
269** Each time it is called, this function generates VDBE code to locate the
270** row in the parent table that corresponds to the row being inserted into
271** or deleted from the child table. If the parent row can be found, no
272** special action is taken. Otherwise, if the parent row can *not* be
273** found in the parent table:
274**
275** Operation | FK type | Action taken
276** --------------------------------------------------------------------------
277** INSERT immediate Throw a "foreign key constraint failed" exception.
278**
279** INSERT deferred Increment the "deferred constraint counter".
280**
281** DELETE deferred Decrement the "deferred constraint counter".
282**
283** This function is never called for a delete on the child table of an
284** immediate foreign key constraint. These operations are identified in
285** the comment at the top of this file (fkey.c) as "I.1" and "D.1".
286*/
287static void fkLookupParent(
dan1da40a32009-09-19 17:00:31 +0000288 Parse *pParse, /* Parse context */
289 int iDb, /* Index of database housing pTab */
dan8099ce62009-09-23 08:43:35 +0000290 Table *pTab, /* Parent table of FK pFKey */
291 Index *pIdx, /* Unique index on parent key columns in pTab */
292 FKey *pFKey, /* Foreign key constraint */
293 int *aiCol, /* Map from parent key columns to child table columns */
294 int regData, /* Address of array containing child table row */
dan32b09f22009-09-23 17:29:59 +0000295 int nIncr /* Increment constraint counter by this */
dan1da40a32009-09-19 17:00:31 +0000296){
dan8099ce62009-09-23 08:43:35 +0000297 int i; /* Iterator variable */
298 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
299 int iCur = pParse->nTab - 1; /* Cursor number to use */
300 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
dan1da40a32009-09-19 17:00:31 +0000301
dan8099ce62009-09-23 08:43:35 +0000302 /* Check if any of the key columns in the child table row are
dan1da40a32009-09-19 17:00:31 +0000303 ** NULL. If any are, then the constraint is satisfied. No need
dan8099ce62009-09-23 08:43:35 +0000304 ** to search for a matching row in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000305 for(i=0; i<pFKey->nCol; i++){
dan36062642009-09-21 18:56:23 +0000306 int iReg = aiCol[i] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000307 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
308 }
309
310 if( pIdx==0 ){
dan8099ce62009-09-23 08:43:35 +0000311 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
312 ** column of the parent table (table pTab). */
dan140026b2009-09-24 18:19:41 +0000313 int regTemp = sqlite3GetTempReg(pParse);
314
315 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
316 ** apply the affinity of the parent key). If this fails, then there
317 ** is no matching parent key. Before using MustBeInt, make a copy of
318 ** the value. Otherwise, the value inserted into the child key column
319 ** will have INTEGER affinity applied to it, which may not be correct. */
320 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
321 sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
dan1da40a32009-09-19 17:00:31 +0000322 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
dan140026b2009-09-24 18:19:41 +0000323 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
dan1da40a32009-09-19 17:00:31 +0000324 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
325 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
dan140026b2009-09-24 18:19:41 +0000326 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-4);
327 sqlite3ReleaseTempReg(pParse, regTemp);
328 assert(
329 sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v)-4)->opcode==OP_MustBeInt
330 );
dan1da40a32009-09-19 17:00:31 +0000331 }else{
dan140026b2009-09-24 18:19:41 +0000332 int nCol = pFKey->nCol;
333 int regTemp = sqlite3GetTempRange(pParse, nCol);
dan1da40a32009-09-19 17:00:31 +0000334 int regRec = sqlite3GetTempReg(pParse);
335 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
336
337 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
338 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
dan140026b2009-09-24 18:19:41 +0000339 for(i=0; i<nCol; i++){
340 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
dan1da40a32009-09-19 17:00:31 +0000341 }
dan140026b2009-09-24 18:19:41 +0000342 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
343 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
dan1da40a32009-09-19 17:00:31 +0000344 sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
345 sqlite3ReleaseTempReg(pParse, regRec);
dan140026b2009-09-24 18:19:41 +0000346 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
dan1da40a32009-09-19 17:00:31 +0000347 }
348
dan32b09f22009-09-23 17:29:59 +0000349 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
350 /* Special case: If this is an INSERT statement that will insert exactly
351 ** one row into the table, raise a constraint immediately instead of
352 ** incrementing a counter. This is necessary as the VM code is being
353 ** generated for will not open a statement transaction. */
354 assert( nIncr==1 );
dan1da40a32009-09-19 17:00:31 +0000355 sqlite3HaltConstraint(
356 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
357 );
dan32b09f22009-09-23 17:29:59 +0000358 }else{
359 if( nIncr>0 && pFKey->isDeferred==0 ){
360 sqlite3ParseToplevel(pParse)->mayAbort = 1;
361 }
362 sqlite3VdbeAddOp2(v, OP_FkCounter, nIncr, pFKey->isDeferred);
dan1da40a32009-09-19 17:00:31 +0000363 }
364
365 sqlite3VdbeResolveLabel(v, iOk);
366}
367
dan8099ce62009-09-23 08:43:35 +0000368/*
369** This function is called to generate code executed when a row is deleted
370** from the parent table of foreign key constraint pFKey and, if pFKey is
371** deferred, when a row is inserted into the same table. When generating
372** code for an SQL UPDATE operation, this function may be called twice -
373** once to "delete" the old row and once to "insert" the new row.
374**
375** The code generated by this function scans through the rows in the child
376** table that correspond to the parent table row being deleted or inserted.
377** For each child row found, one of the following actions is taken:
378**
379** Operation | FK type | Action taken
380** --------------------------------------------------------------------------
381** DELETE immediate Throw a "foreign key constraint failed" exception.
382**
383** DELETE deferred Increment the "deferred constraint counter".
384** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
385** throw a "foreign key constraint failed" exception.
386**
387** INSERT deferred Decrement the "deferred constraint counter".
388**
389** This function is never called for an INSERT operation on the parent table
390** of an immediate foreign key constraint. These operations are identified in
391** the comment at the top of this file (fkey.c) as "I.2" and "D.2".
392*/
393static void fkScanChildren(
dan1da40a32009-09-19 17:00:31 +0000394 Parse *pParse, /* Parse context */
395 SrcList *pSrc, /* SrcList containing the table to scan */
396 Index *pIdx, /* Foreign key index */
397 FKey *pFKey, /* Foreign key relationship */
dan8099ce62009-09-23 08:43:35 +0000398 int *aiCol, /* Map from pIdx cols to child table cols */
dan1da40a32009-09-19 17:00:31 +0000399 int regData, /* Referenced table data starts here */
400 int nIncr /* Amount to increment deferred counter by */
401){
402 sqlite3 *db = pParse->db; /* Database handle */
403 int i; /* Iterator variable */
404 Expr *pWhere = 0; /* WHERE clause to scan with */
405 NameContext sNameContext; /* Context used to resolve WHERE clause */
406 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
407
408 for(i=0; i<pFKey->nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000409 Expr *pLeft; /* Value from parent table row */
410 Expr *pRight; /* Column ref to child table */
dan1da40a32009-09-19 17:00:31 +0000411 Expr *pEq; /* Expression (pLeft = pRight) */
dan8099ce62009-09-23 08:43:35 +0000412 int iCol; /* Index of column in child table */
413 const char *zCol; /* Name of column in child table */
dan1da40a32009-09-19 17:00:31 +0000414
415 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
416 if( pLeft ){
dan140026b2009-09-24 18:19:41 +0000417 if( pIdx ){
418 int iCol = pIdx->aiColumn[i];
419 Column *pCol = &pIdx->pTable->aCol[iCol];
420 pLeft->iTable = regData+iCol+1;
421 pLeft->affinity = pCol->affinity;
422 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
423 }else{
424 pLeft->iTable = regData;
425 pLeft->affinity = SQLITE_AFF_INTEGER;
426 }
dan1da40a32009-09-19 17:00:31 +0000427 }
428 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000429 assert( iCol>=0 );
430 zCol = pFKey->pFrom->aCol[iCol].zName;
dan1da40a32009-09-19 17:00:31 +0000431 pRight = sqlite3Expr(db, TK_ID, zCol);
432 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
433 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
434 }
435
436 /* Resolve the references in the WHERE clause. */
437 memset(&sNameContext, 0, sizeof(NameContext));
438 sNameContext.pSrcList = pSrc;
439 sNameContext.pParse = pParse;
440 sqlite3ResolveExprNames(&sNameContext, pWhere);
441
442 /* Create VDBE to loop through the entries in pSrc that match the WHERE
443 ** clause. If the constraint is not deferred, throw an exception for
444 ** each row found. Otherwise, for deferred constraints, increment the
445 ** deferred constraint counter by nIncr for each row selected. */
446 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
dan32b09f22009-09-23 17:29:59 +0000447 if( nIncr==0 ){
448 /* A RESTRICT Action. */
dan1da40a32009-09-19 17:00:31 +0000449 sqlite3HaltConstraint(
450 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
451 );
dan32b09f22009-09-23 17:29:59 +0000452 }else{
453 if( nIncr>0 && pFKey->isDeferred==0 ){
454 sqlite3ParseToplevel(pParse)->mayAbort = 1;
455 }
456 sqlite3VdbeAddOp2(pParse->pVdbe, OP_FkCounter, nIncr, pFKey->isDeferred);
dan1da40a32009-09-19 17:00:31 +0000457 }
danf59c5ca2009-09-22 16:55:38 +0000458 if( pWInfo ){
459 sqlite3WhereEnd(pWInfo);
460 }
dan1da40a32009-09-19 17:00:31 +0000461
462 /* Clean up the WHERE clause constructed above. */
463 sqlite3ExprDelete(db, pWhere);
464}
465
466/*
467** This function returns a pointer to the head of a linked list of FK
dan8099ce62009-09-23 08:43:35 +0000468** constraints for which table pTab is the parent table. For example,
dan1da40a32009-09-19 17:00:31 +0000469** given the following schema:
470**
471** CREATE TABLE t1(a PRIMARY KEY);
472** CREATE TABLE t2(b REFERENCES t1(a);
473**
474** Calling this function with table "t1" as an argument returns a pointer
475** to the FKey structure representing the foreign key constraint on table
476** "t2". Calling this function with "t2" as the argument would return a
dan8099ce62009-09-23 08:43:35 +0000477** NULL pointer (as there are no FK constraints for which t2 is the parent
478** table).
dan1da40a32009-09-19 17:00:31 +0000479*/
480static FKey *fkRefering(Table *pTab){
481 int nName = sqlite3Strlen30(pTab->zName);
482 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
483}
484
dan8099ce62009-09-23 08:43:35 +0000485/*
486** The second argument is a Trigger structure allocated by the
487** fkActionTrigger() routine. This function deletes the Trigger structure
488** and all of its sub-components.
489**
490** The Trigger structure or any of its sub-components may be allocated from
491** the lookaside buffer belonging to database handle dbMem.
492*/
dan75cbd982009-09-21 16:06:03 +0000493static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
494 if( p ){
495 TriggerStep *pStep = p->step_list;
496 sqlite3ExprDelete(dbMem, pStep->pWhere);
497 sqlite3ExprListDelete(dbMem, pStep->pExprList);
drh788536b2009-09-23 03:01:58 +0000498 sqlite3ExprDelete(dbMem, p->pWhen);
dan75cbd982009-09-21 16:06:03 +0000499 sqlite3DbFree(dbMem, p);
500 }
501}
502
dan8099ce62009-09-23 08:43:35 +0000503/*
504** This function is called when inserting, deleting or updating a row of
505** table pTab to generate VDBE code to perform foreign key constraint
506** processing for the operation.
507**
508** For a DELETE operation, parameter regOld is passed the index of the
509** first register in an array of (pTab->nCol+1) registers containing the
510** rowid of the row being deleted, followed by each of the column values
511** of the row being deleted, from left to right. Parameter regNew is passed
512** zero in this case.
513**
514** For an UPDATE operation, regOld is the first in an array of (pTab->nCol+1)
515** registers containing the old rowid and column values of the row being
516** updated, and regNew is the first in an array of the same size containing
517** the corresponding new values. Parameter pChanges is passed the list of
518** columns being updated by the statement.
519**
520** For an INSERT operation, regOld is passed zero and regNew is passed the
521** first register of an array of (pTab->nCol+1) registers containing the new
522** row data.
523**
524** If an error occurs, an error message is left in the pParse structure.
525*/
dan1da40a32009-09-19 17:00:31 +0000526void sqlite3FkCheck(
527 Parse *pParse, /* Parse context */
528 Table *pTab, /* Row is being deleted from this table */
529 ExprList *pChanges, /* Changed columns if this is an UPDATE */
530 int regOld, /* Previous row data is stored here */
531 int regNew /* New row data is stored here */
532){
533 sqlite3 *db = pParse->db; /* Database handle */
534 Vdbe *v; /* VM to write code to */
535 FKey *pFKey; /* Used to iterate through FKs */
536 int iDb; /* Index of database containing pTab */
537 const char *zDb; /* Name of database containing pTab */
538
539 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
540 || (!pChanges && !regOld && regNew) /* INSERT operation */
541 || (!pChanges && regOld && !regNew) /* DELETE operation */
542 );
543
544 /* If foreign-keys are disabled, this function is a no-op. */
545 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
546
547 v = sqlite3GetVdbe(pParse);
548 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
549 zDb = db->aDb[iDb].zName;
550
dan8099ce62009-09-23 08:43:35 +0000551 /* Loop through all the foreign key constraints for which pTab is the
552 ** child table (the table that the foreign key definition is part of). */
dan1da40a32009-09-19 17:00:31 +0000553 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan8099ce62009-09-23 08:43:35 +0000554 Table *pTo; /* Parent table of foreign key pFKey */
dan1da40a32009-09-19 17:00:31 +0000555 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000556 int *aiFree = 0;
557 int *aiCol;
558 int iCol;
559 int i;
dan1da40a32009-09-19 17:00:31 +0000560
dan8099ce62009-09-23 08:43:35 +0000561 /* Find the parent table of this foreign key. Also find a unique index
562 ** on the parent key columns in the parent table. If either of these
563 ** schema items cannot be located, set an error in pParse and return
564 ** early. */
dan1da40a32009-09-19 17:00:31 +0000565 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
dan36062642009-09-21 18:56:23 +0000566 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return;
567 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000568
569 /* If the key does not overlap with the pChanges list, skip this FK. */
570 if( pChanges ){
571 /* TODO */
572 }
573
dan36062642009-09-21 18:56:23 +0000574 if( aiFree ){
575 aiCol = aiFree;
576 }else{
577 iCol = pFKey->aCol[0].iFrom;
578 aiCol = &iCol;
579 }
580 for(i=0; i<pFKey->nCol; i++){
581 if( aiCol[i]==pTab->iPKey ){
582 aiCol[i] = -1;
583 }
584 }
585
dan8099ce62009-09-23 08:43:35 +0000586 /* Take a shared-cache advisory read-lock on the parent table. Allocate
587 ** a cursor to use to search the unique index on the parent key columns
588 ** in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000589 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
590 pParse->nTab++;
591
dan32b09f22009-09-23 17:29:59 +0000592 if( regOld!=0 ){
593 /* A row is being removed from the child table. Search for the parent.
594 ** If the parent does not exist, removing the child row resolves an
595 ** outstanding foreign key constraint violation. */
dan8099ce62009-09-23 08:43:35 +0000596 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
dan1da40a32009-09-19 17:00:31 +0000597 }
598 if( regNew!=0 ){
dan32b09f22009-09-23 17:29:59 +0000599 /* A row is being added to the child table. If a parent row cannot
600 ** be found, adding the child row has violated the FK constraint. */
dan8099ce62009-09-23 08:43:35 +0000601 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
dan1da40a32009-09-19 17:00:31 +0000602 }
603
dan36062642009-09-21 18:56:23 +0000604 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000605 }
606
607 /* Loop through all the foreign key constraints that refer to this table */
608 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
609 int iGoto; /* Address of OP_Goto instruction */
610 Index *pIdx = 0; /* Foreign key index for pFKey */
611 SrcList *pSrc;
612 int *aiCol = 0;
613
dan32b09f22009-09-23 17:29:59 +0000614 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
615 assert( regOld==0 && regNew!=0 );
616 /* Inserting a single row into a parent table cannot cause an immediate
617 ** foreign key violation. So do nothing in this case. */
618 return;
dan1da40a32009-09-19 17:00:31 +0000619 }
620
621 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
622 assert( aiCol || pFKey->nCol==1 );
623
dan8099ce62009-09-23 08:43:35 +0000624 /* Check if this update statement has modified any of the child key
625 ** columns for this foreign key constraint. If it has not, there is
626 ** no need to search the child table for rows in violation. This is
dan1da40a32009-09-19 17:00:31 +0000627 ** just an optimization. Things would work fine without this check. */
628 if( pChanges ){
629 /* TODO */
630 }
631
632 /* Create a SrcList structure containing a single table (the table
633 ** the foreign key that refers to this table is attached to). This
634 ** is required for the sqlite3WhereXXX() interface. */
635 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000636 if( pSrc ){
637 pSrc->a->pTab = pFKey->pFrom;
638 pSrc->a->pTab->nRef++;
639 pSrc->a->iCursor = pParse->nTab++;
640
641 /* If this is an UPDATE, and none of the columns associated with this
dan8099ce62009-09-23 08:43:35 +0000642 ** FK have been modified, do not scan the child table. Unlike the
643 ** compile-time test implemented above, this is not just an
danf59c5ca2009-09-22 16:55:38 +0000644 ** optimization. It is required so that immediate foreign keys do not
645 ** throw exceptions when the user executes a statement like:
646 **
647 ** UPDATE refd_table SET refd_column = refd_column
648 */
649 if( pChanges ){
650 int i;
651 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
652 for(i=0; i<pFKey->nCol; i++){
653 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
654 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
655 }
656 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
dan1da40a32009-09-19 17:00:31 +0000657 }
danf59c5ca2009-09-22 16:55:38 +0000658
dan32b09f22009-09-23 17:29:59 +0000659 if( regNew!=0 ){
dan8099ce62009-09-23 08:43:35 +0000660 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
danf59c5ca2009-09-22 16:55:38 +0000661 }
662 if( regOld!=0 ){
663 /* If there is a RESTRICT action configured for the current operation
dan8099ce62009-09-23 08:43:35 +0000664 ** on the parent table of this FK, then throw an exception
danf59c5ca2009-09-22 16:55:38 +0000665 ** immediately if the FK constraint is violated, even if this is a
666 ** deferred trigger. That's what RESTRICT means. To defer checking
667 ** the constraint, the FK should specify NO ACTION (represented
668 ** using OE_None). NO ACTION is the default. */
dan8099ce62009-09-23 08:43:35 +0000669 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
670 pFKey->aAction[pChanges!=0]!=OE_Restrict
danf59c5ca2009-09-22 16:55:38 +0000671 );
672 }
673
674 if( pChanges ){
675 sqlite3VdbeJumpHere(v, iGoto);
676 }
677 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000678 }
dan1da40a32009-09-19 17:00:31 +0000679 sqlite3DbFree(db, aiCol);
680 }
681}
682
683#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
684
685/*
686** This function is called before generating code to update or delete a
687** row contained in table pTab. If the operation is an update, then
688** pChanges is a pointer to the list of columns to modify. If this is a
689** delete, then pChanges is NULL.
690*/
691u32 sqlite3FkOldmask(
692 Parse *pParse, /* Parse context */
693 Table *pTab, /* Table being modified */
694 ExprList *pChanges /* Non-NULL for UPDATE operations */
695){
696 u32 mask = 0;
697 if( pParse->db->flags&SQLITE_ForeignKeys ){
698 FKey *p;
699 int i;
700 for(p=pTab->pFKey; p; p=p->pNextFrom){
dan32b09f22009-09-23 17:29:59 +0000701 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
dan1da40a32009-09-19 17:00:31 +0000702 }
703 for(p=fkRefering(pTab); p; p=p->pNextTo){
704 Index *pIdx = 0;
705 locateFkeyIndex(0, pTab, p, &pIdx, 0);
706 if( pIdx ){
707 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
708 }
709 }
710 }
711 return mask;
712}
713
714/*
715** This function is called before generating code to update or delete a
716** row contained in table pTab. If the operation is an update, then
717** pChanges is a pointer to the list of columns to modify. If this is a
718** delete, then pChanges is NULL.
719**
720** If any foreign key processing will be required, this function returns
721** true. If there is no foreign key related processing, this function
722** returns false.
723*/
724int sqlite3FkRequired(
725 Parse *pParse, /* Parse context */
726 Table *pTab, /* Table being modified */
727 ExprList *pChanges /* Non-NULL for UPDATE operations */
728){
729 if( pParse->db->flags&SQLITE_ForeignKeys ){
dan32b09f22009-09-23 17:29:59 +0000730 if( fkRefering(pTab) || pTab->pFKey ) return 1;
dan1da40a32009-09-19 17:00:31 +0000731 }
732 return 0;
733}
734
dan8099ce62009-09-23 08:43:35 +0000735/*
736** This function is called when an UPDATE or DELETE operation is being
737** compiled on table pTab, which is the parent table of foreign-key pFKey.
738** If the current operation is an UPDATE, then the pChanges parameter is
739** passed a pointer to the list of columns being modified. If it is a
740** DELETE, pChanges is passed a NULL pointer.
741**
742** It returns a pointer to a Trigger structure containing a trigger
743** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
744** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
745** returned (these actions require no special handling by the triggers
746** sub-system, code for them is created by fkScanChildren()).
747**
748** For example, if pFKey is the foreign key and pTab is table "p" in
749** the following schema:
750**
751** CREATE TABLE p(pk PRIMARY KEY);
752** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
753**
754** then the returned trigger structure is equivalent to:
755**
756** CREATE TRIGGER ... DELETE ON p BEGIN
757** DELETE FROM c WHERE ck = old.pk;
758** END;
759**
760** The returned pointer is cached as part of the foreign key object. It
761** is eventually freed along with the rest of the foreign key object by
762** sqlite3FkDelete().
763*/
dan1da40a32009-09-19 17:00:31 +0000764static Trigger *fkActionTrigger(
dan8099ce62009-09-23 08:43:35 +0000765 Parse *pParse, /* Parse context */
dan1da40a32009-09-19 17:00:31 +0000766 Table *pTab, /* Table being updated or deleted from */
767 FKey *pFKey, /* Foreign key to get action for */
768 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
769){
770 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000771 int action; /* One of OE_None, OE_Cascade etc. */
772 Trigger *pTrigger; /* Trigger definition to return */
dan8099ce62009-09-23 08:43:35 +0000773 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
dan1da40a32009-09-19 17:00:31 +0000774
dan8099ce62009-09-23 08:43:35 +0000775 action = pFKey->aAction[iAction];
776 pTrigger = pFKey->apTrigger[iAction];
dan1da40a32009-09-19 17:00:31 +0000777
778 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
779 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
780
781 if( action>OE_Restrict && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000782 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan8099ce62009-09-23 08:43:35 +0000783 char const *zFrom; /* Name of child table */
dan1da40a32009-09-19 17:00:31 +0000784 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000785 Index *pIdx = 0; /* Parent key index for this FK */
786 int *aiCol = 0; /* child table cols -> parent key cols */
787 TriggerStep *pStep; /* First (only) step of trigger program */
788 Expr *pWhere = 0; /* WHERE clause of trigger step */
789 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
790 int i; /* Iterator variable */
drh788536b2009-09-23 03:01:58 +0000791 Expr *pWhen = 0; /* WHEN clause for the trigger */
dan1da40a32009-09-19 17:00:31 +0000792
793 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
794 assert( aiCol || pFKey->nCol==1 );
795
dan1da40a32009-09-19 17:00:31 +0000796 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000797 Token tOld = { "old", 3 }; /* Literal "old" token */
798 Token tNew = { "new", 3 }; /* Literal "new" token */
dan8099ce62009-09-23 08:43:35 +0000799 Token tFromCol; /* Name of column in child table */
800 Token tToCol; /* Name of column in parent table */
801 int iFromCol; /* Idx of column in child table */
dan29c7f9c2009-09-22 15:53:47 +0000802 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000803
804 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000805 assert( iFromCol>=0 );
dan1da40a32009-09-19 17:00:31 +0000806 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
dana8f0bf62009-09-23 12:06:52 +0000807 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
dan1da40a32009-09-19 17:00:31 +0000808
809 tToCol.n = sqlite3Strlen30(tToCol.z);
810 tFromCol.n = sqlite3Strlen30(tFromCol.z);
811
812 /* Create the expression "zFromCol = OLD.zToCol" */
813 pEq = sqlite3PExpr(pParse, TK_EQ,
814 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
815 sqlite3PExpr(pParse, TK_DOT,
816 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
817 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
818 , 0)
819 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000820 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000821
drh788536b2009-09-23 03:01:58 +0000822 /* For ON UPDATE, construct the next term of the WHEN clause.
823 ** The final WHEN clause will be like this:
824 **
825 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
826 */
827 if( pChanges ){
828 pEq = sqlite3PExpr(pParse, TK_IS,
829 sqlite3PExpr(pParse, TK_DOT,
830 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
831 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
832 0),
833 sqlite3PExpr(pParse, TK_DOT,
834 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
835 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
836 0),
837 0);
838 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
839 }
840
dan1da40a32009-09-19 17:00:31 +0000841 if( action!=OE_Cascade || pChanges ){
842 Expr *pNew;
843 if( action==OE_Cascade ){
844 pNew = sqlite3PExpr(pParse, TK_DOT,
845 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
846 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
847 , 0);
848 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000849 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000850 if( pDflt ){
851 pNew = sqlite3ExprDup(db, pDflt, 0);
852 }else{
853 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
854 }
855 }else{
856 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
857 }
858 pList = sqlite3ExprListAppend(pParse, pList, pNew);
859 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
860 }
861 }
dan29c7f9c2009-09-22 15:53:47 +0000862 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +0000863
drh1f638ce2009-09-24 13:48:10 +0000864 /* In the current implementation, pTab->dbMem==0 for all tables except
865 ** for temporary tables used to describe subqueries. And temporary
866 ** tables do not have foreign key constraints. Hence, pTab->dbMem
867 ** should always be 0 there.
868 */
dan29c7f9c2009-09-22 15:53:47 +0000869 enableLookaside = db->lookaside.bEnabled;
drh46803c32009-09-24 14:27:33 +0000870 db->lookaside.bEnabled = 0;
dan29c7f9c2009-09-22 15:53:47 +0000871
872 zFrom = pFKey->pFrom->zName;
873 nFrom = sqlite3Strlen30(zFrom);
874 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
875 sizeof(Trigger) + /* struct Trigger */
876 sizeof(TriggerStep) + /* Single step in trigger program */
877 nFrom + 1 /* Space for pStep->target.z */
878 );
879 if( pTrigger ){
880 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
881 pStep->target.z = (char *)&pStep[1];
882 pStep->target.n = nFrom;
883 memcpy((char *)pStep->target.z, zFrom, nFrom);
884
885 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
886 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
drh788536b2009-09-23 03:01:58 +0000887 if( pWhen ){
888 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
889 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
890 }
dan29c7f9c2009-09-22 15:53:47 +0000891 }
892
893 /* Re-enable the lookaside buffer, if it was disabled earlier. */
894 db->lookaside.bEnabled = enableLookaside;
895
drh788536b2009-09-23 03:01:58 +0000896 sqlite3ExprDelete(db, pWhere);
897 sqlite3ExprDelete(db, pWhen);
898 sqlite3ExprListDelete(db, pList);
dan29c7f9c2009-09-22 15:53:47 +0000899 if( db->mallocFailed==1 ){
900 fkTriggerDelete(db, pTrigger);
901 return 0;
902 }
dan1da40a32009-09-19 17:00:31 +0000903
904 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
905 pStep->pTrig = pTrigger;
906 pTrigger->pSchema = pTab->pSchema;
907 pTrigger->pTabSchema = pTab->pSchema;
dan8099ce62009-09-23 08:43:35 +0000908 pFKey->apTrigger[iAction] = pTrigger;
909 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
dan1da40a32009-09-19 17:00:31 +0000910 }
911
912 return pTrigger;
913}
914
dan1da40a32009-09-19 17:00:31 +0000915/*
916** This function is called when deleting or updating a row to implement
917** any required CASCADE, SET NULL or SET DEFAULT actions.
918*/
919void sqlite3FkActions(
920 Parse *pParse, /* Parse context */
921 Table *pTab, /* Table being updated or deleted from */
922 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
923 int regOld /* Address of array containing old row */
924){
925 /* If foreign-key support is enabled, iterate through all FKs that
926 ** refer to table pTab. If there is an action associated with the FK
927 ** for this operation (either update or delete), invoke the associated
928 ** trigger sub-program. */
929 if( pParse->db->flags&SQLITE_ForeignKeys ){
930 FKey *pFKey; /* Iterator variable */
931 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
932 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
933 if( pAction ){
934 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
935 }
936 }
937 }
938}
939
dan75cbd982009-09-21 16:06:03 +0000940#endif /* ifndef SQLITE_OMIT_TRIGGER */
941
dan1da40a32009-09-19 17:00:31 +0000942/*
943** Free all memory associated with foreign key definitions attached to
944** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
945** hash table.
946*/
947void sqlite3FkDelete(Table *pTab){
948 FKey *pFKey; /* Iterator variable */
949 FKey *pNext; /* Copy of pFKey->pNextFrom */
950
951 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
952
953 /* Remove the FK from the fkeyHash hash table. */
954 if( pFKey->pPrevTo ){
955 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
956 }else{
957 void *data = (void *)pFKey->pNextTo;
958 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
959 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
960 }
961 if( pFKey->pNextTo ){
962 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
963 }
964
965 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000966#ifndef SQLITE_OMIT_TRIGGER
dan8099ce62009-09-23 08:43:35 +0000967 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
968 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
dan75cbd982009-09-21 16:06:03 +0000969#endif
dan1da40a32009-09-19 17:00:31 +0000970
971 /* Delete the memory allocated for the FK structure. */
972 pNext = pFKey->pNextFrom;
973 sqlite3DbFree(pTab->dbMem, pFKey);
974 }
975}
dan75cbd982009-09-21 16:06:03 +0000976#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */