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