blob: 8e5a6a96fe0739d56dcd7c0d76f93f41501c54b7 [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++){
261 int iReg = pFKey->aCol[i].iFrom + regData + 1;
262 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
263 }
264
265 if( pIdx==0 ){
266 /* If pIdx is NULL, then the foreign key constraint references the
267 ** INTEGER PRIMARY KEY column in the referenced table (table pTab). */
268 int iReg = pFKey->aCol[0].iFrom + regData + 1;
269 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
270 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iReg);
271 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
272 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
273 }else{
274 int regRec = sqlite3GetTempReg(pParse);
275 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
276
277 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
278 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
279
280 if( aiCol ){
281 int nCol = pFKey->nCol;
282 int regTemp = sqlite3GetTempRange(pParse, nCol);
283 for(i=0; i<nCol; i++){
284 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
285 }
286 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
287 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
288 }else{
289 int iReg = pFKey->aCol[0].iFrom + regData + 1;
290 sqlite3VdbeAddOp3(v, OP_MakeRecord, iReg, 1, regRec);
291 sqlite3IndexAffinityStr(v, pIdx);
292 }
293
294 sqlite3VdbeAddOp3(v, OP_Found, iCur, iOk, regRec);
295 sqlite3ReleaseTempReg(pParse, regRec);
296 }
297
298 if( pFKey->isDeferred ){
299 assert( nIncr==1 || nIncr==-1 );
300 sqlite3VdbeAddOp1(v, OP_DeferredCons, nIncr);
301 }else{
302 sqlite3HaltConstraint(
303 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
304 );
305 }
306
307 sqlite3VdbeResolveLabel(v, iOk);
308}
309
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 }
367 sqlite3WhereEnd(pWInfo);
368
369 /* Clean up the WHERE clause constructed above. */
370 sqlite3ExprDelete(db, pWhere);
371}
372
373/*
374** This function returns a pointer to the head of a linked list of FK
375** constraints that refer to the table passed as an argument. For example,
376** given the following schema:
377**
378** CREATE TABLE t1(a PRIMARY KEY);
379** CREATE TABLE t2(b REFERENCES t1(a);
380**
381** Calling this function with table "t1" as an argument returns a pointer
382** to the FKey structure representing the foreign key constraint on table
383** "t2". Calling this function with "t2" as the argument would return a
384** NULL pointer (as there are no FK constraints that refer to t2).
385*/
386static FKey *fkRefering(Table *pTab){
387 int nName = sqlite3Strlen30(pTab->zName);
388 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
389}
390
dan75cbd982009-09-21 16:06:03 +0000391static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
392 if( p ){
393 TriggerStep *pStep = p->step_list;
394 sqlite3ExprDelete(dbMem, pStep->pWhere);
395 sqlite3ExprListDelete(dbMem, pStep->pExprList);
396 sqlite3DbFree(dbMem, p);
397 }
398}
399
dan1da40a32009-09-19 17:00:31 +0000400void sqlite3FkCheck(
401 Parse *pParse, /* Parse context */
402 Table *pTab, /* Row is being deleted from this table */
403 ExprList *pChanges, /* Changed columns if this is an UPDATE */
404 int regOld, /* Previous row data is stored here */
405 int regNew /* New row data is stored here */
406){
407 sqlite3 *db = pParse->db; /* Database handle */
408 Vdbe *v; /* VM to write code to */
409 FKey *pFKey; /* Used to iterate through FKs */
410 int iDb; /* Index of database containing pTab */
411 const char *zDb; /* Name of database containing pTab */
412
413 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
414 || (!pChanges && !regOld && regNew) /* INSERT operation */
415 || (!pChanges && regOld && !regNew) /* DELETE operation */
416 );
417
418 /* If foreign-keys are disabled, this function is a no-op. */
419 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
420
421 v = sqlite3GetVdbe(pParse);
422 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
423 zDb = db->aDb[iDb].zName;
424
425 /* Loop through all the foreign key constraints attached to the table. */
426 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
427 Table *pTo; /* Table referenced by this FK */
428 Index *pIdx = 0; /* Index on key columns in pTo */
429 int *aiCol = 0;
430
431 if( pFKey->isDeferred==0 && regNew==0 ) continue;
432
433 /* Find the table this foreign key references. Also find a unique
434 ** index on the referenced table that corresponds to the key columns.
435 ** If either of these things cannot be located, set an error in pParse
436 ** and return early. */
437 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
438 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiCol) ) return;
439 assert( pFKey->nCol==1 || (aiCol && pIdx) );
440
441 /* If the key does not overlap with the pChanges list, skip this FK. */
442 if( pChanges ){
443 /* TODO */
444 }
445
446 /* Take a shared-cache advisory read-lock on the referenced table.
447 ** Allocate a cursor to use to search the unique index on the FK
448 ** columns in the referenced table. */
449 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
450 pParse->nTab++;
451
452 if( regOld!=0 && pFKey->isDeferred ){
453 fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
454 }
455 if( regNew!=0 ){
456 fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
457 }
458
459 sqlite3DbFree(db, aiCol);
460 }
461
462 /* Loop through all the foreign key constraints that refer to this table */
463 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
464 int iGoto; /* Address of OP_Goto instruction */
465 Index *pIdx = 0; /* Foreign key index for pFKey */
466 SrcList *pSrc;
467 int *aiCol = 0;
468
469 /* For immediate constraints, skip this scan if:
470 **
471 ** 1) this is an INSERT operation, or
472 ** 2) an UPDATE operation and the FK action is a trigger-action, or
473 ** 3) a DELETE operation and the FK action is a trigger-action.
474 **
475 ** A "trigger-action" is one of CASCADE, SET DEFAULT or SET NULL.
476 */
477 if( pFKey->isDeferred==0 ){
478 if( regOld==0 ) continue; /* 1 */
479 if( regNew!=0 && pFKey->updateConf>OE_Restrict ) continue; /* 2 */
480 if( regNew==0 && pFKey->deleteConf>OE_Restrict ) continue; /* 3 */
481 }
482
483 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
484 assert( aiCol || pFKey->nCol==1 );
485
486 /* Check if this update statement has modified any of the key columns
487 ** for this foreign key constraint. If it has not, there is no need
488 ** to search the referencing table for rows in violation. This is
489 ** just an optimization. Things would work fine without this check. */
490 if( pChanges ){
491 /* TODO */
492 }
493
494 /* Create a SrcList structure containing a single table (the table
495 ** the foreign key that refers to this table is attached to). This
496 ** is required for the sqlite3WhereXXX() interface. */
497 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
498 if( !pSrc ) return;
499 pSrc->a->pTab = pFKey->pFrom;
500 pSrc->a->pTab->nRef++;
501 pSrc->a->iCursor = pParse->nTab++;
502
503 /* If this is an UPDATE, and none of the columns associated with this
504 ** FK have been modified, do not scan the referencing table. Unlike
505 ** the compile-time test implemented above, this is not just an
506 ** optimization. It is required so that immediate foreign keys do not
507 ** throw exceptions when the user executes a statement like:
508 **
509 ** UPDATE refd_table SET refd_column = refd_column
510 */
511 if( pChanges ){
512 int i;
513 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
514 for(i=0; i<pFKey->nCol; i++){
515 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
516 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
517 }
518 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
519 }
520
521 if( regNew!=0 && pFKey->isDeferred ){
522 fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
523 }
524 if( regOld!=0 ){
525 /* If there is a RESTRICT action configured for the current operation
526 ** on the referenced table of this FK, then throw an exception
527 ** immediately if the FK constraint is violated, even if this is a
528 ** deferred trigger. That's what RESTRICT means. To defer checking
529 ** the constraint, the FK should specify NO ACTION (represented
530 ** using OE_None). NO ACTION is the default. */
531 fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
532 (pChanges!=0 && pFKey->updateConf!=OE_Restrict)
533 || (pChanges==0 && pFKey->deleteConf!=OE_Restrict)
534 );
535 }
536
537 if( pChanges ){
538 sqlite3VdbeJumpHere(v, iGoto);
539 }
540 sqlite3SrcListDelete(db, pSrc);
541 sqlite3DbFree(db, aiCol);
542 }
543}
544
545#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
546
547/*
548** This function is called before generating code to update or delete a
549** row contained in table pTab. If the operation is an update, then
550** pChanges is a pointer to the list of columns to modify. If this is a
551** delete, then pChanges is NULL.
552*/
553u32 sqlite3FkOldmask(
554 Parse *pParse, /* Parse context */
555 Table *pTab, /* Table being modified */
556 ExprList *pChanges /* Non-NULL for UPDATE operations */
557){
558 u32 mask = 0;
559 if( pParse->db->flags&SQLITE_ForeignKeys ){
560 FKey *p;
561 int i;
562 for(p=pTab->pFKey; p; p=p->pNextFrom){
563 if( pChanges || p->isDeferred ){
564 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
565 }
566 }
567 for(p=fkRefering(pTab); p; p=p->pNextTo){
568 Index *pIdx = 0;
569 locateFkeyIndex(0, pTab, p, &pIdx, 0);
570 if( pIdx ){
571 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
572 }
573 }
574 }
575 return mask;
576}
577
578/*
579** This function is called before generating code to update or delete a
580** row contained in table pTab. If the operation is an update, then
581** pChanges is a pointer to the list of columns to modify. If this is a
582** delete, then pChanges is NULL.
583**
584** If any foreign key processing will be required, this function returns
585** true. If there is no foreign key related processing, this function
586** returns false.
587*/
588int sqlite3FkRequired(
589 Parse *pParse, /* Parse context */
590 Table *pTab, /* Table being modified */
591 ExprList *pChanges /* Non-NULL for UPDATE operations */
592){
593 if( pParse->db->flags&SQLITE_ForeignKeys ){
594 FKey *p;
595 for(p=pTab->pFKey; p; p=p->pNextFrom){
596 if( pChanges || p->isDeferred ) return 1;
597 }
598 if( fkRefering(pTab) ) return 1;
599 }
600 return 0;
601}
602
603static Trigger *fkActionTrigger(
604 Parse *pParse,
605 Table *pTab, /* Table being updated or deleted from */
606 FKey *pFKey, /* Foreign key to get action for */
607 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
608){
609 sqlite3 *db = pParse->db; /* Database handle */
610 int action;
611 Trigger *pTrigger;
612
613 if( pChanges ){
614 action = pFKey->updateConf;
615 pTrigger = pFKey->pOnUpdate;
616 }else{
617 action = pFKey->deleteConf;
618 pTrigger = pFKey->pOnDelete;
619 }
620
621 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
622 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
623
624 if( action>OE_Restrict && !pTrigger ){
625 char const *zFrom; /* Name of referencing table */
626 int nFrom; /* Length in bytes of zFrom */
627 Index *pIdx = 0;
628 int *aiCol = 0;
629 TriggerStep *pStep;
630 sqlite3 *dbMem = pTab->dbMem;
631 Expr *pWhere = 0;
632 ExprList *pList = 0;
633 int i;
634
635 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
636 assert( aiCol || pFKey->nCol==1 );
637
638 assert( dbMem==0 || dbMem==pParse->db );
639 zFrom = pFKey->pFrom->zName;
640 nFrom = sqlite3Strlen30(zFrom);
641 pTrigger = (Trigger *)sqlite3DbMallocZero(dbMem,
642 sizeof(Trigger) + /* struct Trigger */
643 sizeof(TriggerStep) + /* Single step in trigger program */
644 nFrom + 1 /* Space for pStep->target.z */
645 );
646 if( !pTrigger ){
647 pParse->db->mallocFailed = 1;
648 return 0;
649 }
650 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
651 pStep->target.z = (char *)&pStep[1];
652 pStep->target.n = nFrom;
653 memcpy((char *)pStep->target.z, zFrom, nFrom);
654
655 for(i=0; i<pFKey->nCol; i++){
656 Expr *pEq;
657 int iFromCol; /* Idx of column in referencing table */
658 Token tFromCol; /* Name of column in referencing table */
659 Token tToCol; /* Name of column in referenced table */
660 Token tOld = { "old", 3 }; /* Literal "old" token */
661 Token tNew = { "new", 3 }; /* Literal "new" token */
662
663 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
664 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
665 tFromCol.z = iFromCol<0 ? "oid" : pFKey->pFrom->aCol[iFromCol].zName;
666
667 tToCol.n = sqlite3Strlen30(tToCol.z);
668 tFromCol.n = sqlite3Strlen30(tFromCol.z);
669
670 /* Create the expression "zFromCol = OLD.zToCol" */
671 pEq = sqlite3PExpr(pParse, TK_EQ,
672 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
673 sqlite3PExpr(pParse, TK_DOT,
674 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
675 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
676 , 0)
677 , 0);
678 pWhere = sqlite3ExprAnd(pParse->db, pWhere, pEq);
679
680 if( action!=OE_Cascade || pChanges ){
681 Expr *pNew;
682 if( action==OE_Cascade ){
683 pNew = sqlite3PExpr(pParse, TK_DOT,
684 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
685 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
686 , 0);
687 }else if( action==OE_SetDflt ){
688 Expr *pDflt = pIdx ? 0 : pTab->aCol[pIdx->aiColumn[i]].pDflt;
689 if( pDflt ){
690 pNew = sqlite3ExprDup(db, pDflt, 0);
691 }else{
692 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
693 }
694 }else{
695 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
696 }
697 pList = sqlite3ExprListAppend(pParse, pList, pNew);
698 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
699 }
700 }
701 sqlite3DbFree(pParse->db, aiCol);
702
703 pStep->pWhere = sqlite3ExprDup(dbMem, pWhere, EXPRDUP_REDUCE);
704 pStep->pExprList = sqlite3ExprListDup(dbMem, pList, EXPRDUP_REDUCE);
705 sqlite3ExprDelete(pParse->db, pWhere);
706 sqlite3ExprListDelete(pParse->db, pList);
707
708 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
709 pStep->pTrig = pTrigger;
710 pTrigger->pSchema = pTab->pSchema;
711 pTrigger->pTabSchema = pTab->pSchema;
712
713 if( pChanges ){
714 pFKey->pOnUpdate = pTrigger;
715 pTrigger->op = TK_UPDATE;
716 pStep->op = TK_UPDATE;
717 }else{
718 pFKey->pOnDelete = pTrigger;
719 pTrigger->op = TK_DELETE;
720 pStep->op = (action==OE_Cascade)?TK_DELETE:TK_UPDATE;
721 }
722 }
723
724 return pTrigger;
725}
726
dan1da40a32009-09-19 17:00:31 +0000727/*
728** This function is called when deleting or updating a row to implement
729** any required CASCADE, SET NULL or SET DEFAULT actions.
730*/
731void sqlite3FkActions(
732 Parse *pParse, /* Parse context */
733 Table *pTab, /* Table being updated or deleted from */
734 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
735 int regOld /* Address of array containing old row */
736){
737 /* If foreign-key support is enabled, iterate through all FKs that
738 ** refer to table pTab. If there is an action associated with the FK
739 ** for this operation (either update or delete), invoke the associated
740 ** trigger sub-program. */
741 if( pParse->db->flags&SQLITE_ForeignKeys ){
742 FKey *pFKey; /* Iterator variable */
743 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
744 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
745 if( pAction ){
746 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
747 }
748 }
749 }
750}
751
dan75cbd982009-09-21 16:06:03 +0000752#endif /* ifndef SQLITE_OMIT_TRIGGER */
753
dan1da40a32009-09-19 17:00:31 +0000754/*
755** Free all memory associated with foreign key definitions attached to
756** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
757** hash table.
758*/
759void sqlite3FkDelete(Table *pTab){
760 FKey *pFKey; /* Iterator variable */
761 FKey *pNext; /* Copy of pFKey->pNextFrom */
762
763 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
764
765 /* Remove the FK from the fkeyHash hash table. */
766 if( pFKey->pPrevTo ){
767 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
768 }else{
769 void *data = (void *)pFKey->pNextTo;
770 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
771 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
772 }
773 if( pFKey->pNextTo ){
774 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
775 }
776
777 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000778#ifndef SQLITE_OMIT_TRIGGER
dan1da40a32009-09-19 17:00:31 +0000779 fkTriggerDelete(pTab->dbMem, pFKey->pOnDelete);
780 fkTriggerDelete(pTab->dbMem, pFKey->pOnUpdate);
dan75cbd982009-09-21 16:06:03 +0000781#endif
dan1da40a32009-09-19 17:00:31 +0000782
783 /* Delete the memory allocated for the FK structure. */
784 pNext = pFKey->pNextFrom;
785 sqlite3DbFree(pTab->dbMem, pFKey);
786 }
787}
dan75cbd982009-09-21 16:06:03 +0000788#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */