Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(96)

Side by Side Diff: third_party/sqlite/sqlite-src-3080704/src/fkey.c

Issue 883353008: [sql] Import reference version of SQLite 3.8.7.4. (Closed) Base URL: http://chromium.googlesource.com/chromium/src.git@master
Patch Set: Hold back encoding change which is messing up patch. Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 ** 2 **
3 ** The author disclaims copyright to this source code. In place of 3 ** The author disclaims copyright to this source code. In place of
4 ** a legal notice, here is a blessing: 4 ** a legal notice, here is a blessing:
5 ** 5 **
6 ** May you do good and not evil. 6 ** May you do good and not evil.
7 ** May you find forgiveness for yourself and forgive others. 7 ** May you find forgiveness for yourself and forgive others.
8 ** May you share freely, never taking more than you give. 8 ** May you share freely, never taking more than you give.
9 ** 9 **
10 ************************************************************************* 10 *************************************************************************
11 ** This file contains code used by the compiler to add foreign key 11 ** This file contains code used by the compiler to add foreign key
12 ** support to compiled SQL statements. 12 ** support to compiled SQL statements.
13 */ 13 */
14 #include "sqliteInt.h" 14 #include "sqliteInt.h"
15 15
16 #ifndef SQLITE_OMIT_FOREIGN_KEY 16 #ifndef SQLITE_OMIT_FOREIGN_KEY
17 #ifndef SQLITE_OMIT_TRIGGER 17 #ifndef SQLITE_OMIT_TRIGGER
18 18
19 /* 19 /*
20 ** Deferred and Immediate FKs 20 ** Deferred and Immediate FKs
21 ** -------------------------- 21 ** --------------------------
22 ** 22 **
23 ** Foreign keys in SQLite come in two flavours: deferred and immediate. 23 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
24 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT 24 ** If an immediate foreign key constraint is violated,
25 ** is returned and the current statement transaction rolled back. If a 25 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
26 ** statement transaction rolled back. If a
26 ** deferred foreign key constraint is violated, no action is taken 27 ** deferred foreign key constraint is violated, no action is taken
27 ** immediately. However if the application attempts to commit the 28 ** immediately. However if the application attempts to commit the
28 ** transaction before fixing the constraint violation, the attempt fails. 29 ** transaction before fixing the constraint violation, the attempt fails.
29 ** 30 **
30 ** Deferred constraints are implemented using a simple counter associated 31 ** Deferred constraints are implemented using a simple counter associated
31 ** with the database handle. The counter is set to zero each time a 32 ** 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 ** database transaction is opened. Each time a statement is executed
33 ** that causes a foreign key violation, the counter is incremented. Each 34 ** that causes a foreign key violation, the counter is incremented. Each
34 ** time a statement is executed that removes an existing violation from 35 ** time a statement is executed that removes an existing violation from
35 ** the database, the counter is decremented. When the transaction is 36 ** the database, the counter is decremented. When the transaction is
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
79 ** 80 **
80 ** For the purposes of immediate FK constraints, the OR REPLACE conflict 81 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
81 ** resolution is considered to delete rows before the new row is inserted. 82 ** resolution is considered to delete rows before the new row is inserted.
82 ** If a delete caused by OR REPLACE violates an FK constraint, an exception 83 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
83 ** is thrown, even if the FK constraint would be satisfied after the new 84 ** is thrown, even if the FK constraint would be satisfied after the new
84 ** row is inserted. 85 ** row is inserted.
85 ** 86 **
86 ** Immediate constraints are usually handled similarly. The only difference 87 ** Immediate constraints are usually handled similarly. The only difference
87 ** is that the counter used is stored as part of each individual statement 88 ** is that the counter used is stored as part of each individual statement
88 ** object (struct Vdbe). If, after the statement has run, its immediate 89 ** object (struct Vdbe). If, after the statement has run, its immediate
89 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT 90 ** constraint counter is greater than zero,
91 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
90 ** and the statement transaction is rolled back. An exception is an INSERT 92 ** and the statement transaction is rolled back. An exception is an INSERT
91 ** statement that inserts a single row only (no triggers). In this case, 93 ** statement that inserts a single row only (no triggers). In this case,
92 ** instead of using a counter, an exception is thrown immediately if the 94 ** instead of using a counter, an exception is thrown immediately if the
93 ** INSERT violates a foreign key constraint. This is necessary as such 95 ** INSERT violates a foreign key constraint. This is necessary as such
94 ** an INSERT does not open a statement transaction. 96 ** an INSERT does not open a statement transaction.
95 ** 97 **
96 ** TODO: How should dropping a table be handled? How should renaming a 98 ** TODO: How should dropping a table be handled? How should renaming a
97 ** table be handled? 99 ** table be handled?
98 ** 100 **
99 ** 101 **
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
135 ** Register (x): 2 (type integer) 137 ** Register (x): 2 (type integer)
136 ** Register (x+1): 1 (type integer) 138 ** Register (x+1): 1 (type integer)
137 ** Register (x+2): NULL (type NULL) 139 ** Register (x+2): NULL (type NULL)
138 ** Register (x+3): 3.1 (type real) 140 ** Register (x+3): 3.1 (type real)
139 */ 141 */
140 142
141 /* 143 /*
142 ** A foreign key constraint requires that the key columns in the parent 144 ** A foreign key constraint requires that the key columns in the parent
143 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. 145 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
144 ** Given that pParent is the parent table for foreign key constraint pFKey, 146 ** Given that pParent is the parent table for foreign key constraint pFKey,
145 ** search the schema a unique index on the parent key columns. 147 ** search the schema for a unique index on the parent key columns.
146 ** 148 **
147 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 149 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
148 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 150 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
149 ** is set to point to the unique index. 151 ** is set to point to the unique index.
150 ** 152 **
151 ** If the parent key consists of a single column (the foreign key constraint 153 ** If the parent key consists of a single column (the foreign key constraint
152 ** is not a composite foreign key), output variable *paiCol is set to NULL. 154 ** is not a composite foreign key), output variable *paiCol is set to NULL.
153 ** Otherwise, it is set to point to an allocated array of size N, where 155 ** Otherwise, it is set to point to an allocated array of size N, where
154 ** N is the number of columns in the parent key. The first element of the 156 ** N is the number of columns in the parent key. The first element of the
155 ** array is the index of the child table column that is mapped by the FK 157 ** array is the index of the child table column that is mapped by the FK
156 ** constraint to the parent table column stored in the left-most column 158 ** constraint to the parent table column stored in the left-most column
157 ** of index *ppIdx. The second element of the array is the index of the 159 ** of index *ppIdx. The second element of the array is the index of the
158 ** child table column that corresponds to the second left-most column of 160 ** child table column that corresponds to the second left-most column of
159 ** *ppIdx, and so on. 161 ** *ppIdx, and so on.
160 ** 162 **
161 ** If the required index cannot be found, either because: 163 ** If the required index cannot be found, either because:
162 ** 164 **
163 ** 1) The named parent key columns do not exist, or 165 ** 1) The named parent key columns do not exist, or
164 ** 166 **
165 ** 2) The named parent key columns do exist, but are not subject to a 167 ** 2) The named parent key columns do exist, but are not subject to a
166 ** UNIQUE or PRIMARY KEY constraint, or 168 ** UNIQUE or PRIMARY KEY constraint, or
167 ** 169 **
168 ** 3) No parent key columns were provided explicitly as part of the 170 ** 3) No parent key columns were provided explicitly as part of the
169 ** foreign key definition, and the parent table does not have a 171 ** foreign key definition, and the parent table does not have a
170 ** PRIMARY KEY, or 172 ** PRIMARY KEY, or
171 ** 173 **
172 ** 4) No parent key columns were provided explicitly as part of the 174 ** 4) No parent key columns were provided explicitly as part of the
173 ** foreign key definition, and the PRIMARY KEY of the parent table 175 ** foreign key definition, and the PRIMARY KEY of the parent table
174 ** consists of a a different number of columns to the child key in 176 ** consists of a different number of columns to the child key in
175 ** the child table. 177 ** the child table.
176 ** 178 **
177 ** then non-zero is returned, and a "foreign key mismatch" error loaded 179 ** then non-zero is returned, and a "foreign key mismatch" error loaded
178 ** into pParse. If an OOM error occurs, non-zero is returned and the 180 ** into pParse. If an OOM error occurs, non-zero is returned and the
179 ** pParse->db->mallocFailed flag is set. 181 ** pParse->db->mallocFailed flag is set.
180 */ 182 */
181 static int locateFkeyIndex( 183 int sqlite3FkLocateIndex(
182 Parse *pParse, /* Parse context to store any error in */ 184 Parse *pParse, /* Parse context to store any error in */
183 Table *pParent, /* Parent table of FK constraint pFKey */ 185 Table *pParent, /* Parent table of FK constraint pFKey */
184 FKey *pFKey, /* Foreign key to find index for */ 186 FKey *pFKey, /* Foreign key to find index for */
185 Index **ppIdx, /* OUT: Unique index on parent table */ 187 Index **ppIdx, /* OUT: Unique index on parent table */
186 int **paiCol /* OUT: Map of index columns in pFKey */ 188 int **paiCol /* OUT: Map of index columns in pFKey */
187 ){ 189 ){
188 Index *pIdx = 0; /* Value to return via *ppIdx */ 190 Index *pIdx = 0; /* Value to return via *ppIdx */
189 int *aiCol = 0; /* Value to return via *paiCol */ 191 int *aiCol = 0; /* Value to return via *paiCol */
190 int nCol = pFKey->nCol; /* Number of columns in parent key */ 192 int nCol = pFKey->nCol; /* Number of columns in parent key */
191 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ 193 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
(...skipping 24 matching lines...) Expand all
216 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; 218 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
217 } 219 }
218 }else if( paiCol ){ 220 }else if( paiCol ){
219 assert( nCol>1 ); 221 assert( nCol>1 );
220 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int)); 222 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
221 if( !aiCol ) return 1; 223 if( !aiCol ) return 1;
222 *paiCol = aiCol; 224 *paiCol = aiCol;
223 } 225 }
224 226
225 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ 227 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
226 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 228 if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
227 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number 229 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
228 ** of columns. If each indexed column corresponds to a foreign key 230 ** of columns. If each indexed column corresponds to a foreign key
229 ** column of pFKey, then this index is a winner. */ 231 ** column of pFKey, then this index is a winner. */
230 232
231 if( zKey==0 ){ 233 if( zKey==0 ){
232 /* If zKey is NULL, then this foreign key is implicitly mapped to 234 /* If zKey is NULL, then this foreign key is implicitly mapped to
233 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 235 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
234 ** identified by the test (Index.autoIndex==2). */ 236 ** identified by the test. */
235 if( pIdx->autoIndex==2 ){ 237 if( IsPrimaryKeyIndex(pIdx) ){
236 if( aiCol ){ 238 if( aiCol ){
237 int i; 239 int i;
238 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom; 240 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
239 } 241 }
240 break; 242 break;
241 } 243 }
242 }else{ 244 }else{
243 /* If zKey is non-NULL, then this foreign key was declared to 245 /* If zKey is non-NULL, then this foreign key was declared to
244 ** map to an explicit list of columns in table pParent. Check if this 246 ** map to an explicit list of columns in table pParent. Check if this
245 ** index matches those columns. Also, check that the index uses 247 ** index matches those columns. Also, check that the index uses
246 ** the default collation sequences for each column. */ 248 ** the default collation sequences for each column. */
247 int i, j; 249 int i, j;
248 for(i=0; i<nCol; i++){ 250 for(i=0; i<nCol; i++){
249 int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */ 251 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
250 char *zDfltColl; /* Def. collation for column */ 252 char *zDfltColl; /* Def. collation for column */
251 char *zIdxCol; /* Name of indexed column */ 253 char *zIdxCol; /* Name of indexed column */
252 254
253 /* If the index uses a collation sequence that is different from 255 /* If the index uses a collation sequence that is different from
254 ** the default collation sequence for the column, this index is 256 ** the default collation sequence for the column, this index is
255 ** unusable. Bail out early in this case. */ 257 ** unusable. Bail out early in this case. */
256 zDfltColl = pParent->aCol[iCol].zColl; 258 zDfltColl = pParent->aCol[iCol].zColl;
257 if( !zDfltColl ){ 259 if( !zDfltColl ){
258 zDfltColl = "BINARY"; 260 zDfltColl = "BINARY";
259 } 261 }
260 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; 262 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
261 263
262 zIdxCol = pParent->aCol[iCol].zName; 264 zIdxCol = pParent->aCol[iCol].zName;
263 for(j=0; j<nCol; j++){ 265 for(j=0; j<nCol; j++){
264 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){ 266 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
265 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; 267 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
266 break; 268 break;
267 } 269 }
268 } 270 }
269 if( j==nCol ) break; 271 if( j==nCol ) break;
270 } 272 }
271 if( i==nCol ) break; /* pIdx is usable */ 273 if( i==nCol ) break; /* pIdx is usable */
272 } 274 }
273 } 275 }
274 } 276 }
275 277
276 if( !pIdx ){ 278 if( !pIdx ){
277 if( !pParse->disableTriggers ){ 279 if( !pParse->disableTriggers ){
278 sqlite3ErrorMsg(pParse, "foreign key mismatch"); 280 sqlite3ErrorMsg(pParse,
281 "foreign key mismatch - \"%w\" referencing \"%w\"",
282 pFKey->pFrom->zName, pFKey->zTo);
279 } 283 }
280 sqlite3DbFree(pParse->db, aiCol); 284 sqlite3DbFree(pParse->db, aiCol);
281 return 1; 285 return 1;
282 } 286 }
283 287
284 *ppIdx = pIdx; 288 *ppIdx = pIdx;
285 return 0; 289 return 0;
286 } 290 }
287 291
288 /* 292 /*
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
329 333
330 /* If nIncr is less than zero, then check at runtime if there are any 334 /* If nIncr is less than zero, then check at runtime if there are any
331 ** outstanding constraints to resolve. If there are not, there is no need 335 ** outstanding constraints to resolve. If there are not, there is no need
332 ** to check if deleting this row resolves any outstanding violations. 336 ** to check if deleting this row resolves any outstanding violations.
333 ** 337 **
334 ** Check if any of the key columns in the child table row are NULL. If 338 ** Check if any of the key columns in the child table row are NULL. If
335 ** any are, then the constraint is considered satisfied. No need to 339 ** any are, then the constraint is considered satisfied. No need to
336 ** search for a matching row in the parent table. */ 340 ** search for a matching row in the parent table. */
337 if( nIncr<0 ){ 341 if( nIncr<0 ){
338 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); 342 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
343 VdbeCoverage(v);
339 } 344 }
340 for(i=0; i<pFKey->nCol; i++){ 345 for(i=0; i<pFKey->nCol; i++){
341 int iReg = aiCol[i] + regData + 1; 346 int iReg = aiCol[i] + regData + 1;
342 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); 347 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
343 } 348 }
344 349
345 if( isIgnore==0 ){ 350 if( isIgnore==0 ){
346 if( pIdx==0 ){ 351 if( pIdx==0 ){
347 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY 352 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
348 ** column of the parent table (table pTab). */ 353 ** column of the parent table (table pTab). */
349 int iMustBeInt; /* Address of MustBeInt instruction */ 354 int iMustBeInt; /* Address of MustBeInt instruction */
350 int regTemp = sqlite3GetTempReg(pParse); 355 int regTemp = sqlite3GetTempReg(pParse);
351 356
352 /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 357 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
353 ** apply the affinity of the parent key). If this fails, then there 358 ** apply the affinity of the parent key). If this fails, then there
354 ** is no matching parent key. Before using MustBeInt, make a copy of 359 ** is no matching parent key. Before using MustBeInt, make a copy of
355 ** the value. Otherwise, the value inserted into the child key column 360 ** the value. Otherwise, the value inserted into the child key column
356 ** will have INTEGER affinity applied to it, which may not be correct. */ 361 ** will have INTEGER affinity applied to it, which may not be correct. */
357 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp); 362 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
358 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); 363 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
364 VdbeCoverage(v);
359 365
360 /* If the parent table is the same as the child table, and we are about 366 /* If the parent table is the same as the child table, and we are about
361 ** to increment the constraint-counter (i.e. this is an INSERT operation), 367 ** to increment the constraint-counter (i.e. this is an INSERT operation),
362 ** then check if the row being inserted matches itself. If so, do not 368 ** then check if the row being inserted matches itself. If so, do not
363 ** increment the constraint-counter. */ 369 ** increment the constraint-counter. */
364 if( pTab==pFKey->pFrom && nIncr==1 ){ 370 if( pTab==pFKey->pFrom && nIncr==1 ){
365 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); 371 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
372 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
366 } 373 }
367 374
368 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); 375 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
369 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); 376 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
370 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); 377 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
371 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 378 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
372 sqlite3VdbeJumpHere(v, iMustBeInt); 379 sqlite3VdbeJumpHere(v, iMustBeInt);
373 sqlite3ReleaseTempReg(pParse, regTemp); 380 sqlite3ReleaseTempReg(pParse, regTemp);
374 }else{ 381 }else{
375 int nCol = pFKey->nCol; 382 int nCol = pFKey->nCol;
376 int regTemp = sqlite3GetTempRange(pParse, nCol); 383 int regTemp = sqlite3GetTempRange(pParse, nCol);
377 int regRec = sqlite3GetTempReg(pParse); 384 int regRec = sqlite3GetTempReg(pParse);
378 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
379 385
380 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); 386 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
381 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); 387 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
382 for(i=0; i<nCol; i++){ 388 for(i=0; i<nCol; i++){
383 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i); 389 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
384 } 390 }
385 391
386 /* If the parent table is the same as the child table, and we are about 392 /* If the parent table is the same as the child table, and we are about
387 ** to increment the constraint-counter (i.e. this is an INSERT operation), 393 ** to increment the constraint-counter (i.e. this is an INSERT operation),
388 ** then check if the row being inserted matches itself. If so, do not 394 ** then check if the row being inserted matches itself. If so, do not
389 ** increment the constraint-counter. */ 395 ** increment the constraint-counter.
396 **
397 ** If any of the parent-key values are NULL, then the row cannot match
398 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
399 ** of the parent-key values are NULL (at this point it is known that
400 ** none of the child key values are).
401 */
390 if( pTab==pFKey->pFrom && nIncr==1 ){ 402 if( pTab==pFKey->pFrom && nIncr==1 ){
391 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; 403 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
392 for(i=0; i<nCol; i++){ 404 for(i=0; i<nCol; i++){
393 int iChild = aiCol[i]+1+regData; 405 int iChild = aiCol[i]+1+regData;
394 int iParent = pIdx->aiColumn[i]+1+regData; 406 int iParent = pIdx->aiColumn[i]+1+regData;
395 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); 407 assert( aiCol[i]!=pTab->iPKey );
408 if( pIdx->aiColumn[i]==pTab->iPKey ){
409 /* The parent key is a composite key that includes the IPK column */
410 iParent = regData;
411 }
412 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
413 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
396 } 414 }
397 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); 415 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
398 } 416 }
399 417
400 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec); 418 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
401 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT); 419 sqlite3IndexAffinityStr(v,pIdx), nCol);
402 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); 420 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
403 421
404 sqlite3ReleaseTempReg(pParse, regRec); 422 sqlite3ReleaseTempReg(pParse, regRec);
405 sqlite3ReleaseTempRange(pParse, regTemp, nCol); 423 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
406 } 424 }
407 } 425 }
408 426
409 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){ 427 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
428 && !pParse->pToplevel
429 && !pParse->isMultiWrite
430 ){
410 /* Special case: If this is an INSERT statement that will insert exactly 431 /* Special case: If this is an INSERT statement that will insert exactly
411 ** one row into the table, raise a constraint immediately instead of 432 ** one row into the table, raise a constraint immediately instead of
412 ** incrementing a counter. This is necessary as the VM code is being 433 ** incrementing a counter. This is necessary as the VM code is being
413 ** generated for will not open a statement transaction. */ 434 ** generated for will not open a statement transaction. */
414 assert( nIncr==1 ); 435 assert( nIncr==1 );
415 sqlite3HaltConstraint( 436 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
416 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC 437 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
417 );
418 }else{ 438 }else{
419 if( nIncr>0 && pFKey->isDeferred==0 ){ 439 if( nIncr>0 && pFKey->isDeferred==0 ){
420 sqlite3ParseToplevel(pParse)->mayAbort = 1; 440 sqlite3ParseToplevel(pParse)->mayAbort = 1;
421 } 441 }
422 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); 442 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
423 } 443 }
424 444
425 sqlite3VdbeResolveLabel(v, iOk); 445 sqlite3VdbeResolveLabel(v, iOk);
426 sqlite3VdbeAddOp1(v, OP_Close, iCur); 446 sqlite3VdbeAddOp1(v, OP_Close, iCur);
427 } 447 }
428 448
449
450 /*
451 ** Return an Expr object that refers to a memory register corresponding
452 ** to column iCol of table pTab.
453 **
454 ** regBase is the first of an array of register that contains the data
455 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
456 ** column. regBase+2 holds the second column, and so forth.
457 */
458 static Expr *exprTableRegister(
459 Parse *pParse, /* Parsing and code generating context */
460 Table *pTab, /* The table whose content is at r[regBase]... */
461 int regBase, /* Contents of table pTab */
462 i16 iCol /* Which column of pTab is desired */
463 ){
464 Expr *pExpr;
465 Column *pCol;
466 const char *zColl;
467 sqlite3 *db = pParse->db;
468
469 pExpr = sqlite3Expr(db, TK_REGISTER, 0);
470 if( pExpr ){
471 if( iCol>=0 && iCol!=pTab->iPKey ){
472 pCol = &pTab->aCol[iCol];
473 pExpr->iTable = regBase + iCol + 1;
474 pExpr->affinity = pCol->affinity;
475 zColl = pCol->zColl;
476 if( zColl==0 ) zColl = db->pDfltColl->zName;
477 pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
478 }else{
479 pExpr->iTable = regBase;
480 pExpr->affinity = SQLITE_AFF_INTEGER;
481 }
482 }
483 return pExpr;
484 }
485
486 /*
487 ** Return an Expr object that refers to column iCol of table pTab which
488 ** has cursor iCur.
489 */
490 static Expr *exprTableColumn(
491 sqlite3 *db, /* The database connection */
492 Table *pTab, /* The table whose column is desired */
493 int iCursor, /* The open cursor on the table */
494 i16 iCol /* The column that is wanted */
495 ){
496 Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
497 if( pExpr ){
498 pExpr->pTab = pTab;
499 pExpr->iTable = iCursor;
500 pExpr->iColumn = iCol;
501 }
502 return pExpr;
503 }
504
429 /* 505 /*
430 ** This function is called to generate code executed when a row is deleted 506 ** This function is called to generate code executed when a row is deleted
431 ** from the parent table of foreign key constraint pFKey and, if pFKey is 507 ** from the parent table of foreign key constraint pFKey and, if pFKey is
432 ** deferred, when a row is inserted into the same table. When generating 508 ** deferred, when a row is inserted into the same table. When generating
433 ** code for an SQL UPDATE operation, this function may be called twice - 509 ** code for an SQL UPDATE operation, this function may be called twice -
434 ** once to "delete" the old row and once to "insert" the new row. 510 ** once to "delete" the old row and once to "insert" the new row.
435 ** 511 **
436 ** The code generated by this function scans through the rows in the child 512 ** The code generated by this function scans through the rows in the child
437 ** table that correspond to the parent table row being deleted or inserted. 513 ** table that correspond to the parent table row being deleted or inserted.
438 ** For each child row found, one of the following actions is taken: 514 ** For each child row found, one of the following actions is taken:
439 ** 515 **
440 ** Operation | FK type | Action taken 516 ** Operation | FK type | Action taken
441 ** -------------------------------------------------------------------------- 517 ** --------------------------------------------------------------------------
442 ** DELETE immediate Increment the "immediate constraint counter". 518 ** DELETE immediate Increment the "immediate constraint counter".
443 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, 519 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
444 ** throw a "foreign key constraint failed" exception. 520 ** throw a "FOREIGN KEY constraint failed" exception.
445 ** 521 **
446 ** INSERT immediate Decrement the "immediate constraint counter". 522 ** INSERT immediate Decrement the "immediate constraint counter".
447 ** 523 **
448 ** DELETE deferred Increment the "deferred constraint counter". 524 ** DELETE deferred Increment the "deferred constraint counter".
449 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, 525 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
450 ** throw a "foreign key constraint failed" exception. 526 ** throw a "FOREIGN KEY constraint failed" exception.
451 ** 527 **
452 ** INSERT deferred Decrement the "deferred constraint counter". 528 ** INSERT deferred Decrement the "deferred constraint counter".
453 ** 529 **
454 ** These operations are identified in the comment at the top of this file 530 ** These operations are identified in the comment at the top of this file
455 ** (fkey.c) as "I.2" and "D.2". 531 ** (fkey.c) as "I.2" and "D.2".
456 */ 532 */
457 static void fkScanChildren( 533 static void fkScanChildren(
458 Parse *pParse, /* Parse context */ 534 Parse *pParse, /* Parse context */
459 SrcList *pSrc, /* SrcList containing the table to scan */ 535 SrcList *pSrc, /* The child table to be scanned */
460 Table *pTab, 536 Table *pTab, /* The parent table */
461 Index *pIdx, /* Foreign key index */ 537 Index *pIdx, /* Index on parent covering the foreign key */
462 FKey *pFKey, /* Foreign key relationship */ 538 FKey *pFKey, /* The foreign key linking pSrc to pTab */
463 int *aiCol, /* Map from pIdx cols to child table cols */ 539 int *aiCol, /* Map from pIdx cols to child table cols */
464 int regData, /* Referenced table data starts here */ 540 int regData, /* Parent row data starts here */
465 int nIncr /* Amount to increment deferred counter by */ 541 int nIncr /* Amount to increment deferred counter by */
466 ){ 542 ){
467 sqlite3 *db = pParse->db; /* Database handle */ 543 sqlite3 *db = pParse->db; /* Database handle */
468 int i; /* Iterator variable */ 544 int i; /* Iterator variable */
469 Expr *pWhere = 0; /* WHERE clause to scan with */ 545 Expr *pWhere = 0; /* WHERE clause to scan with */
470 NameContext sNameContext; /* Context used to resolve WHERE clause */ 546 NameContext sNameContext; /* Context used to resolve WHERE clause */
471 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ 547 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
472 int iFkIfZero = 0; /* Address of OP_FkIfZero */ 548 int iFkIfZero = 0; /* Address of OP_FkIfZero */
473 Vdbe *v = sqlite3GetVdbe(pParse); 549 Vdbe *v = sqlite3GetVdbe(pParse);
474 550
475 assert( !pIdx || pIdx->pTable==pTab ); 551 assert( pIdx==0 || pIdx->pTable==pTab );
552 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
553 assert( pIdx!=0 || pFKey->nCol==1 );
554 assert( pIdx!=0 || HasRowid(pTab) );
476 555
477 if( nIncr<0 ){ 556 if( nIncr<0 ){
478 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); 557 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
558 VdbeCoverage(v);
479 } 559 }
480 560
481 /* Create an Expr object representing an SQL expression like: 561 /* Create an Expr object representing an SQL expression like:
482 ** 562 **
483 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ... 563 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
484 ** 564 **
485 ** The collation sequence used for the comparison should be that of 565 ** The collation sequence used for the comparison should be that of
486 ** the parent key columns. The affinity of the parent key column should 566 ** the parent key columns. The affinity of the parent key column should
487 ** be applied to each child key value before the comparison takes place. 567 ** be applied to each child key value before the comparison takes place.
488 */ 568 */
489 for(i=0; i<pFKey->nCol; i++){ 569 for(i=0; i<pFKey->nCol; i++){
490 Expr *pLeft; /* Value from parent table row */ 570 Expr *pLeft; /* Value from parent table row */
491 Expr *pRight; /* Column ref to child table */ 571 Expr *pRight; /* Column ref to child table */
492 Expr *pEq; /* Expression (pLeft = pRight) */ 572 Expr *pEq; /* Expression (pLeft = pRight) */
493 int iCol; /* Index of column in child table */ 573 i16 iCol; /* Index of column in child table */
494 const char *zCol; /* Name of column in child table */ 574 const char *zCol; /* Name of column in child table */
495 575
496 pLeft = sqlite3Expr(db, TK_REGISTER, 0); 576 iCol = pIdx ? pIdx->aiColumn[i] : -1;
497 if( pLeft ){ 577 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
498 /* Set the collation sequence and affinity of the LHS of each TK_EQ
499 ** expression to the parent key column defaults. */
500 if( pIdx ){
501 Column *pCol;
502 iCol = pIdx->aiColumn[i];
503 pCol = &pTab->aCol[iCol];
504 if( pTab->iPKey==iCol ) iCol = -1;
505 pLeft->iTable = regData+iCol+1;
506 pLeft->affinity = pCol->affinity;
507 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
508 }else{
509 pLeft->iTable = regData;
510 pLeft->affinity = SQLITE_AFF_INTEGER;
511 }
512 }
513 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; 578 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
514 assert( iCol>=0 ); 579 assert( iCol>=0 );
515 zCol = pFKey->pFrom->aCol[iCol].zName; 580 zCol = pFKey->pFrom->aCol[iCol].zName;
516 pRight = sqlite3Expr(db, TK_ID, zCol); 581 pRight = sqlite3Expr(db, TK_ID, zCol);
517 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); 582 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
518 pWhere = sqlite3ExprAnd(db, pWhere, pEq); 583 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
519 } 584 }
520 585
521 /* If the child table is the same as the parent table, and this scan 586 /* If the child table is the same as the parent table, then add terms
522 ** is taking place as part of a DELETE operation (operation D.2), omit the 587 ** to the WHERE clause that prevent this entry from being scanned.
523 ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 588 ** The added WHERE clause terms are like this:
524 ** clause, where $rowid is the rowid of the row being deleted. */ 589 **
590 ** $current_rowid!=rowid
591 ** NOT( $current_a==a AND $current_b==b AND ... )
592 **
593 ** The first form is used for rowid tables. The second form is used
594 ** for WITHOUT ROWID tables. In the second form, the primary key is
595 ** (a,b,...)
596 */
525 if( pTab==pFKey->pFrom && nIncr>0 ){ 597 if( pTab==pFKey->pFrom && nIncr>0 ){
526 Expr *pEq; /* Expression (pLeft = pRight) */ 598 Expr *pNe; /* Expression (pLeft != pRight) */
527 Expr *pLeft; /* Value from parent table row */ 599 Expr *pLeft; /* Value from parent table row */
528 Expr *pRight; /* Column ref to child table */ 600 Expr *pRight; /* Column ref to child table */
529 pLeft = sqlite3Expr(db, TK_REGISTER, 0); 601 if( HasRowid(pTab) ){
530 pRight = sqlite3Expr(db, TK_COLUMN, 0); 602 pLeft = exprTableRegister(pParse, pTab, regData, -1);
531 if( pLeft && pRight ){ 603 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
532 pLeft->iTable = regData; 604 pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
533 pLeft->affinity = SQLITE_AFF_INTEGER; 605 }else{
534 pRight->iTable = pSrc->a[0].iCursor; 606 Expr *pEq, *pAll = 0;
535 pRight->iColumn = -1; 607 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
608 assert( pIdx!=0 );
609 for(i=0; i<pPk->nKeyCol; i++){
610 i16 iCol = pIdx->aiColumn[i];
611 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
612 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
613 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
614 pAll = sqlite3ExprAnd(db, pAll, pEq);
615 }
616 pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
536 } 617 }
537 pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); 618 pWhere = sqlite3ExprAnd(db, pWhere, pNe);
538 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
539 } 619 }
540 620
541 /* Resolve the references in the WHERE clause. */ 621 /* Resolve the references in the WHERE clause. */
542 memset(&sNameContext, 0, sizeof(NameContext)); 622 memset(&sNameContext, 0, sizeof(NameContext));
543 sNameContext.pSrcList = pSrc; 623 sNameContext.pSrcList = pSrc;
544 sNameContext.pParse = pParse; 624 sNameContext.pParse = pParse;
545 sqlite3ResolveExprNames(&sNameContext, pWhere); 625 sqlite3ResolveExprNames(&sNameContext, pWhere);
546 626
547 /* Create VDBE to loop through the entries in pSrc that match the WHERE 627 /* Create VDBE to loop through the entries in pSrc that match the WHERE
548 ** clause. If the constraint is not deferred, throw an exception for 628 ** clause. If the constraint is not deferred, throw an exception for
549 ** each row found. Otherwise, for deferred constraints, increment the 629 ** each row found. Otherwise, for deferred constraints, increment the
550 ** deferred constraint counter by nIncr for each row selected. */ 630 ** deferred constraint counter by nIncr for each row selected. */
551 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0); 631 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
552 if( nIncr>0 && pFKey->isDeferred==0 ){ 632 if( nIncr>0 && pFKey->isDeferred==0 ){
553 sqlite3ParseToplevel(pParse)->mayAbort = 1; 633 sqlite3ParseToplevel(pParse)->mayAbort = 1;
554 } 634 }
555 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); 635 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
556 if( pWInfo ){ 636 if( pWInfo ){
557 sqlite3WhereEnd(pWInfo); 637 sqlite3WhereEnd(pWInfo);
558 } 638 }
559 639
560 /* Clean up the WHERE clause constructed above. */ 640 /* Clean up the WHERE clause constructed above. */
561 sqlite3ExprDelete(db, pWhere); 641 sqlite3ExprDelete(db, pWhere);
562 if( iFkIfZero ){ 642 if( iFkIfZero ){
563 sqlite3VdbeJumpHere(v, iFkIfZero); 643 sqlite3VdbeJumpHere(v, iFkIfZero);
564 } 644 }
565 } 645 }
566 646
567 /* 647 /*
568 ** This function returns a pointer to the head of a linked list of FK 648 ** This function returns a linked list of FKey objects (connected by
569 ** constraints for which table pTab is the parent table. For example, 649 ** FKey.pNextTo) holding all children of table pTab. For example,
570 ** given the following schema: 650 ** given the following schema:
571 ** 651 **
572 ** CREATE TABLE t1(a PRIMARY KEY); 652 ** CREATE TABLE t1(a PRIMARY KEY);
573 ** CREATE TABLE t2(b REFERENCES t1(a); 653 ** CREATE TABLE t2(b REFERENCES t1(a);
574 ** 654 **
575 ** Calling this function with table "t1" as an argument returns a pointer 655 ** Calling this function with table "t1" as an argument returns a pointer
576 ** to the FKey structure representing the foreign key constraint on table 656 ** to the FKey structure representing the foreign key constraint on table
577 ** "t2". Calling this function with "t2" as the argument would return a 657 ** "t2". Calling this function with "t2" as the argument would return a
578 ** NULL pointer (as there are no FK constraints for which t2 is the parent 658 ** NULL pointer (as there are no FK constraints for which t2 is the parent
579 ** table). 659 ** table).
580 */ 660 */
581 FKey *sqlite3FkReferences(Table *pTab){ 661 FKey *sqlite3FkReferences(Table *pTab){
582 int nName = sqlite3Strlen30(pTab->zName); 662 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
583 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
584 } 663 }
585 664
586 /* 665 /*
587 ** The second argument is a Trigger structure allocated by the 666 ** The second argument is a Trigger structure allocated by the
588 ** fkActionTrigger() routine. This function deletes the Trigger structure 667 ** fkActionTrigger() routine. This function deletes the Trigger structure
589 ** and all of its sub-components. 668 ** and all of its sub-components.
590 ** 669 **
591 ** The Trigger structure or any of its sub-components may be allocated from 670 ** The Trigger structure or any of its sub-components may be allocated from
592 ** the lookaside buffer belonging to database handle dbMem. 671 ** the lookaside buffer belonging to database handle dbMem.
593 */ 672 */
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
627 706
628 assert( v ); /* VDBE has already been allocated */ 707 assert( v ); /* VDBE has already been allocated */
629 if( sqlite3FkReferences(pTab)==0 ){ 708 if( sqlite3FkReferences(pTab)==0 ){
630 /* Search for a deferred foreign key constraint for which this table 709 /* Search for a deferred foreign key constraint for which this table
631 ** is the child table. If one cannot be found, return without 710 ** is the child table. If one cannot be found, return without
632 ** generating any VDBE code. If one can be found, then jump over 711 ** generating any VDBE code. If one can be found, then jump over
633 ** the entire DELETE if there are no outstanding deferred constraints 712 ** the entire DELETE if there are no outstanding deferred constraints
634 ** when this statement is run. */ 713 ** when this statement is run. */
635 FKey *p; 714 FKey *p;
636 for(p=pTab->pFKey; p; p=p->pNextFrom){ 715 for(p=pTab->pFKey; p; p=p->pNextFrom){
637 if( p->isDeferred ) break; 716 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
638 } 717 }
639 if( !p ) return; 718 if( !p ) return;
640 iSkip = sqlite3VdbeMakeLabel(v); 719 iSkip = sqlite3VdbeMakeLabel(v);
641 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); 720 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
642 } 721 }
643 722
644 pParse->disableTriggers = 1; 723 pParse->disableTriggers = 1;
645 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0); 724 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
646 pParse->disableTriggers = 0; 725 pParse->disableTriggers = 0;
647 726
648 /* If the DELETE has generated immediate foreign key constraint 727 /* If the DELETE has generated immediate foreign key constraint
649 ** violations, halt the VDBE and return an error at this point, before 728 ** violations, halt the VDBE and return an error at this point, before
650 ** any modifications to the schema are made. This is because statement 729 ** any modifications to the schema are made. This is because statement
651 ** transactions are not able to rollback schema changes. */ 730 ** transactions are not able to rollback schema changes.
652 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); 731 **
653 sqlite3HaltConstraint( 732 ** If the SQLITE_DeferFKs flag is set, then this is not required, as
654 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC 733 ** the statement transaction will not be rolled back even if FK
655 ); 734 ** constraints are violated.
735 */
736 if( (db->flags & SQLITE_DeferFKs)==0 ){
737 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
738 VdbeCoverage(v);
739 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
740 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
741 }
656 742
657 if( iSkip ){ 743 if( iSkip ){
658 sqlite3VdbeResolveLabel(v, iSkip); 744 sqlite3VdbeResolveLabel(v, iSkip);
659 } 745 }
660 } 746 }
661 } 747 }
662 748
749
750 /*
751 ** The second argument points to an FKey object representing a foreign key
752 ** for which pTab is the child table. An UPDATE statement against pTab
753 ** is currently being processed. For each column of the table that is
754 ** actually updated, the corresponding element in the aChange[] array
755 ** is zero or greater (if a column is unmodified the corresponding element
756 ** is set to -1). If the rowid column is modified by the UPDATE statement
757 ** the bChngRowid argument is non-zero.
758 **
759 ** This function returns true if any of the columns that are part of the
760 ** child key for FK constraint *p are modified.
761 */
762 static int fkChildIsModified(
763 Table *pTab, /* Table being updated */
764 FKey *p, /* Foreign key for which pTab is the child */
765 int *aChange, /* Array indicating modified columns */
766 int bChngRowid /* True if rowid is modified by this update */
767 ){
768 int i;
769 for(i=0; i<p->nCol; i++){
770 int iChildKey = p->aCol[i].iFrom;
771 if( aChange[iChildKey]>=0 ) return 1;
772 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
773 }
774 return 0;
775 }
776
777 /*
778 ** The second argument points to an FKey object representing a foreign key
779 ** for which pTab is the parent table. An UPDATE statement against pTab
780 ** is currently being processed. For each column of the table that is
781 ** actually updated, the corresponding element in the aChange[] array
782 ** is zero or greater (if a column is unmodified the corresponding element
783 ** is set to -1). If the rowid column is modified by the UPDATE statement
784 ** the bChngRowid argument is non-zero.
785 **
786 ** This function returns true if any of the columns that are part of the
787 ** parent key for FK constraint *p are modified.
788 */
789 static int fkParentIsModified(
790 Table *pTab,
791 FKey *p,
792 int *aChange,
793 int bChngRowid
794 ){
795 int i;
796 for(i=0; i<p->nCol; i++){
797 char *zKey = p->aCol[i].zCol;
798 int iKey;
799 for(iKey=0; iKey<pTab->nCol; iKey++){
800 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
801 Column *pCol = &pTab->aCol[iKey];
802 if( zKey ){
803 if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
804 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
805 return 1;
806 }
807 }
808 }
809 }
810 return 0;
811 }
812
663 /* 813 /*
664 ** This function is called when inserting, deleting or updating a row of 814 ** This function is called when inserting, deleting or updating a row of
665 ** table pTab to generate VDBE code to perform foreign key constraint 815 ** table pTab to generate VDBE code to perform foreign key constraint
666 ** processing for the operation. 816 ** processing for the operation.
667 ** 817 **
668 ** For a DELETE operation, parameter regOld is passed the index of the 818 ** For a DELETE operation, parameter regOld is passed the index of the
669 ** first register in an array of (pTab->nCol+1) registers containing the 819 ** first register in an array of (pTab->nCol+1) registers containing the
670 ** rowid of the row being deleted, followed by each of the column values 820 ** rowid of the row being deleted, followed by each of the column values
671 ** of the row being deleted, from left to right. Parameter regNew is passed 821 ** of the row being deleted, from left to right. Parameter regNew is passed
672 ** zero in this case. 822 ** zero in this case.
673 ** 823 **
674 ** For an INSERT operation, regOld is passed zero and regNew is passed the 824 ** For an INSERT operation, regOld is passed zero and regNew is passed the
675 ** first register of an array of (pTab->nCol+1) registers containing the new 825 ** first register of an array of (pTab->nCol+1) registers containing the new
676 ** row data. 826 ** row data.
677 ** 827 **
678 ** For an UPDATE operation, this function is called twice. Once before 828 ** For an UPDATE operation, this function is called twice. Once before
679 ** the original record is deleted from the table using the calling convention 829 ** the original record is deleted from the table using the calling convention
680 ** described for DELETE. Then again after the original record is deleted 830 ** described for DELETE. Then again after the original record is deleted
681 ** but before the new record is inserted using the INSERT convention. 831 ** but before the new record is inserted using the INSERT convention.
682 */ 832 */
683 void sqlite3FkCheck( 833 void sqlite3FkCheck(
684 Parse *pParse, /* Parse context */ 834 Parse *pParse, /* Parse context */
685 Table *pTab, /* Row is being deleted from this table */ 835 Table *pTab, /* Row is being deleted from this table */
686 int regOld, /* Previous row data is stored here */ 836 int regOld, /* Previous row data is stored here */
687 int regNew /* New row data is stored here */ 837 int regNew, /* New row data is stored here */
838 int *aChange, /* Array indicating UPDATEd columns (or 0) */
839 int bChngRowid /* True if rowid is UPDATEd */
688 ){ 840 ){
689 sqlite3 *db = pParse->db; /* Database handle */ 841 sqlite3 *db = pParse->db; /* Database handle */
690 FKey *pFKey; /* Used to iterate through FKs */ 842 FKey *pFKey; /* Used to iterate through FKs */
691 int iDb; /* Index of database containing pTab */ 843 int iDb; /* Index of database containing pTab */
692 const char *zDb; /* Name of database containing pTab */ 844 const char *zDb; /* Name of database containing pTab */
693 int isIgnoreErrors = pParse->disableTriggers; 845 int isIgnoreErrors = pParse->disableTriggers;
694 846
695 /* Exactly one of regOld and regNew should be non-zero. */ 847 /* Exactly one of regOld and regNew should be non-zero. */
696 assert( (regOld==0)!=(regNew==0) ); 848 assert( (regOld==0)!=(regNew==0) );
697 849
698 /* If foreign-keys are disabled, this function is a no-op. */ 850 /* If foreign-keys are disabled, this function is a no-op. */
699 if( (db->flags&SQLITE_ForeignKeys)==0 ) return; 851 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
700 852
701 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 853 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
702 zDb = db->aDb[iDb].zName; 854 zDb = db->aDb[iDb].zName;
703 855
704 /* Loop through all the foreign key constraints for which pTab is the 856 /* Loop through all the foreign key constraints for which pTab is the
705 ** child table (the table that the foreign key definition is part of). */ 857 ** child table (the table that the foreign key definition is part of). */
706 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 858 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
707 Table *pTo; /* Parent table of foreign key pFKey */ 859 Table *pTo; /* Parent table of foreign key pFKey */
708 Index *pIdx = 0; /* Index on key columns in pTo */ 860 Index *pIdx = 0; /* Index on key columns in pTo */
709 int *aiFree = 0; 861 int *aiFree = 0;
710 int *aiCol; 862 int *aiCol;
711 int iCol; 863 int iCol;
712 int i; 864 int i;
713 int isIgnore = 0; 865 int isIgnore = 0;
714 866
867 if( aChange
868 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
869 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
870 ){
871 continue;
872 }
873
715 /* Find the parent table of this foreign key. Also find a unique index 874 /* Find the parent table of this foreign key. Also find a unique index
716 ** on the parent key columns in the parent table. If either of these 875 ** on the parent key columns in the parent table. If either of these
717 ** schema items cannot be located, set an error in pParse and return 876 ** schema items cannot be located, set an error in pParse and return
718 ** early. */ 877 ** early. */
719 if( pParse->disableTriggers ){ 878 if( pParse->disableTriggers ){
720 pTo = sqlite3FindTable(db, pFKey->zTo, zDb); 879 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
721 }else{ 880 }else{
722 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); 881 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
723 } 882 }
724 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ 883 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
884 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
725 if( !isIgnoreErrors || db->mallocFailed ) return; 885 if( !isIgnoreErrors || db->mallocFailed ) return;
886 if( pTo==0 ){
887 /* If isIgnoreErrors is true, then a table is being dropped. In this
888 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
889 ** before actually dropping it in order to check FK constraints.
890 ** If the parent table of an FK constraint on the current table is
891 ** missing, behave as if it is empty. i.e. decrement the relevant
892 ** FK counter for each row of the current table with non-NULL keys.
893 */
894 Vdbe *v = sqlite3GetVdbe(pParse);
895 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
896 for(i=0; i<pFKey->nCol; i++){
897 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
898 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
899 }
900 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
901 }
726 continue; 902 continue;
727 } 903 }
728 assert( pFKey->nCol==1 || (aiFree && pIdx) ); 904 assert( pFKey->nCol==1 || (aiFree && pIdx) );
729 905
730 if( aiFree ){ 906 if( aiFree ){
731 aiCol = aiFree; 907 aiCol = aiFree;
732 }else{ 908 }else{
733 iCol = pFKey->aCol[0].iFrom; 909 iCol = pFKey->aCol[0].iFrom;
734 aiCol = &iCol; 910 aiCol = &iCol;
735 } 911 }
(...skipping 28 matching lines...) Expand all
764 } 940 }
765 if( regNew!=0 ){ 941 if( regNew!=0 ){
766 /* A row is being added to the child table. If a parent row cannot 942 /* A row is being added to the child table. If a parent row cannot
767 ** be found, adding the child row has violated the FK constraint. */ 943 ** be found, adding the child row has violated the FK constraint. */
768 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore); 944 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
769 } 945 }
770 946
771 sqlite3DbFree(db, aiFree); 947 sqlite3DbFree(db, aiFree);
772 } 948 }
773 949
774 /* Loop through all the foreign key constraints that refer to this table */ 950 /* Loop through all the foreign key constraints that refer to this table.
951 ** (the "child" constraints) */
775 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ 952 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
776 Index *pIdx = 0; /* Foreign key index for pFKey */ 953 Index *pIdx = 0; /* Foreign key index for pFKey */
777 SrcList *pSrc; 954 SrcList *pSrc;
778 int *aiCol = 0; 955 int *aiCol = 0;
779 956
780 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){ 957 if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
958 continue;
959 }
960
961 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
962 && !pParse->pToplevel && !pParse->isMultiWrite
963 ){
781 assert( regOld==0 && regNew!=0 ); 964 assert( regOld==0 && regNew!=0 );
782 /* Inserting a single row into a parent table cannot cause an immediate 965 /* Inserting a single row into a parent table cannot cause an immediate
783 ** foreign key violation. So do nothing in this case. */ 966 ** foreign key violation. So do nothing in this case. */
784 continue; 967 continue;
785 } 968 }
786 969
787 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ 970 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
788 if( !isIgnoreErrors || db->mallocFailed ) return; 971 if( !isIgnoreErrors || db->mallocFailed ) return;
789 continue; 972 continue;
790 } 973 }
791 assert( aiCol || pFKey->nCol==1 ); 974 assert( aiCol || pFKey->nCol==1 );
792 975
793 /* Create a SrcList structure containing a single table (the table 976 /* Create a SrcList structure containing the child table. We need the
794 ** the foreign key that refers to this table is attached to). This 977 ** child table as a SrcList for sqlite3WhereBegin() */
795 ** is required for the sqlite3WhereXXX() interface. */
796 pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 978 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
797 if( pSrc ){ 979 if( pSrc ){
798 struct SrcList_item *pItem = pSrc->a; 980 struct SrcList_item *pItem = pSrc->a;
799 pItem->pTab = pFKey->pFrom; 981 pItem->pTab = pFKey->pFrom;
800 pItem->zName = pFKey->pFrom->zName; 982 pItem->zName = pFKey->pFrom->zName;
801 pItem->pTab->nRef++; 983 pItem->pTab->nRef++;
802 pItem->iCursor = pParse->nTab++; 984 pItem->iCursor = pParse->nTab++;
803 985
804 if( regNew!=0 ){ 986 if( regNew!=0 ){
805 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1); 987 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
(...skipping 26 matching lines...) Expand all
832 ){ 1014 ){
833 u32 mask = 0; 1015 u32 mask = 0;
834 if( pParse->db->flags&SQLITE_ForeignKeys ){ 1016 if( pParse->db->flags&SQLITE_ForeignKeys ){
835 FKey *p; 1017 FKey *p;
836 int i; 1018 int i;
837 for(p=pTab->pFKey; p; p=p->pNextFrom){ 1019 for(p=pTab->pFKey; p; p=p->pNextFrom){
838 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); 1020 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
839 } 1021 }
840 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ 1022 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
841 Index *pIdx = 0; 1023 Index *pIdx = 0;
842 locateFkeyIndex(pParse, pTab, p, &pIdx, 0); 1024 sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
843 if( pIdx ){ 1025 if( pIdx ){
844 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); 1026 for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
845 } 1027 }
846 } 1028 }
847 } 1029 }
848 return mask; 1030 return mask;
849 } 1031 }
850 1032
1033
851 /* 1034 /*
852 ** This function is called before generating code to update or delete a 1035 ** This function is called before generating code to update or delete a
853 ** row contained in table pTab. If the operation is a DELETE, then 1036 ** row contained in table pTab. If the operation is a DELETE, then
854 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points 1037 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
855 ** to an array of size N, where N is the number of columns in table pTab. 1038 ** to an array of size N, where N is the number of columns in table pTab.
856 ** If the i'th column is not modified by the UPDATE, then the corresponding 1039 ** If the i'th column is not modified by the UPDATE, then the corresponding
857 ** entry in the aChange[] array is set to -1. If the column is modified, 1040 ** entry in the aChange[] array is set to -1. If the column is modified,
858 ** the value is 0 or greater. Parameter chngRowid is set to true if the 1041 ** the value is 0 or greater. Parameter chngRowid is set to true if the
859 ** UPDATE statement modifies the rowid fields of the table. 1042 ** UPDATE statement modifies the rowid fields of the table.
860 ** 1043 **
861 ** If any foreign key processing will be required, this function returns 1044 ** If any foreign key processing will be required, this function returns
862 ** true. If there is no foreign key related processing, this function 1045 ** true. If there is no foreign key related processing, this function
863 ** returns false. 1046 ** returns false.
864 */ 1047 */
865 int sqlite3FkRequired( 1048 int sqlite3FkRequired(
866 Parse *pParse, /* Parse context */ 1049 Parse *pParse, /* Parse context */
867 Table *pTab, /* Table being modified */ 1050 Table *pTab, /* Table being modified */
868 int *aChange, /* Non-NULL for UPDATE operations */ 1051 int *aChange, /* Non-NULL for UPDATE operations */
869 int chngRowid /* True for UPDATE that affects rowid */ 1052 int chngRowid /* True for UPDATE that affects rowid */
870 ){ 1053 ){
871 if( pParse->db->flags&SQLITE_ForeignKeys ){ 1054 if( pParse->db->flags&SQLITE_ForeignKeys ){
872 if( !aChange ){ 1055 if( !aChange ){
873 /* A DELETE operation. Foreign key processing is required if the 1056 /* A DELETE operation. Foreign key processing is required if the
874 ** table in question is either the child or parent table for any 1057 ** table in question is either the child or parent table for any
875 ** foreign key constraint. */ 1058 ** foreign key constraint. */
876 return (sqlite3FkReferences(pTab) || pTab->pFKey); 1059 return (sqlite3FkReferences(pTab) || pTab->pFKey);
877 }else{ 1060 }else{
878 /* This is an UPDATE. Foreign key processing is only required if the 1061 /* This is an UPDATE. Foreign key processing is only required if the
879 ** operation modifies one or more child or parent key columns. */ 1062 ** operation modifies one or more child or parent key columns. */
880 int i;
881 FKey *p; 1063 FKey *p;
882 1064
883 /* Check if any child key columns are being modified. */ 1065 /* Check if any child key columns are being modified. */
884 for(p=pTab->pFKey; p; p=p->pNextFrom){ 1066 for(p=pTab->pFKey; p; p=p->pNextFrom){
885 for(i=0; i<p->nCol; i++){ 1067 if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
886 int iChildKey = p->aCol[i].iFrom;
887 if( aChange[iChildKey]>=0 ) return 1;
888 if( iChildKey==pTab->iPKey && chngRowid ) return 1;
889 }
890 } 1068 }
891 1069
892 /* Check if any parent key columns are being modified. */ 1070 /* Check if any parent key columns are being modified. */
893 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ 1071 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
894 for(i=0; i<p->nCol; i++){ 1072 if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
895 char *zKey = p->aCol[i].zCol;
896 int iKey;
897 for(iKey=0; iKey<pTab->nCol; iKey++){
898 Column *pCol = &pTab->aCol[iKey];
899 if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
900 if( aChange[iKey]>=0 ) return 1;
901 if( iKey==pTab->iPKey && chngRowid ) return 1;
902 }
903 }
904 }
905 } 1073 }
906 } 1074 }
907 } 1075 }
908 return 0; 1076 return 0;
909 } 1077 }
910 1078
911 /* 1079 /*
912 ** This function is called when an UPDATE or DELETE operation is being 1080 ** This function is called when an UPDATE or DELETE operation is being
913 ** compiled on table pTab, which is the parent table of foreign-key pFKey. 1081 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
914 ** If the current operation is an UPDATE, then the pChanges parameter is 1082 ** If the current operation is an UPDATE, then the pChanges parameter is
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
957 int nFrom; /* Length in bytes of zFrom */ 1125 int nFrom; /* Length in bytes of zFrom */
958 Index *pIdx = 0; /* Parent key index for this FK */ 1126 Index *pIdx = 0; /* Parent key index for this FK */
959 int *aiCol = 0; /* child table cols -> parent key cols */ 1127 int *aiCol = 0; /* child table cols -> parent key cols */
960 TriggerStep *pStep = 0; /* First (only) step of trigger program */ 1128 TriggerStep *pStep = 0; /* First (only) step of trigger program */
961 Expr *pWhere = 0; /* WHERE clause of trigger step */ 1129 Expr *pWhere = 0; /* WHERE clause of trigger step */
962 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ 1130 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
963 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */ 1131 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
964 int i; /* Iterator variable */ 1132 int i; /* Iterator variable */
965 Expr *pWhen = 0; /* WHEN clause for the trigger */ 1133 Expr *pWhen = 0; /* WHEN clause for the trigger */
966 1134
967 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; 1135 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
968 assert( aiCol || pFKey->nCol==1 ); 1136 assert( aiCol || pFKey->nCol==1 );
969 1137
970 for(i=0; i<pFKey->nCol; i++){ 1138 for(i=0; i<pFKey->nCol; i++){
971 Token tOld = { "old", 3 }; /* Literal "old" token */ 1139 Token tOld = { "old", 3 }; /* Literal "old" token */
972 Token tNew = { "new", 3 }; /* Literal "new" token */ 1140 Token tNew = { "new", 3 }; /* Literal "new" token */
973 Token tFromCol; /* Name of column in child table */ 1141 Token tFromCol; /* Name of column in child table */
974 Token tToCol; /* Name of column in parent table */ 1142 Token tToCol; /* Name of column in parent table */
975 int iFromCol; /* Idx of column in child table */ 1143 int iFromCol; /* Idx of column in child table */
976 Expr *pEq; /* tFromCol = OLD.tToCol */ 1144 Expr *pEq; /* tFromCol = OLD.tToCol */
977 1145
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
1040 1208
1041 zFrom = pFKey->pFrom->zName; 1209 zFrom = pFKey->pFrom->zName;
1042 nFrom = sqlite3Strlen30(zFrom); 1210 nFrom = sqlite3Strlen30(zFrom);
1043 1211
1044 if( action==OE_Restrict ){ 1212 if( action==OE_Restrict ){
1045 Token tFrom; 1213 Token tFrom;
1046 Expr *pRaise; 1214 Expr *pRaise;
1047 1215
1048 tFrom.z = zFrom; 1216 tFrom.z = zFrom;
1049 tFrom.n = nFrom; 1217 tFrom.n = nFrom;
1050 pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed"); 1218 pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
1051 if( pRaise ){ 1219 if( pRaise ){
1052 pRaise->affinity = OE_Abort; 1220 pRaise->affinity = OE_Abort;
1053 } 1221 }
1054 pSelect = sqlite3SelectNew(pParse, 1222 pSelect = sqlite3SelectNew(pParse,
1055 sqlite3ExprListAppend(pParse, 0, pRaise), 1223 sqlite3ExprListAppend(pParse, 0, pRaise),
1056 sqlite3SrcListAppend(db, 0, &tFrom, 0), 1224 sqlite3SrcListAppend(db, 0, &tFrom, 0),
1057 pWhere, 1225 pWhere,
1058 0, 0, 0, 0, 0, 0 1226 0, 0, 0, 0, 0, 0
1059 ); 1227 );
1060 pWhere = 0; 1228 pWhere = 0;
(...skipping 27 matching lines...) Expand all
1088 db->lookaside.bEnabled = enableLookaside; 1256 db->lookaside.bEnabled = enableLookaside;
1089 1257
1090 sqlite3ExprDelete(db, pWhere); 1258 sqlite3ExprDelete(db, pWhere);
1091 sqlite3ExprDelete(db, pWhen); 1259 sqlite3ExprDelete(db, pWhen);
1092 sqlite3ExprListDelete(db, pList); 1260 sqlite3ExprListDelete(db, pList);
1093 sqlite3SelectDelete(db, pSelect); 1261 sqlite3SelectDelete(db, pSelect);
1094 if( db->mallocFailed==1 ){ 1262 if( db->mallocFailed==1 ){
1095 fkTriggerDelete(db, pTrigger); 1263 fkTriggerDelete(db, pTrigger);
1096 return 0; 1264 return 0;
1097 } 1265 }
1266 assert( pStep!=0 );
1098 1267
1099 switch( action ){ 1268 switch( action ){
1100 case OE_Restrict: 1269 case OE_Restrict:
1101 pStep->op = TK_SELECT; 1270 pStep->op = TK_SELECT;
1102 break; 1271 break;
1103 case OE_Cascade: 1272 case OE_Cascade:
1104 if( !pChanges ){ 1273 if( !pChanges ){
1105 pStep->op = TK_DELETE; 1274 pStep->op = TK_DELETE;
1106 break; 1275 break;
1107 } 1276 }
(...skipping 11 matching lines...) Expand all
1119 } 1288 }
1120 1289
1121 /* 1290 /*
1122 ** This function is called when deleting or updating a row to implement 1291 ** This function is called when deleting or updating a row to implement
1123 ** any required CASCADE, SET NULL or SET DEFAULT actions. 1292 ** any required CASCADE, SET NULL or SET DEFAULT actions.
1124 */ 1293 */
1125 void sqlite3FkActions( 1294 void sqlite3FkActions(
1126 Parse *pParse, /* Parse context */ 1295 Parse *pParse, /* Parse context */
1127 Table *pTab, /* Table being updated or deleted from */ 1296 Table *pTab, /* Table being updated or deleted from */
1128 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ 1297 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
1129 int regOld /* Address of array containing old row */ 1298 int regOld, /* Address of array containing old row */
1299 int *aChange, /* Array indicating UPDATEd columns (or 0) */
1300 int bChngRowid /* True if rowid is UPDATEd */
1130 ){ 1301 ){
1131 /* If foreign-key support is enabled, iterate through all FKs that 1302 /* If foreign-key support is enabled, iterate through all FKs that
1132 ** refer to table pTab. If there is an action associated with the FK 1303 ** refer to table pTab. If there is an action associated with the FK
1133 ** for this operation (either update or delete), invoke the associated 1304 ** for this operation (either update or delete), invoke the associated
1134 ** trigger sub-program. */ 1305 ** trigger sub-program. */
1135 if( pParse->db->flags&SQLITE_ForeignKeys ){ 1306 if( pParse->db->flags&SQLITE_ForeignKeys ){
1136 FKey *pFKey; /* Iterator variable */ 1307 FKey *pFKey; /* Iterator variable */
1137 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ 1308 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
1138 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges); 1309 if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
1139 if( pAction ){ 1310 Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
1140 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0); 1311 if( pAct ){
1312 sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
1313 }
1141 } 1314 }
1142 } 1315 }
1143 } 1316 }
1144 } 1317 }
1145 1318
1146 #endif /* ifndef SQLITE_OMIT_TRIGGER */ 1319 #endif /* ifndef SQLITE_OMIT_TRIGGER */
1147 1320
1148 /* 1321 /*
1149 ** Free all memory associated with foreign key definitions attached to 1322 ** Free all memory associated with foreign key definitions attached to
1150 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash 1323 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
1151 ** hash table. 1324 ** hash table.
1152 */ 1325 */
1153 void sqlite3FkDelete(sqlite3 *db, Table *pTab){ 1326 void sqlite3FkDelete(sqlite3 *db, Table *pTab){
1154 FKey *pFKey; /* Iterator variable */ 1327 FKey *pFKey; /* Iterator variable */
1155 FKey *pNext; /* Copy of pFKey->pNextFrom */ 1328 FKey *pNext; /* Copy of pFKey->pNextFrom */
1156 1329
1157 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); 1330 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
1158 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ 1331 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
1159 1332
1160 /* Remove the FK from the fkeyHash hash table. */ 1333 /* Remove the FK from the fkeyHash hash table. */
1161 if( !db || db->pnBytesFreed==0 ){ 1334 if( !db || db->pnBytesFreed==0 ){
1162 if( pFKey->pPrevTo ){ 1335 if( pFKey->pPrevTo ){
1163 pFKey->pPrevTo->pNextTo = pFKey->pNextTo; 1336 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
1164 }else{ 1337 }else{
1165 void *p = (void *)pFKey->pNextTo; 1338 void *p = (void *)pFKey->pNextTo;
1166 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); 1339 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
1167 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p); 1340 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
1168 } 1341 }
1169 if( pFKey->pNextTo ){ 1342 if( pFKey->pNextTo ){
1170 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; 1343 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
1171 } 1344 }
1172 } 1345 }
1173 1346
1174 /* EV: R-30323-21917 Each foreign key constraint in SQLite is 1347 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
1175 ** classified as either immediate or deferred. 1348 ** classified as either immediate or deferred.
1176 */ 1349 */
1177 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 ); 1350 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
1178 1351
1179 /* Delete any triggers created to implement actions for this FK. */ 1352 /* Delete any triggers created to implement actions for this FK. */
1180 #ifndef SQLITE_OMIT_TRIGGER 1353 #ifndef SQLITE_OMIT_TRIGGER
1181 fkTriggerDelete(db, pFKey->apTrigger[0]); 1354 fkTriggerDelete(db, pFKey->apTrigger[0]);
1182 fkTriggerDelete(db, pFKey->apTrigger[1]); 1355 fkTriggerDelete(db, pFKey->apTrigger[1]);
1183 #endif 1356 #endif
1184 1357
1185 pNext = pFKey->pNextFrom; 1358 pNext = pFKey->pNextFrom;
1186 sqlite3DbFree(db, pFKey); 1359 sqlite3DbFree(db, pFKey);
1187 } 1360 }
1188 } 1361 }
1189 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ 1362 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
OLDNEW
« no previous file with comments | « third_party/sqlite/sqlite-src-3080704/src/fault.c ('k') | third_party/sqlite/sqlite-src-3080704/src/func.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698