blob: 1e64310ead3d66e8cd1d596782f14ac00833ac9c [file] [log] [blame]
dan1da40a32009-09-19 17:00:31 +00001/*
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
dan75cbd982009-09-21 16:06:03 +000017#ifndef SQLITE_OMIT_TRIGGER
dan1da40a32009-09-19 17:00:31 +000018
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*/
151static 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
240static 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++){
dan36062642009-09-21 18:56:23 +0000261 int iReg = aiCol[i] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000262 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
dan36062642009-09-21 18:56:23 +0000280 if( pFKey->nCol>1 ){
dan1da40a32009-09-19 17:00:31 +0000281 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{
dan36062642009-09-21 18:56:23 +0000289 int iReg = aiCol[0] + regData + 1;
dan1da40a32009-09-19 17:00:31 +0000290 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
310static 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 }
danf59c5ca2009-09-22 16:55:38 +0000367 if( pWInfo ){
368 sqlite3WhereEnd(pWInfo);
369 }
dan1da40a32009-09-19 17:00:31 +0000370
371 /* Clean up the WHERE clause constructed above. */
372 sqlite3ExprDelete(db, pWhere);
373}
374
375/*
376** This function returns a pointer to the head of a linked list of FK
377** constraints that refer to the table passed as an argument. For example,
378** given the following schema:
379**
380** CREATE TABLE t1(a PRIMARY KEY);
381** CREATE TABLE t2(b REFERENCES t1(a);
382**
383** Calling this function with table "t1" as an argument returns a pointer
384** to the FKey structure representing the foreign key constraint on table
385** "t2". Calling this function with "t2" as the argument would return a
386** NULL pointer (as there are no FK constraints that refer to t2).
387*/
388static FKey *fkRefering(Table *pTab){
389 int nName = sqlite3Strlen30(pTab->zName);
390 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
391}
392
dan75cbd982009-09-21 16:06:03 +0000393static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
394 if( p ){
395 TriggerStep *pStep = p->step_list;
396 sqlite3ExprDelete(dbMem, pStep->pWhere);
397 sqlite3ExprListDelete(dbMem, pStep->pExprList);
drh788536b2009-09-23 03:01:58 +0000398 sqlite3ExprDelete(dbMem, p->pWhen);
dan75cbd982009-09-21 16:06:03 +0000399 sqlite3DbFree(dbMem, p);
400 }
401}
402
dan1da40a32009-09-19 17:00:31 +0000403void sqlite3FkCheck(
404 Parse *pParse, /* Parse context */
405 Table *pTab, /* Row is being deleted from this table */
406 ExprList *pChanges, /* Changed columns if this is an UPDATE */
407 int regOld, /* Previous row data is stored here */
408 int regNew /* New row data is stored here */
409){
410 sqlite3 *db = pParse->db; /* Database handle */
411 Vdbe *v; /* VM to write code to */
412 FKey *pFKey; /* Used to iterate through FKs */
413 int iDb; /* Index of database containing pTab */
414 const char *zDb; /* Name of database containing pTab */
415
416 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
417 || (!pChanges && !regOld && regNew) /* INSERT operation */
418 || (!pChanges && regOld && !regNew) /* DELETE operation */
419 );
420
421 /* If foreign-keys are disabled, this function is a no-op. */
422 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
423
424 v = sqlite3GetVdbe(pParse);
425 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
426 zDb = db->aDb[iDb].zName;
427
428 /* Loop through all the foreign key constraints attached to the table. */
429 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
430 Table *pTo; /* Table referenced by this FK */
431 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000432 int *aiFree = 0;
433 int *aiCol;
434 int iCol;
435 int i;
dan1da40a32009-09-19 17:00:31 +0000436
437 if( pFKey->isDeferred==0 && regNew==0 ) continue;
438
439 /* Find the table this foreign key references. Also find a unique
440 ** index on the referenced table that corresponds to the key columns.
441 ** If either of these things cannot be located, set an error in pParse
442 ** and return early. */
443 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
dan36062642009-09-21 18:56:23 +0000444 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return;
445 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000446
447 /* If the key does not overlap with the pChanges list, skip this FK. */
448 if( pChanges ){
449 /* TODO */
450 }
451
dan36062642009-09-21 18:56:23 +0000452 if( aiFree ){
453 aiCol = aiFree;
454 }else{
455 iCol = pFKey->aCol[0].iFrom;
456 aiCol = &iCol;
457 }
458 for(i=0; i<pFKey->nCol; i++){
459 if( aiCol[i]==pTab->iPKey ){
460 aiCol[i] = -1;
461 }
462 }
463
dan1da40a32009-09-19 17:00:31 +0000464 /* Take a shared-cache advisory read-lock on the referenced table.
465 ** Allocate a cursor to use to search the unique index on the FK
466 ** columns in the referenced table. */
467 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
468 pParse->nTab++;
469
470 if( regOld!=0 && pFKey->isDeferred ){
471 fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
472 }
473 if( regNew!=0 ){
474 fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
475 }
476
dan36062642009-09-21 18:56:23 +0000477 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000478 }
479
480 /* Loop through all the foreign key constraints that refer to this table */
481 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
482 int iGoto; /* Address of OP_Goto instruction */
483 Index *pIdx = 0; /* Foreign key index for pFKey */
484 SrcList *pSrc;
485 int *aiCol = 0;
486
487 /* For immediate constraints, skip this scan if:
488 **
489 ** 1) this is an INSERT operation, or
490 ** 2) an UPDATE operation and the FK action is a trigger-action, or
491 ** 3) a DELETE operation and the FK action is a trigger-action.
492 **
493 ** A "trigger-action" is one of CASCADE, SET DEFAULT or SET NULL.
494 */
495 if( pFKey->isDeferred==0 ){
496 if( regOld==0 ) continue; /* 1 */
497 if( regNew!=0 && pFKey->updateConf>OE_Restrict ) continue; /* 2 */
498 if( regNew==0 && pFKey->deleteConf>OE_Restrict ) continue; /* 3 */
499 }
500
501 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
502 assert( aiCol || pFKey->nCol==1 );
503
504 /* Check if this update statement has modified any of the key columns
505 ** for this foreign key constraint. If it has not, there is no need
506 ** to search the referencing table for rows in violation. This is
507 ** just an optimization. Things would work fine without this check. */
508 if( pChanges ){
509 /* TODO */
510 }
511
512 /* Create a SrcList structure containing a single table (the table
513 ** the foreign key that refers to this table is attached to). This
514 ** is required for the sqlite3WhereXXX() interface. */
515 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000516 if( pSrc ){
517 pSrc->a->pTab = pFKey->pFrom;
518 pSrc->a->pTab->nRef++;
519 pSrc->a->iCursor = pParse->nTab++;
520
521 /* If this is an UPDATE, and none of the columns associated with this
522 ** FK have been modified, do not scan the referencing table. Unlike
523 ** the compile-time test implemented above, this is not just an
524 ** optimization. It is required so that immediate foreign keys do not
525 ** throw exceptions when the user executes a statement like:
526 **
527 ** UPDATE refd_table SET refd_column = refd_column
528 */
529 if( pChanges ){
530 int i;
531 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
532 for(i=0; i<pFKey->nCol; i++){
533 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
534 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
535 }
536 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
dan1da40a32009-09-19 17:00:31 +0000537 }
danf59c5ca2009-09-22 16:55:38 +0000538
539 if( regNew!=0 && pFKey->isDeferred ){
540 fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
541 }
542 if( regOld!=0 ){
543 /* If there is a RESTRICT action configured for the current operation
544 ** on the referenced table of this FK, then throw an exception
545 ** immediately if the FK constraint is violated, even if this is a
546 ** deferred trigger. That's what RESTRICT means. To defer checking
547 ** the constraint, the FK should specify NO ACTION (represented
548 ** using OE_None). NO ACTION is the default. */
549 fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
550 (pChanges!=0 && pFKey->updateConf!=OE_Restrict)
551 || (pChanges==0 && pFKey->deleteConf!=OE_Restrict)
552 );
553 }
554
555 if( pChanges ){
556 sqlite3VdbeJumpHere(v, iGoto);
557 }
558 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000559 }
dan1da40a32009-09-19 17:00:31 +0000560 sqlite3DbFree(db, aiCol);
561 }
562}
563
564#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
565
566/*
567** This function is called before generating code to update or delete a
568** row contained in table pTab. If the operation is an update, then
569** pChanges is a pointer to the list of columns to modify. If this is a
570** delete, then pChanges is NULL.
571*/
572u32 sqlite3FkOldmask(
573 Parse *pParse, /* Parse context */
574 Table *pTab, /* Table being modified */
575 ExprList *pChanges /* Non-NULL for UPDATE operations */
576){
577 u32 mask = 0;
578 if( pParse->db->flags&SQLITE_ForeignKeys ){
579 FKey *p;
580 int i;
581 for(p=pTab->pFKey; p; p=p->pNextFrom){
582 if( pChanges || p->isDeferred ){
583 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
584 }
585 }
586 for(p=fkRefering(pTab); p; p=p->pNextTo){
587 Index *pIdx = 0;
588 locateFkeyIndex(0, pTab, p, &pIdx, 0);
589 if( pIdx ){
590 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
591 }
592 }
593 }
594 return mask;
595}
596
597/*
598** This function is called before generating code to update or delete a
599** row contained in table pTab. If the operation is an update, then
600** pChanges is a pointer to the list of columns to modify. If this is a
601** delete, then pChanges is NULL.
602**
603** If any foreign key processing will be required, this function returns
604** true. If there is no foreign key related processing, this function
605** returns false.
606*/
607int sqlite3FkRequired(
608 Parse *pParse, /* Parse context */
609 Table *pTab, /* Table being modified */
610 ExprList *pChanges /* Non-NULL for UPDATE operations */
611){
612 if( pParse->db->flags&SQLITE_ForeignKeys ){
613 FKey *p;
614 for(p=pTab->pFKey; p; p=p->pNextFrom){
615 if( pChanges || p->isDeferred ) return 1;
616 }
617 if( fkRefering(pTab) ) return 1;
618 }
619 return 0;
620}
621
622static Trigger *fkActionTrigger(
623 Parse *pParse,
624 Table *pTab, /* Table being updated or deleted from */
625 FKey *pFKey, /* Foreign key to get action for */
626 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
627){
628 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000629 int action; /* One of OE_None, OE_Cascade etc. */
630 Trigger *pTrigger; /* Trigger definition to return */
dan1da40a32009-09-19 17:00:31 +0000631
632 if( pChanges ){
633 action = pFKey->updateConf;
634 pTrigger = pFKey->pOnUpdate;
635 }else{
636 action = pFKey->deleteConf;
637 pTrigger = pFKey->pOnDelete;
638 }
639
640 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
641 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
642
643 if( action>OE_Restrict && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000644 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan1da40a32009-09-19 17:00:31 +0000645 char const *zFrom; /* Name of referencing table */
646 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000647 Index *pIdx = 0; /* Parent key index for this FK */
648 int *aiCol = 0; /* child table cols -> parent key cols */
649 TriggerStep *pStep; /* First (only) step of trigger program */
650 Expr *pWhere = 0; /* WHERE clause of trigger step */
651 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
652 int i; /* Iterator variable */
drh788536b2009-09-23 03:01:58 +0000653 Expr *pWhen = 0; /* WHEN clause for the trigger */
dan1da40a32009-09-19 17:00:31 +0000654
655 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
656 assert( aiCol || pFKey->nCol==1 );
657
dan1da40a32009-09-19 17:00:31 +0000658 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000659 Token tOld = { "old", 3 }; /* Literal "old" token */
660 Token tNew = { "new", 3 }; /* Literal "new" token */
dan29c7f9c2009-09-22 15:53:47 +0000661 Token tFromCol; /* Name of column in referencing table */
662 Token tToCol; /* Name of column in referenced table */
663 int iFromCol; /* Idx of column in referencing table */
664 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000665
666 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
667 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
668 tFromCol.z = iFromCol<0 ? "oid" : pFKey->pFrom->aCol[iFromCol].zName;
669
670 tToCol.n = sqlite3Strlen30(tToCol.z);
671 tFromCol.n = sqlite3Strlen30(tFromCol.z);
672
673 /* Create the expression "zFromCol = OLD.zToCol" */
674 pEq = sqlite3PExpr(pParse, TK_EQ,
675 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
676 sqlite3PExpr(pParse, TK_DOT,
677 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
678 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
679 , 0)
680 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000681 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000682
drh788536b2009-09-23 03:01:58 +0000683 /* For ON UPDATE, construct the next term of the WHEN clause.
684 ** The final WHEN clause will be like this:
685 **
686 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
687 */
688 if( pChanges ){
689 pEq = sqlite3PExpr(pParse, TK_IS,
690 sqlite3PExpr(pParse, TK_DOT,
691 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
692 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
693 0),
694 sqlite3PExpr(pParse, TK_DOT,
695 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
696 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
697 0),
698 0);
699 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
700 }
701
dan1da40a32009-09-19 17:00:31 +0000702 if( action!=OE_Cascade || pChanges ){
703 Expr *pNew;
704 if( action==OE_Cascade ){
705 pNew = sqlite3PExpr(pParse, TK_DOT,
706 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
707 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
708 , 0);
709 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000710 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000711 if( pDflt ){
712 pNew = sqlite3ExprDup(db, pDflt, 0);
713 }else{
714 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
715 }
716 }else{
717 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
718 }
719 pList = sqlite3ExprListAppend(pParse, pList, pNew);
720 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
721 }
722 }
dan29c7f9c2009-09-22 15:53:47 +0000723 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +0000724
dan29c7f9c2009-09-22 15:53:47 +0000725 /* If pTab->dbMem==0, then the table may be part of a shared-schema.
726 ** Disable the lookaside buffer before allocating space for the
727 ** trigger definition in this case. */
728 enableLookaside = db->lookaside.bEnabled;
729 if( pTab->dbMem==0 ){
730 db->lookaside.bEnabled = 0;
731 }
732
733 zFrom = pFKey->pFrom->zName;
734 nFrom = sqlite3Strlen30(zFrom);
735 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
736 sizeof(Trigger) + /* struct Trigger */
737 sizeof(TriggerStep) + /* Single step in trigger program */
738 nFrom + 1 /* Space for pStep->target.z */
739 );
740 if( pTrigger ){
741 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
742 pStep->target.z = (char *)&pStep[1];
743 pStep->target.n = nFrom;
744 memcpy((char *)pStep->target.z, zFrom, nFrom);
745
746 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
747 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
drh788536b2009-09-23 03:01:58 +0000748 if( pWhen ){
749 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
750 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
751 }
dan29c7f9c2009-09-22 15:53:47 +0000752 }
753
754 /* Re-enable the lookaside buffer, if it was disabled earlier. */
755 db->lookaside.bEnabled = enableLookaside;
756
drh788536b2009-09-23 03:01:58 +0000757 sqlite3ExprDelete(db, pWhere);
758 sqlite3ExprDelete(db, pWhen);
759 sqlite3ExprListDelete(db, pList);
dan29c7f9c2009-09-22 15:53:47 +0000760 if( db->mallocFailed==1 ){
761 fkTriggerDelete(db, pTrigger);
762 return 0;
763 }
dan1da40a32009-09-19 17:00:31 +0000764
765 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
766 pStep->pTrig = pTrigger;
767 pTrigger->pSchema = pTab->pSchema;
768 pTrigger->pTabSchema = pTab->pSchema;
769
770 if( pChanges ){
771 pFKey->pOnUpdate = pTrigger;
772 pTrigger->op = TK_UPDATE;
773 pStep->op = TK_UPDATE;
774 }else{
775 pFKey->pOnDelete = pTrigger;
776 pTrigger->op = TK_DELETE;
777 pStep->op = (action==OE_Cascade)?TK_DELETE:TK_UPDATE;
778 }
779 }
780
781 return pTrigger;
782}
783
dan1da40a32009-09-19 17:00:31 +0000784/*
785** This function is called when deleting or updating a row to implement
786** any required CASCADE, SET NULL or SET DEFAULT actions.
787*/
788void sqlite3FkActions(
789 Parse *pParse, /* Parse context */
790 Table *pTab, /* Table being updated or deleted from */
791 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
792 int regOld /* Address of array containing old row */
793){
794 /* If foreign-key support is enabled, iterate through all FKs that
795 ** refer to table pTab. If there is an action associated with the FK
796 ** for this operation (either update or delete), invoke the associated
797 ** trigger sub-program. */
798 if( pParse->db->flags&SQLITE_ForeignKeys ){
799 FKey *pFKey; /* Iterator variable */
800 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
801 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
802 if( pAction ){
803 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
804 }
805 }
806 }
807}
808
dan75cbd982009-09-21 16:06:03 +0000809#endif /* ifndef SQLITE_OMIT_TRIGGER */
810
dan1da40a32009-09-19 17:00:31 +0000811/*
812** Free all memory associated with foreign key definitions attached to
813** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
814** hash table.
815*/
816void sqlite3FkDelete(Table *pTab){
817 FKey *pFKey; /* Iterator variable */
818 FKey *pNext; /* Copy of pFKey->pNextFrom */
819
820 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
821
822 /* Remove the FK from the fkeyHash hash table. */
823 if( pFKey->pPrevTo ){
824 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
825 }else{
826 void *data = (void *)pFKey->pNextTo;
827 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
828 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
829 }
830 if( pFKey->pNextTo ){
831 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
832 }
833
834 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000835#ifndef SQLITE_OMIT_TRIGGER
dan1da40a32009-09-19 17:00:31 +0000836 fkTriggerDelete(pTab->dbMem, pFKey->pOnDelete);
837 fkTriggerDelete(pTab->dbMem, pFKey->pOnUpdate);
dan75cbd982009-09-21 16:06:03 +0000838#endif
dan1da40a32009-09-19 17:00:31 +0000839
840 /* Delete the memory allocated for the FK structure. */
841 pNext = pFKey->pNextFrom;
842 sqlite3DbFree(pTab->dbMem, pFKey);
843 }
844}
dan75cbd982009-09-21 16:06:03 +0000845#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */