dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 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 |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 17 | #ifndef SQLITE_OMIT_TRIGGER |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 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, an OP_Halt is |
| 25 | ** executed and the current statement transaction rolled back. If a |
| 26 | ** deferred foreign key constraint is violated, no action is taken |
| 27 | ** immediately. However if the application attempts to commit the |
| 28 | ** transaction before fixing the constraint violation, the attempt fails. |
| 29 | ** |
| 30 | ** Deferred constraints are implemented using a simple counter associated |
| 31 | ** with the database handle. The counter is set to zero each time a |
| 32 | ** database transaction is opened. Each time a statement is executed |
| 33 | ** that causes a foreign key violation, the counter is incremented. Each |
| 34 | ** time a statement is executed that removes an existing violation from |
| 35 | ** the database, the counter is decremented. When the transaction is |
| 36 | ** committed, the commit fails if the current value of the counter is |
| 37 | ** greater than zero. This scheme has two big drawbacks: |
| 38 | ** |
| 39 | ** * When a commit fails due to a deferred foreign key constraint, |
| 40 | ** there is no way to tell which foreign constraint is not satisfied, |
| 41 | ** or which row it is not satisfied for. |
| 42 | ** |
| 43 | ** * If the database contains foreign key violations when the |
| 44 | ** transaction is opened, this may cause the mechanism to malfunction. |
| 45 | ** |
| 46 | ** Despite these problems, this approach is adopted as it seems simpler |
| 47 | ** than the alternatives. |
| 48 | ** |
| 49 | ** INSERT operations: |
| 50 | ** |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 51 | ** I.1) For each FK for which the table is the child table, search |
| 52 | ** the parent table for a match. If none is found, throw an |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 53 | ** exception for an immediate FK, or increment the counter for a |
| 54 | ** deferred FK. |
| 55 | ** |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 56 | ** I.2) For each deferred FK for which the table is the parent table, |
| 57 | ** search the child table for rows that correspond to the new |
| 58 | ** row in the parent table. Decrement the counter for each row |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 59 | ** found (as the constraint is now satisfied). |
| 60 | ** |
| 61 | ** DELETE operations: |
| 62 | ** |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 63 | ** D.1) For each deferred FK for which the table is the child table, |
| 64 | ** search the parent table for a row that corresponds to the |
| 65 | ** deleted row in the child table. If such a row is not found, |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 66 | ** decrement the counter. |
| 67 | ** |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 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, throw an exception for an |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 71 | ** immediate FK, or increment the counter for a deferred FK. |
| 72 | ** |
| 73 | ** UPDATE operations: |
| 74 | ** |
| 75 | ** An UPDATE command requires that all 4 steps above are taken, but only |
| 76 | ** for FK constraints for which the affected columns are actually |
| 77 | ** modified (values must be compared at runtime). |
| 78 | ** |
| 79 | ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2. |
| 80 | ** This simplifies the implementation a bit. |
| 81 | ** |
| 82 | ** For the purposes of immediate FK constraints, the OR REPLACE conflict |
| 83 | ** resolution is considered to delete rows before the new row is inserted. |
| 84 | ** If a delete caused by OR REPLACE violates an FK constraint, an exception |
| 85 | ** is thrown, even if the FK constraint would be satisfied after the new |
| 86 | ** row is inserted. |
| 87 | ** |
| 88 | ** TODO: How should dropping a table be handled? How should renaming a |
| 89 | ** table be handled? |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 90 | ** |
| 91 | ** |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 92 | ** Query API Notes |
| 93 | ** --------------- |
| 94 | ** |
| 95 | ** Before coding an UPDATE or DELETE row operation, the code-generator |
| 96 | ** for those two operations needs to know whether or not the operation |
| 97 | ** requires any FK processing and, if so, which columns of the original |
| 98 | ** row are required by the FK processing VDBE code (i.e. if FKs were |
| 99 | ** implemented using triggers, which of the old.* columns would be |
| 100 | ** accessed). No information is required by the code-generator before |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 101 | ** coding an INSERT operation. The functions used by the UPDATE/DELETE |
| 102 | ** generation code to query for this information are: |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 103 | ** |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 104 | ** sqlite3FkRequired() - Test to see if FK processing is required. |
| 105 | ** sqlite3FkOldmask() - Query for the set of required old.* columns. |
| 106 | ** |
| 107 | ** |
| 108 | ** Externally accessible module functions |
| 109 | ** -------------------------------------- |
| 110 | ** |
| 111 | ** sqlite3FkCheck() - Check for foreign key violations. |
| 112 | ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. |
| 113 | ** sqlite3FkDelete() - Delete an FKey structure. |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 114 | */ |
| 115 | |
| 116 | /* |
| 117 | ** VDBE Calling Convention |
| 118 | ** ----------------------- |
| 119 | ** |
| 120 | ** Example: |
| 121 | ** |
| 122 | ** For the following INSERT statement: |
| 123 | ** |
| 124 | ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); |
| 125 | ** INSERT INTO t1 VALUES(1, 2, 3.1); |
| 126 | ** |
| 127 | ** Register (x): 2 (type integer) |
| 128 | ** Register (x+1): 1 (type integer) |
| 129 | ** Register (x+2): NULL (type NULL) |
| 130 | ** Register (x+3): 3.1 (type real) |
| 131 | */ |
| 132 | |
| 133 | /* |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 134 | ** A foreign key constraint requires that the key columns in the parent |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 135 | ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 136 | ** Given that pParent is the parent table for foreign key constraint pFKey, |
| 137 | ** search the schema a unique index on the parent key columns. |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 138 | ** |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 139 | ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY |
| 140 | ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx |
| 141 | ** is set to point to the unique index. |
| 142 | ** |
| 143 | ** If the parent key consists of a single column (the foreign key constraint |
| 144 | ** is not a composite foreign key), output variable *paiCol is set to NULL. |
| 145 | ** Otherwise, it is set to point to an allocated array of size N, where |
| 146 | ** N is the number of columns in the parent key. The first element of the |
| 147 | ** array is the index of the child table column that is mapped by the FK |
| 148 | ** constraint to the parent table column stored in the left-most column |
| 149 | ** of index *ppIdx. The second element of the array is the index of the |
| 150 | ** child table column that corresponds to the second left-most column of |
| 151 | ** *ppIdx, and so on. |
| 152 | ** |
| 153 | ** If the required index cannot be found, either because: |
| 154 | ** |
| 155 | ** 1) The named parent key columns do not exist, or |
| 156 | ** |
| 157 | ** 2) The named parent key columns do exist, but are not subject to a |
| 158 | ** UNIQUE or PRIMARY KEY constraint, or |
| 159 | ** |
| 160 | ** 3) No parent key columns were provided explicitly as part of the |
| 161 | ** foreign key definition, and the parent table does not have a |
| 162 | ** PRIMARY KEY, or |
| 163 | ** |
| 164 | ** 4) No parent key columns were provided explicitly as part of the |
| 165 | ** foreign key definition, and the PRIMARY KEY of the parent table |
| 166 | ** consists of a a different number of columns to the child key in |
| 167 | ** the child table. |
| 168 | ** |
| 169 | ** then non-zero is returned, and a "foreign key mismatch" error loaded |
| 170 | ** into pParse. If an OOM error occurs, non-zero is returned and the |
| 171 | ** pParse->db->mallocFailed flag is set. |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 172 | */ |
| 173 | static int locateFkeyIndex( |
| 174 | Parse *pParse, /* Parse context to store any error in */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 175 | Table *pParent, /* Parent table of FK constraint pFKey */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 176 | FKey *pFKey, /* Foreign key to find index for */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 177 | Index **ppIdx, /* OUT: Unique index on parent table */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 178 | int **paiCol /* OUT: Map of index columns in pFKey */ |
| 179 | ){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 180 | Index *pIdx = 0; /* Value to return via *ppIdx */ |
| 181 | int *aiCol = 0; /* Value to return via *paiCol */ |
| 182 | int nCol = pFKey->nCol; /* Number of columns in parent key */ |
| 183 | char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 184 | |
| 185 | /* The caller is responsible for zeroing output parameters. */ |
| 186 | assert( ppIdx && *ppIdx==0 ); |
| 187 | assert( !paiCol || *paiCol==0 ); |
| 188 | |
| 189 | /* If this is a non-composite (single column) foreign key, check if it |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 190 | ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 191 | ** and *paiCol set to zero and return early. |
| 192 | ** |
| 193 | ** Otherwise, for a composite foreign key (more than one column), allocate |
| 194 | ** space for the aiCol array (returned via output parameter *paiCol). |
| 195 | ** Non-composite foreign keys do not require the aiCol array. |
| 196 | */ |
| 197 | if( nCol==1 ){ |
| 198 | /* The FK maps to the IPK if any of the following are true: |
| 199 | ** |
dan | d981d44 | 2009-09-23 13:59:17 +0000 | [diff] [blame] | 200 | ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly |
| 201 | ** mapped to the primary key of table pParent, or |
| 202 | ** 2) The FK is explicitly mapped to a column declared as INTEGER |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 203 | ** PRIMARY KEY. |
| 204 | */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 205 | if( pParent->iPKey>=0 ){ |
| 206 | if( !zKey ) return 0; |
| 207 | if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 208 | } |
| 209 | }else if( paiCol ){ |
| 210 | assert( nCol>1 ); |
| 211 | aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int)); |
| 212 | if( !aiCol ) return 1; |
| 213 | *paiCol = aiCol; |
| 214 | } |
| 215 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 216 | for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 217 | if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ |
| 218 | /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number |
| 219 | ** of columns. If each indexed column corresponds to a foreign key |
| 220 | ** column of pFKey, then this index is a winner. */ |
| 221 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 222 | if( zKey==0 ){ |
| 223 | /* If zKey is NULL, then this foreign key is implicitly mapped to |
| 224 | ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 225 | ** identified by the test (Index.autoIndex==2). */ |
| 226 | if( pIdx->autoIndex==2 ){ |
| 227 | if( aiCol ) memcpy(aiCol, pIdx->aiColumn, sizeof(int)*nCol); |
| 228 | break; |
| 229 | } |
| 230 | }else{ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 231 | /* If zKey is non-NULL, then this foreign key was declared to |
| 232 | ** map to an explicit list of columns in table pParent. Check if this |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 233 | ** index matches those columns. */ |
| 234 | int i, j; |
| 235 | for(i=0; i<nCol; i++){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 236 | char *zIdxCol = pParent->aCol[pIdx->aiColumn[i]].zName; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 237 | for(j=0; j<nCol; j++){ |
| 238 | if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){ |
| 239 | if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; |
| 240 | break; |
| 241 | } |
| 242 | } |
| 243 | if( j==nCol ) break; |
| 244 | } |
| 245 | if( i==nCol ) break; /* pIdx is usable */ |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | if( pParse && !pIdx ){ |
| 251 | sqlite3ErrorMsg(pParse, "foreign key mismatch"); |
| 252 | sqlite3DbFree(pParse->db, aiCol); |
| 253 | return 1; |
| 254 | } |
| 255 | |
| 256 | *ppIdx = pIdx; |
| 257 | return 0; |
| 258 | } |
| 259 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 260 | /* |
| 261 | ** This function is called when a row is inserted into the child table of |
| 262 | ** foreign key constraint pFKey and, if pFKey is deferred, when a row is |
| 263 | ** deleted from the child table of pFKey. If an SQL UPDATE is executed on |
| 264 | ** the child table of pFKey, this function is invoked twice for each row |
| 265 | ** affected - once to "delete" the old row, and then again to "insert" the |
| 266 | ** new row. |
| 267 | ** |
| 268 | ** Each time it is called, this function generates VDBE code to locate the |
| 269 | ** row in the parent table that corresponds to the row being inserted into |
| 270 | ** or deleted from the child table. If the parent row can be found, no |
| 271 | ** special action is taken. Otherwise, if the parent row can *not* be |
| 272 | ** found in the parent table: |
| 273 | ** |
| 274 | ** Operation | FK type | Action taken |
| 275 | ** -------------------------------------------------------------------------- |
| 276 | ** INSERT immediate Throw a "foreign key constraint failed" exception. |
| 277 | ** |
| 278 | ** INSERT deferred Increment the "deferred constraint counter". |
| 279 | ** |
| 280 | ** DELETE deferred Decrement the "deferred constraint counter". |
| 281 | ** |
| 282 | ** This function is never called for a delete on the child table of an |
| 283 | ** immediate foreign key constraint. These operations are identified in |
| 284 | ** the comment at the top of this file (fkey.c) as "I.1" and "D.1". |
| 285 | */ |
| 286 | static void fkLookupParent( |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 287 | Parse *pParse, /* Parse context */ |
| 288 | int iDb, /* Index of database housing pTab */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 289 | Table *pTab, /* Parent table of FK pFKey */ |
| 290 | Index *pIdx, /* Unique index on parent key columns in pTab */ |
| 291 | FKey *pFKey, /* Foreign key constraint */ |
| 292 | int *aiCol, /* Map from parent key columns to child table columns */ |
| 293 | int regData, /* Address of array containing child table row */ |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 294 | int nIncr /* Increment constraint counter by this */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 295 | ){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 296 | int i; /* Iterator variable */ |
| 297 | Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ |
| 298 | int iCur = pParse->nTab - 1; /* Cursor number to use */ |
| 299 | int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 300 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 301 | /* Check if any of the key columns in the child table row are |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 302 | ** NULL. If any are, then the constraint is satisfied. No need |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 303 | ** to search for a matching row in the parent table. */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 304 | for(i=0; i<pFKey->nCol; i++){ |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 305 | int iReg = aiCol[i] + regData + 1; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 306 | sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); |
| 307 | } |
| 308 | |
| 309 | if( pIdx==0 ){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 310 | /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY |
| 311 | ** column of the parent table (table pTab). */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 312 | int iReg = pFKey->aCol[0].iFrom + regData + 1; |
| 313 | sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); |
| 314 | sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iReg); |
| 315 | sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); |
| 316 | sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); |
| 317 | }else{ |
| 318 | int regRec = sqlite3GetTempReg(pParse); |
| 319 | KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); |
| 320 | |
| 321 | sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); |
| 322 | sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); |
| 323 | |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 324 | if( pFKey->nCol>1 ){ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 325 | int nCol = pFKey->nCol; |
| 326 | int regTemp = sqlite3GetTempRange(pParse, nCol); |
| 327 | for(i=0; i<nCol; i++){ |
| 328 | sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i); |
| 329 | } |
| 330 | sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec); |
| 331 | sqlite3ReleaseTempRange(pParse, regTemp, nCol); |
| 332 | }else{ |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 333 | int iReg = aiCol[0] + regData + 1; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 334 | sqlite3VdbeAddOp3(v, OP_MakeRecord, iReg, 1, regRec); |
| 335 | sqlite3IndexAffinityStr(v, pIdx); |
| 336 | } |
| 337 | |
| 338 | sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec); |
| 339 | sqlite3ReleaseTempReg(pParse, regRec); |
| 340 | } |
| 341 | |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 342 | if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){ |
| 343 | /* Special case: If this is an INSERT statement that will insert exactly |
| 344 | ** one row into the table, raise a constraint immediately instead of |
| 345 | ** incrementing a counter. This is necessary as the VM code is being |
| 346 | ** generated for will not open a statement transaction. */ |
| 347 | assert( nIncr==1 ); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 348 | sqlite3HaltConstraint( |
| 349 | pParse, OE_Abort, "foreign key constraint failed", P4_STATIC |
| 350 | ); |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 351 | }else{ |
| 352 | if( nIncr>0 && pFKey->isDeferred==0 ){ |
| 353 | sqlite3ParseToplevel(pParse)->mayAbort = 1; |
| 354 | } |
| 355 | sqlite3VdbeAddOp2(v, OP_FkCounter, nIncr, pFKey->isDeferred); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 356 | } |
| 357 | |
| 358 | sqlite3VdbeResolveLabel(v, iOk); |
| 359 | } |
| 360 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 361 | /* |
| 362 | ** This function is called to generate code executed when a row is deleted |
| 363 | ** from the parent table of foreign key constraint pFKey and, if pFKey is |
| 364 | ** deferred, when a row is inserted into the same table. When generating |
| 365 | ** code for an SQL UPDATE operation, this function may be called twice - |
| 366 | ** once to "delete" the old row and once to "insert" the new row. |
| 367 | ** |
| 368 | ** The code generated by this function scans through the rows in the child |
| 369 | ** table that correspond to the parent table row being deleted or inserted. |
| 370 | ** For each child row found, one of the following actions is taken: |
| 371 | ** |
| 372 | ** Operation | FK type | Action taken |
| 373 | ** -------------------------------------------------------------------------- |
| 374 | ** DELETE immediate Throw a "foreign key constraint failed" exception. |
| 375 | ** |
| 376 | ** DELETE deferred Increment the "deferred constraint counter". |
| 377 | ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, |
| 378 | ** throw a "foreign key constraint failed" exception. |
| 379 | ** |
| 380 | ** INSERT deferred Decrement the "deferred constraint counter". |
| 381 | ** |
| 382 | ** This function is never called for an INSERT operation on the parent table |
| 383 | ** of an immediate foreign key constraint. These operations are identified in |
| 384 | ** the comment at the top of this file (fkey.c) as "I.2" and "D.2". |
| 385 | */ |
| 386 | static void fkScanChildren( |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 387 | Parse *pParse, /* Parse context */ |
| 388 | SrcList *pSrc, /* SrcList containing the table to scan */ |
| 389 | Index *pIdx, /* Foreign key index */ |
| 390 | FKey *pFKey, /* Foreign key relationship */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 391 | int *aiCol, /* Map from pIdx cols to child table cols */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 392 | int regData, /* Referenced table data starts here */ |
| 393 | int nIncr /* Amount to increment deferred counter by */ |
| 394 | ){ |
| 395 | sqlite3 *db = pParse->db; /* Database handle */ |
| 396 | int i; /* Iterator variable */ |
| 397 | Expr *pWhere = 0; /* WHERE clause to scan with */ |
| 398 | NameContext sNameContext; /* Context used to resolve WHERE clause */ |
| 399 | WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ |
| 400 | |
| 401 | for(i=0; i<pFKey->nCol; i++){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 402 | Expr *pLeft; /* Value from parent table row */ |
| 403 | Expr *pRight; /* Column ref to child table */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 404 | Expr *pEq; /* Expression (pLeft = pRight) */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 405 | int iCol; /* Index of column in child table */ |
| 406 | const char *zCol; /* Name of column in child table */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 407 | |
| 408 | pLeft = sqlite3Expr(db, TK_REGISTER, 0); |
| 409 | if( pLeft ){ |
| 410 | pLeft->iTable = (pIdx ? (regData+pIdx->aiColumn[i]+1) : regData); |
| 411 | } |
| 412 | iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; |
dan | a8f0bf6 | 2009-09-23 12:06:52 +0000 | [diff] [blame] | 413 | assert( iCol>=0 ); |
| 414 | zCol = pFKey->pFrom->aCol[iCol].zName; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 415 | pRight = sqlite3Expr(db, TK_ID, zCol); |
| 416 | pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); |
| 417 | pWhere = sqlite3ExprAnd(db, pWhere, pEq); |
| 418 | } |
| 419 | |
| 420 | /* Resolve the references in the WHERE clause. */ |
| 421 | memset(&sNameContext, 0, sizeof(NameContext)); |
| 422 | sNameContext.pSrcList = pSrc; |
| 423 | sNameContext.pParse = pParse; |
| 424 | sqlite3ResolveExprNames(&sNameContext, pWhere); |
| 425 | |
| 426 | /* Create VDBE to loop through the entries in pSrc that match the WHERE |
| 427 | ** clause. If the constraint is not deferred, throw an exception for |
| 428 | ** each row found. Otherwise, for deferred constraints, increment the |
| 429 | ** deferred constraint counter by nIncr for each row selected. */ |
| 430 | pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0); |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 431 | if( nIncr==0 ){ |
| 432 | /* A RESTRICT Action. */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 433 | sqlite3HaltConstraint( |
| 434 | pParse, OE_Abort, "foreign key constraint failed", P4_STATIC |
| 435 | ); |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 436 | }else{ |
| 437 | if( nIncr>0 && pFKey->isDeferred==0 ){ |
| 438 | sqlite3ParseToplevel(pParse)->mayAbort = 1; |
| 439 | } |
| 440 | sqlite3VdbeAddOp2(pParse->pVdbe, OP_FkCounter, nIncr, pFKey->isDeferred); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 441 | } |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 442 | if( pWInfo ){ |
| 443 | sqlite3WhereEnd(pWInfo); |
| 444 | } |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 445 | |
| 446 | /* Clean up the WHERE clause constructed above. */ |
| 447 | sqlite3ExprDelete(db, pWhere); |
| 448 | } |
| 449 | |
| 450 | /* |
| 451 | ** This function returns a pointer to the head of a linked list of FK |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 452 | ** constraints for which table pTab is the parent table. For example, |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 453 | ** given the following schema: |
| 454 | ** |
| 455 | ** CREATE TABLE t1(a PRIMARY KEY); |
| 456 | ** CREATE TABLE t2(b REFERENCES t1(a); |
| 457 | ** |
| 458 | ** Calling this function with table "t1" as an argument returns a pointer |
| 459 | ** to the FKey structure representing the foreign key constraint on table |
| 460 | ** "t2". Calling this function with "t2" as the argument would return a |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 461 | ** NULL pointer (as there are no FK constraints for which t2 is the parent |
| 462 | ** table). |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 463 | */ |
| 464 | static FKey *fkRefering(Table *pTab){ |
| 465 | int nName = sqlite3Strlen30(pTab->zName); |
| 466 | return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName); |
| 467 | } |
| 468 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 469 | /* |
| 470 | ** The second argument is a Trigger structure allocated by the |
| 471 | ** fkActionTrigger() routine. This function deletes the Trigger structure |
| 472 | ** and all of its sub-components. |
| 473 | ** |
| 474 | ** The Trigger structure or any of its sub-components may be allocated from |
| 475 | ** the lookaside buffer belonging to database handle dbMem. |
| 476 | */ |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 477 | static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ |
| 478 | if( p ){ |
| 479 | TriggerStep *pStep = p->step_list; |
| 480 | sqlite3ExprDelete(dbMem, pStep->pWhere); |
| 481 | sqlite3ExprListDelete(dbMem, pStep->pExprList); |
drh | 788536b | 2009-09-23 03:01:58 +0000 | [diff] [blame] | 482 | sqlite3ExprDelete(dbMem, p->pWhen); |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 483 | sqlite3DbFree(dbMem, p); |
| 484 | } |
| 485 | } |
| 486 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 487 | /* |
| 488 | ** This function is called when inserting, deleting or updating a row of |
| 489 | ** table pTab to generate VDBE code to perform foreign key constraint |
| 490 | ** processing for the operation. |
| 491 | ** |
| 492 | ** For a DELETE operation, parameter regOld is passed the index of the |
| 493 | ** first register in an array of (pTab->nCol+1) registers containing the |
| 494 | ** rowid of the row being deleted, followed by each of the column values |
| 495 | ** of the row being deleted, from left to right. Parameter regNew is passed |
| 496 | ** zero in this case. |
| 497 | ** |
| 498 | ** For an UPDATE operation, regOld is the first in an array of (pTab->nCol+1) |
| 499 | ** registers containing the old rowid and column values of the row being |
| 500 | ** updated, and regNew is the first in an array of the same size containing |
| 501 | ** the corresponding new values. Parameter pChanges is passed the list of |
| 502 | ** columns being updated by the statement. |
| 503 | ** |
| 504 | ** For an INSERT operation, regOld is passed zero and regNew is passed the |
| 505 | ** first register of an array of (pTab->nCol+1) registers containing the new |
| 506 | ** row data. |
| 507 | ** |
| 508 | ** If an error occurs, an error message is left in the pParse structure. |
| 509 | */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 510 | void sqlite3FkCheck( |
| 511 | Parse *pParse, /* Parse context */ |
| 512 | Table *pTab, /* Row is being deleted from this table */ |
| 513 | ExprList *pChanges, /* Changed columns if this is an UPDATE */ |
| 514 | int regOld, /* Previous row data is stored here */ |
| 515 | int regNew /* New row data is stored here */ |
| 516 | ){ |
| 517 | sqlite3 *db = pParse->db; /* Database handle */ |
| 518 | Vdbe *v; /* VM to write code to */ |
| 519 | FKey *pFKey; /* Used to iterate through FKs */ |
| 520 | int iDb; /* Index of database containing pTab */ |
| 521 | const char *zDb; /* Name of database containing pTab */ |
| 522 | |
| 523 | assert( ( pChanges && regOld && regNew) /* UPDATE operation */ |
| 524 | || (!pChanges && !regOld && regNew) /* INSERT operation */ |
| 525 | || (!pChanges && regOld && !regNew) /* DELETE operation */ |
| 526 | ); |
| 527 | |
| 528 | /* If foreign-keys are disabled, this function is a no-op. */ |
| 529 | if( (db->flags&SQLITE_ForeignKeys)==0 ) return; |
| 530 | |
| 531 | v = sqlite3GetVdbe(pParse); |
| 532 | iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |
| 533 | zDb = db->aDb[iDb].zName; |
| 534 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 535 | /* Loop through all the foreign key constraints for which pTab is the |
| 536 | ** child table (the table that the foreign key definition is part of). */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 537 | for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 538 | Table *pTo; /* Parent table of foreign key pFKey */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 539 | Index *pIdx = 0; /* Index on key columns in pTo */ |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 540 | int *aiFree = 0; |
| 541 | int *aiCol; |
| 542 | int iCol; |
| 543 | int i; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 544 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 545 | /* Find the parent table of this foreign key. Also find a unique index |
| 546 | ** on the parent key columns in the parent table. If either of these |
| 547 | ** schema items cannot be located, set an error in pParse and return |
| 548 | ** early. */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 549 | pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 550 | if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return; |
| 551 | assert( pFKey->nCol==1 || (aiFree && pIdx) ); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 552 | |
| 553 | /* If the key does not overlap with the pChanges list, skip this FK. */ |
| 554 | if( pChanges ){ |
| 555 | /* TODO */ |
| 556 | } |
| 557 | |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 558 | if( aiFree ){ |
| 559 | aiCol = aiFree; |
| 560 | }else{ |
| 561 | iCol = pFKey->aCol[0].iFrom; |
| 562 | aiCol = &iCol; |
| 563 | } |
| 564 | for(i=0; i<pFKey->nCol; i++){ |
| 565 | if( aiCol[i]==pTab->iPKey ){ |
| 566 | aiCol[i] = -1; |
| 567 | } |
| 568 | } |
| 569 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 570 | /* Take a shared-cache advisory read-lock on the parent table. Allocate |
| 571 | ** a cursor to use to search the unique index on the parent key columns |
| 572 | ** in the parent table. */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 573 | sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); |
| 574 | pParse->nTab++; |
| 575 | |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 576 | if( regOld!=0 ){ |
| 577 | /* A row is being removed from the child table. Search for the parent. |
| 578 | ** If the parent does not exist, removing the child row resolves an |
| 579 | ** outstanding foreign key constraint violation. */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 580 | fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 581 | } |
| 582 | if( regNew!=0 ){ |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 583 | /* A row is being added to the child table. If a parent row cannot |
| 584 | ** be found, adding the child row has violated the FK constraint. */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 585 | fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 586 | } |
| 587 | |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 588 | sqlite3DbFree(db, aiFree); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 589 | } |
| 590 | |
| 591 | /* Loop through all the foreign key constraints that refer to this table */ |
| 592 | for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){ |
| 593 | int iGoto; /* Address of OP_Goto instruction */ |
| 594 | Index *pIdx = 0; /* Foreign key index for pFKey */ |
| 595 | SrcList *pSrc; |
| 596 | int *aiCol = 0; |
| 597 | |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 598 | if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){ |
| 599 | assert( regOld==0 && regNew!=0 ); |
| 600 | /* Inserting a single row into a parent table cannot cause an immediate |
| 601 | ** foreign key violation. So do nothing in this case. */ |
| 602 | return; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 603 | } |
| 604 | |
| 605 | if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return; |
| 606 | assert( aiCol || pFKey->nCol==1 ); |
| 607 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 608 | /* Check if this update statement has modified any of the child key |
| 609 | ** columns for this foreign key constraint. If it has not, there is |
| 610 | ** no need to search the child table for rows in violation. This is |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 611 | ** just an optimization. Things would work fine without this check. */ |
| 612 | if( pChanges ){ |
| 613 | /* TODO */ |
| 614 | } |
| 615 | |
| 616 | /* Create a SrcList structure containing a single table (the table |
| 617 | ** the foreign key that refers to this table is attached to). This |
| 618 | ** is required for the sqlite3WhereXXX() interface. */ |
| 619 | pSrc = sqlite3SrcListAppend(db, 0, 0, 0); |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 620 | if( pSrc ){ |
| 621 | pSrc->a->pTab = pFKey->pFrom; |
| 622 | pSrc->a->pTab->nRef++; |
| 623 | pSrc->a->iCursor = pParse->nTab++; |
| 624 | |
| 625 | /* If this is an UPDATE, and none of the columns associated with this |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 626 | ** FK have been modified, do not scan the child table. Unlike the |
| 627 | ** compile-time test implemented above, this is not just an |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 628 | ** optimization. It is required so that immediate foreign keys do not |
| 629 | ** throw exceptions when the user executes a statement like: |
| 630 | ** |
| 631 | ** UPDATE refd_table SET refd_column = refd_column |
| 632 | */ |
| 633 | if( pChanges ){ |
| 634 | int i; |
| 635 | int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; |
| 636 | for(i=0; i<pFKey->nCol; i++){ |
| 637 | int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1; |
| 638 | sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff); |
| 639 | } |
| 640 | iGoto = sqlite3VdbeAddOp0(v, OP_Goto); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 641 | } |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 642 | |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 643 | if( regNew!=0 ){ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 644 | fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1); |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 645 | } |
| 646 | if( regOld!=0 ){ |
| 647 | /* If there is a RESTRICT action configured for the current operation |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 648 | ** on the parent table of this FK, then throw an exception |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 649 | ** immediately if the FK constraint is violated, even if this is a |
| 650 | ** deferred trigger. That's what RESTRICT means. To defer checking |
| 651 | ** the constraint, the FK should specify NO ACTION (represented |
| 652 | ** using OE_None). NO ACTION is the default. */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 653 | fkScanChildren(pParse, pSrc, pIdx, pFKey, aiCol, regOld, |
| 654 | pFKey->aAction[pChanges!=0]!=OE_Restrict |
dan | f59c5ca | 2009-09-22 16:55:38 +0000 | [diff] [blame] | 655 | ); |
| 656 | } |
| 657 | |
| 658 | if( pChanges ){ |
| 659 | sqlite3VdbeJumpHere(v, iGoto); |
| 660 | } |
| 661 | sqlite3SrcListDelete(db, pSrc); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 662 | } |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 663 | sqlite3DbFree(db, aiCol); |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) |
| 668 | |
| 669 | /* |
| 670 | ** This function is called before generating code to update or delete a |
| 671 | ** row contained in table pTab. If the operation is an update, then |
| 672 | ** pChanges is a pointer to the list of columns to modify. If this is a |
| 673 | ** delete, then pChanges is NULL. |
| 674 | */ |
| 675 | u32 sqlite3FkOldmask( |
| 676 | Parse *pParse, /* Parse context */ |
| 677 | Table *pTab, /* Table being modified */ |
| 678 | ExprList *pChanges /* Non-NULL for UPDATE operations */ |
| 679 | ){ |
| 680 | u32 mask = 0; |
| 681 | if( pParse->db->flags&SQLITE_ForeignKeys ){ |
| 682 | FKey *p; |
| 683 | int i; |
| 684 | for(p=pTab->pFKey; p; p=p->pNextFrom){ |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 685 | for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 686 | } |
| 687 | for(p=fkRefering(pTab); p; p=p->pNextTo){ |
| 688 | Index *pIdx = 0; |
| 689 | locateFkeyIndex(0, pTab, p, &pIdx, 0); |
| 690 | if( pIdx ){ |
| 691 | for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); |
| 692 | } |
| 693 | } |
| 694 | } |
| 695 | return mask; |
| 696 | } |
| 697 | |
| 698 | /* |
| 699 | ** This function is called before generating code to update or delete a |
| 700 | ** row contained in table pTab. If the operation is an update, then |
| 701 | ** pChanges is a pointer to the list of columns to modify. If this is a |
| 702 | ** delete, then pChanges is NULL. |
| 703 | ** |
| 704 | ** If any foreign key processing will be required, this function returns |
| 705 | ** true. If there is no foreign key related processing, this function |
| 706 | ** returns false. |
| 707 | */ |
| 708 | int sqlite3FkRequired( |
| 709 | Parse *pParse, /* Parse context */ |
| 710 | Table *pTab, /* Table being modified */ |
| 711 | ExprList *pChanges /* Non-NULL for UPDATE operations */ |
| 712 | ){ |
| 713 | if( pParse->db->flags&SQLITE_ForeignKeys ){ |
dan | 32b09f2 | 2009-09-23 17:29:59 +0000 | [diff] [blame^] | 714 | if( fkRefering(pTab) || pTab->pFKey ) return 1; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 715 | } |
| 716 | return 0; |
| 717 | } |
| 718 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 719 | /* |
| 720 | ** This function is called when an UPDATE or DELETE operation is being |
| 721 | ** compiled on table pTab, which is the parent table of foreign-key pFKey. |
| 722 | ** If the current operation is an UPDATE, then the pChanges parameter is |
| 723 | ** passed a pointer to the list of columns being modified. If it is a |
| 724 | ** DELETE, pChanges is passed a NULL pointer. |
| 725 | ** |
| 726 | ** It returns a pointer to a Trigger structure containing a trigger |
| 727 | ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. |
| 728 | ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is |
| 729 | ** returned (these actions require no special handling by the triggers |
| 730 | ** sub-system, code for them is created by fkScanChildren()). |
| 731 | ** |
| 732 | ** For example, if pFKey is the foreign key and pTab is table "p" in |
| 733 | ** the following schema: |
| 734 | ** |
| 735 | ** CREATE TABLE p(pk PRIMARY KEY); |
| 736 | ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); |
| 737 | ** |
| 738 | ** then the returned trigger structure is equivalent to: |
| 739 | ** |
| 740 | ** CREATE TRIGGER ... DELETE ON p BEGIN |
| 741 | ** DELETE FROM c WHERE ck = old.pk; |
| 742 | ** END; |
| 743 | ** |
| 744 | ** The returned pointer is cached as part of the foreign key object. It |
| 745 | ** is eventually freed along with the rest of the foreign key object by |
| 746 | ** sqlite3FkDelete(). |
| 747 | */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 748 | static Trigger *fkActionTrigger( |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 749 | Parse *pParse, /* Parse context */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 750 | Table *pTab, /* Table being updated or deleted from */ |
| 751 | FKey *pFKey, /* Foreign key to get action for */ |
| 752 | ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ |
| 753 | ){ |
| 754 | sqlite3 *db = pParse->db; /* Database handle */ |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 755 | int action; /* One of OE_None, OE_Cascade etc. */ |
| 756 | Trigger *pTrigger; /* Trigger definition to return */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 757 | int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 758 | |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 759 | action = pFKey->aAction[iAction]; |
| 760 | pTrigger = pFKey->apTrigger[iAction]; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 761 | |
| 762 | assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict ); |
| 763 | assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict ); |
| 764 | |
| 765 | if( action>OE_Restrict && !pTrigger ){ |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 766 | u8 enableLookaside; /* Copy of db->lookaside.bEnabled */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 767 | char const *zFrom; /* Name of child table */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 768 | int nFrom; /* Length in bytes of zFrom */ |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 769 | Index *pIdx = 0; /* Parent key index for this FK */ |
| 770 | int *aiCol = 0; /* child table cols -> parent key cols */ |
| 771 | TriggerStep *pStep; /* First (only) step of trigger program */ |
| 772 | Expr *pWhere = 0; /* WHERE clause of trigger step */ |
| 773 | ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ |
| 774 | int i; /* Iterator variable */ |
drh | 788536b | 2009-09-23 03:01:58 +0000 | [diff] [blame] | 775 | Expr *pWhen = 0; /* WHEN clause for the trigger */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 776 | |
| 777 | if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; |
| 778 | assert( aiCol || pFKey->nCol==1 ); |
| 779 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 780 | for(i=0; i<pFKey->nCol; i++){ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 781 | Token tOld = { "old", 3 }; /* Literal "old" token */ |
| 782 | Token tNew = { "new", 3 }; /* Literal "new" token */ |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 783 | Token tFromCol; /* Name of column in child table */ |
| 784 | Token tToCol; /* Name of column in parent table */ |
| 785 | int iFromCol; /* Idx of column in child table */ |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 786 | Expr *pEq; /* tFromCol = OLD.tToCol */ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 787 | |
| 788 | iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; |
dan | a8f0bf6 | 2009-09-23 12:06:52 +0000 | [diff] [blame] | 789 | assert( iFromCol>=0 ); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 790 | tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid"; |
dan | a8f0bf6 | 2009-09-23 12:06:52 +0000 | [diff] [blame] | 791 | tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 792 | |
| 793 | tToCol.n = sqlite3Strlen30(tToCol.z); |
| 794 | tFromCol.n = sqlite3Strlen30(tFromCol.z); |
| 795 | |
| 796 | /* Create the expression "zFromCol = OLD.zToCol" */ |
| 797 | pEq = sqlite3PExpr(pParse, TK_EQ, |
| 798 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol), |
| 799 | sqlite3PExpr(pParse, TK_DOT, |
| 800 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), |
| 801 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) |
| 802 | , 0) |
| 803 | , 0); |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 804 | pWhere = sqlite3ExprAnd(db, pWhere, pEq); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 805 | |
drh | 788536b | 2009-09-23 03:01:58 +0000 | [diff] [blame] | 806 | /* For ON UPDATE, construct the next term of the WHEN clause. |
| 807 | ** The final WHEN clause will be like this: |
| 808 | ** |
| 809 | ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) |
| 810 | */ |
| 811 | if( pChanges ){ |
| 812 | pEq = sqlite3PExpr(pParse, TK_IS, |
| 813 | sqlite3PExpr(pParse, TK_DOT, |
| 814 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), |
| 815 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol), |
| 816 | 0), |
| 817 | sqlite3PExpr(pParse, TK_DOT, |
| 818 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), |
| 819 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol), |
| 820 | 0), |
| 821 | 0); |
| 822 | pWhen = sqlite3ExprAnd(db, pWhen, pEq); |
| 823 | } |
| 824 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 825 | if( action!=OE_Cascade || pChanges ){ |
| 826 | Expr *pNew; |
| 827 | if( action==OE_Cascade ){ |
| 828 | pNew = sqlite3PExpr(pParse, TK_DOT, |
| 829 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), |
| 830 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) |
| 831 | , 0); |
| 832 | }else if( action==OE_SetDflt ){ |
dan | 934ce30 | 2009-09-22 16:08:58 +0000 | [diff] [blame] | 833 | Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 834 | if( pDflt ){ |
| 835 | pNew = sqlite3ExprDup(db, pDflt, 0); |
| 836 | }else{ |
| 837 | pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); |
| 838 | } |
| 839 | }else{ |
| 840 | pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); |
| 841 | } |
| 842 | pList = sqlite3ExprListAppend(pParse, pList, pNew); |
| 843 | sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); |
| 844 | } |
| 845 | } |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 846 | sqlite3DbFree(db, aiCol); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 847 | |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 848 | /* If pTab->dbMem==0, then the table may be part of a shared-schema. |
| 849 | ** Disable the lookaside buffer before allocating space for the |
| 850 | ** trigger definition in this case. */ |
| 851 | enableLookaside = db->lookaside.bEnabled; |
| 852 | if( pTab->dbMem==0 ){ |
| 853 | db->lookaside.bEnabled = 0; |
| 854 | } |
| 855 | |
| 856 | zFrom = pFKey->pFrom->zName; |
| 857 | nFrom = sqlite3Strlen30(zFrom); |
| 858 | pTrigger = (Trigger *)sqlite3DbMallocZero(db, |
| 859 | sizeof(Trigger) + /* struct Trigger */ |
| 860 | sizeof(TriggerStep) + /* Single step in trigger program */ |
| 861 | nFrom + 1 /* Space for pStep->target.z */ |
| 862 | ); |
| 863 | if( pTrigger ){ |
| 864 | pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; |
| 865 | pStep->target.z = (char *)&pStep[1]; |
| 866 | pStep->target.n = nFrom; |
| 867 | memcpy((char *)pStep->target.z, zFrom, nFrom); |
| 868 | |
| 869 | pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); |
| 870 | pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); |
drh | 788536b | 2009-09-23 03:01:58 +0000 | [diff] [blame] | 871 | if( pWhen ){ |
| 872 | pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0); |
| 873 | pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); |
| 874 | } |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 875 | } |
| 876 | |
| 877 | /* Re-enable the lookaside buffer, if it was disabled earlier. */ |
| 878 | db->lookaside.bEnabled = enableLookaside; |
| 879 | |
drh | 788536b | 2009-09-23 03:01:58 +0000 | [diff] [blame] | 880 | sqlite3ExprDelete(db, pWhere); |
| 881 | sqlite3ExprDelete(db, pWhen); |
| 882 | sqlite3ExprListDelete(db, pList); |
dan | 29c7f9c | 2009-09-22 15:53:47 +0000 | [diff] [blame] | 883 | if( db->mallocFailed==1 ){ |
| 884 | fkTriggerDelete(db, pTrigger); |
| 885 | return 0; |
| 886 | } |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 887 | |
| 888 | pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE; |
| 889 | pStep->pTrig = pTrigger; |
| 890 | pTrigger->pSchema = pTab->pSchema; |
| 891 | pTrigger->pTabSchema = pTab->pSchema; |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 892 | pFKey->apTrigger[iAction] = pTrigger; |
| 893 | pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 894 | } |
| 895 | |
| 896 | return pTrigger; |
| 897 | } |
| 898 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 899 | /* |
| 900 | ** This function is called when deleting or updating a row to implement |
| 901 | ** any required CASCADE, SET NULL or SET DEFAULT actions. |
| 902 | */ |
| 903 | void sqlite3FkActions( |
| 904 | Parse *pParse, /* Parse context */ |
| 905 | Table *pTab, /* Table being updated or deleted from */ |
| 906 | ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ |
| 907 | int regOld /* Address of array containing old row */ |
| 908 | ){ |
| 909 | /* If foreign-key support is enabled, iterate through all FKs that |
| 910 | ** refer to table pTab. If there is an action associated with the FK |
| 911 | ** for this operation (either update or delete), invoke the associated |
| 912 | ** trigger sub-program. */ |
| 913 | if( pParse->db->flags&SQLITE_ForeignKeys ){ |
| 914 | FKey *pFKey; /* Iterator variable */ |
| 915 | for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){ |
| 916 | Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges); |
| 917 | if( pAction ){ |
| 918 | sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0); |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | } |
| 923 | |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 924 | #endif /* ifndef SQLITE_OMIT_TRIGGER */ |
| 925 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 926 | /* |
| 927 | ** Free all memory associated with foreign key definitions attached to |
| 928 | ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash |
| 929 | ** hash table. |
| 930 | */ |
| 931 | void sqlite3FkDelete(Table *pTab){ |
| 932 | FKey *pFKey; /* Iterator variable */ |
| 933 | FKey *pNext; /* Copy of pFKey->pNextFrom */ |
| 934 | |
| 935 | for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ |
| 936 | |
| 937 | /* Remove the FK from the fkeyHash hash table. */ |
| 938 | if( pFKey->pPrevTo ){ |
| 939 | pFKey->pPrevTo->pNextTo = pFKey->pNextTo; |
| 940 | }else{ |
| 941 | void *data = (void *)pFKey->pNextTo; |
| 942 | const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo); |
| 943 | sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data); |
| 944 | } |
| 945 | if( pFKey->pNextTo ){ |
| 946 | pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; |
| 947 | } |
| 948 | |
| 949 | /* Delete any triggers created to implement actions for this FK. */ |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 950 | #ifndef SQLITE_OMIT_TRIGGER |
dan | 8099ce6 | 2009-09-23 08:43:35 +0000 | [diff] [blame] | 951 | fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]); |
| 952 | fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]); |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 953 | #endif |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 954 | |
| 955 | /* Delete the memory allocated for the FK structure. */ |
| 956 | pNext = pFKey->pNextFrom; |
| 957 | sqlite3DbFree(pTab->dbMem, pFKey); |
| 958 | } |
| 959 | } |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 960 | #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ |