blob: fef04b7ace8f6ae58cdd8171fdf7a38c55c54495 [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.
24** If an immediate foreign key constraint is violated, an OP_Halt is
25** executed and the current statement transaction rolled back. If a
26** 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
52** the parent table for a match. If none is found, throw an
dan1da40a32009-09-19 17:00:31 +000053** exception for an immediate FK, or increment the counter for a
54** deferred FK.
55**
dan8099ce62009-09-23 08:43:35 +000056** I.2) For each deferred FK for which the table is the parent table,
57** search the child table for rows that correspond to the new
58** row in the parent table. Decrement the counter for each row
dan1da40a32009-09-19 17:00:31 +000059** found (as the constraint is now satisfied).
60**
61** DELETE operations:
62**
dan8099ce62009-09-23 08:43:35 +000063** D.1) For each deferred FK for which the table is the child table,
64** search the parent table for a row that corresponds to the
65** deleted row in the child table. If such a row is not found,
dan1da40a32009-09-19 17:00:31 +000066** decrement the counter.
67**
dan8099ce62009-09-23 08:43:35 +000068** D.2) For each FK for which the table is the parent table, search
69** the child table for rows that correspond to the deleted row
70** in the parent table. For each found, throw an exception for an
dan1da40a32009-09-19 17:00:31 +000071** immediate FK, or increment the counter for a deferred FK.
72**
73** UPDATE operations:
74**
75** An UPDATE command requires that all 4 steps above are taken, but only
76** for FK constraints for which the affected columns are actually
77** modified (values must be compared at runtime).
78**
79** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
80** This simplifies the implementation a bit.
81**
82** For the purposes of immediate FK constraints, the OR REPLACE conflict
83** resolution is considered to delete rows before the new row is inserted.
84** If a delete caused by OR REPLACE violates an FK constraint, an exception
85** is thrown, even if the FK constraint would be satisfied after the new
86** row is inserted.
87**
88** TODO: How should dropping a table be handled? How should renaming a
89** table be handled?
dan8099ce62009-09-23 08:43:35 +000090**
91**
dan1da40a32009-09-19 17:00:31 +000092** Query API Notes
93** ---------------
94**
95** Before coding an UPDATE or DELETE row operation, the code-generator
96** for those two operations needs to know whether or not the operation
97** requires any FK processing and, if so, which columns of the original
98** row are required by the FK processing VDBE code (i.e. if FKs were
99** implemented using triggers, which of the old.* columns would be
100** accessed). No information is required by the code-generator before
dan8099ce62009-09-23 08:43:35 +0000101** coding an INSERT operation. The functions used by the UPDATE/DELETE
102** generation code to query for this information are:
dan1da40a32009-09-19 17:00:31 +0000103**
dan8099ce62009-09-23 08:43:35 +0000104** sqlite3FkRequired() - Test to see if FK processing is required.
105** sqlite3FkOldmask() - Query for the set of required old.* columns.
106**
107**
108** Externally accessible module functions
109** --------------------------------------
110**
111** sqlite3FkCheck() - Check for foreign key violations.
112** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
113** sqlite3FkDelete() - Delete an FKey structure.
dan1da40a32009-09-19 17:00:31 +0000114*/
115
116/*
117** VDBE Calling Convention
118** -----------------------
119**
120** Example:
121**
122** For the following INSERT statement:
123**
124** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
125** INSERT INTO t1 VALUES(1, 2, 3.1);
126**
127** Register (x): 2 (type integer)
128** Register (x+1): 1 (type integer)
129** Register (x+2): NULL (type NULL)
130** Register (x+3): 3.1 (type real)
131*/
132
133/*
dan8099ce62009-09-23 08:43:35 +0000134** A foreign key constraint requires that the key columns in the parent
dan1da40a32009-09-19 17:00:31 +0000135** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
dan8099ce62009-09-23 08:43:35 +0000136** Given that pParent is the parent table for foreign key constraint pFKey,
137** search the schema a unique index on the parent key columns.
dan1da40a32009-09-19 17:00:31 +0000138**
dan8099ce62009-09-23 08:43:35 +0000139** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
140** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
141** is set to point to the unique index.
142**
143** If the parent key consists of a single column (the foreign key constraint
144** is not a composite foreign key), output variable *paiCol is set to NULL.
145** Otherwise, it is set to point to an allocated array of size N, where
146** N is the number of columns in the parent key. The first element of the
147** array is the index of the child table column that is mapped by the FK
148** constraint to the parent table column stored in the left-most column
149** of index *ppIdx. The second element of the array is the index of the
150** child table column that corresponds to the second left-most column of
151** *ppIdx, and so on.
152**
153** If the required index cannot be found, either because:
154**
155** 1) The named parent key columns do not exist, or
156**
157** 2) The named parent key columns do exist, but are not subject to a
158** UNIQUE or PRIMARY KEY constraint, or
159**
160** 3) No parent key columns were provided explicitly as part of the
161** foreign key definition, and the parent table does not have a
162** PRIMARY KEY, or
163**
164** 4) No parent key columns were provided explicitly as part of the
165** foreign key definition, and the PRIMARY KEY of the parent table
166** consists of a a different number of columns to the child key in
167** the child table.
168**
169** then non-zero is returned, and a "foreign key mismatch" error loaded
170** into pParse. If an OOM error occurs, non-zero is returned and the
171** pParse->db->mallocFailed flag is set.
dan1da40a32009-09-19 17:00:31 +0000172*/
173static int locateFkeyIndex(
174 Parse *pParse, /* Parse context to store any error in */
dan8099ce62009-09-23 08:43:35 +0000175 Table *pParent, /* Parent table of FK constraint pFKey */
dan1da40a32009-09-19 17:00:31 +0000176 FKey *pFKey, /* Foreign key to find index for */
dan8099ce62009-09-23 08:43:35 +0000177 Index **ppIdx, /* OUT: Unique index on parent table */
dan1da40a32009-09-19 17:00:31 +0000178 int **paiCol /* OUT: Map of index columns in pFKey */
179){
dan8099ce62009-09-23 08:43:35 +0000180 Index *pIdx = 0; /* Value to return via *ppIdx */
181 int *aiCol = 0; /* Value to return via *paiCol */
182 int nCol = pFKey->nCol; /* Number of columns in parent key */
183 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
dan1da40a32009-09-19 17:00:31 +0000184
185 /* The caller is responsible for zeroing output parameters. */
186 assert( ppIdx && *ppIdx==0 );
187 assert( !paiCol || *paiCol==0 );
188
189 /* If this is a non-composite (single column) foreign key, check if it
dan8099ce62009-09-23 08:43:35 +0000190 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
dan1da40a32009-09-19 17:00:31 +0000191 ** and *paiCol set to zero and return early.
192 **
193 ** Otherwise, for a composite foreign key (more than one column), allocate
194 ** space for the aiCol array (returned via output parameter *paiCol).
195 ** Non-composite foreign keys do not require the aiCol array.
196 */
197 if( nCol==1 ){
198 /* The FK maps to the IPK if any of the following are true:
199 **
200 ** 1) The FK is explicitly mapped to "rowid", "oid" or "_rowid_", or
201 ** 2) There is an explicit INTEGER PRIMARY KEY column and the FK is
dan8099ce62009-09-23 08:43:35 +0000202 ** implicitly mapped to the primary key of table pParent, or
dan1da40a32009-09-19 17:00:31 +0000203 ** 3) The FK is explicitly mapped to a column declared as INTEGER
204 ** PRIMARY KEY.
205 */
dan8099ce62009-09-23 08:43:35 +0000206 if( zKey && sqlite3IsRowid(zKey) ) return 0;
207 if( pParent->iPKey>=0 ){
208 if( !zKey ) return 0;
209 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
dan1da40a32009-09-19 17:00:31 +0000210 }
211 }else if( paiCol ){
212 assert( nCol>1 );
213 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
214 if( !aiCol ) return 1;
215 *paiCol = aiCol;
216 }
217
dan8099ce62009-09-23 08:43:35 +0000218 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
dan1da40a32009-09-19 17:00:31 +0000219 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
220 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
221 ** of columns. If each indexed column corresponds to a foreign key
222 ** column of pFKey, then this index is a winner. */
223
dan8099ce62009-09-23 08:43:35 +0000224 if( zKey==0 ){
225 /* If zKey is NULL, then this foreign key is implicitly mapped to
226 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
dan1da40a32009-09-19 17:00:31 +0000227 ** identified by the test (Index.autoIndex==2). */
228 if( pIdx->autoIndex==2 ){
229 if( aiCol ) memcpy(aiCol, pIdx->aiColumn, sizeof(int)*nCol);
230 break;
231 }
232 }else{
dan8099ce62009-09-23 08:43:35 +0000233 /* If zKey is non-NULL, then this foreign key was declared to
234 ** map to an explicit list of columns in table pParent. Check if this
dan1da40a32009-09-19 17:00:31 +0000235 ** index matches those columns. */
236 int i, j;
237 for(i=0; i<nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000238 char *zIdxCol = pParent->aCol[pIdx->aiColumn[i]].zName;
dan1da40a32009-09-19 17:00:31 +0000239 for(j=0; j<nCol; j++){
240 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
241 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
242 break;
243 }
244 }
245 if( j==nCol ) break;
246 }
247 if( i==nCol ) break; /* pIdx is usable */
248 }
249 }
250 }
251
252 if( pParse && !pIdx ){
253 sqlite3ErrorMsg(pParse, "foreign key mismatch");
254 sqlite3DbFree(pParse->db, aiCol);
255 return 1;
256 }
257
258 *ppIdx = pIdx;
259 return 0;
260}
261
dan8099ce62009-09-23 08:43:35 +0000262/*
263** This function is called when a row is inserted into the child table of
264** foreign key constraint pFKey and, if pFKey is deferred, when a row is
265** deleted from the child table of pFKey. If an SQL UPDATE is executed on
266** the child table of pFKey, this function is invoked twice for each row
267** affected - once to "delete" the old row, and then again to "insert" the
268** new row.
269**
270** Each time it is called, this function generates VDBE code to locate the
271** row in the parent table that corresponds to the row being inserted into
272** or deleted from the child table. If the parent row can be found, no
273** special action is taken. Otherwise, if the parent row can *not* be
274** found in the parent table:
275**
276** Operation | FK type | Action taken
277** --------------------------------------------------------------------------
278** INSERT immediate Throw a "foreign key constraint failed" exception.
279**
280** INSERT deferred Increment the "deferred constraint counter".
281**
282** DELETE deferred Decrement the "deferred constraint counter".
283**
284** This function is never called for a delete on the child table of an
285** immediate foreign key constraint. These operations are identified in
286** the comment at the top of this file (fkey.c) as "I.1" and "D.1".
287*/
288static void fkLookupParent(
dan1da40a32009-09-19 17:00:31 +0000289 Parse *pParse, /* Parse context */
290 int iDb, /* Index of database housing pTab */
dan8099ce62009-09-23 08:43:35 +0000291 Table *pTab, /* Parent table of FK pFKey */
292 Index *pIdx, /* Unique index on parent key columns in pTab */
293 FKey *pFKey, /* Foreign key constraint */
294 int *aiCol, /* Map from parent key columns to child table columns */
295 int regData, /* Address of array containing child table row */
dan1da40a32009-09-19 17:00:31 +0000296 int nIncr /* If deferred FK, increment counter by this */
297){
dan8099ce62009-09-23 08:43:35 +0000298 int i; /* Iterator variable */
299 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
300 int iCur = pParse->nTab - 1; /* Cursor number to use */
301 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
dan1da40a32009-09-19 17:00:31 +0000302
303 assert( pFKey->isDeferred || nIncr==1 );
304
dan8099ce62009-09-23 08:43:35 +0000305 /* Check if any of the key columns in the child table row are
dan1da40a32009-09-19 17:00:31 +0000306 ** NULL. If any are, then the constraint is satisfied. No need
dan8099ce62009-09-23 08:43:35 +0000307 ** to search for a matching row in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000308 for(i=0; i<pFKey->nCol; i++){
dan36062642009-09-21 18:56:23 +0000309 int iReg = aiCol[i] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000310 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
311 }
312
313 if( pIdx==0 ){
dan8099ce62009-09-23 08:43:35 +0000314 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
315 ** column of the parent table (table pTab). */
dan1da40a32009-09-19 17:00:31 +0000316 int iReg = pFKey->aCol[0].iFrom + regData + 1;
317 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
318 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iReg);
319 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
320 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
321 }else{
322 int regRec = sqlite3GetTempReg(pParse);
323 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
324
325 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
326 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
327
dan36062642009-09-21 18:56:23 +0000328 if( pFKey->nCol>1 ){
dan1da40a32009-09-19 17:00:31 +0000329 int nCol = pFKey->nCol;
330 int regTemp = sqlite3GetTempRange(pParse, nCol);
331 for(i=0; i<nCol; i++){
332 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
333 }
334 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
335 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
336 }else{
dan36062642009-09-21 18:56:23 +0000337 int iReg = aiCol[0] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000338 sqlite3VdbeAddOp3(v, OP_MakeRecord, iReg, 1, regRec);
339 sqlite3IndexAffinityStr(v, pIdx);
340 }
341
342 sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
343 sqlite3ReleaseTempReg(pParse, regRec);
344 }
345
346 if( pFKey->isDeferred ){
347 assert( nIncr==1 || nIncr==-1 );
348 sqlite3VdbeAddOp1(v, OP_DeferredCons, nIncr);
349 }else{
350 sqlite3HaltConstraint(
351 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
352 );
353 }
354
355 sqlite3VdbeResolveLabel(v, iOk);
356}
357
dan8099ce62009-09-23 08:43:35 +0000358/*
359** This function is called to generate code executed when a row is deleted
360** from the parent table of foreign key constraint pFKey and, if pFKey is
361** deferred, when a row is inserted into the same table. When generating
362** code for an SQL UPDATE operation, this function may be called twice -
363** once to "delete" the old row and once to "insert" the new row.
364**
365** The code generated by this function scans through the rows in the child
366** table that correspond to the parent table row being deleted or inserted.
367** For each child row found, one of the following actions is taken:
368**
369** Operation | FK type | Action taken
370** --------------------------------------------------------------------------
371** DELETE immediate Throw a "foreign key constraint failed" exception.
372**
373** DELETE deferred Increment the "deferred constraint counter".
374** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
375** throw a "foreign key constraint failed" exception.
376**
377** INSERT deferred Decrement the "deferred constraint counter".
378**
379** This function is never called for an INSERT operation on the parent table
380** of an immediate foreign key constraint. These operations are identified in
381** the comment at the top of this file (fkey.c) as "I.2" and "D.2".
382*/
383static void fkScanChildren(
dan1da40a32009-09-19 17:00:31 +0000384 Parse *pParse, /* Parse context */
385 SrcList *pSrc, /* SrcList containing the table to scan */
386 Index *pIdx, /* Foreign key index */
387 FKey *pFKey, /* Foreign key relationship */
dan8099ce62009-09-23 08:43:35 +0000388 int *aiCol, /* Map from pIdx cols to child table cols */
dan1da40a32009-09-19 17:00:31 +0000389 int regData, /* Referenced table data starts here */
390 int nIncr /* Amount to increment deferred counter by */
391){
392 sqlite3 *db = pParse->db; /* Database handle */
393 int i; /* Iterator variable */
394 Expr *pWhere = 0; /* WHERE clause to scan with */
395 NameContext sNameContext; /* Context used to resolve WHERE clause */
396 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
397
398 for(i=0; i<pFKey->nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000399 Expr *pLeft; /* Value from parent table row */
400 Expr *pRight; /* Column ref to child table */
dan1da40a32009-09-19 17:00:31 +0000401 Expr *pEq; /* Expression (pLeft = pRight) */
dan8099ce62009-09-23 08:43:35 +0000402 int iCol; /* Index of column in child table */
403 const char *zCol; /* Name of column in child table */
dan1da40a32009-09-19 17:00:31 +0000404
405 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
406 if( pLeft ){
407 pLeft->iTable = (pIdx ? (regData+pIdx->aiColumn[i]+1) : regData);
408 }
409 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000410 assert( iCol>=0 );
411 zCol = pFKey->pFrom->aCol[iCol].zName;
dan1da40a32009-09-19 17:00:31 +0000412 pRight = sqlite3Expr(db, TK_ID, zCol);
413 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
414 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
415 }
416
417 /* Resolve the references in the WHERE clause. */
418 memset(&sNameContext, 0, sizeof(NameContext));
419 sNameContext.pSrcList = pSrc;
420 sNameContext.pParse = pParse;
421 sqlite3ResolveExprNames(&sNameContext, pWhere);
422
423 /* Create VDBE to loop through the entries in pSrc that match the WHERE
424 ** clause. If the constraint is not deferred, throw an exception for
425 ** each row found. Otherwise, for deferred constraints, increment the
426 ** deferred constraint counter by nIncr for each row selected. */
427 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
428 if( pFKey->isDeferred && nIncr ){
429 assert( nIncr==1 || nIncr==-1 );
430 sqlite3VdbeAddOp1(pParse->pVdbe, OP_DeferredCons, nIncr);
431 }else{
432 assert( nIncr==1 || nIncr==0 );
433 sqlite3HaltConstraint(
434 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
435 );
436 }
danf59c5ca2009-09-22 16:55:38 +0000437 if( pWInfo ){
438 sqlite3WhereEnd(pWInfo);
439 }
dan1da40a32009-09-19 17:00:31 +0000440
441 /* Clean up the WHERE clause constructed above. */
442 sqlite3ExprDelete(db, pWhere);
443}
444
445/*
446** This function returns a pointer to the head of a linked list of FK
dan8099ce62009-09-23 08:43:35 +0000447** constraints for which table pTab is the parent table. For example,
dan1da40a32009-09-19 17:00:31 +0000448** given the following schema:
449**
450** CREATE TABLE t1(a PRIMARY KEY);
451** CREATE TABLE t2(b REFERENCES t1(a);
452**
453** Calling this function with table "t1" as an argument returns a pointer
454** to the FKey structure representing the foreign key constraint on table
455** "t2". Calling this function with "t2" as the argument would return a
dan8099ce62009-09-23 08:43:35 +0000456** NULL pointer (as there are no FK constraints for which t2 is the parent
457** table).
dan1da40a32009-09-19 17:00:31 +0000458*/
459static FKey *fkRefering(Table *pTab){
460 int nName = sqlite3Strlen30(pTab->zName);
461 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
462}
463
dan8099ce62009-09-23 08:43:35 +0000464/*
465** The second argument is a Trigger structure allocated by the
466** fkActionTrigger() routine. This function deletes the Trigger structure
467** and all of its sub-components.
468**
469** The Trigger structure or any of its sub-components may be allocated from
470** the lookaside buffer belonging to database handle dbMem.
471*/
dan75cbd982009-09-21 16:06:03 +0000472static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
473 if( p ){
474 TriggerStep *pStep = p->step_list;
475 sqlite3ExprDelete(dbMem, pStep->pWhere);
476 sqlite3ExprListDelete(dbMem, pStep->pExprList);
drh788536b2009-09-23 03:01:58 +0000477 sqlite3ExprDelete(dbMem, p->pWhen);
dan75cbd982009-09-21 16:06:03 +0000478 sqlite3DbFree(dbMem, p);
479 }
480}
481
dan8099ce62009-09-23 08:43:35 +0000482/*
483** This function is called when inserting, deleting or updating a row of
484** table pTab to generate VDBE code to perform foreign key constraint
485** processing for the operation.
486**
487** For a DELETE operation, parameter regOld is passed the index of the
488** first register in an array of (pTab->nCol+1) registers containing the
489** rowid of the row being deleted, followed by each of the column values
490** of the row being deleted, from left to right. Parameter regNew is passed
491** zero in this case.
492**
493** For an UPDATE operation, regOld is the first in an array of (pTab->nCol+1)
494** registers containing the old rowid and column values of the row being
495** updated, and regNew is the first in an array of the same size containing
496** the corresponding new values. Parameter pChanges is passed the list of
497** columns being updated by the statement.
498**
499** For an INSERT operation, regOld is passed zero and regNew is passed the
500** first register of an array of (pTab->nCol+1) registers containing the new
501** row data.
502**
503** If an error occurs, an error message is left in the pParse structure.
504*/
dan1da40a32009-09-19 17:00:31 +0000505void sqlite3FkCheck(
506 Parse *pParse, /* Parse context */
507 Table *pTab, /* Row is being deleted from this table */
508 ExprList *pChanges, /* Changed columns if this is an UPDATE */
509 int regOld, /* Previous row data is stored here */
510 int regNew /* New row data is stored here */
511){
512 sqlite3 *db = pParse->db; /* Database handle */
513 Vdbe *v; /* VM to write code to */
514 FKey *pFKey; /* Used to iterate through FKs */
515 int iDb; /* Index of database containing pTab */
516 const char *zDb; /* Name of database containing pTab */
517
518 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
519 || (!pChanges && !regOld && regNew) /* INSERT operation */
520 || (!pChanges && regOld && !regNew) /* DELETE operation */
521 );
522
523 /* If foreign-keys are disabled, this function is a no-op. */
524 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
525
526 v = sqlite3GetVdbe(pParse);
527 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
528 zDb = db->aDb[iDb].zName;
529
dan8099ce62009-09-23 08:43:35 +0000530 /* Loop through all the foreign key constraints for which pTab is the
531 ** child table (the table that the foreign key definition is part of). */
dan1da40a32009-09-19 17:00:31 +0000532 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan8099ce62009-09-23 08:43:35 +0000533 Table *pTo; /* Parent table of foreign key pFKey */
dan1da40a32009-09-19 17:00:31 +0000534 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000535 int *aiFree = 0;
536 int *aiCol;
537 int iCol;
538 int i;
dan1da40a32009-09-19 17:00:31 +0000539
dan8099ce62009-09-23 08:43:35 +0000540 /* If this is a DELETE operation and the foreign key is not deferred,
541 ** nothing to do. A DELETE on the child table cannot cause the FK
542 ** constraint to fail. */
dan1da40a32009-09-19 17:00:31 +0000543 if( pFKey->isDeferred==0 && regNew==0 ) continue;
544
dan8099ce62009-09-23 08:43:35 +0000545 /* Find the parent table of this foreign key. Also find a unique index
546 ** on the parent key columns in the parent table. If either of these
547 ** schema items cannot be located, set an error in pParse and return
548 ** early. */
dan1da40a32009-09-19 17:00:31 +0000549 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
dan36062642009-09-21 18:56:23 +0000550 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return;
551 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000552
553 /* If the key does not overlap with the pChanges list, skip this FK. */
554 if( pChanges ){
555 /* TODO */
556 }
557
dan36062642009-09-21 18:56:23 +0000558 if( aiFree ){
559 aiCol = aiFree;
560 }else{
561 iCol = pFKey->aCol[0].iFrom;
562 aiCol = &iCol;
563 }
564 for(i=0; i<pFKey->nCol; i++){
565 if( aiCol[i]==pTab->iPKey ){
566 aiCol[i] = -1;
567 }
568 }
569
dan8099ce62009-09-23 08:43:35 +0000570 /* Take a shared-cache advisory read-lock on the parent table. Allocate
571 ** a cursor to use to search the unique index on the parent key columns
572 ** in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000573 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
574 pParse->nTab++;
575
576 if( regOld!=0 && pFKey->isDeferred ){
dan8099ce62009-09-23 08:43:35 +0000577 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
dan1da40a32009-09-19 17:00:31 +0000578 }
579 if( regNew!=0 ){
dan8099ce62009-09-23 08:43:35 +0000580 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
dan1da40a32009-09-19 17:00:31 +0000581 }
582
dan36062642009-09-21 18:56:23 +0000583 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000584 }
585
586 /* Loop through all the foreign key constraints that refer to this table */
587 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
588 int iGoto; /* Address of OP_Goto instruction */
589 Index *pIdx = 0; /* Foreign key index for pFKey */
590 SrcList *pSrc;
591 int *aiCol = 0;
592
593 /* For immediate constraints, skip this scan if:
594 **
595 ** 1) this is an INSERT operation, or
596 ** 2) an UPDATE operation and the FK action is a trigger-action, or
597 ** 3) a DELETE operation and the FK action is a trigger-action.
598 **
599 ** A "trigger-action" is one of CASCADE, SET DEFAULT or SET NULL.
600 */
601 if( pFKey->isDeferred==0 ){
602 if( regOld==0 ) continue; /* 1 */
dan8099ce62009-09-23 08:43:35 +0000603 if( regNew!=0 && pFKey->aAction[1]>OE_Restrict ) continue; /* 2 */
604 if( regNew==0 && pFKey->aAction[0]>OE_Restrict ) continue; /* 3 */
dan1da40a32009-09-19 17:00:31 +0000605 }
606
607 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
608 assert( aiCol || pFKey->nCol==1 );
609
dan8099ce62009-09-23 08:43:35 +0000610 /* Check if this update statement has modified any of the child key
611 ** columns for this foreign key constraint. If it has not, there is
612 ** no need to search the child table for rows in violation. This is
dan1da40a32009-09-19 17:00:31 +0000613 ** just an optimization. Things would work fine without this check. */
614 if( pChanges ){
615 /* TODO */
616 }
617
618 /* Create a SrcList structure containing a single table (the table
619 ** the foreign key that refers to this table is attached to). This
620 ** is required for the sqlite3WhereXXX() interface. */
621 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000622 if( pSrc ){
623 pSrc->a->pTab = pFKey->pFrom;
624 pSrc->a->pTab->nRef++;
625 pSrc->a->iCursor = pParse->nTab++;
626
627 /* If this is an UPDATE, and none of the columns associated with this
dan8099ce62009-09-23 08:43:35 +0000628 ** FK have been modified, do not scan the child table. Unlike the
629 ** compile-time test implemented above, this is not just an
danf59c5ca2009-09-22 16:55:38 +0000630 ** optimization. It is required so that immediate foreign keys do not
631 ** throw exceptions when the user executes a statement like:
632 **
633 ** UPDATE refd_table SET refd_column = refd_column
634 */
635 if( pChanges ){
636 int i;
637 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
638 for(i=0; i<pFKey->nCol; i++){
639 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
640 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
641 }
642 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
dan1da40a32009-09-19 17:00:31 +0000643 }
danf59c5ca2009-09-22 16:55:38 +0000644
645 if( regNew!=0 && pFKey->isDeferred ){
dan8099ce62009-09-23 08:43:35 +0000646 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
danf59c5ca2009-09-22 16:55:38 +0000647 }
648 if( regOld!=0 ){
649 /* If there is a RESTRICT action configured for the current operation
dan8099ce62009-09-23 08:43:35 +0000650 ** on the parent table of this FK, then throw an exception
danf59c5ca2009-09-22 16:55:38 +0000651 ** immediately if the FK constraint is violated, even if this is a
652 ** deferred trigger. That's what RESTRICT means. To defer checking
653 ** the constraint, the FK should specify NO ACTION (represented
654 ** using OE_None). NO ACTION is the default. */
dan8099ce62009-09-23 08:43:35 +0000655 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
656 pFKey->aAction[pChanges!=0]!=OE_Restrict
danf59c5ca2009-09-22 16:55:38 +0000657 );
658 }
659
660 if( pChanges ){
661 sqlite3VdbeJumpHere(v, iGoto);
662 }
663 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000664 }
dan1da40a32009-09-19 17:00:31 +0000665 sqlite3DbFree(db, aiCol);
666 }
667}
668
669#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
670
671/*
672** This function is called before generating code to update or delete a
673** row contained in table pTab. If the operation is an update, then
674** pChanges is a pointer to the list of columns to modify. If this is a
675** delete, then pChanges is NULL.
676*/
677u32 sqlite3FkOldmask(
678 Parse *pParse, /* Parse context */
679 Table *pTab, /* Table being modified */
680 ExprList *pChanges /* Non-NULL for UPDATE operations */
681){
682 u32 mask = 0;
683 if( pParse->db->flags&SQLITE_ForeignKeys ){
684 FKey *p;
685 int i;
686 for(p=pTab->pFKey; p; p=p->pNextFrom){
687 if( pChanges || p->isDeferred ){
688 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
689 }
690 }
691 for(p=fkRefering(pTab); p; p=p->pNextTo){
692 Index *pIdx = 0;
693 locateFkeyIndex(0, pTab, p, &pIdx, 0);
694 if( pIdx ){
695 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
696 }
697 }
698 }
699 return mask;
700}
701
702/*
703** This function is called before generating code to update or delete a
704** row contained in table pTab. If the operation is an update, then
705** pChanges is a pointer to the list of columns to modify. If this is a
706** delete, then pChanges is NULL.
707**
708** If any foreign key processing will be required, this function returns
709** true. If there is no foreign key related processing, this function
710** returns false.
711*/
712int sqlite3FkRequired(
713 Parse *pParse, /* Parse context */
714 Table *pTab, /* Table being modified */
715 ExprList *pChanges /* Non-NULL for UPDATE operations */
716){
717 if( pParse->db->flags&SQLITE_ForeignKeys ){
718 FKey *p;
719 for(p=pTab->pFKey; p; p=p->pNextFrom){
720 if( pChanges || p->isDeferred ) return 1;
721 }
722 if( fkRefering(pTab) ) return 1;
723 }
724 return 0;
725}
726
dan8099ce62009-09-23 08:43:35 +0000727/*
728** This function is called when an UPDATE or DELETE operation is being
729** compiled on table pTab, which is the parent table of foreign-key pFKey.
730** If the current operation is an UPDATE, then the pChanges parameter is
731** passed a pointer to the list of columns being modified. If it is a
732** DELETE, pChanges is passed a NULL pointer.
733**
734** It returns a pointer to a Trigger structure containing a trigger
735** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
736** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
737** returned (these actions require no special handling by the triggers
738** sub-system, code for them is created by fkScanChildren()).
739**
740** For example, if pFKey is the foreign key and pTab is table "p" in
741** the following schema:
742**
743** CREATE TABLE p(pk PRIMARY KEY);
744** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
745**
746** then the returned trigger structure is equivalent to:
747**
748** CREATE TRIGGER ... DELETE ON p BEGIN
749** DELETE FROM c WHERE ck = old.pk;
750** END;
751**
752** The returned pointer is cached as part of the foreign key object. It
753** is eventually freed along with the rest of the foreign key object by
754** sqlite3FkDelete().
755*/
dan1da40a32009-09-19 17:00:31 +0000756static Trigger *fkActionTrigger(
dan8099ce62009-09-23 08:43:35 +0000757 Parse *pParse, /* Parse context */
dan1da40a32009-09-19 17:00:31 +0000758 Table *pTab, /* Table being updated or deleted from */
759 FKey *pFKey, /* Foreign key to get action for */
760 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
761){
762 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000763 int action; /* One of OE_None, OE_Cascade etc. */
764 Trigger *pTrigger; /* Trigger definition to return */
dan8099ce62009-09-23 08:43:35 +0000765 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
dan1da40a32009-09-19 17:00:31 +0000766
dan8099ce62009-09-23 08:43:35 +0000767 action = pFKey->aAction[iAction];
768 pTrigger = pFKey->apTrigger[iAction];
dan1da40a32009-09-19 17:00:31 +0000769
770 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
771 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
772
773 if( action>OE_Restrict && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000774 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan8099ce62009-09-23 08:43:35 +0000775 char const *zFrom; /* Name of child table */
dan1da40a32009-09-19 17:00:31 +0000776 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000777 Index *pIdx = 0; /* Parent key index for this FK */
778 int *aiCol = 0; /* child table cols -> parent key cols */
779 TriggerStep *pStep; /* First (only) step of trigger program */
780 Expr *pWhere = 0; /* WHERE clause of trigger step */
781 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
782 int i; /* Iterator variable */
drh788536b2009-09-23 03:01:58 +0000783 Expr *pWhen = 0; /* WHEN clause for the trigger */
dan1da40a32009-09-19 17:00:31 +0000784
785 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
786 assert( aiCol || pFKey->nCol==1 );
787
dan1da40a32009-09-19 17:00:31 +0000788 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000789 Token tOld = { "old", 3 }; /* Literal "old" token */
790 Token tNew = { "new", 3 }; /* Literal "new" token */
dan8099ce62009-09-23 08:43:35 +0000791 Token tFromCol; /* Name of column in child table */
792 Token tToCol; /* Name of column in parent table */
793 int iFromCol; /* Idx of column in child table */
dan29c7f9c2009-09-22 15:53:47 +0000794 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000795
796 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000797 assert( iFromCol>=0 );
dan1da40a32009-09-19 17:00:31 +0000798 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
dana8f0bf62009-09-23 12:06:52 +0000799 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
dan1da40a32009-09-19 17:00:31 +0000800
801 tToCol.n = sqlite3Strlen30(tToCol.z);
802 tFromCol.n = sqlite3Strlen30(tFromCol.z);
803
804 /* Create the expression "zFromCol = OLD.zToCol" */
805 pEq = sqlite3PExpr(pParse, TK_EQ,
806 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
807 sqlite3PExpr(pParse, TK_DOT,
808 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
809 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
810 , 0)
811 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000812 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000813
drh788536b2009-09-23 03:01:58 +0000814 /* For ON UPDATE, construct the next term of the WHEN clause.
815 ** The final WHEN clause will be like this:
816 **
817 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
818 */
819 if( pChanges ){
820 pEq = sqlite3PExpr(pParse, TK_IS,
821 sqlite3PExpr(pParse, TK_DOT,
822 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
823 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
824 0),
825 sqlite3PExpr(pParse, TK_DOT,
826 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
827 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
828 0),
829 0);
830 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
831 }
832
dan1da40a32009-09-19 17:00:31 +0000833 if( action!=OE_Cascade || pChanges ){
834 Expr *pNew;
835 if( action==OE_Cascade ){
836 pNew = sqlite3PExpr(pParse, TK_DOT,
837 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
838 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
839 , 0);
840 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000841 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000842 if( pDflt ){
843 pNew = sqlite3ExprDup(db, pDflt, 0);
844 }else{
845 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
846 }
847 }else{
848 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
849 }
850 pList = sqlite3ExprListAppend(pParse, pList, pNew);
851 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
852 }
853 }
dan29c7f9c2009-09-22 15:53:47 +0000854 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +0000855
dan29c7f9c2009-09-22 15:53:47 +0000856 /* If pTab->dbMem==0, then the table may be part of a shared-schema.
857 ** Disable the lookaside buffer before allocating space for the
858 ** trigger definition in this case. */
859 enableLookaside = db->lookaside.bEnabled;
860 if( pTab->dbMem==0 ){
861 db->lookaside.bEnabled = 0;
862 }
863
864 zFrom = pFKey->pFrom->zName;
865 nFrom = sqlite3Strlen30(zFrom);
866 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
867 sizeof(Trigger) + /* struct Trigger */
868 sizeof(TriggerStep) + /* Single step in trigger program */
869 nFrom + 1 /* Space for pStep->target.z */
870 );
871 if( pTrigger ){
872 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
873 pStep->target.z = (char *)&pStep[1];
874 pStep->target.n = nFrom;
875 memcpy((char *)pStep->target.z, zFrom, nFrom);
876
877 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
878 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
drh788536b2009-09-23 03:01:58 +0000879 if( pWhen ){
880 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
881 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
882 }
dan29c7f9c2009-09-22 15:53:47 +0000883 }
884
885 /* Re-enable the lookaside buffer, if it was disabled earlier. */
886 db->lookaside.bEnabled = enableLookaside;
887
drh788536b2009-09-23 03:01:58 +0000888 sqlite3ExprDelete(db, pWhere);
889 sqlite3ExprDelete(db, pWhen);
890 sqlite3ExprListDelete(db, pList);
dan29c7f9c2009-09-22 15:53:47 +0000891 if( db->mallocFailed==1 ){
892 fkTriggerDelete(db, pTrigger);
893 return 0;
894 }
dan1da40a32009-09-19 17:00:31 +0000895
896 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
897 pStep->pTrig = pTrigger;
898 pTrigger->pSchema = pTab->pSchema;
899 pTrigger->pTabSchema = pTab->pSchema;
dan8099ce62009-09-23 08:43:35 +0000900 pFKey->apTrigger[iAction] = pTrigger;
901 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
dan1da40a32009-09-19 17:00:31 +0000902 }
903
904 return pTrigger;
905}
906
dan1da40a32009-09-19 17:00:31 +0000907/*
908** This function is called when deleting or updating a row to implement
909** any required CASCADE, SET NULL or SET DEFAULT actions.
910*/
911void sqlite3FkActions(
912 Parse *pParse, /* Parse context */
913 Table *pTab, /* Table being updated or deleted from */
914 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
915 int regOld /* Address of array containing old row */
916){
917 /* If foreign-key support is enabled, iterate through all FKs that
918 ** refer to table pTab. If there is an action associated with the FK
919 ** for this operation (either update or delete), invoke the associated
920 ** trigger sub-program. */
921 if( pParse->db->flags&SQLITE_ForeignKeys ){
922 FKey *pFKey; /* Iterator variable */
923 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
924 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
925 if( pAction ){
926 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
927 }
928 }
929 }
930}
931
dan75cbd982009-09-21 16:06:03 +0000932#endif /* ifndef SQLITE_OMIT_TRIGGER */
933
dan1da40a32009-09-19 17:00:31 +0000934/*
935** Free all memory associated with foreign key definitions attached to
936** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
937** hash table.
938*/
939void sqlite3FkDelete(Table *pTab){
940 FKey *pFKey; /* Iterator variable */
941 FKey *pNext; /* Copy of pFKey->pNextFrom */
942
943 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
944
945 /* Remove the FK from the fkeyHash hash table. */
946 if( pFKey->pPrevTo ){
947 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
948 }else{
949 void *data = (void *)pFKey->pNextTo;
950 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
951 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
952 }
953 if( pFKey->pNextTo ){
954 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
955 }
956
957 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000958#ifndef SQLITE_OMIT_TRIGGER
dan8099ce62009-09-23 08:43:35 +0000959 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
960 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
dan75cbd982009-09-21 16:06:03 +0000961#endif
dan1da40a32009-09-19 17:00:31 +0000962
963 /* Delete the memory allocated for the FK structure. */
964 pNext = pFKey->pNextFrom;
965 sqlite3DbFree(pTab->dbMem, pFKey);
966 }
967}
dan75cbd982009-09-21 16:06:03 +0000968#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */