blob: 76cfaff362a16977f9e14940ddcecabb3c300ff9 [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 **
dand981d442009-09-23 13:59:17 +0000200 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
201 ** mapped to the primary key of table pParent, or
202 ** 2) The FK is explicitly mapped to a column declared as INTEGER
dan1da40a32009-09-19 17:00:31 +0000203 ** PRIMARY KEY.
204 */
dan8099ce62009-09-23 08:43:35 +0000205 if( pParent->iPKey>=0 ){
206 if( !zKey ) return 0;
207 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
dan1da40a32009-09-19 17:00:31 +0000208 }
209 }else if( paiCol ){
210 assert( nCol>1 );
211 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
212 if( !aiCol ) return 1;
213 *paiCol = aiCol;
214 }
215
dan8099ce62009-09-23 08:43:35 +0000216 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
dan1da40a32009-09-19 17:00:31 +0000217 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
218 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
219 ** of columns. If each indexed column corresponds to a foreign key
220 ** column of pFKey, then this index is a winner. */
221
dan8099ce62009-09-23 08:43:35 +0000222 if( zKey==0 ){
223 /* If zKey is NULL, then this foreign key is implicitly mapped to
224 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
dan1da40a32009-09-19 17:00:31 +0000225 ** identified by the test (Index.autoIndex==2). */
226 if( pIdx->autoIndex==2 ){
227 if( aiCol ) memcpy(aiCol, pIdx->aiColumn, sizeof(int)*nCol);
228 break;
229 }
230 }else{
dan8099ce62009-09-23 08:43:35 +0000231 /* If zKey is non-NULL, then this foreign key was declared to
232 ** map to an explicit list of columns in table pParent. Check if this
dan1da40a32009-09-19 17:00:31 +0000233 ** index matches those columns. */
234 int i, j;
235 for(i=0; i<nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000236 char *zIdxCol = pParent->aCol[pIdx->aiColumn[i]].zName;
dan1da40a32009-09-19 17:00:31 +0000237 for(j=0; j<nCol; j++){
238 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
239 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
240 break;
241 }
242 }
243 if( j==nCol ) break;
244 }
245 if( i==nCol ) break; /* pIdx is usable */
246 }
247 }
248 }
249
250 if( pParse && !pIdx ){
251 sqlite3ErrorMsg(pParse, "foreign key mismatch");
252 sqlite3DbFree(pParse->db, aiCol);
253 return 1;
254 }
255
256 *ppIdx = pIdx;
257 return 0;
258}
259
dan8099ce62009-09-23 08:43:35 +0000260/*
261** This function is called when a row is inserted into the child table of
262** foreign key constraint pFKey and, if pFKey is deferred, when a row is
263** deleted from the child table of pFKey. If an SQL UPDATE is executed on
264** the child table of pFKey, this function is invoked twice for each row
265** affected - once to "delete" the old row, and then again to "insert" the
266** new row.
267**
268** Each time it is called, this function generates VDBE code to locate the
269** row in the parent table that corresponds to the row being inserted into
270** or deleted from the child table. If the parent row can be found, no
271** special action is taken. Otherwise, if the parent row can *not* be
272** found in the parent table:
273**
274** Operation | FK type | Action taken
275** --------------------------------------------------------------------------
276** INSERT immediate Throw a "foreign key constraint failed" exception.
277**
278** INSERT deferred Increment the "deferred constraint counter".
279**
280** DELETE deferred Decrement the "deferred constraint counter".
281**
282** This function is never called for a delete on the child table of an
283** immediate foreign key constraint. These operations are identified in
284** the comment at the top of this file (fkey.c) as "I.1" and "D.1".
285*/
286static void fkLookupParent(
dan1da40a32009-09-19 17:00:31 +0000287 Parse *pParse, /* Parse context */
288 int iDb, /* Index of database housing pTab */
dan8099ce62009-09-23 08:43:35 +0000289 Table *pTab, /* Parent table of FK pFKey */
290 Index *pIdx, /* Unique index on parent key columns in pTab */
291 FKey *pFKey, /* Foreign key constraint */
292 int *aiCol, /* Map from parent key columns to child table columns */
293 int regData, /* Address of array containing child table row */
dan1da40a32009-09-19 17:00:31 +0000294 int nIncr /* If deferred FK, increment counter by this */
295){
dan8099ce62009-09-23 08:43:35 +0000296 int i; /* Iterator variable */
297 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
298 int iCur = pParse->nTab - 1; /* Cursor number to use */
299 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
dan1da40a32009-09-19 17:00:31 +0000300
301 assert( pFKey->isDeferred || nIncr==1 );
302
dan8099ce62009-09-23 08:43:35 +0000303 /* Check if any of the key columns in the child table row are
dan1da40a32009-09-19 17:00:31 +0000304 ** NULL. If any are, then the constraint is satisfied. No need
dan8099ce62009-09-23 08:43:35 +0000305 ** to search for a matching row in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000306 for(i=0; i<pFKey->nCol; i++){
dan36062642009-09-21 18:56:23 +0000307 int iReg = aiCol[i] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000308 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
309 }
310
311 if( pIdx==0 ){
dan8099ce62009-09-23 08:43:35 +0000312 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
313 ** column of the parent table (table pTab). */
dan1da40a32009-09-19 17:00:31 +0000314 int iReg = pFKey->aCol[0].iFrom + regData + 1;
315 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
316 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iReg);
317 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
318 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
319 }else{
320 int regRec = sqlite3GetTempReg(pParse);
321 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
322
323 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
324 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
325
dan36062642009-09-21 18:56:23 +0000326 if( pFKey->nCol>1 ){
dan1da40a32009-09-19 17:00:31 +0000327 int nCol = pFKey->nCol;
328 int regTemp = sqlite3GetTempRange(pParse, nCol);
329 for(i=0; i<nCol; i++){
330 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
331 }
332 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
333 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
334 }else{
dan36062642009-09-21 18:56:23 +0000335 int iReg = aiCol[0] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000336 sqlite3VdbeAddOp3(v, OP_MakeRecord, iReg, 1, regRec);
337 sqlite3IndexAffinityStr(v, pIdx);
338 }
339
340 sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
341 sqlite3ReleaseTempReg(pParse, regRec);
342 }
343
344 if( pFKey->isDeferred ){
345 assert( nIncr==1 || nIncr==-1 );
346 sqlite3VdbeAddOp1(v, OP_DeferredCons, nIncr);
347 }else{
348 sqlite3HaltConstraint(
349 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
350 );
351 }
352
353 sqlite3VdbeResolveLabel(v, iOk);
354}
355
dan8099ce62009-09-23 08:43:35 +0000356/*
357** This function is called to generate code executed when a row is deleted
358** from the parent table of foreign key constraint pFKey and, if pFKey is
359** deferred, when a row is inserted into the same table. When generating
360** code for an SQL UPDATE operation, this function may be called twice -
361** once to "delete" the old row and once to "insert" the new row.
362**
363** The code generated by this function scans through the rows in the child
364** table that correspond to the parent table row being deleted or inserted.
365** For each child row found, one of the following actions is taken:
366**
367** Operation | FK type | Action taken
368** --------------------------------------------------------------------------
369** DELETE immediate Throw a "foreign key constraint failed" exception.
370**
371** DELETE deferred Increment the "deferred constraint counter".
372** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
373** throw a "foreign key constraint failed" exception.
374**
375** INSERT deferred Decrement the "deferred constraint counter".
376**
377** This function is never called for an INSERT operation on the parent table
378** of an immediate foreign key constraint. These operations are identified in
379** the comment at the top of this file (fkey.c) as "I.2" and "D.2".
380*/
381static void fkScanChildren(
dan1da40a32009-09-19 17:00:31 +0000382 Parse *pParse, /* Parse context */
383 SrcList *pSrc, /* SrcList containing the table to scan */
384 Index *pIdx, /* Foreign key index */
385 FKey *pFKey, /* Foreign key relationship */
dan8099ce62009-09-23 08:43:35 +0000386 int *aiCol, /* Map from pIdx cols to child table cols */
dan1da40a32009-09-19 17:00:31 +0000387 int regData, /* Referenced table data starts here */
388 int nIncr /* Amount to increment deferred counter by */
389){
390 sqlite3 *db = pParse->db; /* Database handle */
391 int i; /* Iterator variable */
392 Expr *pWhere = 0; /* WHERE clause to scan with */
393 NameContext sNameContext; /* Context used to resolve WHERE clause */
394 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
395
396 for(i=0; i<pFKey->nCol; i++){
dan8099ce62009-09-23 08:43:35 +0000397 Expr *pLeft; /* Value from parent table row */
398 Expr *pRight; /* Column ref to child table */
dan1da40a32009-09-19 17:00:31 +0000399 Expr *pEq; /* Expression (pLeft = pRight) */
dan8099ce62009-09-23 08:43:35 +0000400 int iCol; /* Index of column in child table */
401 const char *zCol; /* Name of column in child table */
dan1da40a32009-09-19 17:00:31 +0000402
403 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
404 if( pLeft ){
405 pLeft->iTable = (pIdx ? (regData+pIdx->aiColumn[i]+1) : regData);
406 }
407 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000408 assert( iCol>=0 );
409 zCol = pFKey->pFrom->aCol[iCol].zName;
dan1da40a32009-09-19 17:00:31 +0000410 pRight = sqlite3Expr(db, TK_ID, zCol);
411 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
412 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
413 }
414
415 /* Resolve the references in the WHERE clause. */
416 memset(&sNameContext, 0, sizeof(NameContext));
417 sNameContext.pSrcList = pSrc;
418 sNameContext.pParse = pParse;
419 sqlite3ResolveExprNames(&sNameContext, pWhere);
420
421 /* Create VDBE to loop through the entries in pSrc that match the WHERE
422 ** clause. If the constraint is not deferred, throw an exception for
423 ** each row found. Otherwise, for deferred constraints, increment the
424 ** deferred constraint counter by nIncr for each row selected. */
425 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
426 if( pFKey->isDeferred && nIncr ){
427 assert( nIncr==1 || nIncr==-1 );
428 sqlite3VdbeAddOp1(pParse->pVdbe, OP_DeferredCons, nIncr);
429 }else{
430 assert( nIncr==1 || nIncr==0 );
431 sqlite3HaltConstraint(
432 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
433 );
434 }
danf59c5ca2009-09-22 16:55:38 +0000435 if( pWInfo ){
436 sqlite3WhereEnd(pWInfo);
437 }
dan1da40a32009-09-19 17:00:31 +0000438
439 /* Clean up the WHERE clause constructed above. */
440 sqlite3ExprDelete(db, pWhere);
441}
442
443/*
444** This function returns a pointer to the head of a linked list of FK
dan8099ce62009-09-23 08:43:35 +0000445** constraints for which table pTab is the parent table. For example,
dan1da40a32009-09-19 17:00:31 +0000446** given the following schema:
447**
448** CREATE TABLE t1(a PRIMARY KEY);
449** CREATE TABLE t2(b REFERENCES t1(a);
450**
451** Calling this function with table "t1" as an argument returns a pointer
452** to the FKey structure representing the foreign key constraint on table
453** "t2". Calling this function with "t2" as the argument would return a
dan8099ce62009-09-23 08:43:35 +0000454** NULL pointer (as there are no FK constraints for which t2 is the parent
455** table).
dan1da40a32009-09-19 17:00:31 +0000456*/
457static FKey *fkRefering(Table *pTab){
458 int nName = sqlite3Strlen30(pTab->zName);
459 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
460}
461
dan8099ce62009-09-23 08:43:35 +0000462/*
463** The second argument is a Trigger structure allocated by the
464** fkActionTrigger() routine. This function deletes the Trigger structure
465** and all of its sub-components.
466**
467** The Trigger structure or any of its sub-components may be allocated from
468** the lookaside buffer belonging to database handle dbMem.
469*/
dan75cbd982009-09-21 16:06:03 +0000470static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
471 if( p ){
472 TriggerStep *pStep = p->step_list;
473 sqlite3ExprDelete(dbMem, pStep->pWhere);
474 sqlite3ExprListDelete(dbMem, pStep->pExprList);
drh788536b2009-09-23 03:01:58 +0000475 sqlite3ExprDelete(dbMem, p->pWhen);
dan75cbd982009-09-21 16:06:03 +0000476 sqlite3DbFree(dbMem, p);
477 }
478}
479
dan8099ce62009-09-23 08:43:35 +0000480/*
481** This function is called when inserting, deleting or updating a row of
482** table pTab to generate VDBE code to perform foreign key constraint
483** processing for the operation.
484**
485** For a DELETE operation, parameter regOld is passed the index of the
486** first register in an array of (pTab->nCol+1) registers containing the
487** rowid of the row being deleted, followed by each of the column values
488** of the row being deleted, from left to right. Parameter regNew is passed
489** zero in this case.
490**
491** For an UPDATE operation, regOld is the first in an array of (pTab->nCol+1)
492** registers containing the old rowid and column values of the row being
493** updated, and regNew is the first in an array of the same size containing
494** the corresponding new values. Parameter pChanges is passed the list of
495** columns being updated by the statement.
496**
497** For an INSERT operation, regOld is passed zero and regNew is passed the
498** first register of an array of (pTab->nCol+1) registers containing the new
499** row data.
500**
501** If an error occurs, an error message is left in the pParse structure.
502*/
dan1da40a32009-09-19 17:00:31 +0000503void sqlite3FkCheck(
504 Parse *pParse, /* Parse context */
505 Table *pTab, /* Row is being deleted from this table */
506 ExprList *pChanges, /* Changed columns if this is an UPDATE */
507 int regOld, /* Previous row data is stored here */
508 int regNew /* New row data is stored here */
509){
510 sqlite3 *db = pParse->db; /* Database handle */
511 Vdbe *v; /* VM to write code to */
512 FKey *pFKey; /* Used to iterate through FKs */
513 int iDb; /* Index of database containing pTab */
514 const char *zDb; /* Name of database containing pTab */
515
516 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
517 || (!pChanges && !regOld && regNew) /* INSERT operation */
518 || (!pChanges && regOld && !regNew) /* DELETE operation */
519 );
520
521 /* If foreign-keys are disabled, this function is a no-op. */
522 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
523
524 v = sqlite3GetVdbe(pParse);
525 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
526 zDb = db->aDb[iDb].zName;
527
dan8099ce62009-09-23 08:43:35 +0000528 /* Loop through all the foreign key constraints for which pTab is the
529 ** child table (the table that the foreign key definition is part of). */
dan1da40a32009-09-19 17:00:31 +0000530 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan8099ce62009-09-23 08:43:35 +0000531 Table *pTo; /* Parent table of foreign key pFKey */
dan1da40a32009-09-19 17:00:31 +0000532 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000533 int *aiFree = 0;
534 int *aiCol;
535 int iCol;
536 int i;
dan1da40a32009-09-19 17:00:31 +0000537
dan8099ce62009-09-23 08:43:35 +0000538 /* If this is a DELETE operation and the foreign key is not deferred,
539 ** nothing to do. A DELETE on the child table cannot cause the FK
540 ** constraint to fail. */
dan1da40a32009-09-19 17:00:31 +0000541 if( pFKey->isDeferred==0 && regNew==0 ) continue;
542
dan8099ce62009-09-23 08:43:35 +0000543 /* Find the parent table of this foreign key. Also find a unique index
544 ** on the parent key columns in the parent table. If either of these
545 ** schema items cannot be located, set an error in pParse and return
546 ** early. */
dan1da40a32009-09-19 17:00:31 +0000547 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
dan36062642009-09-21 18:56:23 +0000548 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return;
549 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000550
551 /* If the key does not overlap with the pChanges list, skip this FK. */
552 if( pChanges ){
553 /* TODO */
554 }
555
dan36062642009-09-21 18:56:23 +0000556 if( aiFree ){
557 aiCol = aiFree;
558 }else{
559 iCol = pFKey->aCol[0].iFrom;
560 aiCol = &iCol;
561 }
562 for(i=0; i<pFKey->nCol; i++){
563 if( aiCol[i]==pTab->iPKey ){
564 aiCol[i] = -1;
565 }
566 }
567
dan8099ce62009-09-23 08:43:35 +0000568 /* Take a shared-cache advisory read-lock on the parent table. Allocate
569 ** a cursor to use to search the unique index on the parent key columns
570 ** in the parent table. */
dan1da40a32009-09-19 17:00:31 +0000571 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
572 pParse->nTab++;
573
574 if( regOld!=0 && pFKey->isDeferred ){
dan8099ce62009-09-23 08:43:35 +0000575 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
dan1da40a32009-09-19 17:00:31 +0000576 }
577 if( regNew!=0 ){
dan8099ce62009-09-23 08:43:35 +0000578 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
dan1da40a32009-09-19 17:00:31 +0000579 }
580
dan36062642009-09-21 18:56:23 +0000581 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000582 }
583
584 /* Loop through all the foreign key constraints that refer to this table */
585 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
586 int iGoto; /* Address of OP_Goto instruction */
587 Index *pIdx = 0; /* Foreign key index for pFKey */
588 SrcList *pSrc;
589 int *aiCol = 0;
590
591 /* For immediate constraints, skip this scan if:
592 **
593 ** 1) this is an INSERT operation, or
594 ** 2) an UPDATE operation and the FK action is a trigger-action, or
595 ** 3) a DELETE operation and the FK action is a trigger-action.
596 **
597 ** A "trigger-action" is one of CASCADE, SET DEFAULT or SET NULL.
598 */
599 if( pFKey->isDeferred==0 ){
600 if( regOld==0 ) continue; /* 1 */
dan8099ce62009-09-23 08:43:35 +0000601 if( regNew!=0 && pFKey->aAction[1]>OE_Restrict ) continue; /* 2 */
602 if( regNew==0 && pFKey->aAction[0]>OE_Restrict ) continue; /* 3 */
dan1da40a32009-09-19 17:00:31 +0000603 }
604
605 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
606 assert( aiCol || pFKey->nCol==1 );
607
dan8099ce62009-09-23 08:43:35 +0000608 /* Check if this update statement has modified any of the child key
609 ** columns for this foreign key constraint. If it has not, there is
610 ** no need to search the child table for rows in violation. This is
dan1da40a32009-09-19 17:00:31 +0000611 ** just an optimization. Things would work fine without this check. */
612 if( pChanges ){
613 /* TODO */
614 }
615
616 /* Create a SrcList structure containing a single table (the table
617 ** the foreign key that refers to this table is attached to). This
618 ** is required for the sqlite3WhereXXX() interface. */
619 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000620 if( pSrc ){
621 pSrc->a->pTab = pFKey->pFrom;
622 pSrc->a->pTab->nRef++;
623 pSrc->a->iCursor = pParse->nTab++;
624
625 /* If this is an UPDATE, and none of the columns associated with this
dan8099ce62009-09-23 08:43:35 +0000626 ** FK have been modified, do not scan the child table. Unlike the
627 ** compile-time test implemented above, this is not just an
danf59c5ca2009-09-22 16:55:38 +0000628 ** optimization. It is required so that immediate foreign keys do not
629 ** throw exceptions when the user executes a statement like:
630 **
631 ** UPDATE refd_table SET refd_column = refd_column
632 */
633 if( pChanges ){
634 int i;
635 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
636 for(i=0; i<pFKey->nCol; i++){
637 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
638 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
639 }
640 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
dan1da40a32009-09-19 17:00:31 +0000641 }
danf59c5ca2009-09-22 16:55:38 +0000642
643 if( regNew!=0 && pFKey->isDeferred ){
dan8099ce62009-09-23 08:43:35 +0000644 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
danf59c5ca2009-09-22 16:55:38 +0000645 }
646 if( regOld!=0 ){
647 /* If there is a RESTRICT action configured for the current operation
dan8099ce62009-09-23 08:43:35 +0000648 ** on the parent table of this FK, then throw an exception
danf59c5ca2009-09-22 16:55:38 +0000649 ** immediately if the FK constraint is violated, even if this is a
650 ** deferred trigger. That's what RESTRICT means. To defer checking
651 ** the constraint, the FK should specify NO ACTION (represented
652 ** using OE_None). NO ACTION is the default. */
dan8099ce62009-09-23 08:43:35 +0000653 fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
654 pFKey->aAction[pChanges!=0]!=OE_Restrict
danf59c5ca2009-09-22 16:55:38 +0000655 );
656 }
657
658 if( pChanges ){
659 sqlite3VdbeJumpHere(v, iGoto);
660 }
661 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000662 }
dan1da40a32009-09-19 17:00:31 +0000663 sqlite3DbFree(db, aiCol);
664 }
665}
666
667#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
668
669/*
670** This function is called before generating code to update or delete a
671** row contained in table pTab. If the operation is an update, then
672** pChanges is a pointer to the list of columns to modify. If this is a
673** delete, then pChanges is NULL.
674*/
675u32 sqlite3FkOldmask(
676 Parse *pParse, /* Parse context */
677 Table *pTab, /* Table being modified */
678 ExprList *pChanges /* Non-NULL for UPDATE operations */
679){
680 u32 mask = 0;
681 if( pParse->db->flags&SQLITE_ForeignKeys ){
682 FKey *p;
683 int i;
684 for(p=pTab->pFKey; p; p=p->pNextFrom){
685 if( pChanges || p->isDeferred ){
686 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
687 }
688 }
689 for(p=fkRefering(pTab); p; p=p->pNextTo){
690 Index *pIdx = 0;
691 locateFkeyIndex(0, pTab, p, &pIdx, 0);
692 if( pIdx ){
693 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
694 }
695 }
696 }
697 return mask;
698}
699
700/*
701** This function is called before generating code to update or delete a
702** row contained in table pTab. If the operation is an update, then
703** pChanges is a pointer to the list of columns to modify. If this is a
704** delete, then pChanges is NULL.
705**
706** If any foreign key processing will be required, this function returns
707** true. If there is no foreign key related processing, this function
708** returns false.
709*/
710int sqlite3FkRequired(
711 Parse *pParse, /* Parse context */
712 Table *pTab, /* Table being modified */
713 ExprList *pChanges /* Non-NULL for UPDATE operations */
714){
715 if( pParse->db->flags&SQLITE_ForeignKeys ){
716 FKey *p;
717 for(p=pTab->pFKey; p; p=p->pNextFrom){
718 if( pChanges || p->isDeferred ) return 1;
719 }
720 if( fkRefering(pTab) ) return 1;
721 }
722 return 0;
723}
724
dan8099ce62009-09-23 08:43:35 +0000725/*
726** This function is called when an UPDATE or DELETE operation is being
727** compiled on table pTab, which is the parent table of foreign-key pFKey.
728** If the current operation is an UPDATE, then the pChanges parameter is
729** passed a pointer to the list of columns being modified. If it is a
730** DELETE, pChanges is passed a NULL pointer.
731**
732** It returns a pointer to a Trigger structure containing a trigger
733** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
734** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
735** returned (these actions require no special handling by the triggers
736** sub-system, code for them is created by fkScanChildren()).
737**
738** For example, if pFKey is the foreign key and pTab is table "p" in
739** the following schema:
740**
741** CREATE TABLE p(pk PRIMARY KEY);
742** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
743**
744** then the returned trigger structure is equivalent to:
745**
746** CREATE TRIGGER ... DELETE ON p BEGIN
747** DELETE FROM c WHERE ck = old.pk;
748** END;
749**
750** The returned pointer is cached as part of the foreign key object. It
751** is eventually freed along with the rest of the foreign key object by
752** sqlite3FkDelete().
753*/
dan1da40a32009-09-19 17:00:31 +0000754static Trigger *fkActionTrigger(
dan8099ce62009-09-23 08:43:35 +0000755 Parse *pParse, /* Parse context */
dan1da40a32009-09-19 17:00:31 +0000756 Table *pTab, /* Table being updated or deleted from */
757 FKey *pFKey, /* Foreign key to get action for */
758 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
759){
760 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000761 int action; /* One of OE_None, OE_Cascade etc. */
762 Trigger *pTrigger; /* Trigger definition to return */
dan8099ce62009-09-23 08:43:35 +0000763 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
dan1da40a32009-09-19 17:00:31 +0000764
dan8099ce62009-09-23 08:43:35 +0000765 action = pFKey->aAction[iAction];
766 pTrigger = pFKey->apTrigger[iAction];
dan1da40a32009-09-19 17:00:31 +0000767
768 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
769 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
770
771 if( action>OE_Restrict && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000772 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan8099ce62009-09-23 08:43:35 +0000773 char const *zFrom; /* Name of child table */
dan1da40a32009-09-19 17:00:31 +0000774 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000775 Index *pIdx = 0; /* Parent key index for this FK */
776 int *aiCol = 0; /* child table cols -> parent key cols */
777 TriggerStep *pStep; /* First (only) step of trigger program */
778 Expr *pWhere = 0; /* WHERE clause of trigger step */
779 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
780 int i; /* Iterator variable */
drh788536b2009-09-23 03:01:58 +0000781 Expr *pWhen = 0; /* WHEN clause for the trigger */
dan1da40a32009-09-19 17:00:31 +0000782
783 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
784 assert( aiCol || pFKey->nCol==1 );
785
dan1da40a32009-09-19 17:00:31 +0000786 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000787 Token tOld = { "old", 3 }; /* Literal "old" token */
788 Token tNew = { "new", 3 }; /* Literal "new" token */
dan8099ce62009-09-23 08:43:35 +0000789 Token tFromCol; /* Name of column in child table */
790 Token tToCol; /* Name of column in parent table */
791 int iFromCol; /* Idx of column in child table */
dan29c7f9c2009-09-22 15:53:47 +0000792 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000793
794 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
dana8f0bf62009-09-23 12:06:52 +0000795 assert( iFromCol>=0 );
dan1da40a32009-09-19 17:00:31 +0000796 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
dana8f0bf62009-09-23 12:06:52 +0000797 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
dan1da40a32009-09-19 17:00:31 +0000798
799 tToCol.n = sqlite3Strlen30(tToCol.z);
800 tFromCol.n = sqlite3Strlen30(tFromCol.z);
801
802 /* Create the expression "zFromCol = OLD.zToCol" */
803 pEq = sqlite3PExpr(pParse, TK_EQ,
804 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
805 sqlite3PExpr(pParse, TK_DOT,
806 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
807 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
808 , 0)
809 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000810 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000811
drh788536b2009-09-23 03:01:58 +0000812 /* For ON UPDATE, construct the next term of the WHEN clause.
813 ** The final WHEN clause will be like this:
814 **
815 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
816 */
817 if( pChanges ){
818 pEq = sqlite3PExpr(pParse, TK_IS,
819 sqlite3PExpr(pParse, TK_DOT,
820 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
821 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
822 0),
823 sqlite3PExpr(pParse, TK_DOT,
824 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
825 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
826 0),
827 0);
828 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
829 }
830
dan1da40a32009-09-19 17:00:31 +0000831 if( action!=OE_Cascade || pChanges ){
832 Expr *pNew;
833 if( action==OE_Cascade ){
834 pNew = sqlite3PExpr(pParse, TK_DOT,
835 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
836 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
837 , 0);
838 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000839 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000840 if( pDflt ){
841 pNew = sqlite3ExprDup(db, pDflt, 0);
842 }else{
843 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
844 }
845 }else{
846 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
847 }
848 pList = sqlite3ExprListAppend(pParse, pList, pNew);
849 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
850 }
851 }
dan29c7f9c2009-09-22 15:53:47 +0000852 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +0000853
dan29c7f9c2009-09-22 15:53:47 +0000854 /* If pTab->dbMem==0, then the table may be part of a shared-schema.
855 ** Disable the lookaside buffer before allocating space for the
856 ** trigger definition in this case. */
857 enableLookaside = db->lookaside.bEnabled;
858 if( pTab->dbMem==0 ){
859 db->lookaside.bEnabled = 0;
860 }
861
862 zFrom = pFKey->pFrom->zName;
863 nFrom = sqlite3Strlen30(zFrom);
864 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
865 sizeof(Trigger) + /* struct Trigger */
866 sizeof(TriggerStep) + /* Single step in trigger program */
867 nFrom + 1 /* Space for pStep->target.z */
868 );
869 if( pTrigger ){
870 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
871 pStep->target.z = (char *)&pStep[1];
872 pStep->target.n = nFrom;
873 memcpy((char *)pStep->target.z, zFrom, nFrom);
874
875 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
876 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
drh788536b2009-09-23 03:01:58 +0000877 if( pWhen ){
878 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
879 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
880 }
dan29c7f9c2009-09-22 15:53:47 +0000881 }
882
883 /* Re-enable the lookaside buffer, if it was disabled earlier. */
884 db->lookaside.bEnabled = enableLookaside;
885
drh788536b2009-09-23 03:01:58 +0000886 sqlite3ExprDelete(db, pWhere);
887 sqlite3ExprDelete(db, pWhen);
888 sqlite3ExprListDelete(db, pList);
dan29c7f9c2009-09-22 15:53:47 +0000889 if( db->mallocFailed==1 ){
890 fkTriggerDelete(db, pTrigger);
891 return 0;
892 }
dan1da40a32009-09-19 17:00:31 +0000893
894 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
895 pStep->pTrig = pTrigger;
896 pTrigger->pSchema = pTab->pSchema;
897 pTrigger->pTabSchema = pTab->pSchema;
dan8099ce62009-09-23 08:43:35 +0000898 pFKey->apTrigger[iAction] = pTrigger;
899 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
dan1da40a32009-09-19 17:00:31 +0000900 }
901
902 return pTrigger;
903}
904
dan1da40a32009-09-19 17:00:31 +0000905/*
906** This function is called when deleting or updating a row to implement
907** any required CASCADE, SET NULL or SET DEFAULT actions.
908*/
909void sqlite3FkActions(
910 Parse *pParse, /* Parse context */
911 Table *pTab, /* Table being updated or deleted from */
912 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
913 int regOld /* Address of array containing old row */
914){
915 /* If foreign-key support is enabled, iterate through all FKs that
916 ** refer to table pTab. If there is an action associated with the FK
917 ** for this operation (either update or delete), invoke the associated
918 ** trigger sub-program. */
919 if( pParse->db->flags&SQLITE_ForeignKeys ){
920 FKey *pFKey; /* Iterator variable */
921 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
922 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
923 if( pAction ){
924 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
925 }
926 }
927 }
928}
929
dan75cbd982009-09-21 16:06:03 +0000930#endif /* ifndef SQLITE_OMIT_TRIGGER */
931
dan1da40a32009-09-19 17:00:31 +0000932/*
933** Free all memory associated with foreign key definitions attached to
934** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
935** hash table.
936*/
937void sqlite3FkDelete(Table *pTab){
938 FKey *pFKey; /* Iterator variable */
939 FKey *pNext; /* Copy of pFKey->pNextFrom */
940
941 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
942
943 /* Remove the FK from the fkeyHash hash table. */
944 if( pFKey->pPrevTo ){
945 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
946 }else{
947 void *data = (void *)pFKey->pNextTo;
948 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
949 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
950 }
951 if( pFKey->pNextTo ){
952 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
953 }
954
955 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000956#ifndef SQLITE_OMIT_TRIGGER
dan8099ce62009-09-23 08:43:35 +0000957 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
958 fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
dan75cbd982009-09-21 16:06:03 +0000959#endif
dan1da40a32009-09-19 17:00:31 +0000960
961 /* Delete the memory allocated for the FK structure. */
962 pNext = pFKey->pNextFrom;
963 sqlite3DbFree(pTab->dbMem, pFKey);
964 }
965}
dan75cbd982009-09-21 16:06:03 +0000966#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */