blob: 32aef9bbe0d4468da7829a52026c2fefb5fa7115 [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);
398 sqlite3DbFree(dbMem, p);
399 }
400}
401
dan1da40a32009-09-19 17:00:31 +0000402void sqlite3FkCheck(
403 Parse *pParse, /* Parse context */
404 Table *pTab, /* Row is being deleted from this table */
405 ExprList *pChanges, /* Changed columns if this is an UPDATE */
406 int regOld, /* Previous row data is stored here */
407 int regNew /* New row data is stored here */
408){
409 sqlite3 *db = pParse->db; /* Database handle */
410 Vdbe *v; /* VM to write code to */
411 FKey *pFKey; /* Used to iterate through FKs */
412 int iDb; /* Index of database containing pTab */
413 const char *zDb; /* Name of database containing pTab */
414
415 assert( ( pChanges && regOld && regNew) /* UPDATE operation */
416 || (!pChanges && !regOld && regNew) /* INSERT operation */
417 || (!pChanges && regOld && !regNew) /* DELETE operation */
418 );
419
420 /* If foreign-keys are disabled, this function is a no-op. */
421 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
422
423 v = sqlite3GetVdbe(pParse);
424 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
425 zDb = db->aDb[iDb].zName;
426
427 /* Loop through all the foreign key constraints attached to the table. */
428 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
429 Table *pTo; /* Table referenced by this FK */
430 Index *pIdx = 0; /* Index on key columns in pTo */
dan36062642009-09-21 18:56:23 +0000431 int *aiFree = 0;
432 int *aiCol;
433 int iCol;
434 int i;
dan1da40a32009-09-19 17:00:31 +0000435
436 if( pFKey->isDeferred==0 && regNew==0 ) continue;
437
438 /* Find the table this foreign key references. Also find a unique
439 ** index on the referenced table that corresponds to the key columns.
440 ** If either of these things cannot be located, set an error in pParse
441 ** and return early. */
442 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
dan36062642009-09-21 18:56:23 +0000443 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ) return;
444 assert( pFKey->nCol==1 || (aiFree && pIdx) );
dan1da40a32009-09-19 17:00:31 +0000445
446 /* If the key does not overlap with the pChanges list, skip this FK. */
447 if( pChanges ){
448 /* TODO */
449 }
450
dan36062642009-09-21 18:56:23 +0000451 if( aiFree ){
452 aiCol = aiFree;
453 }else{
454 iCol = pFKey->aCol[0].iFrom;
455 aiCol = &iCol;
456 }
457 for(i=0; i<pFKey->nCol; i++){
458 if( aiCol[i]==pTab->iPKey ){
459 aiCol[i] = -1;
460 }
461 }
462
dan1da40a32009-09-19 17:00:31 +0000463 /* Take a shared-cache advisory read-lock on the referenced table.
464 ** Allocate a cursor to use to search the unique index on the FK
465 ** columns in the referenced table. */
466 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
467 pParse->nTab++;
468
469 if( regOld!=0 && pFKey->isDeferred ){
470 fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1);
471 }
472 if( regNew!=0 ){
473 fkCheckReference(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1);
474 }
475
dan36062642009-09-21 18:56:23 +0000476 sqlite3DbFree(db, aiFree);
dan1da40a32009-09-19 17:00:31 +0000477 }
478
479 /* Loop through all the foreign key constraints that refer to this table */
480 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
481 int iGoto; /* Address of OP_Goto instruction */
482 Index *pIdx = 0; /* Foreign key index for pFKey */
483 SrcList *pSrc;
484 int *aiCol = 0;
485
486 /* For immediate constraints, skip this scan if:
487 **
488 ** 1) this is an INSERT operation, or
489 ** 2) an UPDATE operation and the FK action is a trigger-action, or
490 ** 3) a DELETE operation and the FK action is a trigger-action.
491 **
492 ** A "trigger-action" is one of CASCADE, SET DEFAULT or SET NULL.
493 */
494 if( pFKey->isDeferred==0 ){
495 if( regOld==0 ) continue; /* 1 */
496 if( regNew!=0 && pFKey->updateConf>OE_Restrict ) continue; /* 2 */
497 if( regNew==0 && pFKey->deleteConf>OE_Restrict ) continue; /* 3 */
498 }
499
500 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return;
501 assert( aiCol || pFKey->nCol==1 );
502
503 /* Check if this update statement has modified any of the key columns
504 ** for this foreign key constraint. If it has not, there is no need
505 ** to search the referencing table for rows in violation. This is
506 ** just an optimization. Things would work fine without this check. */
507 if( pChanges ){
508 /* TODO */
509 }
510
511 /* Create a SrcList structure containing a single table (the table
512 ** the foreign key that refers to this table is attached to). This
513 ** is required for the sqlite3WhereXXX() interface. */
514 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
danf59c5ca2009-09-22 16:55:38 +0000515 if( pSrc ){
516 pSrc->a->pTab = pFKey->pFrom;
517 pSrc->a->pTab->nRef++;
518 pSrc->a->iCursor = pParse->nTab++;
519
520 /* If this is an UPDATE, and none of the columns associated with this
521 ** FK have been modified, do not scan the referencing table. Unlike
522 ** the compile-time test implemented above, this is not just an
523 ** optimization. It is required so that immediate foreign keys do not
524 ** throw exceptions when the user executes a statement like:
525 **
526 ** UPDATE refd_table SET refd_column = refd_column
527 */
528 if( pChanges ){
529 int i;
530 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
531 for(i=0; i<pFKey->nCol; i++){
532 int iOff = (pIdx ? pIdx->aiColumn[i] : -1) + 1;
533 sqlite3VdbeAddOp3(v, OP_Ne, regOld+iOff, iJump, regNew+iOff);
534 }
535 iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
dan1da40a32009-09-19 17:00:31 +0000536 }
danf59c5ca2009-09-22 16:55:38 +0000537
538 if( regNew!=0 && pFKey->isDeferred ){
539 fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regNew, -1);
540 }
541 if( regOld!=0 ){
542 /* If there is a RESTRICT action configured for the current operation
543 ** on the referenced table of this FK, then throw an exception
544 ** immediately if the FK constraint is violated, even if this is a
545 ** deferred trigger. That's what RESTRICT means. To defer checking
546 ** the constraint, the FK should specify NO ACTION (represented
547 ** using OE_None). NO ACTION is the default. */
548 fkScanReferences(pParse, pSrc, pIdx, pFKey, aiCol, regOld,
549 (pChanges!=0 && pFKey->updateConf!=OE_Restrict)
550 || (pChanges==0 && pFKey->deleteConf!=OE_Restrict)
551 );
552 }
553
554 if( pChanges ){
555 sqlite3VdbeJumpHere(v, iGoto);
556 }
557 sqlite3SrcListDelete(db, pSrc);
dan1da40a32009-09-19 17:00:31 +0000558 }
dan1da40a32009-09-19 17:00:31 +0000559 sqlite3DbFree(db, aiCol);
560 }
561}
562
563#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
564
565/*
566** This function is called before generating code to update or delete a
567** row contained in table pTab. If the operation is an update, then
568** pChanges is a pointer to the list of columns to modify. If this is a
569** delete, then pChanges is NULL.
570*/
571u32 sqlite3FkOldmask(
572 Parse *pParse, /* Parse context */
573 Table *pTab, /* Table being modified */
574 ExprList *pChanges /* Non-NULL for UPDATE operations */
575){
576 u32 mask = 0;
577 if( pParse->db->flags&SQLITE_ForeignKeys ){
578 FKey *p;
579 int i;
580 for(p=pTab->pFKey; p; p=p->pNextFrom){
581 if( pChanges || p->isDeferred ){
582 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
583 }
584 }
585 for(p=fkRefering(pTab); p; p=p->pNextTo){
586 Index *pIdx = 0;
587 locateFkeyIndex(0, pTab, p, &pIdx, 0);
588 if( pIdx ){
589 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
590 }
591 }
592 }
593 return mask;
594}
595
596/*
597** This function is called before generating code to update or delete a
598** row contained in table pTab. If the operation is an update, then
599** pChanges is a pointer to the list of columns to modify. If this is a
600** delete, then pChanges is NULL.
601**
602** If any foreign key processing will be required, this function returns
603** true. If there is no foreign key related processing, this function
604** returns false.
605*/
606int sqlite3FkRequired(
607 Parse *pParse, /* Parse context */
608 Table *pTab, /* Table being modified */
609 ExprList *pChanges /* Non-NULL for UPDATE operations */
610){
611 if( pParse->db->flags&SQLITE_ForeignKeys ){
612 FKey *p;
613 for(p=pTab->pFKey; p; p=p->pNextFrom){
614 if( pChanges || p->isDeferred ) return 1;
615 }
616 if( fkRefering(pTab) ) return 1;
617 }
618 return 0;
619}
620
621static Trigger *fkActionTrigger(
622 Parse *pParse,
623 Table *pTab, /* Table being updated or deleted from */
624 FKey *pFKey, /* Foreign key to get action for */
625 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
626){
627 sqlite3 *db = pParse->db; /* Database handle */
dan29c7f9c2009-09-22 15:53:47 +0000628 int action; /* One of OE_None, OE_Cascade etc. */
629 Trigger *pTrigger; /* Trigger definition to return */
dan1da40a32009-09-19 17:00:31 +0000630
631 if( pChanges ){
632 action = pFKey->updateConf;
633 pTrigger = pFKey->pOnUpdate;
634 }else{
635 action = pFKey->deleteConf;
636 pTrigger = pFKey->pOnDelete;
637 }
638
639 assert( OE_SetNull>OE_Restrict && OE_SetDflt>OE_Restrict );
640 assert( OE_Cascade>OE_Restrict && OE_None<OE_Restrict );
641
642 if( action>OE_Restrict && !pTrigger ){
dan29c7f9c2009-09-22 15:53:47 +0000643 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
dan1da40a32009-09-19 17:00:31 +0000644 char const *zFrom; /* Name of referencing table */
645 int nFrom; /* Length in bytes of zFrom */
dan29c7f9c2009-09-22 15:53:47 +0000646 Index *pIdx = 0; /* Parent key index for this FK */
647 int *aiCol = 0; /* child table cols -> parent key cols */
648 TriggerStep *pStep; /* First (only) step of trigger program */
649 Expr *pWhere = 0; /* WHERE clause of trigger step */
650 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
651 int i; /* Iterator variable */
dan1da40a32009-09-19 17:00:31 +0000652
653 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
654 assert( aiCol || pFKey->nCol==1 );
655
dan1da40a32009-09-19 17:00:31 +0000656 for(i=0; i<pFKey->nCol; i++){
dan1da40a32009-09-19 17:00:31 +0000657 Token tOld = { "old", 3 }; /* Literal "old" token */
658 Token tNew = { "new", 3 }; /* Literal "new" token */
dan29c7f9c2009-09-22 15:53:47 +0000659 Token tFromCol; /* Name of column in referencing table */
660 Token tToCol; /* Name of column in referenced table */
661 int iFromCol; /* Idx of column in referencing table */
662 Expr *pEq; /* tFromCol = OLD.tToCol */
dan1da40a32009-09-19 17:00:31 +0000663
664 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
665 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
666 tFromCol.z = iFromCol<0 ? "oid" : pFKey->pFrom->aCol[iFromCol].zName;
667
668 tToCol.n = sqlite3Strlen30(tToCol.z);
669 tFromCol.n = sqlite3Strlen30(tFromCol.z);
670
671 /* Create the expression "zFromCol = OLD.zToCol" */
672 pEq = sqlite3PExpr(pParse, TK_EQ,
673 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol),
674 sqlite3PExpr(pParse, TK_DOT,
675 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
676 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
677 , 0)
678 , 0);
dan29c7f9c2009-09-22 15:53:47 +0000679 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
dan1da40a32009-09-19 17:00:31 +0000680
681 if( action!=OE_Cascade || pChanges ){
682 Expr *pNew;
683 if( action==OE_Cascade ){
684 pNew = sqlite3PExpr(pParse, TK_DOT,
685 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
686 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
687 , 0);
688 }else if( action==OE_SetDflt ){
dan934ce302009-09-22 16:08:58 +0000689 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
dan1da40a32009-09-19 17:00:31 +0000690 if( pDflt ){
691 pNew = sqlite3ExprDup(db, pDflt, 0);
692 }else{
693 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
694 }
695 }else{
696 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
697 }
698 pList = sqlite3ExprListAppend(pParse, pList, pNew);
699 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
700 }
701 }
dan29c7f9c2009-09-22 15:53:47 +0000702 sqlite3DbFree(db, aiCol);
dan1da40a32009-09-19 17:00:31 +0000703
dan29c7f9c2009-09-22 15:53:47 +0000704 /* If pTab->dbMem==0, then the table may be part of a shared-schema.
705 ** Disable the lookaside buffer before allocating space for the
706 ** trigger definition in this case. */
707 enableLookaside = db->lookaside.bEnabled;
708 if( pTab->dbMem==0 ){
709 db->lookaside.bEnabled = 0;
710 }
711
712 zFrom = pFKey->pFrom->zName;
713 nFrom = sqlite3Strlen30(zFrom);
714 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
715 sizeof(Trigger) + /* struct Trigger */
716 sizeof(TriggerStep) + /* Single step in trigger program */
717 nFrom + 1 /* Space for pStep->target.z */
718 );
719 if( pTrigger ){
720 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
721 pStep->target.z = (char *)&pStep[1];
722 pStep->target.n = nFrom;
723 memcpy((char *)pStep->target.z, zFrom, nFrom);
724
725 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
726 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
727 }
728
729 /* Re-enable the lookaside buffer, if it was disabled earlier. */
730 db->lookaside.bEnabled = enableLookaside;
731
dan1da40a32009-09-19 17:00:31 +0000732 sqlite3ExprDelete(pParse->db, pWhere);
733 sqlite3ExprListDelete(pParse->db, pList);
dan29c7f9c2009-09-22 15:53:47 +0000734 if( db->mallocFailed==1 ){
735 fkTriggerDelete(db, pTrigger);
736 return 0;
737 }
dan1da40a32009-09-19 17:00:31 +0000738
739 pStep->op = (action!=OE_Cascade || pChanges) ? TK_UPDATE : TK_DELETE;
740 pStep->pTrig = pTrigger;
741 pTrigger->pSchema = pTab->pSchema;
742 pTrigger->pTabSchema = pTab->pSchema;
743
744 if( pChanges ){
745 pFKey->pOnUpdate = pTrigger;
746 pTrigger->op = TK_UPDATE;
747 pStep->op = TK_UPDATE;
748 }else{
749 pFKey->pOnDelete = pTrigger;
750 pTrigger->op = TK_DELETE;
751 pStep->op = (action==OE_Cascade)?TK_DELETE:TK_UPDATE;
752 }
753 }
754
755 return pTrigger;
756}
757
dan1da40a32009-09-19 17:00:31 +0000758/*
759** This function is called when deleting or updating a row to implement
760** any required CASCADE, SET NULL or SET DEFAULT actions.
761*/
762void sqlite3FkActions(
763 Parse *pParse, /* Parse context */
764 Table *pTab, /* Table being updated or deleted from */
765 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
766 int regOld /* Address of array containing old row */
767){
768 /* If foreign-key support is enabled, iterate through all FKs that
769 ** refer to table pTab. If there is an action associated with the FK
770 ** for this operation (either update or delete), invoke the associated
771 ** trigger sub-program. */
772 if( pParse->db->flags&SQLITE_ForeignKeys ){
773 FKey *pFKey; /* Iterator variable */
774 for(pFKey = fkRefering(pTab); pFKey; pFKey=pFKey->pNextTo){
775 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
776 if( pAction ){
777 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
778 }
779 }
780 }
781}
782
dan75cbd982009-09-21 16:06:03 +0000783#endif /* ifndef SQLITE_OMIT_TRIGGER */
784
dan1da40a32009-09-19 17:00:31 +0000785/*
786** Free all memory associated with foreign key definitions attached to
787** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
788** hash table.
789*/
790void sqlite3FkDelete(Table *pTab){
791 FKey *pFKey; /* Iterator variable */
792 FKey *pNext; /* Copy of pFKey->pNextFrom */
793
794 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
795
796 /* Remove the FK from the fkeyHash hash table. */
797 if( pFKey->pPrevTo ){
798 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
799 }else{
800 void *data = (void *)pFKey->pNextTo;
801 const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
802 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
803 }
804 if( pFKey->pNextTo ){
805 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
806 }
807
808 /* Delete any triggers created to implement actions for this FK. */
dan75cbd982009-09-21 16:06:03 +0000809#ifndef SQLITE_OMIT_TRIGGER
dan1da40a32009-09-19 17:00:31 +0000810 fkTriggerDelete(pTab->dbMem, pFKey->pOnDelete);
811 fkTriggerDelete(pTab->dbMem, pFKey->pOnUpdate);
dan75cbd982009-09-21 16:06:03 +0000812#endif
dan1da40a32009-09-19 17:00:31 +0000813
814 /* Delete the memory allocated for the FK structure. */
815 pNext = pFKey->pNextFrom;
816 sqlite3DbFree(pTab->dbMem, pFKey);
817 }
818}
dan75cbd982009-09-21 16:06:03 +0000819#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */