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 | ** |
| 51 | ** I.1) For each FK for which the table is the referencing table, search |
| 52 | ** the referenced table for a match. If none is found, throw an |
| 53 | ** exception for an immediate FK, or increment the counter for a |
| 54 | ** deferred FK. |
| 55 | ** |
| 56 | ** I.2) For each deferred FK for which the table is the referenced table, |
| 57 | ** search the referencing table for rows that correspond to the new |
| 58 | ** row in the referenced table. Decrement the counter for each row |
| 59 | ** found (as the constraint is now satisfied). |
| 60 | ** |
| 61 | ** DELETE operations: |
| 62 | ** |
| 63 | ** D.1) For each deferred FK for which the table is the referencing table, |
| 64 | ** search the referenced table for a row that corresponds to the |
| 65 | ** deleted row in the referencing table. If such a row is not found, |
| 66 | ** decrement the counter. |
| 67 | ** |
| 68 | ** D.2) For each FK for which the table is the referenced table, search |
| 69 | ** the referencing table for rows that correspond to the deleted row |
| 70 | ** in the referenced table. For each found, throw an exception for an |
| 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? |
| 90 | */ |
| 91 | |
| 92 | /* |
| 93 | ** Query API Notes |
| 94 | ** --------------- |
| 95 | ** |
| 96 | ** Before coding an UPDATE or DELETE row operation, the code-generator |
| 97 | ** for those two operations needs to know whether or not the operation |
| 98 | ** requires any FK processing and, if so, which columns of the original |
| 99 | ** row are required by the FK processing VDBE code (i.e. if FKs were |
| 100 | ** implemented using triggers, which of the old.* columns would be |
| 101 | ** accessed). No information is required by the code-generator before |
| 102 | ** coding an INSERT operation. |
| 103 | ** |
| 104 | */ |
| 105 | |
| 106 | /* |
| 107 | ** VDBE Calling Convention |
| 108 | ** ----------------------- |
| 109 | ** |
| 110 | ** Example: |
| 111 | ** |
| 112 | ** For the following INSERT statement: |
| 113 | ** |
| 114 | ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); |
| 115 | ** INSERT INTO t1 VALUES(1, 2, 3.1); |
| 116 | ** |
| 117 | ** Register (x): 2 (type integer) |
| 118 | ** Register (x+1): 1 (type integer) |
| 119 | ** Register (x+2): NULL (type NULL) |
| 120 | ** Register (x+3): 3.1 (type real) |
| 121 | */ |
| 122 | |
| 123 | /* |
| 124 | ** ON UPDATE and ON DELETE clauses |
| 125 | ** ------------------------------- |
| 126 | */ |
| 127 | |
| 128 | /* |
| 129 | ** Externally accessible module functions |
| 130 | ** -------------------------------------- |
| 131 | ** |
| 132 | ** sqlite3FkRequired() |
| 133 | ** sqlite3FkOldmask() |
| 134 | ** |
| 135 | ** sqlite3FkCheck() |
| 136 | ** sqlite3FkActions() |
| 137 | ** |
| 138 | ** sqlite3FkDelete() |
| 139 | ** |
| 140 | */ |
| 141 | |
| 142 | /* |
| 143 | ** A foreign key constraint requires that the key columns in the referenced |
| 144 | ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. |
| 145 | ** Given that pTo is the referenced table for foreign key constraint |
| 146 | ** pFKey, check that the columns in pTo are indeed subject to a such a |
| 147 | ** constraint. If they are not, return non-zero and leave an error in pParse. |
| 148 | ** |
| 149 | ** If an error does not occur, return zero. |
| 150 | */ |
| 151 | static int locateFkeyIndex( |
| 152 | Parse *pParse, /* Parse context to store any error in */ |
| 153 | Table *pTo, /* Referenced table */ |
| 154 | FKey *pFKey, /* Foreign key to find index for */ |
| 155 | Index **ppIdx, /* OUT: Unique index on referenced table */ |
| 156 | int **paiCol /* OUT: Map of index columns in pFKey */ |
| 157 | ){ |
| 158 | Index *pIdx = 0; |
| 159 | int *aiCol = 0; |
| 160 | int nCol = pFKey->nCol; |
| 161 | char *zFirst = pFKey->aCol[0].zCol; |
| 162 | |
| 163 | /* The caller is responsible for zeroing output parameters. */ |
| 164 | assert( ppIdx && *ppIdx==0 ); |
| 165 | assert( !paiCol || *paiCol==0 ); |
| 166 | |
| 167 | /* If this is a non-composite (single column) foreign key, check if it |
| 168 | ** maps to the INTEGER PRIMARY KEY of table pTo. If so, leave *ppIdx |
| 169 | ** and *paiCol set to zero and return early. |
| 170 | ** |
| 171 | ** Otherwise, for a composite foreign key (more than one column), allocate |
| 172 | ** space for the aiCol array (returned via output parameter *paiCol). |
| 173 | ** Non-composite foreign keys do not require the aiCol array. |
| 174 | */ |
| 175 | if( nCol==1 ){ |
| 176 | /* The FK maps to the IPK if any of the following are true: |
| 177 | ** |
| 178 | ** 1) The FK is explicitly mapped to "rowid", "oid" or "_rowid_", or |
| 179 | ** 2) There is an explicit INTEGER PRIMARY KEY column and the FK is |
| 180 | ** implicitly mapped to the primary key of table pTo, or |
| 181 | ** 3) The FK is explicitly mapped to a column declared as INTEGER |
| 182 | ** PRIMARY KEY. |
| 183 | */ |
| 184 | if( zFirst && sqlite3IsRowid(zFirst) ) return 0; |
| 185 | if( pTo->iPKey>=0 ){ |
| 186 | if( !zFirst ) return 0; |
| 187 | if( !sqlite3StrICmp(pTo->aCol[pTo->iPKey].zName, zFirst) ) return 0; |
| 188 | } |
| 189 | }else if( paiCol ){ |
| 190 | assert( nCol>1 ); |
| 191 | aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int)); |
| 192 | if( !aiCol ) return 1; |
| 193 | *paiCol = aiCol; |
| 194 | } |
| 195 | |
| 196 | for(pIdx=pTo->pIndex; pIdx; pIdx=pIdx->pNext){ |
| 197 | if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ |
| 198 | /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number |
| 199 | ** of columns. If each indexed column corresponds to a foreign key |
| 200 | ** column of pFKey, then this index is a winner. */ |
| 201 | |
| 202 | if( zFirst==0 ){ |
| 203 | /* If zFirst is NULL, then this foreign key is implicitly mapped to |
| 204 | ** the PRIMARY KEY of table pTo. The PRIMARY KEY index may be |
| 205 | ** identified by the test (Index.autoIndex==2). */ |
| 206 | if( pIdx->autoIndex==2 ){ |
| 207 | if( aiCol ) memcpy(aiCol, pIdx->aiColumn, sizeof(int)*nCol); |
| 208 | break; |
| 209 | } |
| 210 | }else{ |
| 211 | /* If zFirst is non-NULL, then this foreign key was declared to |
| 212 | ** map to an explicit list of columns in table pTo. Check if this |
| 213 | ** index matches those columns. */ |
| 214 | int i, j; |
| 215 | for(i=0; i<nCol; i++){ |
| 216 | char *zIdxCol = pTo->aCol[pIdx->aiColumn[i]].zName; |
| 217 | for(j=0; j<nCol; j++){ |
| 218 | if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){ |
| 219 | if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; |
| 220 | break; |
| 221 | } |
| 222 | } |
| 223 | if( j==nCol ) break; |
| 224 | } |
| 225 | if( i==nCol ) break; /* pIdx is usable */ |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | if( pParse && !pIdx ){ |
| 231 | sqlite3ErrorMsg(pParse, "foreign key mismatch"); |
| 232 | sqlite3DbFree(pParse->db, aiCol); |
| 233 | return 1; |
| 234 | } |
| 235 | |
| 236 | *ppIdx = pIdx; |
| 237 | return 0; |
| 238 | } |
| 239 | |
| 240 | static void fkCheckReference( |
| 241 | Parse *pParse, /* Parse context */ |
| 242 | int iDb, /* Index of database housing pTab */ |
| 243 | Table *pTab, /* Table referenced by FK pFKey */ |
| 244 | Index *pIdx, /* Index ensuring uniqueness of FK in pTab */ |
| 245 | FKey *pFKey, /* Foreign key to check */ |
| 246 | int *aiCol, /* Map from FK column to referencing table column */ |
| 247 | int regData, /* Address of array containing referencing row */ |
| 248 | int nIncr /* If deferred FK, increment counter by this */ |
| 249 | ){ |
| 250 | int i; |
| 251 | Vdbe *v = sqlite3GetVdbe(pParse); |
| 252 | int iCur = pParse->nTab - 1; |
| 253 | int iOk = sqlite3VdbeMakeLabel(v); |
| 254 | |
| 255 | assert( pFKey->isDeferred || nIncr==1 ); |
| 256 | |
| 257 | /* Check if any of the key columns in the referencing table are |
| 258 | ** NULL. If any are, then the constraint is satisfied. No need |
| 259 | ** to search for a matching row in the referenced table. */ |
| 260 | for(i=0; i<pFKey->nCol; i++){ |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 261 | int iReg = aiCol[i] + regData + 1; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 262 | sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); |
| 263 | } |
| 264 | |
| 265 | if( pIdx==0 ){ |
| 266 | /* If pIdx is NULL, then the foreign key constraint references the |
| 267 | ** INTEGER PRIMARY KEY column in the referenced table (table pTab). */ |
| 268 | int iReg = pFKey->aCol[0].iFrom + regData + 1; |
| 269 | sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); |
| 270 | sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iReg); |
| 271 | sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); |
| 272 | sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); |
| 273 | }else{ |
| 274 | int regRec = sqlite3GetTempReg(pParse); |
| 275 | KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); |
| 276 | |
| 277 | sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); |
| 278 | sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); |
| 279 | |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 280 | if( pFKey->nCol>1 ){ |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 281 | int nCol = pFKey->nCol; |
| 282 | int regTemp = sqlite3GetTempRange(pParse, nCol); |
| 283 | for(i=0; i<nCol; i++){ |
| 284 | sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i); |
| 285 | } |
| 286 | sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec); |
| 287 | sqlite3ReleaseTempRange(pParse, regTemp, nCol); |
| 288 | }else{ |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 289 | int iReg = aiCol[0] + regData + 1; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 290 | sqlite3VdbeAddOp3(v, OP_MakeRecord, iReg, 1, regRec); |
| 291 | sqlite3IndexAffinityStr(v, pIdx); |
| 292 | } |
| 293 | |
| 294 | sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec); |
| 295 | sqlite3ReleaseTempReg(pParse, regRec); |
| 296 | } |
| 297 | |
| 298 | if( pFKey->isDeferred ){ |
| 299 | assert( nIncr==1 || nIncr==-1 ); |
| 300 | sqlite3VdbeAddOp1(v, OP_DeferredCons, nIncr); |
| 301 | }else{ |
| 302 | sqlite3HaltConstraint( |
| 303 | pParse, OE_Abort, "foreign key constraint failed", P4_STATIC |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | sqlite3VdbeResolveLabel(v, iOk); |
| 308 | } |
| 309 | |
| 310 | static void fkScanReferences( |
| 311 | Parse *pParse, /* Parse context */ |
| 312 | SrcList *pSrc, /* SrcList containing the table to scan */ |
| 313 | Index *pIdx, /* Foreign key index */ |
| 314 | FKey *pFKey, /* Foreign key relationship */ |
| 315 | int *aiCol, /* Map from FK to referenced table columns */ |
| 316 | int regData, /* Referenced table data starts here */ |
| 317 | int nIncr /* Amount to increment deferred counter by */ |
| 318 | ){ |
| 319 | sqlite3 *db = pParse->db; /* Database handle */ |
| 320 | int i; /* Iterator variable */ |
| 321 | Expr *pWhere = 0; /* WHERE clause to scan with */ |
| 322 | NameContext sNameContext; /* Context used to resolve WHERE clause */ |
| 323 | WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ |
| 324 | |
| 325 | for(i=0; i<pFKey->nCol; i++){ |
| 326 | Expr *pLeft; /* Value from deleted row */ |
| 327 | Expr *pRight; /* Column ref to referencing table */ |
| 328 | Expr *pEq; /* Expression (pLeft = pRight) */ |
| 329 | int iCol; /* Index of column in referencing table */ |
| 330 | const char *zCol; /* Name of column in referencing table */ |
| 331 | |
| 332 | pLeft = sqlite3Expr(db, TK_REGISTER, 0); |
| 333 | if( pLeft ){ |
| 334 | pLeft->iTable = (pIdx ? (regData+pIdx->aiColumn[i]+1) : regData); |
| 335 | } |
| 336 | iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; |
| 337 | if( iCol<0 ){ |
| 338 | zCol = "rowid"; |
| 339 | }else{ |
| 340 | zCol = pFKey->pFrom->aCol[iCol].zName; |
| 341 | } |
| 342 | pRight = sqlite3Expr(db, TK_ID, zCol); |
| 343 | pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); |
| 344 | pWhere = sqlite3ExprAnd(db, pWhere, pEq); |
| 345 | } |
| 346 | |
| 347 | /* Resolve the references in the WHERE clause. */ |
| 348 | memset(&sNameContext, 0, sizeof(NameContext)); |
| 349 | sNameContext.pSrcList = pSrc; |
| 350 | sNameContext.pParse = pParse; |
| 351 | sqlite3ResolveExprNames(&sNameContext, pWhere); |
| 352 | |
| 353 | /* Create VDBE to loop through the entries in pSrc that match the WHERE |
| 354 | ** clause. If the constraint is not deferred, throw an exception for |
| 355 | ** each row found. Otherwise, for deferred constraints, increment the |
| 356 | ** deferred constraint counter by nIncr for each row selected. */ |
| 357 | pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0); |
| 358 | if( pFKey->isDeferred && nIncr ){ |
| 359 | assert( nIncr==1 || nIncr==-1 ); |
| 360 | sqlite3VdbeAddOp1(pParse->pVdbe, OP_DeferredCons, nIncr); |
| 361 | }else{ |
| 362 | assert( nIncr==1 || nIncr==0 ); |
| 363 | sqlite3HaltConstraint( |
| 364 | pParse, OE_Abort, "foreign key constraint failed", P4_STATIC |
| 365 | ); |
| 366 | } |
| 367 | sqlite3WhereEnd(pWInfo); |
| 368 | |
| 369 | /* Clean up the WHERE clause constructed above. */ |
| 370 | sqlite3ExprDelete(db, pWhere); |
| 371 | } |
| 372 | |
| 373 | /* |
| 374 | ** This function returns a pointer to the head of a linked list of FK |
| 375 | ** constraints that refer to the table passed as an argument. For example, |
| 376 | ** given the following schema: |
| 377 | ** |
| 378 | ** CREATE TABLE t1(a PRIMARY KEY); |
| 379 | ** CREATE TABLE t2(b REFERENCES t1(a); |
| 380 | ** |
| 381 | ** Calling this function with table "t1" as an argument returns a pointer |
| 382 | ** to the FKey structure representing the foreign key constraint on table |
| 383 | ** "t2". Calling this function with "t2" as the argument would return a |
| 384 | ** NULL pointer (as there are no FK constraints that refer to t2). |
| 385 | */ |
| 386 | static FKey *fkRefering(Table *pTab){ |
| 387 | int nName = sqlite3Strlen30(pTab->zName); |
| 388 | return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName); |
| 389 | } |
| 390 | |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 391 | static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ |
| 392 | if( p ){ |
| 393 | TriggerStep *pStep = p->step_list; |
| 394 | sqlite3ExprDelete(dbMem, pStep->pWhere); |
| 395 | sqlite3ExprListDelete(dbMem, pStep->pExprList); |
| 396 | sqlite3DbFree(dbMem, p); |
| 397 | } |
| 398 | } |
| 399 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 400 | void sqlite3FkCheck( |
| 401 | Parse *pParse, /* Parse context */ |
| 402 | Table *pTab, /* Row is being deleted from this table */ |
| 403 | ExprList *pChanges, /* Changed columns if this is an UPDATE */ |
| 404 | int regOld, /* Previous row data is stored here */ |
| 405 | int regNew /* New row data is stored here */ |
| 406 | ){ |
| 407 | sqlite3 *db = pParse->db; /* Database handle */ |
| 408 | Vdbe *v; /* VM to write code to */ |
| 409 | FKey *pFKey; /* Used to iterate through FKs */ |
| 410 | int iDb; /* Index of database containing pTab */ |
| 411 | const char *zDb; /* Name of database containing pTab */ |
| 412 | |
| 413 | assert( ( pChanges && regOld && regNew) /* UPDATE operation */ |
| 414 | || (!pChanges && !regOld && regNew) /* INSERT operation */ |
| 415 | || (!pChanges && regOld && !regNew) /* DELETE operation */ |
| 416 | ); |
| 417 | |
| 418 | /* If foreign-keys are disabled, this function is a no-op. */ |
| 419 | if( (db->flags&SQLITE_ForeignKeys)==0 ) return; |
| 420 | |
| 421 | v = sqlite3GetVdbe(pParse); |
| 422 | iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |
| 423 | zDb = db->aDb[iDb].zName; |
| 424 | |
| 425 | /* Loop through all the foreign key constraints attached to the table. */ |
| 426 | for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ |
| 427 | Table *pTo; /* Table referenced by this FK */ |
| 428 | Index *pIdx = 0; /* Index on key columns in pTo */ |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 429 | int *aiFree = 0; |
| 430 | int *aiCol; |
| 431 | int iCol; |
| 432 | int i; |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 433 | |
| 434 | if( pFKey->isDeferred==0 && regNew==0 ) continue; |
| 435 | |
| 436 | /* Find the table this foreign key references. Also find a unique |
| 437 | ** index on the referenced table that corresponds to the key columns. |
| 438 | ** If either of these things cannot be located, set an error in pParse |
| 439 | ** and return early. */ |
| 440 | pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 441 | if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return; |
| 442 | assert( pFKey->nCol==1 || (aiFree && pIdx) ); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 443 | |
| 444 | /* If the key does not overlap with the pChanges list, skip this FK. */ |
| 445 | if( pChanges ){ |
| 446 | /* TODO */ |
| 447 | } |
| 448 | |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 449 | if( aiFree ){ |
| 450 | aiCol = aiFree; |
| 451 | }else{ |
| 452 | iCol = pFKey->aCol[0].iFrom; |
| 453 | aiCol = &iCol; |
| 454 | } |
| 455 | for(i=0; i<pFKey->nCol; i++){ |
| 456 | if( aiCol[i]==pTab->iPKey ){ |
| 457 | aiCol[i] = -1; |
| 458 | } |
| 459 | } |
| 460 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 461 | /* Take a shared-cache advisory read-lock on the referenced table. |
| 462 | ** Allocate a cursor to use to search the unique index on the FK |
| 463 | ** columns in the referenced table. */ |
| 464 | sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); |
| 465 | pParse->nTab++; |
| 466 | |
| 467 | if( regOld!=0 && pFKey->isDeferred ){ |
| 468 | fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1); |
| 469 | } |
| 470 | if( regNew!=0 ){ |
| 471 | fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1); |
| 472 | } |
| 473 | |
dan | 3606264 | 2009-09-21 18:56:23 +0000 | [diff] [blame] | 474 | sqlite3DbFree(db, aiFree); |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 475 | } |
| 476 | |
| 477 | /* Loop through all the foreign key constraints that refer to this table */ |
| 478 | for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){ |
| 479 | int iGoto; /* Address of OP_Goto instruction */ |
| 480 | Index *pIdx = 0; /* Foreign key index for pFKey */ |
| 481 | SrcList *pSrc; |
| 482 | int *aiCol = 0; |
| 483 | |
| 484 | /* For immediate constraints, skip this scan if: |
| 485 | ** |
| 486 | ** 1) this is an INSERT operation, or |
| 487 | ** 2) an UPDATE operation and the FK action is a trigger-action, or |
| 488 | ** 3) a DELETE operation and the FK action is a trigger-action. |
| 489 | ** |
| 490 | ** A "trigger-action" is one of CASCADE, SET DEFAULT or SET NULL. |
| 491 | */ |
| 492 | if( pFKey->isDeferred==0 ){ |
| 493 | if( regOld==0 ) continue; /* 1 */ |
| 494 | if( regNew!=0 && pFKey->updateConf>OE_Restrict ) continue; /* 2 */ |
| 495 | if( regNew==0 && pFKey->deleteConf>OE_Restrict ) continue; /* 3 */ |
| 496 | } |
| 497 | |
| 498 | if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return; |
| 499 | assert( aiCol || pFKey->nCol==1 ); |
| 500 | |
| 501 | /* Check if this update statement has modified any of the key columns |
| 502 | ** for this foreign key constraint. If it has not, there is no need |
| 503 | ** to search the referencing table for rows in violation. This is |
| 504 | ** just an optimization. Things would work fine without this check. */ |
| 505 | if( pChanges ){ |
| 506 | /* TODO */ |
| 507 | } |
| 508 | |
| 509 | /* Create a SrcList structure containing a single table (the table |
| 510 | ** the foreign key that refers to this table is attached to). This |
| 511 | ** is required for the sqlite3WhereXXX() interface. */ |
| 512 | pSrc = sqlite3SrcListAppend(db, 0, 0, 0); |
| 513 | if( !pSrc ) return; |
| 514 | pSrc->a->pTab = pFKey->pFrom; |
| 515 | pSrc->a->pTab->nRef++; |
| 516 | pSrc->a->iCursor = pParse->nTab++; |
| 517 | |
| 518 | /* If this is an UPDATE, and none of the columns associated with this |
| 519 | ** FK have been modified, do not scan the referencing table. Unlike |
| 520 | ** the compile-time test implemented above, this is not just an |
| 521 | ** optimization. It is required so that immediate foreign keys do not |
| 522 | ** throw exceptions when the user executes a statement like: |
| 523 | ** |
| 524 | ** UPDATE refd_table SET refd_column = refd_column |
| 525 | */ |
| 526 | if( pChanges ){ |
| 527 | int i; |
| 528 | int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; |
| 529 | for(i=0; i<pFKey->nCol; i++){ |
| 530 | int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1; |
| 531 | sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff); |
| 532 | } |
| 533 | iGoto = sqlite3VdbeAddOp0(v, OP_Goto); |
| 534 | } |
| 535 | |
| 536 | if( regNew!=0 && pFKey->isDeferred ){ |
| 537 | fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1); |
| 538 | } |
| 539 | if( regOld!=0 ){ |
| 540 | /* If there is a RESTRICT action configured for the current operation |
| 541 | ** on the referenced table of this FK, then throw an exception |
| 542 | ** immediately if the FK constraint is violated, even if this is a |
| 543 | ** deferred trigger. That's what RESTRICT means. To defer checking |
| 544 | ** the constraint, the FK should specify NO ACTION (represented |
| 545 | ** using OE_None). NO ACTION is the default. */ |
| 546 | fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regOld, |
| 547 | (pChanges!=0 && pFKey->updateConf!=OE_Restrict) |
| 548 | || (pChanges==0 && pFKey->deleteConf!=OE_Restrict) |
| 549 | ); |
| 550 | } |
| 551 | |
| 552 | if( pChanges ){ |
| 553 | sqlite3VdbeJumpHere(v, iGoto); |
| 554 | } |
| 555 | sqlite3SrcListDelete(db, pSrc); |
| 556 | sqlite3DbFree(db, aiCol); |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) |
| 561 | |
| 562 | /* |
| 563 | ** This function is called before generating code to update or delete a |
| 564 | ** row contained in table pTab. If the operation is an update, then |
| 565 | ** pChanges is a pointer to the list of columns to modify. If this is a |
| 566 | ** delete, then pChanges is NULL. |
| 567 | */ |
| 568 | u32 sqlite3FkOldmask( |
| 569 | Parse *pParse, /* Parse context */ |
| 570 | Table *pTab, /* Table being modified */ |
| 571 | ExprList *pChanges /* Non-NULL for UPDATE operations */ |
| 572 | ){ |
| 573 | u32 mask = 0; |
| 574 | if( pParse->db->flags&SQLITE_ForeignKeys ){ |
| 575 | FKey *p; |
| 576 | int i; |
| 577 | for(p=pTab->pFKey; p; p=p->pNextFrom){ |
| 578 | if( pChanges || p->isDeferred ){ |
| 579 | for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); |
| 580 | } |
| 581 | } |
| 582 | for(p=fkRefering(pTab); p; p=p->pNextTo){ |
| 583 | Index *pIdx = 0; |
| 584 | locateFkeyIndex(0, pTab, p, &pIdx, 0); |
| 585 | if( pIdx ){ |
| 586 | for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | return mask; |
| 591 | } |
| 592 | |
| 593 | /* |
| 594 | ** This function is called before generating code to update or delete a |
| 595 | ** row contained in table pTab. If the operation is an update, then |
| 596 | ** pChanges is a pointer to the list of columns to modify. If this is a |
| 597 | ** delete, then pChanges is NULL. |
| 598 | ** |
| 599 | ** If any foreign key processing will be required, this function returns |
| 600 | ** true. If there is no foreign key related processing, this function |
| 601 | ** returns false. |
| 602 | */ |
| 603 | int sqlite3FkRequired( |
| 604 | Parse *pParse, /* Parse context */ |
| 605 | Table *pTab, /* Table being modified */ |
| 606 | ExprList *pChanges /* Non-NULL for UPDATE operations */ |
| 607 | ){ |
| 608 | if( pParse->db->flags&SQLITE_ForeignKeys ){ |
| 609 | FKey *p; |
| 610 | for(p=pTab->pFKey; p; p=p->pNextFrom){ |
| 611 | if( pChanges || p->isDeferred ) return 1; |
| 612 | } |
| 613 | if( fkRefering(pTab) ) return 1; |
| 614 | } |
| 615 | return 0; |
| 616 | } |
| 617 | |
| 618 | static Trigger *fkActionTrigger( |
| 619 | Parse *pParse, |
| 620 | Table *pTab, /* Table being updated or deleted from */ |
| 621 | FKey *pFKey, /* Foreign key to get action for */ |
| 622 | ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ |
| 623 | ){ |
| 624 | sqlite3 *db = pParse->db; /* Database handle */ |
| 625 | int action; |
| 626 | Trigger *pTrigger; |
| 627 | |
| 628 | if( pChanges ){ |
| 629 | action = pFKey->updateConf; |
| 630 | pTrigger = pFKey->pOnUpdate; |
| 631 | }else{ |
| 632 | action = pFKey->deleteConf; |
| 633 | pTrigger = pFKey->pOnDelete; |
| 634 | } |
| 635 | |
| 636 | assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict ); |
| 637 | assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict ); |
| 638 | |
| 639 | if( action>OE_Restrict && !pTrigger ){ |
| 640 | char const *zFrom; /* Name of referencing table */ |
| 641 | int nFrom; /* Length in bytes of zFrom */ |
| 642 | Index *pIdx = 0; |
| 643 | int *aiCol = 0; |
| 644 | TriggerStep *pStep; |
| 645 | sqlite3 *dbMem = pTab->dbMem; |
| 646 | Expr *pWhere = 0; |
| 647 | ExprList *pList = 0; |
| 648 | int i; |
| 649 | |
| 650 | if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; |
| 651 | assert( aiCol || pFKey->nCol==1 ); |
| 652 | |
| 653 | assert( dbMem==0 || dbMem==pParse->db ); |
| 654 | zFrom = pFKey->pFrom->zName; |
| 655 | nFrom = sqlite3Strlen30(zFrom); |
| 656 | pTrigger = (Trigger *)sqlite3DbMallocZero(dbMem, |
| 657 | sizeof(Trigger) + /* struct Trigger */ |
| 658 | sizeof(TriggerStep) + /* Single step in trigger program */ |
| 659 | nFrom + 1 /* Space for pStep->target.z */ |
| 660 | ); |
| 661 | if( !pTrigger ){ |
| 662 | pParse->db->mallocFailed = 1; |
| 663 | return 0; |
| 664 | } |
| 665 | pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; |
| 666 | pStep->target.z = (char *)&pStep[1]; |
| 667 | pStep->target.n = nFrom; |
| 668 | memcpy((char *)pStep->target.z, zFrom, nFrom); |
| 669 | |
| 670 | for(i=0; i<pFKey->nCol; i++){ |
| 671 | Expr *pEq; |
| 672 | int iFromCol; /* Idx of column in referencing table */ |
| 673 | Token tFromCol; /* Name of column in referencing table */ |
| 674 | Token tToCol; /* Name of column in referenced table */ |
| 675 | Token tOld = { "old", 3 }; /* Literal "old" token */ |
| 676 | Token tNew = { "new", 3 }; /* Literal "new" token */ |
| 677 | |
| 678 | iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; |
| 679 | tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid"; |
| 680 | tFromCol.z = iFromCol<0 ? "oid" : pFKey->pFrom->aCol[iFromCol].zName; |
| 681 | |
| 682 | tToCol.n = sqlite3Strlen30(tToCol.z); |
| 683 | tFromCol.n = sqlite3Strlen30(tFromCol.z); |
| 684 | |
| 685 | /* Create the expression "zFromCol = OLD.zToCol" */ |
| 686 | pEq = sqlite3PExpr(pParse, TK_EQ, |
| 687 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol), |
| 688 | sqlite3PExpr(pParse, TK_DOT, |
| 689 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), |
| 690 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) |
| 691 | , 0) |
| 692 | , 0); |
| 693 | pWhere = sqlite3ExprAnd(pParse->db, pWhere, pEq); |
| 694 | |
| 695 | if( action!=OE_Cascade || pChanges ){ |
| 696 | Expr *pNew; |
| 697 | if( action==OE_Cascade ){ |
| 698 | pNew = sqlite3PExpr(pParse, TK_DOT, |
| 699 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), |
| 700 | sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) |
| 701 | , 0); |
| 702 | }else if( action==OE_SetDflt ){ |
| 703 | Expr *pDflt = pIdx ? 0 : pTab->aCol[pIdx->aiColumn[i]].pDflt; |
| 704 | if( pDflt ){ |
| 705 | pNew = sqlite3ExprDup(db, pDflt, 0); |
| 706 | }else{ |
| 707 | pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); |
| 708 | } |
| 709 | }else{ |
| 710 | pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); |
| 711 | } |
| 712 | pList = sqlite3ExprListAppend(pParse, pList, pNew); |
| 713 | sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); |
| 714 | } |
| 715 | } |
| 716 | sqlite3DbFree(pParse->db, aiCol); |
| 717 | |
| 718 | pStep->pWhere = sqlite3ExprDup(dbMem, pWhere, EXPRDUP_REDUCE); |
| 719 | pStep->pExprList = sqlite3ExprListDup(dbMem, pList, EXPRDUP_REDUCE); |
| 720 | sqlite3ExprDelete(pParse->db, pWhere); |
| 721 | sqlite3ExprListDelete(pParse->db, pList); |
| 722 | |
| 723 | pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE; |
| 724 | pStep->pTrig = pTrigger; |
| 725 | pTrigger->pSchema = pTab->pSchema; |
| 726 | pTrigger->pTabSchema = pTab->pSchema; |
| 727 | |
| 728 | if( pChanges ){ |
| 729 | pFKey->pOnUpdate = pTrigger; |
| 730 | pTrigger->op = TK_UPDATE; |
| 731 | pStep->op = TK_UPDATE; |
| 732 | }else{ |
| 733 | pFKey->pOnDelete = pTrigger; |
| 734 | pTrigger->op = TK_DELETE; |
| 735 | pStep->op = (action==OE_Cascade)?TK_DELETE:TK_UPDATE; |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | return pTrigger; |
| 740 | } |
| 741 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 742 | /* |
| 743 | ** This function is called when deleting or updating a row to implement |
| 744 | ** any required CASCADE, SET NULL or SET DEFAULT actions. |
| 745 | */ |
| 746 | void sqlite3FkActions( |
| 747 | Parse *pParse, /* Parse context */ |
| 748 | Table *pTab, /* Table being updated or deleted from */ |
| 749 | ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ |
| 750 | int regOld /* Address of array containing old row */ |
| 751 | ){ |
| 752 | /* If foreign-key support is enabled, iterate through all FKs that |
| 753 | ** refer to table pTab. If there is an action associated with the FK |
| 754 | ** for this operation (either update or delete), invoke the associated |
| 755 | ** trigger sub-program. */ |
| 756 | if( pParse->db->flags&SQLITE_ForeignKeys ){ |
| 757 | FKey *pFKey; /* Iterator variable */ |
| 758 | for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){ |
| 759 | Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges); |
| 760 | if( pAction ){ |
| 761 | sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0); |
| 762 | } |
| 763 | } |
| 764 | } |
| 765 | } |
| 766 | |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 767 | #endif /* ifndef SQLITE_OMIT_TRIGGER */ |
| 768 | |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 769 | /* |
| 770 | ** Free all memory associated with foreign key definitions attached to |
| 771 | ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash |
| 772 | ** hash table. |
| 773 | */ |
| 774 | void sqlite3FkDelete(Table *pTab){ |
| 775 | FKey *pFKey; /* Iterator variable */ |
| 776 | FKey *pNext; /* Copy of pFKey->pNextFrom */ |
| 777 | |
| 778 | for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ |
| 779 | |
| 780 | /* Remove the FK from the fkeyHash hash table. */ |
| 781 | if( pFKey->pPrevTo ){ |
| 782 | pFKey->pPrevTo->pNextTo = pFKey->pNextTo; |
| 783 | }else{ |
| 784 | void *data = (void *)pFKey->pNextTo; |
| 785 | const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo); |
| 786 | sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data); |
| 787 | } |
| 788 | if( pFKey->pNextTo ){ |
| 789 | pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; |
| 790 | } |
| 791 | |
| 792 | /* Delete any triggers created to implement actions for this FK. */ |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 793 | #ifndef SQLITE_OMIT_TRIGGER |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 794 | fkTriggerDelete(pTab->dbMem, pFKey->pOnDelete); |
| 795 | fkTriggerDelete(pTab->dbMem, pFKey->pOnUpdate); |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 796 | #endif |
dan | 1da40a3 | 2009-09-19 17:00:31 +0000 | [diff] [blame] | 797 | |
| 798 | /* Delete the memory allocated for the FK structure. */ |
| 799 | pNext = pFKey->pNextFrom; |
| 800 | sqlite3DbFree(pTab->dbMem, pFKey); |
| 801 | } |
| 802 | } |
dan | 75cbd98 | 2009-09-21 16:06:03 +0000 | [diff] [blame] | 803 | #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ |