xref: /sqlite-3.40.0/src/fkey.c (revision 9edb5ceb)
1 /*
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
17 #ifndef SQLITE_OMIT_TRIGGER
18 
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,
25 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
26 ** statement transaction rolled back. If a
27 ** deferred foreign key constraint is violated, no action is taken
28 ** immediately. However if the application attempts to commit the
29 ** transaction before fixing the constraint violation, the attempt fails.
30 **
31 ** Deferred constraints are implemented using a simple counter associated
32 ** with the database handle. The counter is set to zero each time a
33 ** database transaction is opened. Each time a statement is executed
34 ** that causes a foreign key violation, the counter is incremented. Each
35 ** time a statement is executed that removes an existing violation from
36 ** the database, the counter is decremented. When the transaction is
37 ** committed, the commit fails if the current value of the counter is
38 ** greater than zero. This scheme has two big drawbacks:
39 **
40 **   * When a commit fails due to a deferred foreign key constraint,
41 **     there is no way to tell which foreign constraint is not satisfied,
42 **     or which row it is not satisfied for.
43 **
44 **   * If the database contains foreign key violations when the
45 **     transaction is opened, this may cause the mechanism to malfunction.
46 **
47 ** Despite these problems, this approach is adopted as it seems simpler
48 ** than the alternatives.
49 **
50 ** INSERT operations:
51 **
52 **   I.1) For each FK for which the table is the child table, search
53 **        the parent table for a match. If none is found increment the
54 **        constraint counter.
55 **
56 **   I.2) For each 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
59 **        found (as the constraint is now satisfied).
60 **
61 ** DELETE operations:
62 **
63 **   D.1) For each 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,
66 **        decrement the counter.
67 **
68 **   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 increment the counter.
71 **
72 ** UPDATE operations:
73 **
74 **   An UPDATE command requires that all 4 steps above are taken, but only
75 **   for FK constraints for which the affected columns are actually
76 **   modified (values must be compared at runtime).
77 **
78 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
79 ** This simplifies the implementation a bit.
80 **
81 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
82 ** resolution is considered to delete rows before the new row is inserted.
83 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
84 ** is thrown, even if the FK constraint would be satisfied after the new
85 ** row is inserted.
86 **
87 ** Immediate constraints are usually handled similarly. The only difference
88 ** is that the counter used is stored as part of each individual statement
89 ** object (struct Vdbe). If, after the statement has run, its immediate
90 ** constraint counter is greater than zero,
91 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
92 ** and the statement transaction is rolled back. An exception is an INSERT
93 ** statement that inserts a single row only (no triggers). In this case,
94 ** instead of using a counter, an exception is thrown immediately if the
95 ** INSERT violates a foreign key constraint. This is necessary as such
96 ** an INSERT does not open a statement transaction.
97 **
98 ** TODO: How should dropping a table be handled? How should renaming a
99 ** table be handled?
100 **
101 **
102 ** Query API Notes
103 ** ---------------
104 **
105 ** Before coding an UPDATE or DELETE row operation, the code-generator
106 ** for those two operations needs to know whether or not the operation
107 ** requires any FK processing and, if so, which columns of the original
108 ** row are required by the FK processing VDBE code (i.e. if FKs were
109 ** implemented using triggers, which of the old.* columns would be
110 ** accessed). No information is required by the code-generator before
111 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
112 ** generation code to query for this information are:
113 **
114 **   sqlite3FkRequired() - Test to see if FK processing is required.
115 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
116 **
117 **
118 ** Externally accessible module functions
119 ** --------------------------------------
120 **
121 **   sqlite3FkCheck()    - Check for foreign key violations.
122 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
123 **   sqlite3FkDelete()   - Delete an FKey structure.
124 */
125 
126 /*
127 ** VDBE Calling Convention
128 ** -----------------------
129 **
130 ** Example:
131 **
132 **   For the following INSERT statement:
133 **
134 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
135 **     INSERT INTO t1 VALUES(1, 2, 3.1);
136 **
137 **   Register (x):        2    (type integer)
138 **   Register (x+1):      1    (type integer)
139 **   Register (x+2):      NULL (type NULL)
140 **   Register (x+3):      3.1  (type real)
141 */
142 
143 /*
144 ** A foreign key constraint requires that the key columns in the parent
145 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
146 ** Given that pParent is the parent table for foreign key constraint pFKey,
147 ** search the schema for a unique index on the parent key columns.
148 **
149 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
150 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
151 ** is set to point to the unique index.
152 **
153 ** If the parent key consists of a single column (the foreign key constraint
154 ** is not a composite foreign key), output variable *paiCol is set to NULL.
155 ** Otherwise, it is set to point to an allocated array of size N, where
156 ** N is the number of columns in the parent key. The first element of the
157 ** array is the index of the child table column that is mapped by the FK
158 ** constraint to the parent table column stored in the left-most column
159 ** of index *ppIdx. The second element of the array is the index of the
160 ** child table column that corresponds to the second left-most column of
161 ** *ppIdx, and so on.
162 **
163 ** If the required index cannot be found, either because:
164 **
165 **   1) The named parent key columns do not exist, or
166 **
167 **   2) The named parent key columns do exist, but are not subject to a
168 **      UNIQUE or PRIMARY KEY constraint, or
169 **
170 **   3) No parent key columns were provided explicitly as part of the
171 **      foreign key definition, and the parent table does not have a
172 **      PRIMARY KEY, or
173 **
174 **   4) No parent key columns were provided explicitly as part of the
175 **      foreign key definition, and the PRIMARY KEY of the parent table
176 **      consists of a different number of columns to the child key in
177 **      the child table.
178 **
179 ** then non-zero is returned, and a "foreign key mismatch" error loaded
180 ** into pParse. If an OOM error occurs, non-zero is returned and the
181 ** pParse->db->mallocFailed flag is set.
182 */
183 int sqlite3FkLocateIndex(
184   Parse *pParse,                  /* Parse context to store any error in */
185   Table *pParent,                 /* Parent table of FK constraint pFKey */
186   FKey *pFKey,                    /* Foreign key to find index for */
187   Index **ppIdx,                  /* OUT: Unique index on parent table */
188   int **paiCol                    /* OUT: Map of index columns in pFKey */
189 ){
190   Index *pIdx = 0;                    /* Value to return via *ppIdx */
191   int *aiCol = 0;                     /* Value to return via *paiCol */
192   int nCol = pFKey->nCol;             /* Number of columns in parent key */
193   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
194 
195   /* The caller is responsible for zeroing output parameters. */
196   assert( ppIdx && *ppIdx==0 );
197   assert( !paiCol || *paiCol==0 );
198   assert( pParse );
199 
200   /* If this is a non-composite (single column) foreign key, check if it
201   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
202   ** and *paiCol set to zero and return early.
203   **
204   ** Otherwise, for a composite foreign key (more than one column), allocate
205   ** space for the aiCol array (returned via output parameter *paiCol).
206   ** Non-composite foreign keys do not require the aiCol array.
207   */
208   if( nCol==1 ){
209     /* The FK maps to the IPK if any of the following are true:
210     **
211     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
212     **      mapped to the primary key of table pParent, or
213     **   2) The FK is explicitly mapped to a column declared as INTEGER
214     **      PRIMARY KEY.
215     */
216     if( pParent->iPKey>=0 ){
217       if( !zKey ) return 0;
218       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
219     }
220   }else if( paiCol ){
221     assert( nCol>1 );
222     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
223     if( !aiCol ) return 1;
224     *paiCol = aiCol;
225   }
226 
227   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
228     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
229       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
230       ** of columns. If each indexed column corresponds to a foreign key
231       ** column of pFKey, then this index is a winner.  */
232 
233       if( zKey==0 ){
234         /* If zKey is NULL, then this foreign key is implicitly mapped to
235         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
236         ** identified by the test.  */
237         if( IsPrimaryKeyIndex(pIdx) ){
238           if( aiCol ){
239             int i;
240             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
241           }
242           break;
243         }
244       }else{
245         /* If zKey is non-NULL, then this foreign key was declared to
246         ** map to an explicit list of columns in table pParent. Check if this
247         ** index matches those columns. Also, check that the index uses
248         ** the default collation sequences for each column. */
249         int i, j;
250         for(i=0; i<nCol; i++){
251           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
252           char *zDfltColl;                  /* Def. collation for column */
253           char *zIdxCol;                    /* Name of indexed column */
254 
255           /* If the index uses a collation sequence that is different from
256           ** the default collation sequence for the column, this index is
257           ** unusable. Bail out early in this case.  */
258           zDfltColl = pParent->aCol[iCol].zColl;
259           if( !zDfltColl ){
260             zDfltColl = "BINARY";
261           }
262           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
263 
264           zIdxCol = pParent->aCol[iCol].zName;
265           for(j=0; j<nCol; j++){
266             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
267               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
268               break;
269             }
270           }
271           if( j==nCol ) break;
272         }
273         if( i==nCol ) break;      /* pIdx is usable */
274       }
275     }
276   }
277 
278   if( !pIdx ){
279     if( !pParse->disableTriggers ){
280       sqlite3ErrorMsg(pParse,
281            "foreign key mismatch - \"%w\" referencing \"%w\"",
282            pFKey->pFrom->zName, pFKey->zTo);
283     }
284     sqlite3DbFree(pParse->db, aiCol);
285     return 1;
286   }
287 
288   *ppIdx = pIdx;
289   return 0;
290 }
291 
292 /*
293 ** This function is called when a row is inserted into or deleted from the
294 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
295 ** on the child table of pFKey, this function is invoked twice for each row
296 ** affected - once to "delete" the old row, and then again to "insert" the
297 ** new row.
298 **
299 ** Each time it is called, this function generates VDBE code to locate the
300 ** row in the parent table that corresponds to the row being inserted into
301 ** or deleted from the child table. If the parent row can be found, no
302 ** special action is taken. Otherwise, if the parent row can *not* be
303 ** found in the parent table:
304 **
305 **   Operation | FK type   | Action taken
306 **   --------------------------------------------------------------------------
307 **   INSERT      immediate   Increment the "immediate constraint counter".
308 **
309 **   DELETE      immediate   Decrement the "immediate constraint counter".
310 **
311 **   INSERT      deferred    Increment the "deferred constraint counter".
312 **
313 **   DELETE      deferred    Decrement the "deferred constraint counter".
314 **
315 ** These operations are identified in the comment at the top of this file
316 ** (fkey.c) as "I.1" and "D.1".
317 */
318 static void fkLookupParent(
319   Parse *pParse,        /* Parse context */
320   int iDb,              /* Index of database housing pTab */
321   Table *pTab,          /* Parent table of FK pFKey */
322   Index *pIdx,          /* Unique index on parent key columns in pTab */
323   FKey *pFKey,          /* Foreign key constraint */
324   int *aiCol,           /* Map from parent key columns to child table columns */
325   int regData,          /* Address of array containing child table row */
326   int nIncr,            /* Increment constraint counter by this */
327   int isIgnore          /* If true, pretend pTab contains all NULL values */
328 ){
329   int i;                                    /* Iterator variable */
330   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
331   int iCur = pParse->nTab - 1;              /* Cursor number to use */
332   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
333 
334   /* If nIncr is less than zero, then check at runtime if there are any
335   ** outstanding constraints to resolve. If there are not, there is no need
336   ** to check if deleting this row resolves any outstanding violations.
337   **
338   ** Check if any of the key columns in the child table row are NULL. If
339   ** any are, then the constraint is considered satisfied. No need to
340   ** search for a matching row in the parent table.  */
341   if( nIncr<0 ){
342     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
343     VdbeCoverage(v);
344   }
345   for(i=0; i<pFKey->nCol; i++){
346     int iReg = aiCol[i] + regData + 1;
347     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
348   }
349 
350   if( isIgnore==0 ){
351     if( pIdx==0 ){
352       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
353       ** column of the parent table (table pTab).  */
354       int iMustBeInt;               /* Address of MustBeInt instruction */
355       int regTemp = sqlite3GetTempReg(pParse);
356 
357       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
358       ** apply the affinity of the parent key). If this fails, then there
359       ** is no matching parent key. Before using MustBeInt, make a copy of
360       ** the value. Otherwise, the value inserted into the child key column
361       ** will have INTEGER affinity applied to it, which may not be correct.  */
362       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
363       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
364       VdbeCoverage(v);
365 
366       /* If the parent table is the same as the child table, and we are about
367       ** to increment the constraint-counter (i.e. this is an INSERT operation),
368       ** then check if the row being inserted matches itself. If so, do not
369       ** increment the constraint-counter.  */
370       if( pTab==pFKey->pFrom && nIncr==1 ){
371         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
372         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
373       }
374 
375       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
376       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
377       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
378       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
379       sqlite3VdbeJumpHere(v, iMustBeInt);
380       sqlite3ReleaseTempReg(pParse, regTemp);
381     }else{
382       int nCol = pFKey->nCol;
383       int regTemp = sqlite3GetTempRange(pParse, nCol);
384       int regRec = sqlite3GetTempReg(pParse);
385 
386       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
387       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
388       for(i=0; i<nCol; i++){
389         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
390       }
391 
392       /* If the parent table is the same as the child table, and we are about
393       ** to increment the constraint-counter (i.e. this is an INSERT operation),
394       ** then check if the row being inserted matches itself. If so, do not
395       ** increment the constraint-counter.
396       **
397       ** If any of the parent-key values are NULL, then the row cannot match
398       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
399       ** of the parent-key values are NULL (at this point it is known that
400       ** none of the child key values are).
401       */
402       if( pTab==pFKey->pFrom && nIncr==1 ){
403         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
404         for(i=0; i<nCol; i++){
405           int iChild = aiCol[i]+1+regData;
406           int iParent = pIdx->aiColumn[i]+1+regData;
407           assert( aiCol[i]!=pTab->iPKey );
408           if( pIdx->aiColumn[i]==pTab->iPKey ){
409             /* The parent key is a composite key that includes the IPK column */
410             iParent = regData;
411           }
412           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
413           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
414         }
415         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
416       }
417 
418       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
419                         sqlite3IndexAffinityStr(v,pIdx), nCol);
420       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
421 
422       sqlite3ReleaseTempReg(pParse, regRec);
423       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
424     }
425   }
426 
427   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
428    && !pParse->pToplevel
429    && !pParse->isMultiWrite
430   ){
431     /* Special case: If this is an INSERT statement that will insert exactly
432     ** one row into the table, raise a constraint immediately instead of
433     ** incrementing a counter. This is necessary as the VM code is being
434     ** generated for will not open a statement transaction.  */
435     assert( nIncr==1 );
436     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
437         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
438   }else{
439     if( nIncr>0 && pFKey->isDeferred==0 ){
440       sqlite3MayAbort(pParse);
441     }
442     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
443   }
444 
445   sqlite3VdbeResolveLabel(v, iOk);
446   sqlite3VdbeAddOp1(v, OP_Close, iCur);
447 }
448 
449 
450 /*
451 ** Return an Expr object that refers to a memory register corresponding
452 ** to column iCol of table pTab.
453 **
454 ** regBase is the first of an array of register that contains the data
455 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
456 ** column.  regBase+2 holds the second column, and so forth.
457 */
458 static Expr *exprTableRegister(
459   Parse *pParse,     /* Parsing and code generating context */
460   Table *pTab,       /* The table whose content is at r[regBase]... */
461   int regBase,       /* Contents of table pTab */
462   i16 iCol           /* Which column of pTab is desired */
463 ){
464   Expr *pExpr;
465   Column *pCol;
466   const char *zColl;
467   sqlite3 *db = pParse->db;
468 
469   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
470   if( pExpr ){
471     if( iCol>=0 && iCol!=pTab->iPKey ){
472       pCol = &pTab->aCol[iCol];
473       pExpr->iTable = regBase + iCol + 1;
474       pExpr->affinity = pCol->affinity;
475       zColl = pCol->zColl;
476       if( zColl==0 ) zColl = db->pDfltColl->zName;
477       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
478     }else{
479       pExpr->iTable = regBase;
480       pExpr->affinity = SQLITE_AFF_INTEGER;
481     }
482   }
483   return pExpr;
484 }
485 
486 /*
487 ** Return an Expr object that refers to column iCol of table pTab which
488 ** has cursor iCur.
489 */
490 static Expr *exprTableColumn(
491   sqlite3 *db,      /* The database connection */
492   Table *pTab,      /* The table whose column is desired */
493   int iCursor,      /* The open cursor on the table */
494   i16 iCol          /* The column that is wanted */
495 ){
496   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
497   if( pExpr ){
498     pExpr->pTab = pTab;
499     pExpr->iTable = iCursor;
500     pExpr->iColumn = iCol;
501   }
502   return pExpr;
503 }
504 
505 /*
506 ** This function is called to generate code executed when a row is deleted
507 ** from the parent table of foreign key constraint pFKey and, if pFKey is
508 ** deferred, when a row is inserted into the same table. When generating
509 ** code for an SQL UPDATE operation, this function may be called twice -
510 ** once to "delete" the old row and once to "insert" the new row.
511 **
512 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
513 ** the number of FK violations in the db) or +1 when deleting one (as this
514 ** may increase the number of FK constraint problems).
515 **
516 ** The code generated by this function scans through the rows in the child
517 ** table that correspond to the parent table row being deleted or inserted.
518 ** For each child row found, one of the following actions is taken:
519 **
520 **   Operation | FK type   | Action taken
521 **   --------------------------------------------------------------------------
522 **   DELETE      immediate   Increment the "immediate constraint counter".
523 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
524 **                           throw a "FOREIGN KEY constraint failed" exception.
525 **
526 **   INSERT      immediate   Decrement the "immediate constraint counter".
527 **
528 **   DELETE      deferred    Increment the "deferred constraint counter".
529 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
530 **                           throw a "FOREIGN KEY constraint failed" exception.
531 **
532 **   INSERT      deferred    Decrement the "deferred constraint counter".
533 **
534 ** These operations are identified in the comment at the top of this file
535 ** (fkey.c) as "I.2" and "D.2".
536 */
537 static void fkScanChildren(
538   Parse *pParse,                  /* Parse context */
539   SrcList *pSrc,                  /* The child table to be scanned */
540   Table *pTab,                    /* The parent table */
541   Index *pIdx,                    /* Index on parent covering the foreign key */
542   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
543   int *aiCol,                     /* Map from pIdx cols to child table cols */
544   int regData,                    /* Parent row data starts here */
545   int nIncr                       /* Amount to increment deferred counter by */
546 ){
547   sqlite3 *db = pParse->db;       /* Database handle */
548   int i;                          /* Iterator variable */
549   Expr *pWhere = 0;               /* WHERE clause to scan with */
550   NameContext sNameContext;       /* Context used to resolve WHERE clause */
551   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
552   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
553   Vdbe *v = sqlite3GetVdbe(pParse);
554 
555   assert( pIdx==0 || pIdx->pTable==pTab );
556   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
557   assert( pIdx!=0 || pFKey->nCol==1 );
558   assert( pIdx!=0 || HasRowid(pTab) );
559 
560   if( nIncr<0 ){
561     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
562     VdbeCoverage(v);
563   }
564 
565   /* Create an Expr object representing an SQL expression like:
566   **
567   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
568   **
569   ** The collation sequence used for the comparison should be that of
570   ** the parent key columns. The affinity of the parent key column should
571   ** be applied to each child key value before the comparison takes place.
572   */
573   for(i=0; i<pFKey->nCol; i++){
574     Expr *pLeft;                  /* Value from parent table row */
575     Expr *pRight;                 /* Column ref to child table */
576     Expr *pEq;                    /* Expression (pLeft = pRight) */
577     i16 iCol;                     /* Index of column in child table */
578     const char *zCol;             /* Name of column in child table */
579 
580     iCol = pIdx ? pIdx->aiColumn[i] : -1;
581     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
582     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
583     assert( iCol>=0 );
584     zCol = pFKey->pFrom->aCol[iCol].zName;
585     pRight = sqlite3Expr(db, TK_ID, zCol);
586     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
587     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
588   }
589 
590   /* If the child table is the same as the parent table, then add terms
591   ** to the WHERE clause that prevent this entry from being scanned.
592   ** The added WHERE clause terms are like this:
593   **
594   **     $current_rowid!=rowid
595   **     NOT( $current_a==a AND $current_b==b AND ... )
596   **
597   ** The first form is used for rowid tables.  The second form is used
598   ** for WITHOUT ROWID tables.  In the second form, the primary key is
599   ** (a,b,...)
600   */
601   if( pTab==pFKey->pFrom && nIncr>0 ){
602     Expr *pNe;                    /* Expression (pLeft != pRight) */
603     Expr *pLeft;                  /* Value from parent table row */
604     Expr *pRight;                 /* Column ref to child table */
605     if( HasRowid(pTab) ){
606       pLeft = exprTableRegister(pParse, pTab, regData, -1);
607       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
608       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
609     }else{
610       Expr *pEq, *pAll = 0;
611       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
612       assert( pIdx!=0 );
613       for(i=0; i<pPk->nKeyCol; i++){
614         i16 iCol = pIdx->aiColumn[i];
615         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
616         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
617         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
618         pAll = sqlite3ExprAnd(db, pAll, pEq);
619       }
620       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
621     }
622     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
623   }
624 
625   /* Resolve the references in the WHERE clause. */
626   memset(&sNameContext, 0, sizeof(NameContext));
627   sNameContext.pSrcList = pSrc;
628   sNameContext.pParse = pParse;
629   sqlite3ResolveExprNames(&sNameContext, pWhere);
630 
631   /* Create VDBE to loop through the entries in pSrc that match the WHERE
632   ** clause. For each row found, increment either the deferred or immediate
633   ** foreign key constraint counter. */
634   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
635   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
636   if( pWInfo ){
637     sqlite3WhereEnd(pWInfo);
638   }
639 
640   /* Clean up the WHERE clause constructed above. */
641   sqlite3ExprDelete(db, pWhere);
642   if( iFkIfZero ){
643     sqlite3VdbeJumpHere(v, iFkIfZero);
644   }
645 }
646 
647 /*
648 ** This function returns a linked list of FKey objects (connected by
649 ** FKey.pNextTo) holding all children of table pTab.  For example,
650 ** given the following schema:
651 **
652 **   CREATE TABLE t1(a PRIMARY KEY);
653 **   CREATE TABLE t2(b REFERENCES t1(a);
654 **
655 ** Calling this function with table "t1" as an argument returns a pointer
656 ** to the FKey structure representing the foreign key constraint on table
657 ** "t2". Calling this function with "t2" as the argument would return a
658 ** NULL pointer (as there are no FK constraints for which t2 is the parent
659 ** table).
660 */
661 FKey *sqlite3FkReferences(Table *pTab){
662   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
663 }
664 
665 /*
666 ** The second argument is a Trigger structure allocated by the
667 ** fkActionTrigger() routine. This function deletes the Trigger structure
668 ** and all of its sub-components.
669 **
670 ** The Trigger structure or any of its sub-components may be allocated from
671 ** the lookaside buffer belonging to database handle dbMem.
672 */
673 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
674   if( p ){
675     TriggerStep *pStep = p->step_list;
676     sqlite3ExprDelete(dbMem, pStep->pWhere);
677     sqlite3ExprListDelete(dbMem, pStep->pExprList);
678     sqlite3SelectDelete(dbMem, pStep->pSelect);
679     sqlite3ExprDelete(dbMem, p->pWhen);
680     sqlite3DbFree(dbMem, p);
681   }
682 }
683 
684 /*
685 ** This function is called to generate code that runs when table pTab is
686 ** being dropped from the database. The SrcList passed as the second argument
687 ** to this function contains a single entry guaranteed to resolve to
688 ** table pTab.
689 **
690 ** Normally, no code is required. However, if either
691 **
692 **   (a) The table is the parent table of a FK constraint, or
693 **   (b) The table is the child table of a deferred FK constraint and it is
694 **       determined at runtime that there are outstanding deferred FK
695 **       constraint violations in the database,
696 **
697 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
698 ** the table from the database. Triggers are disabled while running this
699 ** DELETE, but foreign key actions are not.
700 */
701 void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
702   sqlite3 *db = pParse->db;
703   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
704     int iSkip = 0;
705     Vdbe *v = sqlite3GetVdbe(pParse);
706 
707     assert( v );                  /* VDBE has already been allocated */
708     if( sqlite3FkReferences(pTab)==0 ){
709       /* Search for a deferred foreign key constraint for which this table
710       ** is the child table. If one cannot be found, return without
711       ** generating any VDBE code. If one can be found, then jump over
712       ** the entire DELETE if there are no outstanding deferred constraints
713       ** when this statement is run.  */
714       FKey *p;
715       for(p=pTab->pFKey; p; p=p->pNextFrom){
716         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
717       }
718       if( !p ) return;
719       iSkip = sqlite3VdbeMakeLabel(v);
720       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
721     }
722 
723     pParse->disableTriggers = 1;
724     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
725     pParse->disableTriggers = 0;
726 
727     /* If the DELETE has generated immediate foreign key constraint
728     ** violations, halt the VDBE and return an error at this point, before
729     ** any modifications to the schema are made. This is because statement
730     ** transactions are not able to rollback schema changes.
731     **
732     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
733     ** the statement transaction will not be rolled back even if FK
734     ** constraints are violated.
735     */
736     if( (db->flags & SQLITE_DeferFKs)==0 ){
737       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
738       VdbeCoverage(v);
739       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
740           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
741     }
742 
743     if( iSkip ){
744       sqlite3VdbeResolveLabel(v, iSkip);
745     }
746   }
747 }
748 
749 
750 /*
751 ** The second argument points to an FKey object representing a foreign key
752 ** for which pTab is the child table. An UPDATE statement against pTab
753 ** is currently being processed. For each column of the table that is
754 ** actually updated, the corresponding element in the aChange[] array
755 ** is zero or greater (if a column is unmodified the corresponding element
756 ** is set to -1). If the rowid column is modified by the UPDATE statement
757 ** the bChngRowid argument is non-zero.
758 **
759 ** This function returns true if any of the columns that are part of the
760 ** child key for FK constraint *p are modified.
761 */
762 static int fkChildIsModified(
763   Table *pTab,                    /* Table being updated */
764   FKey *p,                        /* Foreign key for which pTab is the child */
765   int *aChange,                   /* Array indicating modified columns */
766   int bChngRowid                  /* True if rowid is modified by this update */
767 ){
768   int i;
769   for(i=0; i<p->nCol; i++){
770     int iChildKey = p->aCol[i].iFrom;
771     if( aChange[iChildKey]>=0 ) return 1;
772     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
773   }
774   return 0;
775 }
776 
777 /*
778 ** The second argument points to an FKey object representing a foreign key
779 ** for which pTab is the parent table. An UPDATE statement against pTab
780 ** is currently being processed. For each column of the table that is
781 ** actually updated, the corresponding element in the aChange[] array
782 ** is zero or greater (if a column is unmodified the corresponding element
783 ** is set to -1). If the rowid column is modified by the UPDATE statement
784 ** the bChngRowid argument is non-zero.
785 **
786 ** This function returns true if any of the columns that are part of the
787 ** parent key for FK constraint *p are modified.
788 */
789 static int fkParentIsModified(
790   Table *pTab,
791   FKey *p,
792   int *aChange,
793   int bChngRowid
794 ){
795   int i;
796   for(i=0; i<p->nCol; i++){
797     char *zKey = p->aCol[i].zCol;
798     int iKey;
799     for(iKey=0; iKey<pTab->nCol; iKey++){
800       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
801         Column *pCol = &pTab->aCol[iKey];
802         if( zKey ){
803           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
804         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
805           return 1;
806         }
807       }
808     }
809   }
810   return 0;
811 }
812 
813 /*
814 ** Return true if the parser passed as the first argument is being
815 ** used to code a trigger that is really a "SET NULL" action belonging
816 ** to trigger pFKey.
817 */
818 static int isSetNullAction(Parse *pParse, FKey *pFKey){
819   Parse *pTop = sqlite3ParseToplevel(pParse);
820   if( pTop->pTriggerPrg ){
821     Trigger *p = pTop->pTriggerPrg->pTrigger;
822     if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
823      || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
824     ){
825       return 1;
826     }
827   }
828   return 0;
829 }
830 
831 /*
832 ** This function is called when inserting, deleting or updating a row of
833 ** table pTab to generate VDBE code to perform foreign key constraint
834 ** processing for the operation.
835 **
836 ** For a DELETE operation, parameter regOld is passed the index of the
837 ** first register in an array of (pTab->nCol+1) registers containing the
838 ** rowid of the row being deleted, followed by each of the column values
839 ** of the row being deleted, from left to right. Parameter regNew is passed
840 ** zero in this case.
841 **
842 ** For an INSERT operation, regOld is passed zero and regNew is passed the
843 ** first register of an array of (pTab->nCol+1) registers containing the new
844 ** row data.
845 **
846 ** For an UPDATE operation, this function is called twice. Once before
847 ** the original record is deleted from the table using the calling convention
848 ** described for DELETE. Then again after the original record is deleted
849 ** but before the new record is inserted using the INSERT convention.
850 */
851 void sqlite3FkCheck(
852   Parse *pParse,                  /* Parse context */
853   Table *pTab,                    /* Row is being deleted from this table */
854   int regOld,                     /* Previous row data is stored here */
855   int regNew,                     /* New row data is stored here */
856   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
857   int bChngRowid                  /* True if rowid is UPDATEd */
858 ){
859   sqlite3 *db = pParse->db;       /* Database handle */
860   FKey *pFKey;                    /* Used to iterate through FKs */
861   int iDb;                        /* Index of database containing pTab */
862   const char *zDb;                /* Name of database containing pTab */
863   int isIgnoreErrors = pParse->disableTriggers;
864 
865   /* Exactly one of regOld and regNew should be non-zero. */
866   assert( (regOld==0)!=(regNew==0) );
867 
868   /* If foreign-keys are disabled, this function is a no-op. */
869   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
870 
871   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
872   zDb = db->aDb[iDb].zName;
873 
874   /* Loop through all the foreign key constraints for which pTab is the
875   ** child table (the table that the foreign key definition is part of).  */
876   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
877     Table *pTo;                   /* Parent table of foreign key pFKey */
878     Index *pIdx = 0;              /* Index on key columns in pTo */
879     int *aiFree = 0;
880     int *aiCol;
881     int iCol;
882     int i;
883     int bIgnore = 0;
884 
885     if( aChange
886      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
887      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
888     ){
889       continue;
890     }
891 
892     /* Find the parent table of this foreign key. Also find a unique index
893     ** on the parent key columns in the parent table. If either of these
894     ** schema items cannot be located, set an error in pParse and return
895     ** early.  */
896     if( pParse->disableTriggers ){
897       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
898     }else{
899       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
900     }
901     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
902       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
903       if( !isIgnoreErrors || db->mallocFailed ) return;
904       if( pTo==0 ){
905         /* If isIgnoreErrors is true, then a table is being dropped. In this
906         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
907         ** before actually dropping it in order to check FK constraints.
908         ** If the parent table of an FK constraint on the current table is
909         ** missing, behave as if it is empty. i.e. decrement the relevant
910         ** FK counter for each row of the current table with non-NULL keys.
911         */
912         Vdbe *v = sqlite3GetVdbe(pParse);
913         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
914         for(i=0; i<pFKey->nCol; i++){
915           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
916           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
917         }
918         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
919       }
920       continue;
921     }
922     assert( pFKey->nCol==1 || (aiFree && pIdx) );
923 
924     if( aiFree ){
925       aiCol = aiFree;
926     }else{
927       iCol = pFKey->aCol[0].iFrom;
928       aiCol = &iCol;
929     }
930     for(i=0; i<pFKey->nCol; i++){
931       if( aiCol[i]==pTab->iPKey ){
932         aiCol[i] = -1;
933       }
934 #ifndef SQLITE_OMIT_AUTHORIZATION
935       /* Request permission to read the parent key columns. If the
936       ** authorization callback returns SQLITE_IGNORE, behave as if any
937       ** values read from the parent table are NULL. */
938       if( db->xAuth ){
939         int rcauth;
940         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
941         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
942         bIgnore = (rcauth==SQLITE_IGNORE);
943       }
944 #endif
945     }
946 
947     /* Take a shared-cache advisory read-lock on the parent table. Allocate
948     ** a cursor to use to search the unique index on the parent key columns
949     ** in the parent table.  */
950     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
951     pParse->nTab++;
952 
953     if( regOld!=0 ){
954       /* A row is being removed from the child table. Search for the parent.
955       ** If the parent does not exist, removing the child row resolves an
956       ** outstanding foreign key constraint violation. */
957       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
958     }
959     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
960       /* A row is being added to the child table. If a parent row cannot
961       ** be found, adding the child row has violated the FK constraint.
962       **
963       ** If this operation is being performed as part of a trigger program
964       ** that is actually a "SET NULL" action belonging to this very
965       ** foreign key, then omit this scan altogether. As all child key
966       ** values are guaranteed to be NULL, it is not possible for adding
967       ** this row to cause an FK violation.  */
968       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
969     }
970 
971     sqlite3DbFree(db, aiFree);
972   }
973 
974   /* Loop through all the foreign key constraints that refer to this table.
975   ** (the "child" constraints) */
976   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
977     Index *pIdx = 0;              /* Foreign key index for pFKey */
978     SrcList *pSrc;
979     int *aiCol = 0;
980 
981     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
982       continue;
983     }
984 
985     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
986      && !pParse->pToplevel && !pParse->isMultiWrite
987     ){
988       assert( regOld==0 && regNew!=0 );
989       /* Inserting a single row into a parent table cannot cause (or fix)
990       ** an immediate foreign key violation. So do nothing in this case.  */
991       continue;
992     }
993 
994     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
995       if( !isIgnoreErrors || db->mallocFailed ) return;
996       continue;
997     }
998     assert( aiCol || pFKey->nCol==1 );
999 
1000     /* Create a SrcList structure containing the child table.  We need the
1001     ** child table as a SrcList for sqlite3WhereBegin() */
1002     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
1003     if( pSrc ){
1004       struct SrcList_item *pItem = pSrc->a;
1005       pItem->pTab = pFKey->pFrom;
1006       pItem->zName = pFKey->pFrom->zName;
1007       pItem->pTab->nRef++;
1008       pItem->iCursor = pParse->nTab++;
1009 
1010       if( regNew!=0 ){
1011         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
1012       }
1013       if( regOld!=0 ){
1014         int eAction = pFKey->aAction[aChange!=0];
1015         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
1016         /* If this is a deferred FK constraint, or a CASCADE or SET NULL
1017         ** action applies, then any foreign key violations caused by
1018         ** removing the parent key will be rectified by the action trigger.
1019         ** So do not set the "may-abort" flag in this case.
1020         **
1021         ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
1022         ** may-abort flag will eventually be set on this statement anyway
1023         ** (when this function is called as part of processing the UPDATE
1024         ** within the action trigger).
1025         **
1026         ** Note 2: At first glance it may seem like SQLite could simply omit
1027         ** all OP_FkCounter related scans when either CASCADE or SET NULL
1028         ** applies. The trouble starts if the CASCADE or SET NULL action
1029         ** trigger causes other triggers or action rules attached to the
1030         ** child table to fire. In these cases the fk constraint counters
1031         ** might be set incorrectly if any OP_FkCounter related scans are
1032         ** omitted.  */
1033         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
1034           sqlite3MayAbort(pParse);
1035         }
1036       }
1037       pItem->zName = 0;
1038       sqlite3SrcListDelete(db, pSrc);
1039     }
1040     sqlite3DbFree(db, aiCol);
1041   }
1042 }
1043 
1044 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
1045 
1046 /*
1047 ** This function is called before generating code to update or delete a
1048 ** row contained in table pTab.
1049 */
1050 u32 sqlite3FkOldmask(
1051   Parse *pParse,                  /* Parse context */
1052   Table *pTab                     /* Table being modified */
1053 ){
1054   u32 mask = 0;
1055   if( pParse->db->flags&SQLITE_ForeignKeys ){
1056     FKey *p;
1057     int i;
1058     for(p=pTab->pFKey; p; p=p->pNextFrom){
1059       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
1060     }
1061     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
1062       Index *pIdx = 0;
1063       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
1064       if( pIdx ){
1065         for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
1066       }
1067     }
1068   }
1069   return mask;
1070 }
1071 
1072 
1073 /*
1074 ** This function is called before generating code to update or delete a
1075 ** row contained in table pTab. If the operation is a DELETE, then
1076 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
1077 ** to an array of size N, where N is the number of columns in table pTab.
1078 ** If the i'th column is not modified by the UPDATE, then the corresponding
1079 ** entry in the aChange[] array is set to -1. If the column is modified,
1080 ** the value is 0 or greater. Parameter chngRowid is set to true if the
1081 ** UPDATE statement modifies the rowid fields of the table.
1082 **
1083 ** If any foreign key processing will be required, this function returns
1084 ** true. If there is no foreign key related processing, this function
1085 ** returns false.
1086 */
1087 int sqlite3FkRequired(
1088   Parse *pParse,                  /* Parse context */
1089   Table *pTab,                    /* Table being modified */
1090   int *aChange,                   /* Non-NULL for UPDATE operations */
1091   int chngRowid                   /* True for UPDATE that affects rowid */
1092 ){
1093   if( pParse->db->flags&SQLITE_ForeignKeys ){
1094     if( !aChange ){
1095       /* A DELETE operation. Foreign key processing is required if the
1096       ** table in question is either the child or parent table for any
1097       ** foreign key constraint.  */
1098       return (sqlite3FkReferences(pTab) || pTab->pFKey);
1099     }else{
1100       /* This is an UPDATE. Foreign key processing is only required if the
1101       ** operation modifies one or more child or parent key columns. */
1102       FKey *p;
1103 
1104       /* Check if any child key columns are being modified. */
1105       for(p=pTab->pFKey; p; p=p->pNextFrom){
1106         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
1107       }
1108 
1109       /* Check if any parent key columns are being modified. */
1110       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
1111         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
1112       }
1113     }
1114   }
1115   return 0;
1116 }
1117 
1118 /*
1119 ** This function is called when an UPDATE or DELETE operation is being
1120 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
1121 ** If the current operation is an UPDATE, then the pChanges parameter is
1122 ** passed a pointer to the list of columns being modified. If it is a
1123 ** DELETE, pChanges is passed a NULL pointer.
1124 **
1125 ** It returns a pointer to a Trigger structure containing a trigger
1126 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
1127 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
1128 ** returned (these actions require no special handling by the triggers
1129 ** sub-system, code for them is created by fkScanChildren()).
1130 **
1131 ** For example, if pFKey is the foreign key and pTab is table "p" in
1132 ** the following schema:
1133 **
1134 **   CREATE TABLE p(pk PRIMARY KEY);
1135 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
1136 **
1137 ** then the returned trigger structure is equivalent to:
1138 **
1139 **   CREATE TRIGGER ... DELETE ON p BEGIN
1140 **     DELETE FROM c WHERE ck = old.pk;
1141 **   END;
1142 **
1143 ** The returned pointer is cached as part of the foreign key object. It
1144 ** is eventually freed along with the rest of the foreign key object by
1145 ** sqlite3FkDelete().
1146 */
1147 static Trigger *fkActionTrigger(
1148   Parse *pParse,                  /* Parse context */
1149   Table *pTab,                    /* Table being updated or deleted from */
1150   FKey *pFKey,                    /* Foreign key to get action for */
1151   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
1152 ){
1153   sqlite3 *db = pParse->db;       /* Database handle */
1154   int action;                     /* One of OE_None, OE_Cascade etc. */
1155   Trigger *pTrigger;              /* Trigger definition to return */
1156   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
1157 
1158   action = pFKey->aAction[iAction];
1159   pTrigger = pFKey->apTrigger[iAction];
1160 
1161   if( action!=OE_None && !pTrigger ){
1162     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
1163     char const *zFrom;            /* Name of child table */
1164     int nFrom;                    /* Length in bytes of zFrom */
1165     Index *pIdx = 0;              /* Parent key index for this FK */
1166     int *aiCol = 0;               /* child table cols -> parent key cols */
1167     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
1168     Expr *pWhere = 0;             /* WHERE clause of trigger step */
1169     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
1170     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
1171     int i;                        /* Iterator variable */
1172     Expr *pWhen = 0;              /* WHEN clause for the trigger */
1173 
1174     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
1175     assert( aiCol || pFKey->nCol==1 );
1176 
1177     for(i=0; i<pFKey->nCol; i++){
1178       Token tOld = { "old", 3 };  /* Literal "old" token */
1179       Token tNew = { "new", 3 };  /* Literal "new" token */
1180       Token tFromCol;             /* Name of column in child table */
1181       Token tToCol;               /* Name of column in parent table */
1182       int iFromCol;               /* Idx of column in child table */
1183       Expr *pEq;                  /* tFromCol = OLD.tToCol */
1184 
1185       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
1186       assert( iFromCol>=0 );
1187       assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
1188       tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
1189       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
1190 
1191       tToCol.n = sqlite3Strlen30(tToCol.z);
1192       tFromCol.n = sqlite3Strlen30(tFromCol.z);
1193 
1194       /* Create the expression "OLD.zToCol = zFromCol". It is important
1195       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
1196       ** that the affinity and collation sequence associated with the
1197       ** parent table are used for the comparison. */
1198       pEq = sqlite3PExpr(pParse, TK_EQ,
1199           sqlite3PExpr(pParse, TK_DOT,
1200             sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
1201             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
1202           , 0),
1203           sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
1204       , 0);
1205       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
1206 
1207       /* For ON UPDATE, construct the next term of the WHEN clause.
1208       ** The final WHEN clause will be like this:
1209       **
1210       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
1211       */
1212       if( pChanges ){
1213         pEq = sqlite3PExpr(pParse, TK_IS,
1214             sqlite3PExpr(pParse, TK_DOT,
1215               sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
1216               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
1217               0),
1218             sqlite3PExpr(pParse, TK_DOT,
1219               sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
1220               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
1221               0),
1222             0);
1223         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
1224       }
1225 
1226       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
1227         Expr *pNew;
1228         if( action==OE_Cascade ){
1229           pNew = sqlite3PExpr(pParse, TK_DOT,
1230             sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
1231             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
1232           , 0);
1233         }else if( action==OE_SetDflt ){
1234           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
1235           if( pDflt ){
1236             pNew = sqlite3ExprDup(db, pDflt, 0);
1237           }else{
1238             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
1239           }
1240         }else{
1241           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
1242         }
1243         pList = sqlite3ExprListAppend(pParse, pList, pNew);
1244         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
1245       }
1246     }
1247     sqlite3DbFree(db, aiCol);
1248 
1249     zFrom = pFKey->pFrom->zName;
1250     nFrom = sqlite3Strlen30(zFrom);
1251 
1252     if( action==OE_Restrict ){
1253       Token tFrom;
1254       Expr *pRaise;
1255 
1256       tFrom.z = zFrom;
1257       tFrom.n = nFrom;
1258       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
1259       if( pRaise ){
1260         pRaise->affinity = OE_Abort;
1261       }
1262       pSelect = sqlite3SelectNew(pParse,
1263           sqlite3ExprListAppend(pParse, 0, pRaise),
1264           sqlite3SrcListAppend(db, 0, &tFrom, 0),
1265           pWhere,
1266           0, 0, 0, 0, 0, 0
1267       );
1268       pWhere = 0;
1269     }
1270 
1271     /* Disable lookaside memory allocation */
1272     enableLookaside = db->lookaside.bEnabled;
1273     db->lookaside.bEnabled = 0;
1274 
1275     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
1276         sizeof(Trigger) +         /* struct Trigger */
1277         sizeof(TriggerStep) +     /* Single step in trigger program */
1278         nFrom + 1                 /* Space for pStep->zTarget */
1279     );
1280     if( pTrigger ){
1281       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
1282       pStep->zTarget = (char *)&pStep[1];
1283       memcpy((char *)pStep->zTarget, zFrom, nFrom);
1284 
1285       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
1286       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
1287       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
1288       if( pWhen ){
1289         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
1290         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
1291       }
1292     }
1293 
1294     /* Re-enable the lookaside buffer, if it was disabled earlier. */
1295     db->lookaside.bEnabled = enableLookaside;
1296 
1297     sqlite3ExprDelete(db, pWhere);
1298     sqlite3ExprDelete(db, pWhen);
1299     sqlite3ExprListDelete(db, pList);
1300     sqlite3SelectDelete(db, pSelect);
1301     if( db->mallocFailed==1 ){
1302       fkTriggerDelete(db, pTrigger);
1303       return 0;
1304     }
1305     assert( pStep!=0 );
1306 
1307     switch( action ){
1308       case OE_Restrict:
1309         pStep->op = TK_SELECT;
1310         break;
1311       case OE_Cascade:
1312         if( !pChanges ){
1313           pStep->op = TK_DELETE;
1314           break;
1315         }
1316       default:
1317         pStep->op = TK_UPDATE;
1318     }
1319     pStep->pTrig = pTrigger;
1320     pTrigger->pSchema = pTab->pSchema;
1321     pTrigger->pTabSchema = pTab->pSchema;
1322     pFKey->apTrigger[iAction] = pTrigger;
1323     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
1324   }
1325 
1326   return pTrigger;
1327 }
1328 
1329 /*
1330 ** This function is called when deleting or updating a row to implement
1331 ** any required CASCADE, SET NULL or SET DEFAULT actions.
1332 */
1333 void sqlite3FkActions(
1334   Parse *pParse,                  /* Parse context */
1335   Table *pTab,                    /* Table being updated or deleted from */
1336   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
1337   int regOld,                     /* Address of array containing old row */
1338   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
1339   int bChngRowid                  /* True if rowid is UPDATEd */
1340 ){
1341   /* If foreign-key support is enabled, iterate through all FKs that
1342   ** refer to table pTab. If there is an action associated with the FK
1343   ** for this operation (either update or delete), invoke the associated
1344   ** trigger sub-program.  */
1345   if( pParse->db->flags&SQLITE_ForeignKeys ){
1346     FKey *pFKey;                  /* Iterator variable */
1347     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
1348       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
1349         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
1350         if( pAct ){
1351           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
1352         }
1353       }
1354     }
1355   }
1356 }
1357 
1358 #endif /* ifndef SQLITE_OMIT_TRIGGER */
1359 
1360 /*
1361 ** Free all memory associated with foreign key definitions attached to
1362 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
1363 ** hash table.
1364 */
1365 void sqlite3FkDelete(sqlite3 *db, Table *pTab){
1366   FKey *pFKey;                    /* Iterator variable */
1367   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
1368 
1369   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
1370   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
1371 
1372     /* Remove the FK from the fkeyHash hash table. */
1373     if( !db || db->pnBytesFreed==0 ){
1374       if( pFKey->pPrevTo ){
1375         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
1376       }else{
1377         void *p = (void *)pFKey->pNextTo;
1378         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
1379         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
1380       }
1381       if( pFKey->pNextTo ){
1382         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
1383       }
1384     }
1385 
1386     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
1387     ** classified as either immediate or deferred.
1388     */
1389     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
1390 
1391     /* Delete any triggers created to implement actions for this FK. */
1392 #ifndef SQLITE_OMIT_TRIGGER
1393     fkTriggerDelete(db, pFKey->apTrigger[0]);
1394     fkTriggerDelete(db, pFKey->apTrigger[1]);
1395 #endif
1396 
1397     pNext = pFKey->pNextFrom;
1398     sqlite3DbFree(db, pFKey);
1399   }
1400 }
1401 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
1402