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