xref: /sqlite-3.40.0/src/fkey.c (revision 41ce47c4)
11da40a38Sdan /*
21da40a38Sdan **
31da40a38Sdan ** The author disclaims copyright to this source code.  In place of
41da40a38Sdan ** a legal notice, here is a blessing:
51da40a38Sdan **
61da40a38Sdan **    May you do good and not evil.
71da40a38Sdan **    May you find forgiveness for yourself and forgive others.
81da40a38Sdan **    May you share freely, never taking more than you give.
91da40a38Sdan **
101da40a38Sdan *************************************************************************
111da40a38Sdan ** This file contains code used by the compiler to add foreign key
121da40a38Sdan ** support to compiled SQL statements.
131da40a38Sdan */
141da40a38Sdan #include "sqliteInt.h"
151da40a38Sdan 
161da40a38Sdan #ifndef SQLITE_OMIT_FOREIGN_KEY
1775cbd984Sdan #ifndef SQLITE_OMIT_TRIGGER
181da40a38Sdan 
191da40a38Sdan /*
201da40a38Sdan ** Deferred and Immediate FKs
211da40a38Sdan ** --------------------------
221da40a38Sdan **
231da40a38Sdan ** Foreign keys in SQLite come in two flavours: deferred and immediate.
24d91c1a17Sdrh ** If an immediate foreign key constraint is violated,
25d91c1a17Sdrh ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
26d91c1a17Sdrh ** statement transaction rolled back. If a
271da40a38Sdan ** deferred foreign key constraint is violated, no action is taken
281da40a38Sdan ** immediately. However if the application attempts to commit the
291da40a38Sdan ** transaction before fixing the constraint violation, the attempt fails.
301da40a38Sdan **
311da40a38Sdan ** Deferred constraints are implemented using a simple counter associated
321da40a38Sdan ** with the database handle. The counter is set to zero each time a
331da40a38Sdan ** database transaction is opened. Each time a statement is executed
341da40a38Sdan ** that causes a foreign key violation, the counter is incremented. Each
351da40a38Sdan ** time a statement is executed that removes an existing violation from
361da40a38Sdan ** the database, the counter is decremented. When the transaction is
371da40a38Sdan ** committed, the commit fails if the current value of the counter is
381da40a38Sdan ** greater than zero. This scheme has two big drawbacks:
391da40a38Sdan **
401da40a38Sdan **   * When a commit fails due to a deferred foreign key constraint,
411da40a38Sdan **     there is no way to tell which foreign constraint is not satisfied,
421da40a38Sdan **     or which row it is not satisfied for.
431da40a38Sdan **
441da40a38Sdan **   * If the database contains foreign key violations when the
451da40a38Sdan **     transaction is opened, this may cause the mechanism to malfunction.
461da40a38Sdan **
471da40a38Sdan ** Despite these problems, this approach is adopted as it seems simpler
481da40a38Sdan ** than the alternatives.
491da40a38Sdan **
501da40a38Sdan ** INSERT operations:
511da40a38Sdan **
528099ce6fSdan **   I.1) For each FK for which the table is the child table, search
538a2fff7aSdan **        the parent table for a match. If none is found increment the
548a2fff7aSdan **        constraint counter.
551da40a38Sdan **
568a2fff7aSdan **   I.2) For each FK for which the table is the parent table,
578099ce6fSdan **        search the child table for rows that correspond to the new
588099ce6fSdan **        row in the parent table. Decrement the counter for each row
591da40a38Sdan **        found (as the constraint is now satisfied).
601da40a38Sdan **
611da40a38Sdan ** DELETE operations:
621da40a38Sdan **
638a2fff7aSdan **   D.1) For each FK for which the table is the child table,
648099ce6fSdan **        search the parent table for a row that corresponds to the
658099ce6fSdan **        deleted row in the child table. If such a row is not found,
661da40a38Sdan **        decrement the counter.
671da40a38Sdan **
688099ce6fSdan **   D.2) For each FK for which the table is the parent table, search
698099ce6fSdan **        the child table for rows that correspond to the deleted row
708a2fff7aSdan **        in the parent table. For each found increment the counter.
711da40a38Sdan **
721da40a38Sdan ** UPDATE operations:
731da40a38Sdan **
741da40a38Sdan **   An UPDATE command requires that all 4 steps above are taken, but only
751da40a38Sdan **   for FK constraints for which the affected columns are actually
761da40a38Sdan **   modified (values must be compared at runtime).
771da40a38Sdan **
781da40a38Sdan ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
791da40a38Sdan ** This simplifies the implementation a bit.
801da40a38Sdan **
811da40a38Sdan ** For the purposes of immediate FK constraints, the OR REPLACE conflict
821da40a38Sdan ** resolution is considered to delete rows before the new row is inserted.
831da40a38Sdan ** If a delete caused by OR REPLACE violates an FK constraint, an exception
841da40a38Sdan ** is thrown, even if the FK constraint would be satisfied after the new
851da40a38Sdan ** row is inserted.
861da40a38Sdan **
87bd747832Sdan ** Immediate constraints are usually handled similarly. The only difference
88bd747832Sdan ** is that the counter used is stored as part of each individual statement
89bd747832Sdan ** object (struct Vdbe). If, after the statement has run, its immediate
90d91c1a17Sdrh ** constraint counter is greater than zero,
91d91c1a17Sdrh ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
92bd747832Sdan ** and the statement transaction is rolled back. An exception is an INSERT
93bd747832Sdan ** statement that inserts a single row only (no triggers). In this case,
94bd747832Sdan ** instead of using a counter, an exception is thrown immediately if the
95bd747832Sdan ** INSERT violates a foreign key constraint. This is necessary as such
96bd747832Sdan ** an INSERT does not open a statement transaction.
97bd747832Sdan **
981da40a38Sdan ** TODO: How should dropping a table be handled? How should renaming a
991da40a38Sdan ** table be handled?
1008099ce6fSdan **
1018099ce6fSdan **
1021da40a38Sdan ** Query API Notes
1031da40a38Sdan ** ---------------
1041da40a38Sdan **
1051da40a38Sdan ** Before coding an UPDATE or DELETE row operation, the code-generator
1061da40a38Sdan ** for those two operations needs to know whether or not the operation
1071da40a38Sdan ** requires any FK processing and, if so, which columns of the original
1081da40a38Sdan ** row are required by the FK processing VDBE code (i.e. if FKs were
1091da40a38Sdan ** implemented using triggers, which of the old.* columns would be
1101da40a38Sdan ** accessed). No information is required by the code-generator before
1118099ce6fSdan ** coding an INSERT operation. The functions used by the UPDATE/DELETE
1128099ce6fSdan ** generation code to query for this information are:
1131da40a38Sdan **
1148099ce6fSdan **   sqlite3FkRequired() - Test to see if FK processing is required.
1158099ce6fSdan **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
1168099ce6fSdan **
1178099ce6fSdan **
1188099ce6fSdan ** Externally accessible module functions
1198099ce6fSdan ** --------------------------------------
1208099ce6fSdan **
1218099ce6fSdan **   sqlite3FkCheck()    - Check for foreign key violations.
1228099ce6fSdan **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
1238099ce6fSdan **   sqlite3FkDelete()   - Delete an FKey structure.
1241da40a38Sdan */
1251da40a38Sdan 
1261da40a38Sdan /*
1271da40a38Sdan ** VDBE Calling Convention
1281da40a38Sdan ** -----------------------
1291da40a38Sdan **
1301da40a38Sdan ** Example:
1311da40a38Sdan **
1321da40a38Sdan **   For the following INSERT statement:
1331da40a38Sdan **
1341da40a38Sdan **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
1351da40a38Sdan **     INSERT INTO t1 VALUES(1, 2, 3.1);
1361da40a38Sdan **
1371da40a38Sdan **   Register (x):        2    (type integer)
1381da40a38Sdan **   Register (x+1):      1    (type integer)
1391da40a38Sdan **   Register (x+2):      NULL (type NULL)
1401da40a38Sdan **   Register (x+3):      3.1  (type real)
1411da40a38Sdan */
1421da40a38Sdan 
1431da40a38Sdan /*
1448099ce6fSdan ** A foreign key constraint requires that the key columns in the parent
1451da40a38Sdan ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
1468099ce6fSdan ** Given that pParent is the parent table for foreign key constraint pFKey,
1476c5b915fSdrh ** search the schema for a unique index on the parent key columns.
1481da40a38Sdan **
1498099ce6fSdan ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
1508099ce6fSdan ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
1518099ce6fSdan ** is set to point to the unique index.
1528099ce6fSdan **
1538099ce6fSdan ** If the parent key consists of a single column (the foreign key constraint
1548099ce6fSdan ** is not a composite foreign key), output variable *paiCol is set to NULL.
1558099ce6fSdan ** Otherwise, it is set to point to an allocated array of size N, where
1568099ce6fSdan ** N is the number of columns in the parent key. The first element of the
1578099ce6fSdan ** array is the index of the child table column that is mapped by the FK
1588099ce6fSdan ** constraint to the parent table column stored in the left-most column
1598099ce6fSdan ** of index *ppIdx. The second element of the array is the index of the
1608099ce6fSdan ** child table column that corresponds to the second left-most column of
1618099ce6fSdan ** *ppIdx, and so on.
1628099ce6fSdan **
1638099ce6fSdan ** If the required index cannot be found, either because:
1648099ce6fSdan **
1658099ce6fSdan **   1) The named parent key columns do not exist, or
1668099ce6fSdan **
1678099ce6fSdan **   2) The named parent key columns do exist, but are not subject to a
1688099ce6fSdan **      UNIQUE or PRIMARY KEY constraint, or
1698099ce6fSdan **
1708099ce6fSdan **   3) No parent key columns were provided explicitly as part of the
1718099ce6fSdan **      foreign key definition, and the parent table does not have a
1728099ce6fSdan **      PRIMARY KEY, or
1738099ce6fSdan **
1748099ce6fSdan **   4) No parent key columns were provided explicitly as part of the
1758099ce6fSdan **      foreign key definition, and the PRIMARY KEY of the parent table
17660ec914cSpeter.d.reid **      consists of a different number of columns to the child key in
1778099ce6fSdan **      the child table.
1788099ce6fSdan **
1798099ce6fSdan ** then non-zero is returned, and a "foreign key mismatch" error loaded
1808099ce6fSdan ** into pParse. If an OOM error occurs, non-zero is returned and the
1818099ce6fSdan ** pParse->db->mallocFailed flag is set.
1821da40a38Sdan */
sqlite3FkLocateIndex(Parse * pParse,Table * pParent,FKey * pFKey,Index ** ppIdx,int ** paiCol)1836c5b915fSdrh int sqlite3FkLocateIndex(
1841da40a38Sdan   Parse *pParse,                  /* Parse context to store any error in */
1858099ce6fSdan   Table *pParent,                 /* Parent table of FK constraint pFKey */
1861da40a38Sdan   FKey *pFKey,                    /* Foreign key to find index for */
1878099ce6fSdan   Index **ppIdx,                  /* OUT: Unique index on parent table */
1881da40a38Sdan   int **paiCol                    /* OUT: Map of index columns in pFKey */
1891da40a38Sdan ){
1908099ce6fSdan   Index *pIdx = 0;                    /* Value to return via *ppIdx */
1918099ce6fSdan   int *aiCol = 0;                     /* Value to return via *paiCol */
1928099ce6fSdan   int nCol = pFKey->nCol;             /* Number of columns in parent key */
1938099ce6fSdan   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
1941da40a38Sdan 
1951da40a38Sdan   /* The caller is responsible for zeroing output parameters. */
1961da40a38Sdan   assert( ppIdx && *ppIdx==0 );
1971da40a38Sdan   assert( !paiCol || *paiCol==0 );
198f7a94543Sdan   assert( pParse );
1991da40a38Sdan 
2001da40a38Sdan   /* If this is a non-composite (single column) foreign key, check if it
2018099ce6fSdan   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
2021da40a38Sdan   ** and *paiCol set to zero and return early.
2031da40a38Sdan   **
2041da40a38Sdan   ** Otherwise, for a composite foreign key (more than one column), allocate
2051da40a38Sdan   ** space for the aiCol array (returned via output parameter *paiCol).
2061da40a38Sdan   ** Non-composite foreign keys do not require the aiCol array.
2071da40a38Sdan   */
2081da40a38Sdan   if( nCol==1 ){
2091da40a38Sdan     /* The FK maps to the IPK if any of the following are true:
2101da40a38Sdan     **
211d981d447Sdan     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
212d981d447Sdan     **      mapped to the primary key of table pParent, or
213d981d447Sdan     **   2) The FK is explicitly mapped to a column declared as INTEGER
2141da40a38Sdan     **      PRIMARY KEY.
2151da40a38Sdan     */
2168099ce6fSdan     if( pParent->iPKey>=0 ){
2178099ce6fSdan       if( !zKey ) return 0;
218cf9d36d1Sdrh       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zCnName, zKey) ){
219cf9d36d1Sdrh         return 0;
220cf9d36d1Sdrh       }
2211da40a38Sdan     }
2221da40a38Sdan   }else if( paiCol ){
2231da40a38Sdan     assert( nCol>1 );
224575fad65Sdrh     aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
2251da40a38Sdan     if( !aiCol ) return 1;
2261da40a38Sdan     *paiCol = aiCol;
2271da40a38Sdan   }
2281da40a38Sdan 
2298099ce6fSdan   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
23068a494c0Sdan     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
2311da40a38Sdan       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
2321da40a38Sdan       ** of columns. If each indexed column corresponds to a foreign key
2331da40a38Sdan       ** column of pFKey, then this index is a winner.  */
2341da40a38Sdan 
2358099ce6fSdan       if( zKey==0 ){
2368099ce6fSdan         /* If zKey is NULL, then this foreign key is implicitly mapped to
2378099ce6fSdan         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
23848dd1d8eSdrh         ** identified by the test.  */
23948dd1d8eSdrh         if( IsPrimaryKeyIndex(pIdx) ){
2408a2fff7aSdan           if( aiCol ){
2418a2fff7aSdan             int i;
2428a2fff7aSdan             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
2438a2fff7aSdan           }
2441da40a38Sdan           break;
2451da40a38Sdan         }
2461da40a38Sdan       }else{
2478099ce6fSdan         /* If zKey is non-NULL, then this foreign key was declared to
2488099ce6fSdan         ** map to an explicit list of columns in table pParent. Check if this
2499707c7b1Sdan         ** index matches those columns. Also, check that the index uses
2509707c7b1Sdan         ** the default collation sequences for each column. */
2511da40a38Sdan         int i, j;
2521da40a38Sdan         for(i=0; i<nCol; i++){
253bbbdc83bSdrh           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
254f19aa5faSdrh           const char *zDfltColl;            /* Def. collation for column */
2559707c7b1Sdan           char *zIdxCol;                    /* Name of indexed column */
2569707c7b1Sdan 
2574b92f98cSdrh           if( iCol<0 ) break; /* No foreign keys against expression indexes */
2584b92f98cSdrh 
2599707c7b1Sdan           /* If the index uses a collation sequence that is different from
2609707c7b1Sdan           ** the default collation sequence for the column, this index is
2619707c7b1Sdan           ** unusable. Bail out early in this case.  */
26265b40093Sdrh           zDfltColl = sqlite3ColumnColl(&pParent->aCol[iCol]);
263f19aa5faSdrh           if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
2649707c7b1Sdan           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
2659707c7b1Sdan 
266cf9d36d1Sdrh           zIdxCol = pParent->aCol[iCol].zCnName;
2671da40a38Sdan           for(j=0; j<nCol; j++){
2681da40a38Sdan             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
2691da40a38Sdan               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
2701da40a38Sdan               break;
2711da40a38Sdan             }
2721da40a38Sdan           }
2731da40a38Sdan           if( j==nCol ) break;
2741da40a38Sdan         }
2751da40a38Sdan         if( i==nCol ) break;      /* pIdx is usable */
2761da40a38Sdan       }
2771da40a38Sdan     }
2781da40a38Sdan   }
2791da40a38Sdan 
280f7a94543Sdan   if( !pIdx ){
281f0662567Sdan     if( !pParse->disableTriggers ){
2829148defaSdrh       sqlite3ErrorMsg(pParse,
2839148defaSdrh            "foreign key mismatch - \"%w\" referencing \"%w\"",
2849148defaSdrh            pFKey->pFrom->zName, pFKey->zTo);
285f0662567Sdan     }
2861da40a38Sdan     sqlite3DbFree(pParse->db, aiCol);
2871da40a38Sdan     return 1;
2881da40a38Sdan   }
2891da40a38Sdan 
2901da40a38Sdan   *ppIdx = pIdx;
2911da40a38Sdan   return 0;
2921da40a38Sdan }
2931da40a38Sdan 
2948099ce6fSdan /*
295bd747832Sdan ** This function is called when a row is inserted into or deleted from the
296bd747832Sdan ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
297bd747832Sdan ** on the child table of pFKey, this function is invoked twice for each row
2988099ce6fSdan ** affected - once to "delete" the old row, and then again to "insert" the
2998099ce6fSdan ** new row.
3008099ce6fSdan **
3018099ce6fSdan ** Each time it is called, this function generates VDBE code to locate the
3028099ce6fSdan ** row in the parent table that corresponds to the row being inserted into
3038099ce6fSdan ** or deleted from the child table. If the parent row can be found, no
3048099ce6fSdan ** special action is taken. Otherwise, if the parent row can *not* be
3058099ce6fSdan ** found in the parent table:
3068099ce6fSdan **
3078099ce6fSdan **   Operation | FK type   | Action taken
3088099ce6fSdan **   --------------------------------------------------------------------------
309bd747832Sdan **   INSERT      immediate   Increment the "immediate constraint counter".
310bd747832Sdan **
311bd747832Sdan **   DELETE      immediate   Decrement the "immediate constraint counter".
3128099ce6fSdan **
3138099ce6fSdan **   INSERT      deferred    Increment the "deferred constraint counter".
3148099ce6fSdan **
3158099ce6fSdan **   DELETE      deferred    Decrement the "deferred constraint counter".
3168099ce6fSdan **
317bd747832Sdan ** These operations are identified in the comment at the top of this file
318bd747832Sdan ** (fkey.c) as "I.1" and "D.1".
3198099ce6fSdan */
fkLookupParent(Parse * pParse,int iDb,Table * pTab,Index * pIdx,FKey * pFKey,int * aiCol,int regData,int nIncr,int isIgnore)3208099ce6fSdan static void fkLookupParent(
3211da40a38Sdan   Parse *pParse,        /* Parse context */
3221da40a38Sdan   int iDb,              /* Index of database housing pTab */
3238099ce6fSdan   Table *pTab,          /* Parent table of FK pFKey */
3248099ce6fSdan   Index *pIdx,          /* Unique index on parent key columns in pTab */
3258099ce6fSdan   FKey *pFKey,          /* Foreign key constraint */
3268099ce6fSdan   int *aiCol,           /* Map from parent key columns to child table columns */
3278099ce6fSdan   int regData,          /* Address of array containing child table row */
32802470b20Sdan   int nIncr,            /* Increment constraint counter by this */
32902470b20Sdan   int isIgnore          /* If true, pretend pTab contains all NULL values */
3301da40a38Sdan ){
3318099ce6fSdan   int i;                                    /* Iterator variable */
3328099ce6fSdan   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
3338099ce6fSdan   int iCur = pParse->nTab - 1;              /* Cursor number to use */
334ec4ccdbcSdrh   int iOk = sqlite3VdbeMakeLabel(pParse);   /* jump here if parent key found */
3351da40a38Sdan 
3364031bafaSdrh   sqlite3VdbeVerifyAbortable(v,
3374031bafaSdrh     (!pFKey->isDeferred
3384031bafaSdrh       && !(pParse->db->flags & SQLITE_DeferFKs)
3394031bafaSdrh       && !pParse->pToplevel
3404031bafaSdrh       && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
3414031bafaSdrh 
3420ff297eaSdan   /* If nIncr is less than zero, then check at runtime if there are any
3430ff297eaSdan   ** outstanding constraints to resolve. If there are not, there is no need
3440ff297eaSdan   ** to check if deleting this row resolves any outstanding violations.
3450ff297eaSdan   **
3460ff297eaSdan   ** Check if any of the key columns in the child table row are NULL. If
3470ff297eaSdan   ** any are, then the constraint is considered satisfied. No need to
3480ff297eaSdan   ** search for a matching row in the parent table.  */
3490ff297eaSdan   if( nIncr<0 ){
3500ff297eaSdan     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
351688852abSdrh     VdbeCoverage(v);
3520ff297eaSdan   }
3531da40a38Sdan   for(i=0; i<pFKey->nCol; i++){
354a1a01ffbSdrh     int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
355688852abSdrh     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
3561da40a38Sdan   }
3571da40a38Sdan 
35802470b20Sdan   if( isIgnore==0 ){
3591da40a38Sdan     if( pIdx==0 ){
3608099ce6fSdan       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
3618099ce6fSdan       ** column of the parent table (table pTab).  */
3629277efa3Sdan       int iMustBeInt;               /* Address of MustBeInt instruction */
363140026bdSdan       int regTemp = sqlite3GetTempReg(pParse);
364140026bdSdan 
365140026bdSdan       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
366140026bdSdan       ** apply the affinity of the parent key). If this fails, then there
367140026bdSdan       ** is no matching parent key. Before using MustBeInt, make a copy of
368140026bdSdan       ** the value. Otherwise, the value inserted into the child key column
369140026bdSdan       ** will have INTEGER affinity applied to it, which may not be correct.  */
370a1a01ffbSdrh       sqlite3VdbeAddOp2(v, OP_SCopy,
371a1a01ffbSdrh         sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
3729277efa3Sdan       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
373688852abSdrh       VdbeCoverage(v);
3749277efa3Sdan 
3759277efa3Sdan       /* If the parent table is the same as the child table, and we are about
3769277efa3Sdan       ** to increment the constraint-counter (i.e. this is an INSERT operation),
3779277efa3Sdan       ** then check if the row being inserted matches itself. If so, do not
3789277efa3Sdan       ** increment the constraint-counter.  */
3799277efa3Sdan       if( pTab==pFKey->pFrom && nIncr==1 ){
380688852abSdrh         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
3813d77dee9Sdrh         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
3829277efa3Sdan       }
3839277efa3Sdan 
3841da40a38Sdan       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
385688852abSdrh       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
386076e85f5Sdrh       sqlite3VdbeGoto(v, iOk);
3871da40a38Sdan       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
3889277efa3Sdan       sqlite3VdbeJumpHere(v, iMustBeInt);
389140026bdSdan       sqlite3ReleaseTempReg(pParse, regTemp);
3901da40a38Sdan     }else{
391140026bdSdan       int nCol = pFKey->nCol;
392140026bdSdan       int regTemp = sqlite3GetTempRange(pParse, nCol);
3931da40a38Sdan 
3941da40a38Sdan       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
3952ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
3961da40a38Sdan       for(i=0; i<nCol; i++){
397a1a01ffbSdrh         sqlite3VdbeAddOp2(v, OP_Copy,
398a1a01ffbSdrh                sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
399a1a01ffbSdrh                regTemp+i);
4001da40a38Sdan       }
4019277efa3Sdan 
4029277efa3Sdan       /* If the parent table is the same as the child table, and we are about
4039277efa3Sdan       ** to increment the constraint-counter (i.e. this is an INSERT operation),
4049277efa3Sdan       ** then check if the row being inserted matches itself. If so, do not
405b328debcSdan       ** increment the constraint-counter.
406b328debcSdan       **
407b328debcSdan       ** If any of the parent-key values are NULL, then the row cannot match
408b328debcSdan       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
409b328debcSdan       ** of the parent-key values are NULL (at this point it is known that
410b328debcSdan       ** none of the child key values are).
411b328debcSdan       */
4129277efa3Sdan       if( pTab==pFKey->pFrom && nIncr==1 ){
4139277efa3Sdan         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
4149277efa3Sdan         for(i=0; i<nCol; i++){
415a1a01ffbSdrh           int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
416a1a01ffbSdrh                               +1+regData;
417a1a01ffbSdrh           int iParent = 1+regData;
418a1a01ffbSdrh           iParent += sqlite3TableColumnToStorage(pIdx->pTable,
419a1a01ffbSdrh                                                  pIdx->aiColumn[i]);
4204b92f98cSdrh           assert( pIdx->aiColumn[i]>=0 );
421b328debcSdan           assert( aiCol[i]!=pTab->iPKey );
422b328debcSdan           if( pIdx->aiColumn[i]==pTab->iPKey ){
423b328debcSdan             /* The parent key is a composite key that includes the IPK column */
424b328debcSdan             iParent = regData;
425b328debcSdan           }
426688852abSdrh           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
427b328debcSdan           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
4289277efa3Sdan         }
429076e85f5Sdrh         sqlite3VdbeGoto(v, iOk);
4309277efa3Sdan       }
4319277efa3Sdan 
43236d2d090Sdrh       sqlite3VdbeAddOp4(v, OP_Affinity, regTemp, nCol, 0,
433e9107698Sdrh                         sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
43436d2d090Sdrh       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regTemp, nCol);
43536d2d090Sdrh       VdbeCoverage(v);
436140026bdSdan       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
4371da40a38Sdan     }
43802470b20Sdan   }
4391da40a38Sdan 
440648e2643Sdrh   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
441648e2643Sdrh    && !pParse->pToplevel
442648e2643Sdrh    && !pParse->isMultiWrite
443648e2643Sdrh   ){
44432b09f29Sdan     /* Special case: If this is an INSERT statement that will insert exactly
44532b09f29Sdan     ** one row into the table, raise a constraint immediately instead of
44632b09f29Sdan     ** incrementing a counter. This is necessary as the VM code is being
44732b09f29Sdan     ** generated for will not open a statement transaction.  */
44832b09f29Sdan     assert( nIncr==1 );
449d91c1a17Sdrh     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
450f9c8ce3cSdrh         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
45132b09f29Sdan   }else{
45232b09f29Sdan     if( nIncr>0 && pFKey->isDeferred==0 ){
45304668833Sdan       sqlite3MayAbort(pParse);
45432b09f29Sdan     }
4550ff297eaSdan     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
4561da40a38Sdan   }
4571da40a38Sdan 
4581da40a38Sdan   sqlite3VdbeResolveLabel(v, iOk);
459ed81bf60Sdan   sqlite3VdbeAddOp1(v, OP_Close, iCur);
4601da40a38Sdan }
4611da40a38Sdan 
46290e758ffSdrh 
46390e758ffSdrh /*
46490e758ffSdrh ** Return an Expr object that refers to a memory register corresponding
46590e758ffSdrh ** to column iCol of table pTab.
46690e758ffSdrh **
46790e758ffSdrh ** regBase is the first of an array of register that contains the data
46890e758ffSdrh ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
46990e758ffSdrh ** column.  regBase+2 holds the second column, and so forth.
47090e758ffSdrh */
exprTableRegister(Parse * pParse,Table * pTab,int regBase,i16 iCol)47190e758ffSdrh static Expr *exprTableRegister(
47290e758ffSdrh   Parse *pParse,     /* Parsing and code generating context */
47390e758ffSdrh   Table *pTab,       /* The table whose content is at r[regBase]... */
47490e758ffSdrh   int regBase,       /* Contents of table pTab */
47590e758ffSdrh   i16 iCol           /* Which column of pTab is desired */
47690e758ffSdrh ){
47790e758ffSdrh   Expr *pExpr;
47890e758ffSdrh   Column *pCol;
47990e758ffSdrh   const char *zColl;
48090e758ffSdrh   sqlite3 *db = pParse->db;
48190e758ffSdrh 
48290e758ffSdrh   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
48390e758ffSdrh   if( pExpr ){
48490e758ffSdrh     if( iCol>=0 && iCol!=pTab->iPKey ){
48590e758ffSdrh       pCol = &pTab->aCol[iCol];
486f09a14fbSdrh       pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
4871194904bSdrh       pExpr->affExpr = pCol->affinity;
48865b40093Sdrh       zColl = sqlite3ColumnColl(pCol);
48990e758ffSdrh       if( zColl==0 ) zColl = db->pDfltColl->zName;
49090e758ffSdrh       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
49190e758ffSdrh     }else{
49290e758ffSdrh       pExpr->iTable = regBase;
4931194904bSdrh       pExpr->affExpr = SQLITE_AFF_INTEGER;
49490e758ffSdrh     }
49590e758ffSdrh   }
49690e758ffSdrh   return pExpr;
49790e758ffSdrh }
49890e758ffSdrh 
49990e758ffSdrh /*
50090e758ffSdrh ** Return an Expr object that refers to column iCol of table pTab which
50190e758ffSdrh ** has cursor iCur.
50290e758ffSdrh */
exprTableColumn(sqlite3 * db,Table * pTab,int iCursor,i16 iCol)50390e758ffSdrh static Expr *exprTableColumn(
50490e758ffSdrh   sqlite3 *db,      /* The database connection */
50590e758ffSdrh   Table *pTab,      /* The table whose column is desired */
50690e758ffSdrh   int iCursor,      /* The open cursor on the table */
50790e758ffSdrh   i16 iCol          /* The column that is wanted */
50890e758ffSdrh ){
50990e758ffSdrh   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
51090e758ffSdrh   if( pExpr ){
511477572b9Sdrh     assert( ExprUseYTab(pExpr) );
512eda079cdSdrh     pExpr->y.pTab = pTab;
51390e758ffSdrh     pExpr->iTable = iCursor;
51490e758ffSdrh     pExpr->iColumn = iCol;
51590e758ffSdrh   }
51690e758ffSdrh   return pExpr;
51790e758ffSdrh }
51890e758ffSdrh 
5198099ce6fSdan /*
5208099ce6fSdan ** This function is called to generate code executed when a row is deleted
5218099ce6fSdan ** from the parent table of foreign key constraint pFKey and, if pFKey is
5228099ce6fSdan ** deferred, when a row is inserted into the same table. When generating
5238099ce6fSdan ** code for an SQL UPDATE operation, this function may be called twice -
5248099ce6fSdan ** once to "delete" the old row and once to "insert" the new row.
5258099ce6fSdan **
52604668833Sdan ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
52704668833Sdan ** the number of FK violations in the db) or +1 when deleting one (as this
52804668833Sdan ** may increase the number of FK constraint problems).
52904668833Sdan **
5308099ce6fSdan ** The code generated by this function scans through the rows in the child
5318099ce6fSdan ** table that correspond to the parent table row being deleted or inserted.
5328099ce6fSdan ** For each child row found, one of the following actions is taken:
5338099ce6fSdan **
5348099ce6fSdan **   Operation | FK type   | Action taken
5358099ce6fSdan **   --------------------------------------------------------------------------
536bd747832Sdan **   DELETE      immediate   Increment the "immediate constraint counter".
537bd747832Sdan **
538bd747832Sdan **   INSERT      immediate   Decrement the "immediate constraint counter".
5398099ce6fSdan **
5408099ce6fSdan **   DELETE      deferred    Increment the "deferred constraint counter".
5418099ce6fSdan **
5428099ce6fSdan **   INSERT      deferred    Decrement the "deferred constraint counter".
5438099ce6fSdan **
544bd747832Sdan ** These operations are identified in the comment at the top of this file
545bd747832Sdan ** (fkey.c) as "I.2" and "D.2".
5468099ce6fSdan */
fkScanChildren(Parse * pParse,SrcList * pSrc,Table * pTab,Index * pIdx,FKey * pFKey,int * aiCol,int regData,int nIncr)5478099ce6fSdan static void fkScanChildren(
5481da40a38Sdan   Parse *pParse,                  /* Parse context */
549bd50a926Sdrh   SrcList *pSrc,                  /* The child table to be scanned */
550bd50a926Sdrh   Table *pTab,                    /* The parent table */
551bd50a926Sdrh   Index *pIdx,                    /* Index on parent covering the foreign key */
552bd50a926Sdrh   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
5538099ce6fSdan   int *aiCol,                     /* Map from pIdx cols to child table cols */
554bd50a926Sdrh   int regData,                    /* Parent row data starts here */
5551da40a38Sdan   int nIncr                       /* Amount to increment deferred counter by */
5561da40a38Sdan ){
5571da40a38Sdan   sqlite3 *db = pParse->db;       /* Database handle */
5581da40a38Sdan   int i;                          /* Iterator variable */
5591da40a38Sdan   Expr *pWhere = 0;               /* WHERE clause to scan with */
5601da40a38Sdan   NameContext sNameContext;       /* Context used to resolve WHERE clause */
5611da40a38Sdan   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
5620ff297eaSdan   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
5630ff297eaSdan   Vdbe *v = sqlite3GetVdbe(pParse);
5640ff297eaSdan 
565bd50a926Sdrh   assert( pIdx==0 || pIdx->pTable==pTab );
566bd50a926Sdrh   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
567bd50a926Sdrh   assert( pIdx!=0 || pFKey->nCol==1 );
5682bea7cdeSdrh   assert( pIdx!=0 || HasRowid(pTab) );
5699277efa3Sdan 
5700ff297eaSdan   if( nIncr<0 ){
5710ff297eaSdan     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
572688852abSdrh     VdbeCoverage(v);
5730ff297eaSdan   }
5741da40a38Sdan 
575bd747832Sdan   /* Create an Expr object representing an SQL expression like:
576bd747832Sdan   **
577bd747832Sdan   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
578bd747832Sdan   **
579bd747832Sdan   ** The collation sequence used for the comparison should be that of
580bd747832Sdan   ** the parent key columns. The affinity of the parent key column should
581bd747832Sdan   ** be applied to each child key value before the comparison takes place.
582bd747832Sdan   */
5831da40a38Sdan   for(i=0; i<pFKey->nCol; i++){
5848099ce6fSdan     Expr *pLeft;                  /* Value from parent table row */
5858099ce6fSdan     Expr *pRight;                 /* Column ref to child table */
5861da40a38Sdan     Expr *pEq;                    /* Expression (pLeft = pRight) */
587bbbdc83bSdrh     i16 iCol;                     /* Index of column in child table */
5888099ce6fSdan     const char *zCol;             /* Name of column in child table */
5891da40a38Sdan 
59090e758ffSdrh     iCol = pIdx ? pIdx->aiColumn[i] : -1;
59190e758ffSdrh     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
5921da40a38Sdan     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
593a8f0bf64Sdan     assert( iCol>=0 );
594cf9d36d1Sdrh     zCol = pFKey->pFrom->aCol[iCol].zCnName;
5951da40a38Sdan     pRight = sqlite3Expr(db, TK_ID, zCol);
596abfd35eaSdrh     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
597d5c851c1Sdrh     pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
5981da40a38Sdan   }
5991da40a38Sdan 
60090e758ffSdrh   /* If the child table is the same as the parent table, then add terms
60190e758ffSdrh   ** to the WHERE clause that prevent this entry from being scanned.
60290e758ffSdrh   ** The added WHERE clause terms are like this:
60390e758ffSdrh   **
60490e758ffSdrh   **     $current_rowid!=rowid
60590e758ffSdrh   **     NOT( $current_a==a AND $current_b==b AND ... )
60690e758ffSdrh   **
60790e758ffSdrh   ** The first form is used for rowid tables.  The second form is used
608e46201e2Sdan   ** for WITHOUT ROWID tables. In the second form, the *parent* key is
609e46201e2Sdan   ** (a,b,...). Either the parent or primary key could be used to
610e46201e2Sdan   ** uniquely identify the current row, but the parent key is more convenient
611e46201e2Sdan   ** as the required values have already been loaded into registers
612e46201e2Sdan   ** by the caller.
61390e758ffSdrh   */
61490e758ffSdrh   if( pTab==pFKey->pFrom && nIncr>0 ){
615bd50a926Sdrh     Expr *pNe;                    /* Expression (pLeft != pRight) */
6169277efa3Sdan     Expr *pLeft;                  /* Value from parent table row */
6179277efa3Sdan     Expr *pRight;                 /* Column ref to child table */
61890e758ffSdrh     if( HasRowid(pTab) ){
61990e758ffSdrh       pLeft = exprTableRegister(pParse, pTab, regData, -1);
62090e758ffSdrh       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
621abfd35eaSdrh       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
62290e758ffSdrh     }else{
62390e758ffSdrh       Expr *pEq, *pAll = 0;
6242bea7cdeSdrh       assert( pIdx!=0 );
625e46201e2Sdan       for(i=0; i<pIdx->nKeyCol; i++){
62690e758ffSdrh         i16 iCol = pIdx->aiColumn[i];
6274b92f98cSdrh         assert( iCol>=0 );
62890e758ffSdrh         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
629cf9d36d1Sdrh         pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zCnName);
630e46201e2Sdan         pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
631d5c851c1Sdrh         pAll = sqlite3ExprAnd(pParse, pAll, pEq);
63290e758ffSdrh       }
633abfd35eaSdrh       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
63490e758ffSdrh     }
635d5c851c1Sdrh     pWhere = sqlite3ExprAnd(pParse, pWhere, pNe);
6369277efa3Sdan   }
6379277efa3Sdan 
6381da40a38Sdan   /* Resolve the references in the WHERE clause. */
6391da40a38Sdan   memset(&sNameContext, 0, sizeof(NameContext));
6401da40a38Sdan   sNameContext.pSrcList = pSrc;
6411da40a38Sdan   sNameContext.pParse = pParse;
6421da40a38Sdan   sqlite3ResolveExprNames(&sNameContext, pWhere);
6431da40a38Sdan 
6441da40a38Sdan   /* Create VDBE to loop through the entries in pSrc that match the WHERE
645d4572711Sdan   ** clause. For each row found, increment either the deferred or immediate
646d4572711Sdan   ** foreign key constraint counter. */
647c456a76fSdan   if( pParse->nErr==0 ){
648895bab33Sdrh     pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0, 0);
6490ff297eaSdan     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
650f59c5cacSdan     if( pWInfo ){
6511da40a38Sdan       sqlite3WhereEnd(pWInfo);
652f59c5cacSdan     }
653c456a76fSdan   }
6541da40a38Sdan 
6551da40a38Sdan   /* Clean up the WHERE clause constructed above. */
6561da40a38Sdan   sqlite3ExprDelete(db, pWhere);
6570ff297eaSdan   if( iFkIfZero ){
658dc4f6fc0Sdrh     sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero);
6590ff297eaSdan   }
6601da40a38Sdan }
6611da40a38Sdan 
6621da40a38Sdan /*
663bd50a926Sdrh ** This function returns a linked list of FKey objects (connected by
664bd50a926Sdrh ** FKey.pNextTo) holding all children of table pTab.  For example,
6651da40a38Sdan ** given the following schema:
6661da40a38Sdan **
6671da40a38Sdan **   CREATE TABLE t1(a PRIMARY KEY);
6681da40a38Sdan **   CREATE TABLE t2(b REFERENCES t1(a);
6691da40a38Sdan **
6701da40a38Sdan ** Calling this function with table "t1" as an argument returns a pointer
6711da40a38Sdan ** to the FKey structure representing the foreign key constraint on table
6721da40a38Sdan ** "t2". Calling this function with "t2" as the argument would return a
6738099ce6fSdan ** NULL pointer (as there are no FK constraints for which t2 is the parent
6748099ce6fSdan ** table).
6751da40a38Sdan */
sqlite3FkReferences(Table * pTab)676432cc5b9Sdan FKey *sqlite3FkReferences(Table *pTab){
677acbcb7e0Sdrh   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
6781da40a38Sdan }
6791da40a38Sdan 
6808099ce6fSdan /*
6818099ce6fSdan ** The second argument is a Trigger structure allocated by the
6828099ce6fSdan ** fkActionTrigger() routine. This function deletes the Trigger structure
6838099ce6fSdan ** and all of its sub-components.
6848099ce6fSdan **
6858099ce6fSdan ** The Trigger structure or any of its sub-components may be allocated from
6868099ce6fSdan ** the lookaside buffer belonging to database handle dbMem.
6878099ce6fSdan */
fkTriggerDelete(sqlite3 * dbMem,Trigger * p)68875cbd984Sdan static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
68975cbd984Sdan   if( p ){
69075cbd984Sdan     TriggerStep *pStep = p->step_list;
69175cbd984Sdan     sqlite3ExprDelete(dbMem, pStep->pWhere);
69275cbd984Sdan     sqlite3ExprListDelete(dbMem, pStep->pExprList);
6939277efa3Sdan     sqlite3SelectDelete(dbMem, pStep->pSelect);
694788536b1Sdrh     sqlite3ExprDelete(dbMem, p->pWhen);
69575cbd984Sdan     sqlite3DbFree(dbMem, p);
69675cbd984Sdan   }
69775cbd984Sdan }
69875cbd984Sdan 
6998099ce6fSdan /*
70044a5c025Sdrh ** Clear the apTrigger[] cache of CASCADE triggers for all foreign keys
70144a5c025Sdrh ** in a particular database.  This needs to happen when the schema
70244a5c025Sdrh ** changes.
70344a5c025Sdrh */
sqlite3FkClearTriggerCache(sqlite3 * db,int iDb)70444a5c025Sdrh void sqlite3FkClearTriggerCache(sqlite3 *db, int iDb){
70544a5c025Sdrh   HashElem *k;
70644a5c025Sdrh   Hash *pHash = &db->aDb[iDb].pSchema->tblHash;
70744a5c025Sdrh   for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k)){
70844a5c025Sdrh     Table *pTab = sqliteHashData(k);
70944a5c025Sdrh     FKey *pFKey;
71044a5c025Sdrh     if( !IsOrdinaryTable(pTab) ) continue;
71144a5c025Sdrh     for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
71244a5c025Sdrh       fkTriggerDelete(db, pFKey->apTrigger[0]); pFKey->apTrigger[0] = 0;
71344a5c025Sdrh       fkTriggerDelete(db, pFKey->apTrigger[1]); pFKey->apTrigger[1] = 0;
71444a5c025Sdrh     }
71544a5c025Sdrh   }
71644a5c025Sdrh }
71744a5c025Sdrh 
71844a5c025Sdrh /*
719d66c8309Sdan ** This function is called to generate code that runs when table pTab is
720d66c8309Sdan ** being dropped from the database. The SrcList passed as the second argument
721d66c8309Sdan ** to this function contains a single entry guaranteed to resolve to
722d66c8309Sdan ** table pTab.
723d66c8309Sdan **
724d66c8309Sdan ** Normally, no code is required. However, if either
725d66c8309Sdan **
726d66c8309Sdan **   (a) The table is the parent table of a FK constraint, or
727d66c8309Sdan **   (b) The table is the child table of a deferred FK constraint and it is
728d66c8309Sdan **       determined at runtime that there are outstanding deferred FK
729d66c8309Sdan **       constraint violations in the database,
730d66c8309Sdan **
731d66c8309Sdan ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
732d66c8309Sdan ** the table from the database. Triggers are disabled while running this
733d66c8309Sdan ** DELETE, but foreign key actions are not.
734d66c8309Sdan */
sqlite3FkDropTable(Parse * pParse,SrcList * pName,Table * pTab)735d66c8309Sdan void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
736d66c8309Sdan   sqlite3 *db = pParse->db;
73778b2fa86Sdrh   if( (db->flags&SQLITE_ForeignKeys) && IsOrdinaryTable(pTab) ){
738d66c8309Sdan     int iSkip = 0;
739d66c8309Sdan     Vdbe *v = sqlite3GetVdbe(pParse);
740d66c8309Sdan 
741d66c8309Sdan     assert( v );                  /* VDBE has already been allocated */
74278b2fa86Sdrh     assert( IsOrdinaryTable(pTab) );
743d66c8309Sdan     if( sqlite3FkReferences(pTab)==0 ){
744d66c8309Sdan       /* Search for a deferred foreign key constraint for which this table
745d66c8309Sdan       ** is the child table. If one cannot be found, return without
746d66c8309Sdan       ** generating any VDBE code. If one can be found, then jump over
747d66c8309Sdan       ** the entire DELETE if there are no outstanding deferred constraints
748d66c8309Sdan       ** when this statement is run.  */
749d66c8309Sdan       FKey *p;
750f38524d2Sdrh       for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
751a8dbadacSdan         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
752d66c8309Sdan       }
753d66c8309Sdan       if( !p ) return;
754ec4ccdbcSdrh       iSkip = sqlite3VdbeMakeLabel(pParse);
755688852abSdrh       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
756d66c8309Sdan     }
757d66c8309Sdan 
758d66c8309Sdan     pParse->disableTriggers = 1;
7598c0833fbSdrh     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
760d66c8309Sdan     pParse->disableTriggers = 0;
761d66c8309Sdan 
762d66c8309Sdan     /* If the DELETE has generated immediate foreign key constraint
763d66c8309Sdan     ** violations, halt the VDBE and return an error at this point, before
764d66c8309Sdan     ** any modifications to the schema are made. This is because statement
765a8dbadacSdan     ** transactions are not able to rollback schema changes.
766a8dbadacSdan     **
767a8dbadacSdan     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
768a8dbadacSdan     ** the statement transaction will not be rolled back even if FK
769a8dbadacSdan     ** constraints are violated.
770a8dbadacSdan     */
771a8dbadacSdan     if( (db->flags & SQLITE_DeferFKs)==0 ){
7724031bafaSdrh       sqlite3VdbeVerifyAbortable(v, OE_Abort);
773d66c8309Sdan       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
774688852abSdrh       VdbeCoverage(v);
775d91c1a17Sdrh       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
776f9c8ce3cSdrh           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
777a8dbadacSdan     }
778d66c8309Sdan 
779d66c8309Sdan     if( iSkip ){
780d66c8309Sdan       sqlite3VdbeResolveLabel(v, iSkip);
781d66c8309Sdan     }
782d66c8309Sdan   }
783d66c8309Sdan }
784d66c8309Sdan 
7858ff2d956Sdan 
7868ff2d956Sdan /*
7878ff2d956Sdan ** The second argument points to an FKey object representing a foreign key
7888ff2d956Sdan ** for which pTab is the child table. An UPDATE statement against pTab
7898ff2d956Sdan ** is currently being processed. For each column of the table that is
7908ff2d956Sdan ** actually updated, the corresponding element in the aChange[] array
7918ff2d956Sdan ** is zero or greater (if a column is unmodified the corresponding element
7928ff2d956Sdan ** is set to -1). If the rowid column is modified by the UPDATE statement
7938ff2d956Sdan ** the bChngRowid argument is non-zero.
7948ff2d956Sdan **
7958ff2d956Sdan ** This function returns true if any of the columns that are part of the
7968ff2d956Sdan ** child key for FK constraint *p are modified.
7978ff2d956Sdan */
fkChildIsModified(Table * pTab,FKey * p,int * aChange,int bChngRowid)7988ff2d956Sdan static int fkChildIsModified(
7998ff2d956Sdan   Table *pTab,                    /* Table being updated */
8008ff2d956Sdan   FKey *p,                        /* Foreign key for which pTab is the child */
8018ff2d956Sdan   int *aChange,                   /* Array indicating modified columns */
8028ff2d956Sdan   int bChngRowid                  /* True if rowid is modified by this update */
8038ff2d956Sdan ){
8048ff2d956Sdan   int i;
8058ff2d956Sdan   for(i=0; i<p->nCol; i++){
8068ff2d956Sdan     int iChildKey = p->aCol[i].iFrom;
8078ff2d956Sdan     if( aChange[iChildKey]>=0 ) return 1;
8088ff2d956Sdan     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
8098ff2d956Sdan   }
8108ff2d956Sdan   return 0;
8118ff2d956Sdan }
8128ff2d956Sdan 
8138ff2d956Sdan /*
8148ff2d956Sdan ** The second argument points to an FKey object representing a foreign key
8158ff2d956Sdan ** for which pTab is the parent table. An UPDATE statement against pTab
8168ff2d956Sdan ** is currently being processed. For each column of the table that is
8178ff2d956Sdan ** actually updated, the corresponding element in the aChange[] array
8188ff2d956Sdan ** is zero or greater (if a column is unmodified the corresponding element
8198ff2d956Sdan ** is set to -1). If the rowid column is modified by the UPDATE statement
8208ff2d956Sdan ** the bChngRowid argument is non-zero.
8218ff2d956Sdan **
8228ff2d956Sdan ** This function returns true if any of the columns that are part of the
8238ff2d956Sdan ** parent key for FK constraint *p are modified.
8248ff2d956Sdan */
fkParentIsModified(Table * pTab,FKey * p,int * aChange,int bChngRowid)8258ff2d956Sdan static int fkParentIsModified(
8268ff2d956Sdan   Table *pTab,
8278ff2d956Sdan   FKey *p,
8288ff2d956Sdan   int *aChange,
8298ff2d956Sdan   int bChngRowid
8308ff2d956Sdan ){
8318ff2d956Sdan   int i;
8328ff2d956Sdan   for(i=0; i<p->nCol; i++){
8338ff2d956Sdan     char *zKey = p->aCol[i].zCol;
8348ff2d956Sdan     int iKey;
8358ff2d956Sdan     for(iKey=0; iKey<pTab->nCol; iKey++){
8368ff2d956Sdan       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
8378ff2d956Sdan         Column *pCol = &pTab->aCol[iKey];
8388ff2d956Sdan         if( zKey ){
839cf9d36d1Sdrh           if( 0==sqlite3StrICmp(pCol->zCnName, zKey) ) return 1;
8408ff2d956Sdan         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
8418ff2d956Sdan           return 1;
8428ff2d956Sdan         }
8438ff2d956Sdan       }
8448ff2d956Sdan     }
8458ff2d956Sdan   }
8468ff2d956Sdan   return 0;
8478ff2d956Sdan }
8488ff2d956Sdan 
849d66c8309Sdan /*
85004668833Sdan ** Return true if the parser passed as the first argument is being
85104668833Sdan ** used to code a trigger that is really a "SET NULL" action belonging
85204668833Sdan ** to trigger pFKey.
85304668833Sdan */
isSetNullAction(Parse * pParse,FKey * pFKey)85404668833Sdan static int isSetNullAction(Parse *pParse, FKey *pFKey){
85504668833Sdan   Parse *pTop = sqlite3ParseToplevel(pParse);
85604668833Sdan   if( pTop->pTriggerPrg ){
85704668833Sdan     Trigger *p = pTop->pTriggerPrg->pTrigger;
85804668833Sdan     if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
85904668833Sdan      || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
86004668833Sdan     ){
86104668833Sdan       return 1;
86204668833Sdan     }
86304668833Sdan   }
86404668833Sdan   return 0;
86504668833Sdan }
86604668833Sdan 
86704668833Sdan /*
8688099ce6fSdan ** This function is called when inserting, deleting or updating a row of
8698099ce6fSdan ** table pTab to generate VDBE code to perform foreign key constraint
8708099ce6fSdan ** processing for the operation.
8718099ce6fSdan **
8728099ce6fSdan ** For a DELETE operation, parameter regOld is passed the index of the
8738099ce6fSdan ** first register in an array of (pTab->nCol+1) registers containing the
8748099ce6fSdan ** rowid of the row being deleted, followed by each of the column values
8758099ce6fSdan ** of the row being deleted, from left to right. Parameter regNew is passed
8768099ce6fSdan ** zero in this case.
8778099ce6fSdan **
8788099ce6fSdan ** For an INSERT operation, regOld is passed zero and regNew is passed the
8798099ce6fSdan ** first register of an array of (pTab->nCol+1) registers containing the new
8808099ce6fSdan ** row data.
8818099ce6fSdan **
8829277efa3Sdan ** For an UPDATE operation, this function is called twice. Once before
8839277efa3Sdan ** the original record is deleted from the table using the calling convention
8849277efa3Sdan ** described for DELETE. Then again after the original record is deleted
885e7a94d81Sdan ** but before the new record is inserted using the INSERT convention.
8868099ce6fSdan */
sqlite3FkCheck(Parse * pParse,Table * pTab,int regOld,int regNew,int * aChange,int bChngRowid)8871da40a38Sdan void sqlite3FkCheck(
8881da40a38Sdan   Parse *pParse,                  /* Parse context */
8891da40a38Sdan   Table *pTab,                    /* Row is being deleted from this table */
8901da40a38Sdan   int regOld,                     /* Previous row data is stored here */
8918ff2d956Sdan   int regNew,                     /* New row data is stored here */
8928ff2d956Sdan   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
8938ff2d956Sdan   int bChngRowid                  /* True if rowid is UPDATEd */
8941da40a38Sdan ){
8951da40a38Sdan   sqlite3 *db = pParse->db;       /* Database handle */
8961da40a38Sdan   FKey *pFKey;                    /* Used to iterate through FKs */
8971da40a38Sdan   int iDb;                        /* Index of database containing pTab */
8981da40a38Sdan   const char *zDb;                /* Name of database containing pTab */
899f0662567Sdan   int isIgnoreErrors = pParse->disableTriggers;
9001da40a38Sdan 
901792e9201Sdan   /* Exactly one of regOld and regNew should be non-zero. */
902792e9201Sdan   assert( (regOld==0)!=(regNew==0) );
9031da40a38Sdan 
9041da40a38Sdan   /* If foreign-keys are disabled, this function is a no-op. */
9051da40a38Sdan   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
90678b2fa86Sdrh   if( !IsOrdinaryTable(pTab) ) return;
9071da40a38Sdan 
9081da40a38Sdan   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90969c33826Sdrh   zDb = db->aDb[iDb].zDbSName;
9101da40a38Sdan 
9118099ce6fSdan   /* Loop through all the foreign key constraints for which pTab is the
9128099ce6fSdan   ** child table (the table that the foreign key definition is part of).  */
913f38524d2Sdrh   for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
9148099ce6fSdan     Table *pTo;                   /* Parent table of foreign key pFKey */
9151da40a38Sdan     Index *pIdx = 0;              /* Index on key columns in pTo */
9163606264bSdan     int *aiFree = 0;
9173606264bSdan     int *aiCol;
9183606264bSdan     int iCol;
9193606264bSdan     int i;
92004668833Sdan     int bIgnore = 0;
9211da40a38Sdan 
9228ff2d956Sdan     if( aChange
9238ff2d956Sdan      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
9248ff2d956Sdan      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
9258ff2d956Sdan     ){
9268ff2d956Sdan       continue;
9278ff2d956Sdan     }
9288ff2d956Sdan 
9298099ce6fSdan     /* Find the parent table of this foreign key. Also find a unique index
9308099ce6fSdan     ** on the parent key columns in the parent table. If either of these
9318099ce6fSdan     ** schema items cannot be located, set an error in pParse and return
9328099ce6fSdan     ** early.  */
933f0662567Sdan     if( pParse->disableTriggers ){
934f0662567Sdan       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
935f0662567Sdan     }else{
9361da40a38Sdan       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
937f0662567Sdan     }
9386c5b915fSdrh     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
9393098dc5cSdan       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
940f0662567Sdan       if( !isIgnoreErrors || db->mallocFailed ) return;
9419147c7b0Sdrh       if( pTo==0 ){
9423098dc5cSdan         /* If isIgnoreErrors is true, then a table is being dropped. In this
9433098dc5cSdan         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
9443098dc5cSdan         ** before actually dropping it in order to check FK constraints.
9453098dc5cSdan         ** If the parent table of an FK constraint on the current table is
9463098dc5cSdan         ** missing, behave as if it is empty. i.e. decrement the relevant
9473098dc5cSdan         ** FK counter for each row of the current table with non-NULL keys.
9483098dc5cSdan         */
9493098dc5cSdan         Vdbe *v = sqlite3GetVdbe(pParse);
9503098dc5cSdan         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
9513098dc5cSdan         for(i=0; i<pFKey->nCol; i++){
9529c6a9298Sdrh           int iFromCol, iReg;
9539c6a9298Sdrh           iFromCol = pFKey->aCol[i].iFrom;
9549c6a9298Sdrh           iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
955688852abSdrh           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
9563098dc5cSdan         }
9573098dc5cSdan         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
9583098dc5cSdan       }
959f0662567Sdan       continue;
960f0662567Sdan     }
9613606264bSdan     assert( pFKey->nCol==1 || (aiFree && pIdx) );
9621da40a38Sdan 
9633606264bSdan     if( aiFree ){
9643606264bSdan       aiCol = aiFree;
9653606264bSdan     }else{
9663606264bSdan       iCol = pFKey->aCol[0].iFrom;
9673606264bSdan       aiCol = &iCol;
9683606264bSdan     }
9693606264bSdan     for(i=0; i<pFKey->nCol; i++){
9703606264bSdan       if( aiCol[i]==pTab->iPKey ){
9713606264bSdan         aiCol[i] = -1;
9723606264bSdan       }
9734b92f98cSdrh       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
97447a06346Sdan #ifndef SQLITE_OMIT_AUTHORIZATION
97502470b20Sdan       /* Request permission to read the parent key columns. If the
97602470b20Sdan       ** authorization callback returns SQLITE_IGNORE, behave as if any
97702470b20Sdan       ** values read from the parent table are NULL. */
97847a06346Sdan       if( db->xAuth ){
97902470b20Sdan         int rcauth;
980cf9d36d1Sdrh         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
98102470b20Sdan         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
98204668833Sdan         bIgnore = (rcauth==SQLITE_IGNORE);
98347a06346Sdan       }
98447a06346Sdan #endif
9853606264bSdan     }
9863606264bSdan 
9878099ce6fSdan     /* Take a shared-cache advisory read-lock on the parent table. Allocate
9888099ce6fSdan     ** a cursor to use to search the unique index on the parent key columns
9898099ce6fSdan     ** in the parent table.  */
9901da40a38Sdan     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
9911da40a38Sdan     pParse->nTab++;
9921da40a38Sdan 
99332b09f29Sdan     if( regOld!=0 ){
99432b09f29Sdan       /* A row is being removed from the child table. Search for the parent.
99532b09f29Sdan       ** If the parent does not exist, removing the child row resolves an
99632b09f29Sdan       ** outstanding foreign key constraint violation. */
99704668833Sdan       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
9981da40a38Sdan     }
99904668833Sdan     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
100032b09f29Sdan       /* A row is being added to the child table. If a parent row cannot
100104668833Sdan       ** be found, adding the child row has violated the FK constraint.
100204668833Sdan       **
100304668833Sdan       ** If this operation is being performed as part of a trigger program
100404668833Sdan       ** that is actually a "SET NULL" action belonging to this very
1005d4572711Sdan       ** foreign key, then omit this scan altogether. As all child key
100604668833Sdan       ** values are guaranteed to be NULL, it is not possible for adding
100704668833Sdan       ** this row to cause an FK violation.  */
100804668833Sdan       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
10091da40a38Sdan     }
10101da40a38Sdan 
10113606264bSdan     sqlite3DbFree(db, aiFree);
10121da40a38Sdan   }
10131da40a38Sdan 
1014bd50a926Sdrh   /* Loop through all the foreign key constraints that refer to this table.
1015bd50a926Sdrh   ** (the "child" constraints) */
1016432cc5b9Sdan   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
10171da40a38Sdan     Index *pIdx = 0;              /* Foreign key index for pFKey */
10181da40a38Sdan     SrcList *pSrc;
10191da40a38Sdan     int *aiCol = 0;
10201da40a38Sdan 
10218ff2d956Sdan     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
10228ff2d956Sdan       continue;
10238ff2d956Sdan     }
10248ff2d956Sdan 
1025648e2643Sdrh     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
1026648e2643Sdrh      && !pParse->pToplevel && !pParse->isMultiWrite
1027648e2643Sdrh     ){
102832b09f29Sdan       assert( regOld==0 && regNew!=0 );
102904668833Sdan       /* Inserting a single row into a parent table cannot cause (or fix)
103004668833Sdan       ** an immediate foreign key violation. So do nothing in this case.  */
1031f0662567Sdan       continue;
10321da40a38Sdan     }
10331da40a38Sdan 
10346c5b915fSdrh     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
1035f0662567Sdan       if( !isIgnoreErrors || db->mallocFailed ) return;
1036f0662567Sdan       continue;
1037f0662567Sdan     }
10381da40a38Sdan     assert( aiCol || pFKey->nCol==1 );
10391da40a38Sdan 
1040bd50a926Sdrh     /* Create a SrcList structure containing the child table.  We need the
1041bd50a926Sdrh     ** child table as a SrcList for sqlite3WhereBegin() */
104229c992cbSdrh     pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
1043f59c5cacSdan     if( pSrc ){
10447601294aSdrh       SrcItem *pItem = pSrc->a;
10459a616f56Sdrh       pItem->pTab = pFKey->pFrom;
10469a616f56Sdrh       pItem->zName = pFKey->pFrom->zName;
104779df7782Sdrh       pItem->pTab->nTabRef++;
10489a616f56Sdrh       pItem->iCursor = pParse->nTab++;
10491da40a38Sdan 
105032b09f29Sdan       if( regNew!=0 ){
10519277efa3Sdan         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
10521da40a38Sdan       }
10531da40a38Sdan       if( regOld!=0 ){
105404668833Sdan         int eAction = pFKey->aAction[aChange!=0];
10559277efa3Sdan         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
105604668833Sdan         /* If this is a deferred FK constraint, or a CASCADE or SET NULL
1057d4572711Sdan         ** action applies, then any foreign key violations caused by
1058d4572711Sdan         ** removing the parent key will be rectified by the action trigger.
1059d4572711Sdan         ** So do not set the "may-abort" flag in this case.
1060d4572711Sdan         **
1061d4572711Sdan         ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
1062d4572711Sdan         ** may-abort flag will eventually be set on this statement anyway
1063d4572711Sdan         ** (when this function is called as part of processing the UPDATE
1064d4572711Sdan         ** within the action trigger).
1065d4572711Sdan         **
1066d4572711Sdan         ** Note 2: At first glance it may seem like SQLite could simply omit
1067d4572711Sdan         ** all OP_FkCounter related scans when either CASCADE or SET NULL
1068d4572711Sdan         ** applies. The trouble starts if the CASCADE or SET NULL action
1069d4572711Sdan         ** trigger causes other triggers or action rules attached to the
1070d4572711Sdan         ** child table to fire. In these cases the fk constraint counters
1071d4572711Sdan         ** might be set incorrectly if any OP_FkCounter related scans are
1072d4572711Sdan         ** omitted.  */
107304668833Sdan         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
107404668833Sdan           sqlite3MayAbort(pParse);
107504668833Sdan         }
10761da40a38Sdan       }
10779a616f56Sdrh       pItem->zName = 0;
10781da40a38Sdan       sqlite3SrcListDelete(db, pSrc);
1079f59c5cacSdan     }
10801da40a38Sdan     sqlite3DbFree(db, aiCol);
10811da40a38Sdan   }
10821da40a38Sdan }
10831da40a38Sdan 
10841da40a38Sdan #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
10851da40a38Sdan 
10861da40a38Sdan /*
10871da40a38Sdan ** This function is called before generating code to update or delete a
1088e7a94d81Sdan ** row contained in table pTab.
10891da40a38Sdan */
sqlite3FkOldmask(Parse * pParse,Table * pTab)10901da40a38Sdan u32 sqlite3FkOldmask(
10911da40a38Sdan   Parse *pParse,                  /* Parse context */
1092e7a94d81Sdan   Table *pTab                     /* Table being modified */
10931da40a38Sdan ){
10941da40a38Sdan   u32 mask = 0;
109578b2fa86Sdrh   if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
10961da40a38Sdan     FKey *p;
10971da40a38Sdan     int i;
1098f38524d2Sdrh     for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
10991da40a38Sdan       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
11001da40a38Sdan     }
1101432cc5b9Sdan     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
11021da40a38Sdan       Index *pIdx = 0;
11036c5b915fSdrh       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
11041da40a38Sdan       if( pIdx ){
11054b92f98cSdrh         for(i=0; i<pIdx->nKeyCol; i++){
11064b92f98cSdrh           assert( pIdx->aiColumn[i]>=0 );
11074b92f98cSdrh           mask |= COLUMN_MASK(pIdx->aiColumn[i]);
11084b92f98cSdrh         }
11091da40a38Sdan       }
11101da40a38Sdan     }
11111da40a38Sdan   }
11121da40a38Sdan   return mask;
11131da40a38Sdan }
11141da40a38Sdan 
11158ff2d956Sdan 
11161da40a38Sdan /*
11171da40a38Sdan ** This function is called before generating code to update or delete a
1118e7a94d81Sdan ** row contained in table pTab. If the operation is a DELETE, then
1119e7a94d81Sdan ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
1120e7a94d81Sdan ** to an array of size N, where N is the number of columns in table pTab.
1121e7a94d81Sdan ** If the i'th column is not modified by the UPDATE, then the corresponding
1122e7a94d81Sdan ** entry in the aChange[] array is set to -1. If the column is modified,
1123e7a94d81Sdan ** the value is 0 or greater. Parameter chngRowid is set to true if the
1124e7a94d81Sdan ** UPDATE statement modifies the rowid fields of the table.
11251da40a38Sdan **
11261da40a38Sdan ** If any foreign key processing will be required, this function returns
1127940b5eaaSdan ** non-zero. If there is no foreign key related processing, this function
1128940b5eaaSdan ** returns zero.
1129940b5eaaSdan **
1130940b5eaaSdan ** For an UPDATE, this function returns 2 if:
1131940b5eaaSdan **
11327937f632Sdan **   * There are any FKs for which pTab is the child and the parent table
11337937f632Sdan **     and any FK processing at all is required (even of a different FK), or
11347937f632Sdan **
1135940b5eaaSdan **   * the UPDATE modifies one or more parent keys for which the action is
1136940b5eaaSdan **     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
1137940b5eaaSdan **
1138940b5eaaSdan ** Or, assuming some other foreign key processing is required, 1.
11391da40a38Sdan */
sqlite3FkRequired(Parse * pParse,Table * pTab,int * aChange,int chngRowid)11401da40a38Sdan int sqlite3FkRequired(
11411da40a38Sdan   Parse *pParse,                  /* Parse context */
11421da40a38Sdan   Table *pTab,                    /* Table being modified */
1143e7a94d81Sdan   int *aChange,                   /* Non-NULL for UPDATE operations */
1144e7a94d81Sdan   int chngRowid                   /* True for UPDATE that affects rowid */
11451da40a38Sdan ){
11467937f632Sdan   int eRet = 1;                   /* Value to return if bHaveFK is true */
11477937f632Sdan   int bHaveFK = 0;                /* If FK processing is required */
114878b2fa86Sdrh   if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
1149e7a94d81Sdan     if( !aChange ){
1150e7a94d81Sdan       /* A DELETE operation. Foreign key processing is required if the
1151e7a94d81Sdan       ** table in question is either the child or parent table for any
1152e7a94d81Sdan       ** foreign key constraint.  */
1153f38524d2Sdrh       bHaveFK = (sqlite3FkReferences(pTab) || pTab->u.tab.pFKey);
1154e7a94d81Sdan     }else{
1155e7a94d81Sdan       /* This is an UPDATE. Foreign key processing is only required if the
1156e7a94d81Sdan       ** operation modifies one or more child or parent key columns. */
1157e7a94d81Sdan       FKey *p;
1158e7a94d81Sdan 
1159e7a94d81Sdan       /* Check if any child key columns are being modified. */
1160f38524d2Sdrh       for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
1161940b5eaaSdan         if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
11627937f632Sdan           if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) eRet = 2;
11637937f632Sdan           bHaveFK = 1;
1164940b5eaaSdan         }
1165e7a94d81Sdan       }
1166e7a94d81Sdan 
1167e7a94d81Sdan       /* Check if any parent key columns are being modified. */
1168e7a94d81Sdan       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
1169940b5eaaSdan         if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
1170940b5eaaSdan           if( p->aAction[1]!=OE_None ) return 2;
11717937f632Sdan           bHaveFK = 1;
1172e7a94d81Sdan         }
1173e7a94d81Sdan       }
11741da40a38Sdan     }
1175940b5eaaSdan   }
11767937f632Sdan   return bHaveFK ? eRet : 0;
11771da40a38Sdan }
11781da40a38Sdan 
11798099ce6fSdan /*
11808099ce6fSdan ** This function is called when an UPDATE or DELETE operation is being
11818099ce6fSdan ** compiled on table pTab, which is the parent table of foreign-key pFKey.
11828099ce6fSdan ** If the current operation is an UPDATE, then the pChanges parameter is
11838099ce6fSdan ** passed a pointer to the list of columns being modified. If it is a
11848099ce6fSdan ** DELETE, pChanges is passed a NULL pointer.
11858099ce6fSdan **
11868099ce6fSdan ** It returns a pointer to a Trigger structure containing a trigger
11878099ce6fSdan ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
1188b1929708Sdan ** If the action is "NO ACTION" then a NULL pointer is returned (these actions
1189b1929708Sdan ** require no special handling by the triggers sub-system, code for them is
1190b1929708Sdan ** created by fkScanChildren()).
11918099ce6fSdan **
11928099ce6fSdan ** For example, if pFKey is the foreign key and pTab is table "p" in
11938099ce6fSdan ** the following schema:
11948099ce6fSdan **
11958099ce6fSdan **   CREATE TABLE p(pk PRIMARY KEY);
11968099ce6fSdan **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
11978099ce6fSdan **
11988099ce6fSdan ** then the returned trigger structure is equivalent to:
11998099ce6fSdan **
12008099ce6fSdan **   CREATE TRIGGER ... DELETE ON p BEGIN
12018099ce6fSdan **     DELETE FROM c WHERE ck = old.pk;
12028099ce6fSdan **   END;
12038099ce6fSdan **
12048099ce6fSdan ** The returned pointer is cached as part of the foreign key object. It
12058099ce6fSdan ** is eventually freed along with the rest of the foreign key object by
12068099ce6fSdan ** sqlite3FkDelete().
12078099ce6fSdan */
fkActionTrigger(Parse * pParse,Table * pTab,FKey * pFKey,ExprList * pChanges)12081da40a38Sdan static Trigger *fkActionTrigger(
12098099ce6fSdan   Parse *pParse,                  /* Parse context */
12101da40a38Sdan   Table *pTab,                    /* Table being updated or deleted from */
12111da40a38Sdan   FKey *pFKey,                    /* Foreign key to get action for */
12121da40a38Sdan   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
12131da40a38Sdan ){
12141da40a38Sdan   sqlite3 *db = pParse->db;       /* Database handle */
121529c7f9caSdan   int action;                     /* One of OE_None, OE_Cascade etc. */
121629c7f9caSdan   Trigger *pTrigger;              /* Trigger definition to return */
12178099ce6fSdan   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
12181da40a38Sdan 
12198099ce6fSdan   action = pFKey->aAction[iAction];
12209d970c3cSmistachkin   if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
1221aa9ffabaSdan     return 0;
1222aa9ffabaSdan   }
12238099ce6fSdan   pTrigger = pFKey->apTrigger[iAction];
12241da40a38Sdan 
12259277efa3Sdan   if( action!=OE_None && !pTrigger ){
12268099ce6fSdan     char const *zFrom;            /* Name of child table */
12271da40a38Sdan     int nFrom;                    /* Length in bytes of zFrom */
122829c7f9caSdan     Index *pIdx = 0;              /* Parent key index for this FK */
122929c7f9caSdan     int *aiCol = 0;               /* child table cols -> parent key cols */
1230d3ceeb50Sdrh     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
123129c7f9caSdan     Expr *pWhere = 0;             /* WHERE clause of trigger step */
123229c7f9caSdan     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
12339277efa3Sdan     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
123429c7f9caSdan     int i;                        /* Iterator variable */
1235788536b1Sdrh     Expr *pWhen = 0;              /* WHEN clause for the trigger */
12361da40a38Sdan 
12376c5b915fSdrh     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
12381da40a38Sdan     assert( aiCol || pFKey->nCol==1 );
12391da40a38Sdan 
12401da40a38Sdan     for(i=0; i<pFKey->nCol; i++){
12411da40a38Sdan       Token tOld = { "old", 3 };  /* Literal "old" token */
12421da40a38Sdan       Token tNew = { "new", 3 };  /* Literal "new" token */
12438099ce6fSdan       Token tFromCol;             /* Name of column in child table */
12448099ce6fSdan       Token tToCol;               /* Name of column in parent table */
12458099ce6fSdan       int iFromCol;               /* Idx of column in child table */
124629c7f9caSdan       Expr *pEq;                  /* tFromCol = OLD.tToCol */
12471da40a38Sdan 
12481da40a38Sdan       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
1249a8f0bf64Sdan       assert( iFromCol>=0 );
1250e918aabaSdrh       assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
12514b92f98cSdrh       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
125240aced5cSdrh       sqlite3TokenInit(&tToCol,
1253cf9d36d1Sdrh                    pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zCnName);
1254cf9d36d1Sdrh       sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zCnName);
12551da40a38Sdan 
1256652ac1d0Sdan       /* Create the expression "OLD.zToCol = zFromCol". It is important
1257652ac1d0Sdan       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
1258652ac1d0Sdan       ** that the affinity and collation sequence associated with the
1259652ac1d0Sdan       ** parent table are used for the comparison. */
12601da40a38Sdan       pEq = sqlite3PExpr(pParse, TK_EQ,
12611da40a38Sdan           sqlite3PExpr(pParse, TK_DOT,
1262b6b676eaSdrh             sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
1263abfd35eaSdrh             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
1264b6b676eaSdrh           sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
1265abfd35eaSdrh       );
1266d5c851c1Sdrh       pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
12671da40a38Sdan 
1268788536b1Sdrh       /* For ON UPDATE, construct the next term of the WHEN clause.
1269788536b1Sdrh       ** The final WHEN clause will be like this:
1270788536b1Sdrh       **
1271788536b1Sdrh       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
1272788536b1Sdrh       */
1273788536b1Sdrh       if( pChanges ){
1274788536b1Sdrh         pEq = sqlite3PExpr(pParse, TK_IS,
1275788536b1Sdrh             sqlite3PExpr(pParse, TK_DOT,
1276b6b676eaSdrh               sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
1277abfd35eaSdrh               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
1278788536b1Sdrh             sqlite3PExpr(pParse, TK_DOT,
1279b6b676eaSdrh               sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
1280abfd35eaSdrh               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
1281abfd35eaSdrh             );
1282d5c851c1Sdrh         pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);
1283788536b1Sdrh       }
1284788536b1Sdrh 
12859277efa3Sdan       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
12861da40a38Sdan         Expr *pNew;
12871da40a38Sdan         if( action==OE_Cascade ){
12881da40a38Sdan           pNew = sqlite3PExpr(pParse, TK_DOT,
1289b6b676eaSdrh             sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
1290abfd35eaSdrh             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
12911da40a38Sdan         }else if( action==OE_SetDflt ){
1292bc4974c8Sdrh           Column *pCol = pFKey->pFrom->aCol + iFromCol;
1293bc4974c8Sdrh           Expr *pDflt;
1294bc4974c8Sdrh           if( pCol->colFlags & COLFLAG_GENERATED ){
1295bc4974c8Sdrh             testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1296bc4974c8Sdrh             testcase( pCol->colFlags & COLFLAG_STORED );
1297bc4974c8Sdrh             pDflt = 0;
1298bc4974c8Sdrh           }else{
129979cf2b71Sdrh             pDflt = sqlite3ColumnExpr(pFKey->pFrom, pCol);
1300bc4974c8Sdrh           }
13011da40a38Sdan           if( pDflt ){
13021da40a38Sdan             pNew = sqlite3ExprDup(db, pDflt, 0);
13031da40a38Sdan           }else{
1304e1c03b62Sdrh             pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
13051da40a38Sdan           }
13061da40a38Sdan         }else{
1307e1c03b62Sdrh           pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
13081da40a38Sdan         }
13091da40a38Sdan         pList = sqlite3ExprListAppend(pParse, pList, pNew);
13101da40a38Sdan         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
13111da40a38Sdan       }
13121da40a38Sdan     }
131329c7f9caSdan     sqlite3DbFree(db, aiCol);
13141da40a38Sdan 
13159277efa3Sdan     zFrom = pFKey->pFrom->zName;
13169277efa3Sdan     nFrom = sqlite3Strlen30(zFrom);
13179277efa3Sdan 
13189277efa3Sdan     if( action==OE_Restrict ){
1319b1929708Sdan       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
13209277efa3Sdan       Token tFrom;
1321b1929708Sdan       Token tDb;
13229277efa3Sdan       Expr *pRaise;
13239277efa3Sdan 
13249277efa3Sdan       tFrom.z = zFrom;
13259277efa3Sdan       tFrom.n = nFrom;
1326b1929708Sdan       tDb.z = db->aDb[iDb].zDbSName;
1327b1929708Sdan       tDb.n = sqlite3Strlen30(tDb.z);
1328b1929708Sdan 
1329f9c8ce3cSdrh       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
13309277efa3Sdan       if( pRaise ){
13311194904bSdrh         pRaise->affExpr = OE_Abort;
13329277efa3Sdan       }
13339277efa3Sdan       pSelect = sqlite3SelectNew(pParse,
13349277efa3Sdan           sqlite3ExprListAppend(pParse, 0, pRaise),
1335b1929708Sdan           sqlite3SrcListAppend(pParse, 0, &tDb, &tFrom),
13369277efa3Sdan           pWhere,
13378c0833fbSdrh           0, 0, 0, 0, 0
13389277efa3Sdan       );
13399277efa3Sdan       pWhere = 0;
13409277efa3Sdan     }
13419277efa3Sdan 
1342b2468954Sdrh     /* Disable lookaside memory allocation */
134331f69626Sdrh     DisableLookaside;
134429c7f9caSdan 
134529c7f9caSdan     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
134629c7f9caSdan         sizeof(Trigger) +         /* struct Trigger */
134729c7f9caSdan         sizeof(TriggerStep) +     /* Single step in trigger program */
134846408354Sdan         nFrom + 1                 /* Space for pStep->zTarget */
134929c7f9caSdan     );
135029c7f9caSdan     if( pTrigger ){
135129c7f9caSdan       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
135246408354Sdan       pStep->zTarget = (char *)&pStep[1];
135346408354Sdan       memcpy((char *)pStep->zTarget, zFrom, nFrom);
135429c7f9caSdan 
135529c7f9caSdan       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
135629c7f9caSdan       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
13579277efa3Sdan       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
1358788536b1Sdrh       if( pWhen ){
1359abfd35eaSdrh         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
1360788536b1Sdrh         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
1361788536b1Sdrh       }
136229c7f9caSdan     }
136329c7f9caSdan 
136429c7f9caSdan     /* Re-enable the lookaside buffer, if it was disabled earlier. */
136531f69626Sdrh     EnableLookaside;
136629c7f9caSdan 
1367788536b1Sdrh     sqlite3ExprDelete(db, pWhere);
1368788536b1Sdrh     sqlite3ExprDelete(db, pWhen);
1369788536b1Sdrh     sqlite3ExprListDelete(db, pList);
13709277efa3Sdan     sqlite3SelectDelete(db, pSelect);
137129c7f9caSdan     if( db->mallocFailed==1 ){
137229c7f9caSdan       fkTriggerDelete(db, pTrigger);
137329c7f9caSdan       return 0;
137429c7f9caSdan     }
1375b07028f7Sdrh     assert( pStep!=0 );
137655f66b34Sdrh     assert( pTrigger!=0 );
13771da40a38Sdan 
13789277efa3Sdan     switch( action ){
13799277efa3Sdan       case OE_Restrict:
13809277efa3Sdan         pStep->op = TK_SELECT;
13819277efa3Sdan         break;
13829277efa3Sdan       case OE_Cascade:
13839277efa3Sdan         if( !pChanges ){
13849277efa3Sdan           pStep->op = TK_DELETE;
13859277efa3Sdan           break;
13869277efa3Sdan         }
138708b92086Sdrh         /* no break */ deliberate_fall_through
13889277efa3Sdan       default:
13899277efa3Sdan         pStep->op = TK_UPDATE;
13909277efa3Sdan     }
13911da40a38Sdan     pStep->pTrig = pTrigger;
13921da40a38Sdan     pTrigger->pSchema = pTab->pSchema;
13931da40a38Sdan     pTrigger->pTabSchema = pTab->pSchema;
13948099ce6fSdan     pFKey->apTrigger[iAction] = pTrigger;
13958099ce6fSdan     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
13961da40a38Sdan   }
13971da40a38Sdan 
13981da40a38Sdan   return pTrigger;
13991da40a38Sdan }
14001da40a38Sdan 
14011da40a38Sdan /*
14021da40a38Sdan ** This function is called when deleting or updating a row to implement
14031da40a38Sdan ** any required CASCADE, SET NULL or SET DEFAULT actions.
14041da40a38Sdan */
sqlite3FkActions(Parse * pParse,Table * pTab,ExprList * pChanges,int regOld,int * aChange,int bChngRowid)14051da40a38Sdan void sqlite3FkActions(
14061da40a38Sdan   Parse *pParse,                  /* Parse context */
14071da40a38Sdan   Table *pTab,                    /* Table being updated or deleted from */
14081da40a38Sdan   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
14098ff2d956Sdan   int regOld,                     /* Address of array containing old row */
14108ff2d956Sdan   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
14118ff2d956Sdan   int bChngRowid                  /* True if rowid is UPDATEd */
14121da40a38Sdan ){
14131da40a38Sdan   /* If foreign-key support is enabled, iterate through all FKs that
14141da40a38Sdan   ** refer to table pTab. If there is an action associated with the FK
14151da40a38Sdan   ** for this operation (either update or delete), invoke the associated
14161da40a38Sdan   ** trigger sub-program.  */
14171da40a38Sdan   if( pParse->db->flags&SQLITE_ForeignKeys ){
14181da40a38Sdan     FKey *pFKey;                  /* Iterator variable */
1419432cc5b9Sdan     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
14208ff2d956Sdan       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
14218ff2d956Sdan         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
14228ff2d956Sdan         if( pAct ){
14238ff2d956Sdan           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
14248ff2d956Sdan         }
14251da40a38Sdan       }
14261da40a38Sdan     }
14271da40a38Sdan   }
14281da40a38Sdan }
14291da40a38Sdan 
143075cbd984Sdan #endif /* ifndef SQLITE_OMIT_TRIGGER */
143175cbd984Sdan 
14321da40a38Sdan /*
14331da40a38Sdan ** Free all memory associated with foreign key definitions attached to
14341da40a38Sdan ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
14351da40a38Sdan ** hash table.
14361da40a38Sdan */
sqlite3FkDelete(sqlite3 * db,Table * pTab)14371feeaed2Sdan void sqlite3FkDelete(sqlite3 *db, Table *pTab){
14381da40a38Sdan   FKey *pFKey;                    /* Iterator variable */
14391da40a38Sdan   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
14401da40a38Sdan 
144178b2fa86Sdrh   assert( IsOrdinaryTable(pTab) );
1442*41ce47c4Sdrh   assert( db!=0 );
1443f38524d2Sdrh   for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pNext){
144476f24775Sdrh     assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
14451da40a38Sdan 
14461da40a38Sdan     /* Remove the FK from the fkeyHash hash table. */
1447*41ce47c4Sdrh     if( db->pnBytesFreed==0 ){
14481da40a38Sdan       if( pFKey->pPrevTo ){
14491da40a38Sdan         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
14501da40a38Sdan       }else{
1451d46def77Sdan         void *p = (void *)pFKey->pNextTo;
1452d46def77Sdan         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
1453acbcb7e0Sdrh         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
14541da40a38Sdan       }
14551da40a38Sdan       if( pFKey->pNextTo ){
14561da40a38Sdan         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
14571da40a38Sdan       }
1458d46def77Sdan     }
1459d46def77Sdan 
1460d46def77Sdan     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
1461d46def77Sdan     ** classified as either immediate or deferred.
1462d46def77Sdan     */
1463d46def77Sdan     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
14641da40a38Sdan 
14651da40a38Sdan     /* Delete any triggers created to implement actions for this FK. */
146675cbd984Sdan #ifndef SQLITE_OMIT_TRIGGER
14671feeaed2Sdan     fkTriggerDelete(db, pFKey->apTrigger[0]);
14681feeaed2Sdan     fkTriggerDelete(db, pFKey->apTrigger[1]);
146975cbd984Sdan #endif
14701da40a38Sdan 
14711da40a38Sdan     pNext = pFKey->pNextFrom;
14721feeaed2Sdan     sqlite3DbFree(db, pFKey);
14731da40a38Sdan   }
14741da40a38Sdan }
147575cbd984Sdan #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
1476