blob: acac588cf445b76338413ee105e79e699e49b395 [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
dan1da40a32009-09-19 17:00:31 +0000244 ** index matches those columns. */
245 int i, j;
246 for(i=0; i<nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000247 char *zIdxCol = pParent->aCol[pIdx->aiColumn[i]].zName;
dan1da40a32009-09-19 17:00:31 +0000248 for(j=0; j<nCol; j++){
249 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
250 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
251 break;
252 }
253 }
254 if( j==nCol ) break;
255 }
256 if( i==nCol ) break; /* pIdx is usable */
257 }
258 }
259 }
260
261 if( pParse && !pIdx ){
262 sqlite3ErrorMsg(pParse, "foreign key mismatch");
263 sqlite3DbFree(pParse->db, aiCol);
264 return 1;
265 }
266
267 *ppIdx = pIdx;
268 return 0;
269}
270
dan8099ce62009-09-23 08:43:35 +0000271/*
danbd747832009-09-25 12:00:01 +0000272** This function is called when a row is inserted into or deleted from the
273** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
274** on the child table of pFKey, this function is invoked twice for each row
dan8099ce62009-09-23 08:43:35 +0000275** affected - once to "delete" the old row, and then again to "insert" the
276** new row.
277**
278** Each time it is called, this function generates VDBE code to locate the
279** row in the parent table that corresponds to the row being inserted into
280** or deleted from the child table. If the parent row can be found, no
281** special action is taken. Otherwise, if the parent row can *not* be
282** found in the parent table:
283**
284** Operation | FK type | Action taken
285** --------------------------------------------------------------------------
danbd747832009-09-25 12:00:01 +0000286** INSERT immediate Increment the "immediate constraint counter".
287**
288** DELETE immediate Decrement the "immediate constraint counter".
dan8099ce62009-09-23 08:43:35 +0000289**
290** INSERT deferred Increment the "deferred constraint counter".
291**
292** DELETE deferred Decrement the "deferred constraint counter".
293**
danbd747832009-09-25 12:00:01 +0000294** These operations are identified in the comment at the top of this file
295** (fkey.c) as "I.1" and "D.1".
dan8099ce62009-09-23 08:43:35 +0000296*/
297static void fkLookupParent(
dan1da40a32009-09-19 17:00:31 +0000298 Parse *pParse, /* Parse context */
299 int iDb, /* Index of database housing pTab */
dan8099ce62009-09-23 08:43:35 +0000300 Table *pTab, /* Parent table of FK pFKey */
301 Index *pIdx, /* Unique index on parent key columns in pTab */
302 FKey *pFKey, /* Foreign key constraint */
303 int *aiCol, /* Map from parent key columns to child table columns */
304 int regData, /* Address of array containing child table row */
dan32b09f22009-09-23 17:29:59 +0000305 int nIncr /* Increment constraint counter by this */
dan1da40a32009-09-19 17:00:31 +0000306){
dan8099ce62009-09-23 08:43:35 +0000307 int i; /* Iterator variable */
308 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
309 int iCur = pParse->nTab - 1; /* Cursor number to use */
310 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
dan1da40a32009-09-19 17:00:31 +0000311
dan8099ce62009-09-23 08:43:35 +0000312 /* Check if any of the key columns in the child table row are
dan1da40a32009-09-19 17:00:31 +0000313 ** NULL. If any are, then the constraint is satisfied. No need
dan8099ce62009-09-23 08:43:35 +0000314 ** to search for a matching row in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000315 for(i=0; i<pFKey->nCol; i++){
dan36062642009-09-21 18:56:23 +0000316 int iReg = aiCol[i] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000317 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
318 }
319
320 if( pIdx==0 ){
dan8099ce62009-09-23 08:43:35 +0000321 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
322 ** column of the parent table (table pTab). */
dan140026b2009-09-24 18:19:41 +0000323 int regTemp = sqlite3GetTempReg(pParse);
324
325 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
326 ** apply the affinity of the parent key). If this fails, then there
327 ** is no matching parent key. Before using MustBeInt, make a copy of
328 ** the value. Otherwise, the value inserted into the child key column
329 ** will have INTEGER affinity applied to it, which may not be correct. */
330 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
331 sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
dan1da40a32009-09-19 17:00:31 +0000332 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
dan140026b2009-09-24 18:19:41 +0000333 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
dan1da40a32009-09-19 17:00:31 +0000334 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
335 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
dan140026b2009-09-24 18:19:41 +0000336 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-4);
337 sqlite3ReleaseTempReg(pParse, regTemp);
338 assert(
339 sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v)-4)->opcode==OP_MustBeInt
340 );
dan1da40a32009-09-19 17:00:31 +0000341 }else{
dan140026b2009-09-24 18:19:41 +0000342 int nCol = pFKey->nCol;
343 int regTemp = sqlite3GetTempRange(pParse, nCol);
dan1da40a32009-09-19 17:00:31 +0000344 int regRec = sqlite3GetTempReg(pParse);
345 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
346
347 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
348 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
dan140026b2009-09-24 18:19:41 +0000349 for(i=0; i<nCol; i++){
350 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
dan1da40a32009-09-19 17:00:31 +0000351 }
dan140026b2009-09-24 18:19:41 +0000352 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
353 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
dan1da40a32009-09-19 17:00:31 +0000354 sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
355 sqlite3ReleaseTempReg(pParse, regRec);
dan140026b2009-09-24 18:19:41 +0000356 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
dan1da40a32009-09-19 17:00:31 +0000357 }
358
dan32b09f22009-09-23 17:29:59 +0000359 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
360 /* Special case: If this is an INSERT statement that will insert exactly
361 ** one row into the table, raise a constraint immediately instead of
362 ** incrementing a counter. This is necessary as the VM code is being
363 ** generated for will not open a statement transaction. */
364 assert( nIncr==1 );
dan1da40a32009-09-19 17:00:31 +0000365 sqlite3HaltConstraint(
366 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
367 );
dan32b09f22009-09-23 17:29:59 +0000368 }else{
369 if( nIncr>0 && pFKey->isDeferred==0 ){
370 sqlite3ParseToplevel(pParse)->mayAbort = 1;
371 }
372 sqlite3VdbeAddOp2(v, OP_FkCounter, nIncr, pFKey->isDeferred);
dan1da40a32009-09-19 17:00:31 +0000373 }
374
375 sqlite3VdbeResolveLabel(v, iOk);
376}
377
dan8099ce62009-09-23 08:43:35 +0000378/*
379** This function is called to generate code executed when a row is deleted
380** from the parent table of foreign key constraint pFKey and, if pFKey is
381** deferred, when a row is inserted into the same table. When generating
382** code for an SQL UPDATE operation, this function may be called twice -
383** once to "delete" the old row and once to "insert" the new row.
384**
385** The code generated by this function scans through the rows in the child
386** table that correspond to the parent table row being deleted or inserted.
387** For each child row found, one of the following actions is taken:
388**
389** Operation | FK type | Action taken
390** --------------------------------------------------------------------------
danbd747832009-09-25 12:00:01 +0000391** DELETE immediate Increment the "immediate constraint counter".
392** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
393** throw a "foreign key constraint failed" exception.
394**
395** INSERT immediate Decrement the "immediate constraint counter".
dan8099ce62009-09-23 08:43:35 +0000396**
397** DELETE deferred Increment the "deferred constraint counter".
398** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
399** throw a "foreign key constraint failed" exception.
400**
401** INSERT deferred Decrement the "deferred constraint counter".
402**
danbd747832009-09-25 12:00:01 +0000403** These operations are identified in the comment at the top of this file
404** (fkey.c) as "I.2" and "D.2".
dan8099ce62009-09-23 08:43:35 +0000405*/
406static void fkScanChildren(
dan1da40a32009-09-19 17:00:31 +0000407 Parse *pParse, /* Parse context */
408 SrcList *pSrc, /* SrcList containing the table to scan */
409 Index *pIdx, /* Foreign key index */
410 FKey *pFKey, /* Foreign key relationship */
dan8099ce62009-09-23 08:43:35 +0000411 int *aiCol, /* Map from pIdx cols to child table cols */
dan1da40a32009-09-19 17:00:31 +0000412 int regData, /* Referenced table data starts here */
413 int nIncr /* Amount to increment deferred counter by */
414){
415 sqlite3 *db = pParse->db; /* Database handle */
416 int i; /* Iterator variable */
417 Expr *pWhere = 0; /* WHERE clause to scan with */
418 NameContext sNameContext; /* Context used to resolve WHERE clause */
419 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
420
danbd747832009-09-25 12:00:01 +0000421 /* Create an Expr object representing an SQL expression like:
422 **
423 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
424 **
425 ** The collation sequence used for the comparison should be that of
426 ** the parent key columns. The affinity of the parent key column should
427 ** be applied to each child key value before the comparison takes place.
428 */
dan1da40a32009-09-19 17:00:31 +0000429 for(i=0; i<pFKey->nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000430 Expr *pLeft; /* Value from parent table row */
431 Expr *pRight; /* Column ref to child table */
dan1da40a32009-09-19 17:00:31 +0000432 Expr *pEq; /* Expression (pLeft = pRight) */
dan8099ce62009-09-23 08:43:35 +0000433 int iCol; /* Index of column in child table */
434 const char *zCol; /* Name of column in child table */
dan1da40a32009-09-19 17:00:31 +0000435
436 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
437 if( pLeft ){
danbd747832009-09-25 12:00:01 +0000438 /* Set the collation sequence and affinity of the LHS of each TK_EQ
439 ** expression to the parent key column defaults. */
dan140026b2009-09-24 18:19:41 +0000440 if( pIdx ){
441 int iCol = pIdx->aiColumn[i];
442 Column *pCol = &pIdx->pTable->aCol[iCol];
443 pLeft->iTable = regData+iCol+1;
444 pLeft->affinity = pCol->affinity;
445 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
446 }else{
447 pLeft->iTable = regData;
448 pLeft->affinity = SQLITE_AFF_INTEGER;
449 }
dan1da40a32009-09-19 17:00:31 +0000450 }
451 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000452 assert( iCol>=0 );
453 zCol = pFKey->pFrom->aCol[iCol].zName;
dan1da40a32009-09-19 17:00:31 +0000454 pRight = sqlite3Expr(db, TK_ID, zCol);
455 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
456 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
457 }
458
459 /* Resolve the references in the WHERE clause. */
460 memset(&sNameContext, 0, sizeof(NameContext));
461 sNameContext.pSrcList = pSrc;
462 sNameContext.pParse = pParse;
463 sqlite3ResolveExprNames(&sNameContext, pWhere);
464
465 /* Create VDBE to loop through the entries in pSrc that match the WHERE
466 ** clause. If the constraint is not deferred, throw an exception for
467 ** each row found. Otherwise, for deferred constraints, increment the
468 ** deferred constraint counter by nIncr for each row selected. */
469 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
dan32b09f22009-09-23 17:29:59 +0000470 if( nIncr==0 ){
danbd747832009-09-25 12:00:01 +0000471 /* Special case: A RESTRICT Action. Throw an error immediately if one
472 ** of these is encountered. */
dan1da40a32009-09-19 17:00:31 +0000473 sqlite3HaltConstraint(
474 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
475 );
dan32b09f22009-09-23 17:29:59 +0000476 }else{
477 if( nIncr>0 && pFKey->isDeferred==0 ){
478 sqlite3ParseToplevel(pParse)->mayAbort = 1;
479 }
480 sqlite3VdbeAddOp2(pParse->pVdbe, OP_FkCounter, nIncr, pFKey->isDeferred);
dan1da40a32009-09-19 17:00:31 +0000481 }
danf59c5ca2009-09-22 16:55:38 +0000482 if( pWInfo ){
483 sqlite3WhereEnd(pWInfo);
484 }
dan1da40a32009-09-19 17:00:31 +0000485
486 /* Clean up the WHERE clause constructed above. */
487 sqlite3ExprDelete(db, pWhere);
488}
489
490/*
491** This function returns a pointer to the head of a linked list of FK
dan8099ce62009-09-23 08:43:35 +0000492** constraints for which table pTab is the parent table. For example,
dan1da40a32009-09-19 17:00:31 +0000493** given the following schema:
494**
495** CREATE TABLE t1(a PRIMARY KEY);
496** CREATE TABLE t2(b REFERENCES t1(a);
497**
498** Calling this function with table "t1" as an argument returns a pointer
499** to the FKey structure representing the foreign key constraint on table
500** "t2". Calling this function with "t2" as the argument would return a
dan8099ce62009-09-23 08:43:35 +0000501** NULL pointer (as there are no FK constraints for which t2 is the parent
502** table).
dan1da40a32009-09-19 17:00:31 +0000503*/
504static FKey *fkRefering(Table *pTab){
505 int nName = sqlite3Strlen30(pTab->zName);
506 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
507}
508
dan8099ce62009-09-23 08:43:35 +0000509/*
510** The second argument is a Trigger structure allocated by the
511** fkActionTrigger() routine. This function deletes the Trigger structure
512** and all of its sub-components.
513**
514** The Trigger structure or any of its sub-components may be allocated from
515** the lookaside buffer belonging to database handle dbMem.
516*/
dan75cbd982009-09-21 16:06:03 +0000517static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
518 if( p ){
519 TriggerStep *pStep = p->step_list;
520 sqlite3ExprDelete(dbMem, pStep->pWhere);
521 sqlite3ExprListDelete(dbMem, pStep->pExprList);
drh788536b2009-09-23 03:01:58 +0000522 sqlite3ExprDelete(dbMem, p->pWhen);
dan75cbd982009-09-21 16:06:03 +0000523 sqlite3DbFree(dbMem, p);
524 }
525}
526
dan8099ce62009-09-23 08:43:35 +0000527/*
528** This function is called when inserting, deleting or updating a row of
529** table pTab to generate VDBE code to perform foreign key constraint
530** processing for the operation.
531**
532** For a DELETE operation, parameter regOld is passed the index of the
533** first register in an array of (pTab->nCol+1) registers containing the
534** rowid of the row being deleted, followed by each of the column values
535** of the row being deleted, from left to right. Parameter regNew is passed
536** zero in this case.
537**
538** For an UPDATE operation, regOld is the first in an array of (pTab->nCol+1)
539** registers containing the old rowid and column values of the row being
540** updated, and regNew is the first in an array of the same size containing
541** the corresponding new values. Parameter pChanges is passed the list of
542** columns being updated by the statement.
543**
544** For an INSERT operation, regOld is passed zero and regNew is passed the
545** first register of an array of (pTab->nCol+1) registers containing the new
546** row data.
547**
548** If an error occurs, an error message is left in the pParse structure.
549*/
dan1da40a32009-09-19 17:00:31 +0000550void sqlite3FkCheck(
551 Parse *pParse, /* Parse context */
552 Table *pTab, /* Row is being deleted from this table */
553 ExprList *pChanges, /* Changed columns if this is an UPDATE */
554 int regOld, /* Previous row data is stored here */
555 int regNew /* New row data is stored here */
556){
557 sqlite3 *db = pParse->db; /* Database handle */
558 Vdbe *v; /* VM to write code to */
559 FKey *pFKey; /* Used to iterate through FKs */
560 int iDb; /* Index of database containing pTab */
561 const char *zDb; /* Name of database containing pTab */
562
563 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
564 || (!pChanges && !regOld && regNew) /* INSERT operation */
565 || (!pChanges && regOld && !regNew) /* DELETE operation */
566 );
567
568 /* If foreign-keys are disabled, this function is a no-op. */
569 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
570
571 v = sqlite3GetVdbe(pParse);
572 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
573 zDb = db->aDb[iDb].zName;
574
dan8099ce62009-09-23 08:43:35 +0000575 /* Loop through all the foreign key constraints for which pTab is the
576 ** child table (the table that the foreign key definition is part of). */
dan1da40a32009-09-19 17:00:31 +0000577 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan8099ce62009-09-23 08:43:35 +0000578 Table *pTo; /* Parent table of foreign key pFKey */
dan1da40a32009-09-19 17:00:31 +0000579 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000580 int *aiFree = 0;
581 int *aiCol;
582 int iCol;
583 int i;
dan1da40a32009-09-19 17:00:31 +0000584
dan8099ce62009-09-23 08:43:35 +0000585 /* Find the parent table of this foreign key. Also find a unique index
586 ** on the parent key columns in the parent table. If either of these
587 ** schema items cannot be located, set an error in pParse and return
588 ** early. */
dan1da40a32009-09-19 17:00:31 +0000589 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
dan36062642009-09-21 18:56:23 +0000590 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return;
591 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000592
593 /* If the key does not overlap with the pChanges list, skip this FK. */
594 if( pChanges ){
595 /* TODO */
596 }
597
dan36062642009-09-21 18:56:23 +0000598 if( aiFree ){
599 aiCol = aiFree;
600 }else{
601 iCol = pFKey->aCol[0].iFrom;
602 aiCol = &iCol;
603 }
604 for(i=0; i<pFKey->nCol; i++){
605 if( aiCol[i]==pTab->iPKey ){
606 aiCol[i] = -1;
607 }
608 }
609
dan8099ce62009-09-23 08:43:35 +0000610 /* Take a shared-cache advisory read-lock on the parent table. Allocate
611 ** a cursor to use to search the unique index on the parent key columns
612 ** in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000613 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
614 pParse->nTab++;
615
dan32b09f22009-09-23 17:29:59 +0000616 if( regOld!=0 ){
617 /* A row is being removed from the child table. Search for the parent.
618 ** If the parent does not exist, removing the child row resolves an
619 ** outstanding foreign key constraint violation. */
dan8099ce62009-09-23 08:43:35 +0000620 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
dan1da40a32009-09-19 17:00:31 +0000621 }
622 if( regNew!=0 ){
dan32b09f22009-09-23 17:29:59 +0000623 /* A row is being added to the child table. If a parent row cannot
624 ** be found, adding the child row has violated the FK constraint. */
dan8099ce62009-09-23 08:43:35 +0000625 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
dan1da40a32009-09-19 17:00:31 +0000626 }
627
dan36062642009-09-21 18:56:23 +0000628 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000629 }
630
631 /* Loop through all the foreign key constraints that refer to this table */
632 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
633 int iGoto; /* Address of OP_Goto instruction */
634 Index *pIdx = 0; /* Foreign key index for pFKey */
635 SrcList *pSrc;
636 int *aiCol = 0;
637
dan32b09f22009-09-23 17:29:59 +0000638 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
639 assert( regOld==0 && regNew!=0 );
640 /* Inserting a single row into a parent table cannot cause an immediate
641 ** foreign key violation. So do nothing in this case. */
642 return;
dan1da40a32009-09-19 17:00:31 +0000643 }
644
645 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
646 assert( aiCol || pFKey->nCol==1 );
647
dan8099ce62009-09-23 08:43:35 +0000648 /* Check if this update statement has modified any of the child key
649 ** columns for this foreign key constraint. If it has not, there is
650 ** no need to search the child table for rows in violation. This is
dan1da40a32009-09-19 17:00:31 +0000651 ** just an optimization. Things would work fine without this check. */
652 if( pChanges ){
653 /* TODO */
654 }
655
656 /* Create a SrcList structure containing a single table (the table
657 ** the foreign key that refers to this table is attached to). This
658 ** is required for the sqlite3WhereXXX() interface. */
659 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000660 if( pSrc ){
661 pSrc->a->pTab = pFKey->pFrom;
662 pSrc->a->pTab->nRef++;
663 pSrc->a->iCursor = pParse->nTab++;
664
665 /* If this is an UPDATE, and none of the columns associated with this
dan8099ce62009-09-23 08:43:35 +0000666 ** FK have been modified, do not scan the child table. Unlike the
667 ** compile-time test implemented above, this is not just an
danf59c5ca2009-09-22 16:55:38 +0000668 ** optimization. It is required so that immediate foreign keys do not
669 ** throw exceptions when the user executes a statement like:
670 **
671 ** UPDATE refd_table SET refd_column = refd_column
672 */
673 if( pChanges ){
674 int i;
675 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
676 for(i=0; i<pFKey->nCol; i++){
677 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
678 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
679 }
680 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
dan1da40a32009-09-19 17:00:31 +0000681 }
danf59c5ca2009-09-22 16:55:38 +0000682
dan32b09f22009-09-23 17:29:59 +0000683 if( regNew!=0 ){
dan8099ce62009-09-23 08:43:35 +0000684 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
danf59c5ca2009-09-22 16:55:38 +0000685 }
686 if( regOld!=0 ){
687 /* If there is a RESTRICT action configured for the current operation
dan8099ce62009-09-23 08:43:35 +0000688 ** on the parent table of this FK, then throw an exception
danf59c5ca2009-09-22 16:55:38 +0000689 ** immediately if the FK constraint is violated, even if this is a
690 ** deferred trigger. That's what RESTRICT means. To defer checking
691 ** the constraint, the FK should specify NO ACTION (represented
692 ** using OE_None). NO ACTION is the default. */
dan8099ce62009-09-23 08:43:35 +0000693 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
694 pFKey->aAction[pChanges!=0]!=OE_Restrict
danf59c5ca2009-09-22 16:55:38 +0000695 );
696 }
697
698 if( pChanges ){
699 sqlite3VdbeJumpHere(v, iGoto);
700 }
701 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000702 }
dan1da40a32009-09-19 17:00:31 +0000703 sqlite3DbFree(db, aiCol);
704 }
705}
706
707#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
708
709/*
710** This function is called before generating code to update or delete a
711** row contained in table pTab. If the operation is an update, then
712** pChanges is a pointer to the list of columns to modify. If this is a
713** delete, then pChanges is NULL.
714*/
715u32 sqlite3FkOldmask(
716 Parse *pParse, /* Parse context */
717 Table *pTab, /* Table being modified */
718 ExprList *pChanges /* Non-NULL for UPDATE operations */
719){
720 u32 mask = 0;
721 if( pParse->db->flags&SQLITE_ForeignKeys ){
722 FKey *p;
723 int i;
724 for(p=pTab->pFKey; p; p=p->pNextFrom){
dan32b09f22009-09-23 17:29:59 +0000725 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
dan1da40a32009-09-19 17:00:31 +0000726 }
727 for(p=fkRefering(pTab); p; p=p->pNextTo){
728 Index *pIdx = 0;
729 locateFkeyIndex(0, pTab, p, &pIdx, 0);
730 if( pIdx ){
731 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
732 }
733 }
734 }
735 return mask;
736}
737
738/*
739** This function is called before generating code to update or delete a
740** row contained in table pTab. If the operation is an update, then
741** pChanges is a pointer to the list of columns to modify. If this is a
742** delete, then pChanges is NULL.
743**
744** If any foreign key processing will be required, this function returns
745** true. If there is no foreign key related processing, this function
746** returns false.
747*/
748int sqlite3FkRequired(
749 Parse *pParse, /* Parse context */
750 Table *pTab, /* Table being modified */
751 ExprList *pChanges /* Non-NULL for UPDATE operations */
752){
753 if( pParse->db->flags&SQLITE_ForeignKeys ){
dan32b09f22009-09-23 17:29:59 +0000754 if( fkRefering(pTab) || pTab->pFKey ) return 1;
dan1da40a32009-09-19 17:00:31 +0000755 }
756 return 0;
757}
758
dan8099ce62009-09-23 08:43:35 +0000759/*
760** This function is called when an UPDATE or DELETE operation is being
761** compiled on table pTab, which is the parent table of foreign-key pFKey.
762** If the current operation is an UPDATE, then the pChanges parameter is
763** passed a pointer to the list of columns being modified. If it is a
764** DELETE, pChanges is passed a NULL pointer.
765**
766** It returns a pointer to a Trigger structure containing a trigger
767** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
768** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
769** returned (these actions require no special handling by the triggers
770** sub-system, code for them is created by fkScanChildren()).
771**
772** For example, if pFKey is the foreign key and pTab is table "p" in
773** the following schema:
774**
775** CREATE TABLE p(pk PRIMARY KEY);
776** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
777**
778** then the returned trigger structure is equivalent to:
779**
780** CREATE TRIGGER ... DELETE ON p BEGIN
781** DELETE FROM c WHERE ck = old.pk;
782** END;
783**
784** The returned pointer is cached as part of the foreign key object. It
785** is eventually freed along with the rest of the foreign key object by
786** sqlite3FkDelete().
787*/
dan1da40a32009-09-19 17:00:31 +0000788static Trigger *fkActionTrigger(
dan8099ce62009-09-23 08:43:35 +0000789 Parse *pParse, /* Parse context */
dan1da40a32009-09-19 17:00:31 +0000790 Table *pTab, /* Table being updated or deleted from */
791 FKey *pFKey, /* Foreign key to get action for */
792 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
793){
794 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000795 int action; /* One of OE_None, OE_Cascade etc. */
796 Trigger *pTrigger; /* Trigger definition to return */
dan8099ce62009-09-23 08:43:35 +0000797 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
dan1da40a32009-09-19 17:00:31 +0000798
dan8099ce62009-09-23 08:43:35 +0000799 action = pFKey->aAction[iAction];
800 pTrigger = pFKey->apTrigger[iAction];
dan1da40a32009-09-19 17:00:31 +0000801
802 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
803 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
804
805 if( action>OE_Restrict && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000806 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan8099ce62009-09-23 08:43:35 +0000807 char const *zFrom; /* Name of child table */
dan1da40a32009-09-19 17:00:31 +0000808 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000809 Index *pIdx = 0; /* Parent key index for this FK */
810 int *aiCol = 0; /* child table cols -> parent key cols */
811 TriggerStep *pStep; /* First (only) step of trigger program */
812 Expr *pWhere = 0; /* WHERE clause of trigger step */
813 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
814 int i; /* Iterator variable */
drh788536b2009-09-23 03:01:58 +0000815 Expr *pWhen = 0; /* WHEN clause for the trigger */
dan1da40a32009-09-19 17:00:31 +0000816
817 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
818 assert( aiCol || pFKey->nCol==1 );
819
dan1da40a32009-09-19 17:00:31 +0000820 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000821 Token tOld = { "old", 3 }; /* Literal "old" token */
822 Token tNew = { "new", 3 }; /* Literal "new" token */
dan8099ce62009-09-23 08:43:35 +0000823 Token tFromCol; /* Name of column in child table */
824 Token tToCol; /* Name of column in parent table */
825 int iFromCol; /* Idx of column in child table */
dan29c7f9c2009-09-22 15:53:47 +0000826 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000827
828 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000829 assert( iFromCol>=0 );
dan1da40a32009-09-19 17:00:31 +0000830 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
dana8f0bf62009-09-23 12:06:52 +0000831 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
dan1da40a32009-09-19 17:00:31 +0000832
833 tToCol.n = sqlite3Strlen30(tToCol.z);
834 tFromCol.n = sqlite3Strlen30(tFromCol.z);
835
836 /* Create the expression "zFromCol = OLD.zToCol" */
837 pEq = sqlite3PExpr(pParse, TK_EQ,
838 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
839 sqlite3PExpr(pParse, TK_DOT,
840 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
841 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
842 , 0)
843 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000844 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000845
drh788536b2009-09-23 03:01:58 +0000846 /* For ON UPDATE, construct the next term of the WHEN clause.
847 ** The final WHEN clause will be like this:
848 **
849 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
850 */
851 if( pChanges ){
852 pEq = sqlite3PExpr(pParse, TK_IS,
853 sqlite3PExpr(pParse, TK_DOT,
854 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
855 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
856 0),
857 sqlite3PExpr(pParse, TK_DOT,
858 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
859 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
860 0),
861 0);
862 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
863 }
864
dan1da40a32009-09-19 17:00:31 +0000865 if( action!=OE_Cascade || pChanges ){
866 Expr *pNew;
867 if( action==OE_Cascade ){
868 pNew = sqlite3PExpr(pParse, TK_DOT,
869 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
870 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
871 , 0);
872 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000873 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000874 if( pDflt ){
875 pNew = sqlite3ExprDup(db, pDflt, 0);
876 }else{
877 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
878 }
879 }else{
880 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
881 }
882 pList = sqlite3ExprListAppend(pParse, pList, pNew);
883 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
884 }
885 }
dan29c7f9c2009-09-22 15:53:47 +0000886 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +0000887
drh1f638ce2009-09-24 13:48:10 +0000888 /* In the current implementation, pTab->dbMem==0 for all tables except
889 ** for temporary tables used to describe subqueries. And temporary
890 ** tables do not have foreign key constraints. Hence, pTab->dbMem
891 ** should always be 0 there.
892 */
dan29c7f9c2009-09-22 15:53:47 +0000893 enableLookaside = db->lookaside.bEnabled;
drh46803c32009-09-24 14:27:33 +0000894 db->lookaside.bEnabled = 0;
dan29c7f9c2009-09-22 15:53:47 +0000895
896 zFrom = pFKey->pFrom->zName;
897 nFrom = sqlite3Strlen30(zFrom);
898 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
899 sizeof(Trigger) + /* struct Trigger */
900 sizeof(TriggerStep) + /* Single step in trigger program */
901 nFrom + 1 /* Space for pStep->target.z */
902 );
903 if( pTrigger ){
904 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
905 pStep->target.z = (char *)&pStep[1];
906 pStep->target.n = nFrom;
907 memcpy((char *)pStep->target.z, zFrom, nFrom);
908
909 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
910 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
drh788536b2009-09-23 03:01:58 +0000911 if( pWhen ){
912 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
913 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
914 }
dan29c7f9c2009-09-22 15:53:47 +0000915 }
916
917 /* Re-enable the lookaside buffer, if it was disabled earlier. */
918 db->lookaside.bEnabled = enableLookaside;
919
drh788536b2009-09-23 03:01:58 +0000920 sqlite3ExprDelete(db, pWhere);
921 sqlite3ExprDelete(db, pWhen);
922 sqlite3ExprListDelete(db, pList);
dan29c7f9c2009-09-22 15:53:47 +0000923 if( db->mallocFailed==1 ){
924 fkTriggerDelete(db, pTrigger);
925 return 0;
926 }
dan1da40a32009-09-19 17:00:31 +0000927
928 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
929 pStep->pTrig = pTrigger;
930 pTrigger->pSchema = pTab->pSchema;
931 pTrigger->pTabSchema = pTab->pSchema;
dan8099ce62009-09-23 08:43:35 +0000932 pFKey->apTrigger[iAction] = pTrigger;
933 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
dan1da40a32009-09-19 17:00:31 +0000934 }
935
936 return pTrigger;
937}
938
dan1da40a32009-09-19 17:00:31 +0000939/*
940** This function is called when deleting or updating a row to implement
941** any required CASCADE, SET NULL or SET DEFAULT actions.
942*/
943void sqlite3FkActions(
944 Parse *pParse, /* Parse context */
945 Table *pTab, /* Table being updated or deleted from */
946 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
947 int regOld /* Address of array containing old row */
948){
949 /* If foreign-key support is enabled, iterate through all FKs that
950 ** refer to table pTab. If there is an action associated with the FK
951 ** for this operation (either update or delete), invoke the associated
952 ** trigger sub-program. */
953 if( pParse->db->flags&SQLITE_ForeignKeys ){
954 FKey *pFKey; /* Iterator variable */
955 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
956 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
957 if( pAction ){
958 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
959 }
960 }
961 }
962}
963
dan75cbd982009-09-21 16:06:03 +0000964#endif /* ifndef SQLITE_OMIT_TRIGGER */
965
dan1da40a32009-09-19 17:00:31 +0000966/*
967** Free all memory associated with foreign key definitions attached to
968** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
969** hash table.
970*/
971void sqlite3FkDelete(Table *pTab){
972 FKey *pFKey; /* Iterator variable */
973 FKey *pNext; /* Copy of pFKey->pNextFrom */
974
975 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
976
977 /* Remove the FK from the fkeyHash hash table. */
978 if( pFKey->pPrevTo ){
979 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
980 }else{
981 void *data = (void *)pFKey->pNextTo;
982 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
983 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
984 }
985 if( pFKey->pNextTo ){
986 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
987 }
988
989 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000990#ifndef SQLITE_OMIT_TRIGGER
dan8099ce62009-09-23 08:43:35 +0000991 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
992 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
dan75cbd982009-09-21 16:06:03 +0000993#endif
dan1da40a32009-09-19 17:00:31 +0000994
995 /* Delete the memory allocated for the FK structure. */
996 pNext = pFKey->pNextFrom;
997 sqlite3DbFree(pTab->dbMem, pFKey);
998 }
999}
dan75cbd982009-09-21 16:06:03 +00001000#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */