fkey.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. /*
  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. #ifndef SQLITE_OMIT_FOREIGN_KEY
  16. #ifndef SQLITE_OMIT_TRIGGER
  17. /*
  18. ** Deferred and Immediate FKs
  19. ** --------------------------
  20. **
  21. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  22. ** If an immediate foreign key constraint is violated,
  23. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  24. ** 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 child table, search
  51. ** the parent table for a match. If none is found increment the
  52. ** constraint counter.
  53. **
  54. ** I.2) For each FK for which the table is the parent table,
  55. ** search the child table for rows that correspond to the new
  56. ** row in the parent table. Decrement the counter for each row
  57. ** found (as the constraint is now satisfied).
  58. **
  59. ** DELETE operations:
  60. **
  61. ** D.1) For each FK for which the table is the child table,
  62. ** search the parent table for a row that corresponds to the
  63. ** deleted row in the child table. If such a row is not found,
  64. ** decrement the counter.
  65. **
  66. ** D.2) For each FK for which the table is the parent table, search
  67. ** the child table for rows that correspond to the deleted row
  68. ** in the parent table. For each found increment the counter.
  69. **
  70. ** UPDATE operations:
  71. **
  72. ** An UPDATE command requires that all 4 steps above are taken, but only
  73. ** for FK constraints for which the affected columns are actually
  74. ** modified (values must be compared at runtime).
  75. **
  76. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  77. ** This simplifies the implementation a bit.
  78. **
  79. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  80. ** resolution is considered to delete rows before the new row is inserted.
  81. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  82. ** is thrown, even if the FK constraint would be satisfied after the new
  83. ** row is inserted.
  84. **
  85. ** Immediate constraints are usually handled similarly. The only difference
  86. ** is that the counter used is stored as part of each individual statement
  87. ** object (struct Vdbe). If, after the statement has run, its immediate
  88. ** constraint counter is greater than zero,
  89. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  90. ** and the statement transaction is rolled back. An exception is an INSERT
  91. ** statement that inserts a single row only (no triggers). In this case,
  92. ** instead of using a counter, an exception is thrown immediately if the
  93. ** INSERT violates a foreign key constraint. This is necessary as such
  94. ** an INSERT does not open a statement transaction.
  95. **
  96. ** TODO: How should dropping a table be handled? How should renaming a
  97. ** table be handled?
  98. **
  99. **
  100. ** Query API Notes
  101. ** ---------------
  102. **
  103. ** Before coding an UPDATE or DELETE row operation, the code-generator
  104. ** for those two operations needs to know whether or not the operation
  105. ** requires any FK processing and, if so, which columns of the original
  106. ** row are required by the FK processing VDBE code (i.e. if FKs were
  107. ** implemented using triggers, which of the old.* columns would be
  108. ** accessed). No information is required by the code-generator before
  109. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  110. ** generation code to query for this information are:
  111. **
  112. ** sqlite3FkRequired() - Test to see if FK processing is required.
  113. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  114. **
  115. **
  116. ** Externally accessible module functions
  117. ** --------------------------------------
  118. **
  119. ** sqlite3FkCheck() - Check for foreign key violations.
  120. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  121. ** sqlite3FkDelete() - Delete an FKey structure.
  122. */
  123. /*
  124. ** VDBE Calling Convention
  125. ** -----------------------
  126. **
  127. ** Example:
  128. **
  129. ** For the following INSERT statement:
  130. **
  131. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  132. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  133. **
  134. ** Register (x): 2 (type integer)
  135. ** Register (x+1): 1 (type integer)
  136. ** Register (x+2): NULL (type NULL)
  137. ** Register (x+3): 3.1 (type real)
  138. */
  139. /*
  140. ** A foreign key constraint requires that the key columns in the parent
  141. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  142. ** Given that pParent is the parent table for foreign key constraint pFKey,
  143. ** search the schema for a unique index on the parent key columns.
  144. **
  145. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  146. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  147. ** is set to point to the unique index.
  148. **
  149. ** If the parent key consists of a single column (the foreign key constraint
  150. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  151. ** Otherwise, it is set to point to an allocated array of size N, where
  152. ** N is the number of columns in the parent key. The first element of the
  153. ** array is the index of the child table column that is mapped by the FK
  154. ** constraint to the parent table column stored in the left-most column
  155. ** of index *ppIdx. The second element of the array is the index of the
  156. ** child table column that corresponds to the second left-most column of
  157. ** *ppIdx, and so on.
  158. **
  159. ** If the required index cannot be found, either because:
  160. **
  161. ** 1) The named parent key columns do not exist, or
  162. **
  163. ** 2) The named parent key columns do exist, but are not subject to a
  164. ** UNIQUE or PRIMARY KEY constraint, or
  165. **
  166. ** 3) No parent key columns were provided explicitly as part of the
  167. ** foreign key definition, and the parent table does not have a
  168. ** PRIMARY KEY, or
  169. **
  170. ** 4) No parent key columns were provided explicitly as part of the
  171. ** foreign key definition, and the PRIMARY KEY of the parent table
  172. ** consists of a a different number of columns to the child key in
  173. ** the child table.
  174. **
  175. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  176. ** into pParse. If an OOM error occurs, non-zero is returned and the
  177. ** pParse->db->mallocFailed flag is set.
  178. */
  179. int sqlite3FkLocateIndex(
  180. Parse *pParse, /* Parse context to store any error in */
  181. Table *pParent, /* Parent table of FK constraint pFKey */
  182. FKey *pFKey, /* Foreign key to find index for */
  183. Index **ppIdx, /* OUT: Unique index on parent table */
  184. int **paiCol /* OUT: Map of index columns in pFKey */
  185. ){
  186. Index *pIdx = 0; /* Value to return via *ppIdx */
  187. int *aiCol = 0; /* Value to return via *paiCol */
  188. int nCol = pFKey->nCol; /* Number of columns in parent key */
  189. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  190. /* The caller is responsible for zeroing output parameters. */
  191. assert( ppIdx && *ppIdx==0 );
  192. assert( !paiCol || *paiCol==0 );
  193. assert( pParse );
  194. /* If this is a non-composite (single column) foreign key, check if it
  195. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  196. ** and *paiCol set to zero and return early.
  197. **
  198. ** Otherwise, for a composite foreign key (more than one column), allocate
  199. ** space for the aiCol array (returned via output parameter *paiCol).
  200. ** Non-composite foreign keys do not require the aiCol array.
  201. */
  202. if( nCol==1 ){
  203. /* The FK maps to the IPK if any of the following are true:
  204. **
  205. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  206. ** mapped to the primary key of table pParent, or
  207. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  208. ** PRIMARY KEY.
  209. */
  210. if( pParent->iPKey>=0 ){
  211. if( !zKey ) return 0;
  212. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  213. }
  214. }else if( paiCol ){
  215. assert( nCol>1 );
  216. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  217. if( !aiCol ) return 1;
  218. *paiCol = aiCol;
  219. }
  220. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  221. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  222. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  223. ** of columns. If each indexed column corresponds to a foreign key
  224. ** column of pFKey, then this index is a winner. */
  225. if( zKey==0 ){
  226. /* If zKey is NULL, then this foreign key is implicitly mapped to
  227. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  228. ** identified by the test (Index.autoIndex==2). */
  229. if( pIdx->autoIndex==2 ){
  230. if( aiCol ){
  231. int i;
  232. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  233. }
  234. break;
  235. }
  236. }else{
  237. /* If zKey is non-NULL, then this foreign key was declared to
  238. ** map to an explicit list of columns in table pParent. Check if this
  239. ** index matches those columns. Also, check that the index uses
  240. ** the default collation sequences for each column. */
  241. int i, j;
  242. for(i=0; i<nCol; i++){
  243. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  244. char *zDfltColl; /* Def. collation for column */
  245. char *zIdxCol; /* Name of indexed column */
  246. /* If the index uses a collation sequence that is different from
  247. ** the default collation sequence for the column, this index is
  248. ** unusable. Bail out early in this case. */
  249. zDfltColl = pParent->aCol[iCol].zColl;
  250. if( !zDfltColl ){
  251. zDfltColl = "BINARY";
  252. }
  253. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  254. zIdxCol = pParent->aCol[iCol].zName;
  255. for(j=0; j<nCol; j++){
  256. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  257. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  258. break;
  259. }
  260. }
  261. if( j==nCol ) break;
  262. }
  263. if( i==nCol ) break; /* pIdx is usable */
  264. }
  265. }
  266. }
  267. if( !pIdx ){
  268. if( !pParse->disableTriggers ){
  269. sqlite3ErrorMsg(pParse,
  270. "foreign key mismatch - \"%w\" referencing \"%w\"",
  271. pFKey->pFrom->zName, pFKey->zTo);
  272. }
  273. sqlite3DbFree(pParse->db, aiCol);
  274. return 1;
  275. }
  276. *ppIdx = pIdx;
  277. return 0;
  278. }
  279. /*
  280. ** This function is called when a row is inserted into or deleted from the
  281. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  282. ** on the child table of pFKey, this function is invoked twice for each row
  283. ** affected - once to "delete" the old row, and then again to "insert" the
  284. ** new row.
  285. **
  286. ** Each time it is called, this function generates VDBE code to locate the
  287. ** row in the parent table that corresponds to the row being inserted into
  288. ** or deleted from the child table. If the parent row can be found, no
  289. ** special action is taken. Otherwise, if the parent row can *not* be
  290. ** found in the parent table:
  291. **
  292. ** Operation | FK type | Action taken
  293. ** --------------------------------------------------------------------------
  294. ** INSERT immediate Increment the "immediate constraint counter".
  295. **
  296. ** DELETE immediate Decrement the "immediate constraint counter".
  297. **
  298. ** INSERT deferred Increment the "deferred constraint counter".
  299. **
  300. ** DELETE deferred Decrement the "deferred constraint counter".
  301. **
  302. ** These operations are identified in the comment at the top of this file
  303. ** (fkey.c) as "I.1" and "D.1".
  304. */
  305. static void fkLookupParent(
  306. Parse *pParse, /* Parse context */
  307. int iDb, /* Index of database housing pTab */
  308. Table *pTab, /* Parent table of FK pFKey */
  309. Index *pIdx, /* Unique index on parent key columns in pTab */
  310. FKey *pFKey, /* Foreign key constraint */
  311. int *aiCol, /* Map from parent key columns to child table columns */
  312. int regData, /* Address of array containing child table row */
  313. int nIncr, /* Increment constraint counter by this */
  314. int isIgnore /* If true, pretend pTab contains all NULL values */
  315. ){
  316. int i; /* Iterator variable */
  317. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  318. int iCur = pParse->nTab - 1; /* Cursor number to use */
  319. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  320. /* If nIncr is less than zero, then check at runtime if there are any
  321. ** outstanding constraints to resolve. If there are not, there is no need
  322. ** to check if deleting this row resolves any outstanding violations.
  323. **
  324. ** Check if any of the key columns in the child table row are NULL. If
  325. ** any are, then the constraint is considered satisfied. No need to
  326. ** search for a matching row in the parent table. */
  327. if( nIncr<0 ){
  328. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  329. }
  330. for(i=0; i<pFKey->nCol; i++){
  331. int iReg = aiCol[i] + regData + 1;
  332. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  333. }
  334. if( isIgnore==0 ){
  335. if( pIdx==0 ){
  336. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  337. ** column of the parent table (table pTab). */
  338. int iMustBeInt; /* Address of MustBeInt instruction */
  339. int regTemp = sqlite3GetTempReg(pParse);
  340. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  341. ** apply the affinity of the parent key). If this fails, then there
  342. ** is no matching parent key. Before using MustBeInt, make a copy of
  343. ** the value. Otherwise, the value inserted into the child key column
  344. ** will have INTEGER affinity applied to it, which may not be correct. */
  345. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  346. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  347. /* If the parent table is the same as the child table, and we are about
  348. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  349. ** then check if the row being inserted matches itself. If so, do not
  350. ** increment the constraint-counter. */
  351. if( pTab==pFKey->pFrom && nIncr==1 ){
  352. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  353. }
  354. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  355. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  356. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  357. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  358. sqlite3VdbeJumpHere(v, iMustBeInt);
  359. sqlite3ReleaseTempReg(pParse, regTemp);
  360. }else{
  361. int nCol = pFKey->nCol;
  362. int regTemp = sqlite3GetTempRange(pParse, nCol);
  363. int regRec = sqlite3GetTempReg(pParse);
  364. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  365. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  366. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  367. for(i=0; i<nCol; i++){
  368. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  369. }
  370. /* If the parent table is the same as the child table, and we are about
  371. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  372. ** then check if the row being inserted matches itself. If so, do not
  373. ** increment the constraint-counter.
  374. **
  375. ** If any of the parent-key values are NULL, then the row cannot match
  376. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  377. ** of the parent-key values are NULL (at this point it is known that
  378. ** none of the child key values are).
  379. */
  380. if( pTab==pFKey->pFrom && nIncr==1 ){
  381. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  382. for(i=0; i<nCol; i++){
  383. int iChild = aiCol[i]+1+regData;
  384. int iParent = pIdx->aiColumn[i]+1+regData;
  385. assert( aiCol[i]!=pTab->iPKey );
  386. if( pIdx->aiColumn[i]==pTab->iPKey ){
  387. /* The parent key is a composite key that includes the IPK column */
  388. iParent = regData;
  389. }
  390. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  391. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  392. }
  393. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  394. }
  395. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  396. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  397. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  398. sqlite3ReleaseTempReg(pParse, regRec);
  399. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  400. }
  401. }
  402. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  403. && !pParse->pToplevel
  404. && !pParse->isMultiWrite
  405. ){
  406. /* Special case: If this is an INSERT statement that will insert exactly
  407. ** one row into the table, raise a constraint immediately instead of
  408. ** incrementing a counter. This is necessary as the VM code is being
  409. ** generated for will not open a statement transaction. */
  410. assert( nIncr==1 );
  411. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  412. OE_Abort, "foreign key constraint failed", P4_STATIC
  413. );
  414. }else{
  415. if( nIncr>0 && pFKey->isDeferred==0 ){
  416. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  417. }
  418. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  419. }
  420. sqlite3VdbeResolveLabel(v, iOk);
  421. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  422. }
  423. /*
  424. ** This function is called to generate code executed when a row is deleted
  425. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  426. ** deferred, when a row is inserted into the same table. When generating
  427. ** code for an SQL UPDATE operation, this function may be called twice -
  428. ** once to "delete" the old row and once to "insert" the new row.
  429. **
  430. ** The code generated by this function scans through the rows in the child
  431. ** table that correspond to the parent table row being deleted or inserted.
  432. ** For each child row found, one of the following actions is taken:
  433. **
  434. ** Operation | FK type | Action taken
  435. ** --------------------------------------------------------------------------
  436. ** DELETE immediate Increment the "immediate constraint counter".
  437. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  438. ** throw a "foreign key constraint failed" exception.
  439. **
  440. ** INSERT immediate Decrement the "immediate constraint counter".
  441. **
  442. ** DELETE deferred Increment the "deferred constraint counter".
  443. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  444. ** throw a "foreign key constraint failed" exception.
  445. **
  446. ** INSERT deferred Decrement the "deferred constraint counter".
  447. **
  448. ** These operations are identified in the comment at the top of this file
  449. ** (fkey.c) as "I.2" and "D.2".
  450. */
  451. static void fkScanChildren(
  452. Parse *pParse, /* Parse context */
  453. SrcList *pSrc, /* SrcList containing the table to scan */
  454. Table *pTab,
  455. Index *pIdx, /* Foreign key index */
  456. FKey *pFKey, /* Foreign key relationship */
  457. int *aiCol, /* Map from pIdx cols to child table cols */
  458. int regData, /* Referenced table data starts here */
  459. int nIncr /* Amount to increment deferred counter by */
  460. ){
  461. sqlite3 *db = pParse->db; /* Database handle */
  462. int i; /* Iterator variable */
  463. Expr *pWhere = 0; /* WHERE clause to scan with */
  464. NameContext sNameContext; /* Context used to resolve WHERE clause */
  465. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  466. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  467. Vdbe *v = sqlite3GetVdbe(pParse);
  468. assert( !pIdx || pIdx->pTable==pTab );
  469. if( nIncr<0 ){
  470. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  471. }
  472. /* Create an Expr object representing an SQL expression like:
  473. **
  474. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  475. **
  476. ** The collation sequence used for the comparison should be that of
  477. ** the parent key columns. The affinity of the parent key column should
  478. ** be applied to each child key value before the comparison takes place.
  479. */
  480. for(i=0; i<pFKey->nCol; i++){
  481. Expr *pLeft; /* Value from parent table row */
  482. Expr *pRight; /* Column ref to child table */
  483. Expr *pEq; /* Expression (pLeft = pRight) */
  484. int iCol; /* Index of column in child table */
  485. const char *zCol; /* Name of column in child table */
  486. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  487. if( pLeft ){
  488. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  489. ** expression to the parent key column defaults. */
  490. if( pIdx ){
  491. Column *pCol;
  492. const char *zColl;
  493. iCol = pIdx->aiColumn[i];
  494. pCol = &pTab->aCol[iCol];
  495. if( pTab->iPKey==iCol ) iCol = -1;
  496. pLeft->iTable = regData+iCol+1;
  497. pLeft->affinity = pCol->affinity;
  498. zColl = pCol->zColl;
  499. if( zColl==0 ) zColl = db->pDfltColl->zName;
  500. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  501. }else{
  502. pLeft->iTable = regData;
  503. pLeft->affinity = SQLITE_AFF_INTEGER;
  504. }
  505. }
  506. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  507. assert( iCol>=0 );
  508. zCol = pFKey->pFrom->aCol[iCol].zName;
  509. pRight = sqlite3Expr(db, TK_ID, zCol);
  510. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  511. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  512. }
  513. /* If the child table is the same as the parent table, and this scan
  514. ** is taking place as part of a DELETE operation (operation D.2), omit the
  515. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  516. ** clause, where $rowid is the rowid of the row being deleted. */
  517. if( pTab==pFKey->pFrom && nIncr>0 ){
  518. Expr *pEq; /* Expression (pLeft = pRight) */
  519. Expr *pLeft; /* Value from parent table row */
  520. Expr *pRight; /* Column ref to child table */
  521. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  522. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  523. if( pLeft && pRight ){
  524. pLeft->iTable = regData;
  525. pLeft->affinity = SQLITE_AFF_INTEGER;
  526. pRight->iTable = pSrc->a[0].iCursor;
  527. pRight->iColumn = -1;
  528. }
  529. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  530. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  531. }
  532. /* Resolve the references in the WHERE clause. */
  533. memset(&sNameContext, 0, sizeof(NameContext));
  534. sNameContext.pSrcList = pSrc;
  535. sNameContext.pParse = pParse;
  536. sqlite3ResolveExprNames(&sNameContext, pWhere);
  537. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  538. ** clause. If the constraint is not deferred, throw an exception for
  539. ** each row found. Otherwise, for deferred constraints, increment the
  540. ** deferred constraint counter by nIncr for each row selected. */
  541. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  542. if( nIncr>0 && pFKey->isDeferred==0 ){
  543. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  544. }
  545. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  546. if( pWInfo ){
  547. sqlite3WhereEnd(pWInfo);
  548. }
  549. /* Clean up the WHERE clause constructed above. */
  550. sqlite3ExprDelete(db, pWhere);
  551. if( iFkIfZero ){
  552. sqlite3VdbeJumpHere(v, iFkIfZero);
  553. }
  554. }
  555. /*
  556. ** This function returns a pointer to the head of a linked list of FK
  557. ** constraints for which table pTab is the parent table. For example,
  558. ** given the following schema:
  559. **
  560. ** CREATE TABLE t1(a PRIMARY KEY);
  561. ** CREATE TABLE t2(b REFERENCES t1(a);
  562. **
  563. ** Calling this function with table "t1" as an argument returns a pointer
  564. ** to the FKey structure representing the foreign key constraint on table
  565. ** "t2". Calling this function with "t2" as the argument would return a
  566. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  567. ** table).
  568. */
  569. FKey *sqlite3FkReferences(Table *pTab){
  570. int nName = sqlite3Strlen30(pTab->zName);
  571. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  572. }
  573. /*
  574. ** The second argument is a Trigger structure allocated by the
  575. ** fkActionTrigger() routine. This function deletes the Trigger structure
  576. ** and all of its sub-components.
  577. **
  578. ** The Trigger structure or any of its sub-components may be allocated from
  579. ** the lookaside buffer belonging to database handle dbMem.
  580. */
  581. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  582. if( p ){
  583. TriggerStep *pStep = p->step_list;
  584. sqlite3ExprDelete(dbMem, pStep->pWhere);
  585. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  586. sqlite3SelectDelete(dbMem, pStep->pSelect);
  587. sqlite3ExprDelete(dbMem, p->pWhen);
  588. sqlite3DbFree(dbMem, p);
  589. }
  590. }
  591. /*
  592. ** This function is called to generate code that runs when table pTab is
  593. ** being dropped from the database. The SrcList passed as the second argument
  594. ** to this function contains a single entry guaranteed to resolve to
  595. ** table pTab.
  596. **
  597. ** Normally, no code is required. However, if either
  598. **
  599. ** (a) The table is the parent table of a FK constraint, or
  600. ** (b) The table is the child table of a deferred FK constraint and it is
  601. ** determined at runtime that there are outstanding deferred FK
  602. ** constraint violations in the database,
  603. **
  604. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  605. ** the table from the database. Triggers are disabled while running this
  606. ** DELETE, but foreign key actions are not.
  607. */
  608. void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  609. sqlite3 *db = pParse->db;
  610. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  611. int iSkip = 0;
  612. Vdbe *v = sqlite3GetVdbe(pParse);
  613. assert( v ); /* VDBE has already been allocated */
  614. if( sqlite3FkReferences(pTab)==0 ){
  615. /* Search for a deferred foreign key constraint for which this table
  616. ** is the child table. If one cannot be found, return without
  617. ** generating any VDBE code. If one can be found, then jump over
  618. ** the entire DELETE if there are no outstanding deferred constraints
  619. ** when this statement is run. */
  620. FKey *p;
  621. for(p=pTab->pFKey; p; p=p->pNextFrom){
  622. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  623. }
  624. if( !p ) return;
  625. iSkip = sqlite3VdbeMakeLabel(v);
  626. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  627. }
  628. pParse->disableTriggers = 1;
  629. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  630. pParse->disableTriggers = 0;
  631. /* If the DELETE has generated immediate foreign key constraint
  632. ** violations, halt the VDBE and return an error at this point, before
  633. ** any modifications to the schema are made. This is because statement
  634. ** transactions are not able to rollback schema changes.
  635. **
  636. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  637. ** the statement transaction will not be rolled back even if FK
  638. ** constraints are violated.
  639. */
  640. if( (db->flags & SQLITE_DeferFKs)==0 ){
  641. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  642. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  643. OE_Abort, "foreign key constraint failed", P4_STATIC
  644. );
  645. }
  646. if( iSkip ){
  647. sqlite3VdbeResolveLabel(v, iSkip);
  648. }
  649. }
  650. }
  651. /*
  652. ** The second argument points to an FKey object representing a foreign key
  653. ** for which pTab is the child table. An UPDATE statement against pTab
  654. ** is currently being processed. For each column of the table that is
  655. ** actually updated, the corresponding element in the aChange[] array
  656. ** is zero or greater (if a column is unmodified the corresponding element
  657. ** is set to -1). If the rowid column is modified by the UPDATE statement
  658. ** the bChngRowid argument is non-zero.
  659. **
  660. ** This function returns true if any of the columns that are part of the
  661. ** child key for FK constraint *p are modified.
  662. */
  663. static int fkChildIsModified(
  664. Table *pTab, /* Table being updated */
  665. FKey *p, /* Foreign key for which pTab is the child */
  666. int *aChange, /* Array indicating modified columns */
  667. int bChngRowid /* True if rowid is modified by this update */
  668. ){
  669. int i;
  670. for(i=0; i<p->nCol; i++){
  671. int iChildKey = p->aCol[i].iFrom;
  672. if( aChange[iChildKey]>=0 ) return 1;
  673. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  674. }
  675. return 0;
  676. }
  677. /*
  678. ** The second argument points to an FKey object representing a foreign key
  679. ** for which pTab is the parent table. An UPDATE statement against pTab
  680. ** is currently being processed. For each column of the table that is
  681. ** actually updated, the corresponding element in the aChange[] array
  682. ** is zero or greater (if a column is unmodified the corresponding element
  683. ** is set to -1). If the rowid column is modified by the UPDATE statement
  684. ** the bChngRowid argument is non-zero.
  685. **
  686. ** This function returns true if any of the columns that are part of the
  687. ** parent key for FK constraint *p are modified.
  688. */
  689. static int fkParentIsModified(
  690. Table *pTab,
  691. FKey *p,
  692. int *aChange,
  693. int bChngRowid
  694. ){
  695. int i;
  696. for(i=0; i<p->nCol; i++){
  697. char *zKey = p->aCol[i].zCol;
  698. int iKey;
  699. for(iKey=0; iKey<pTab->nCol; iKey++){
  700. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  701. Column *pCol = &pTab->aCol[iKey];
  702. if( zKey ){
  703. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  704. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  705. return 1;
  706. }
  707. }
  708. }
  709. }
  710. return 0;
  711. }
  712. /*
  713. ** This function is called when inserting, deleting or updating a row of
  714. ** table pTab to generate VDBE code to perform foreign key constraint
  715. ** processing for the operation.
  716. **
  717. ** For a DELETE operation, parameter regOld is passed the index of the
  718. ** first register in an array of (pTab->nCol+1) registers containing the
  719. ** rowid of the row being deleted, followed by each of the column values
  720. ** of the row being deleted, from left to right. Parameter regNew is passed
  721. ** zero in this case.
  722. **
  723. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  724. ** first register of an array of (pTab->nCol+1) registers containing the new
  725. ** row data.
  726. **
  727. ** For an UPDATE operation, this function is called twice. Once before
  728. ** the original record is deleted from the table using the calling convention
  729. ** described for DELETE. Then again after the original record is deleted
  730. ** but before the new record is inserted using the INSERT convention.
  731. */
  732. void sqlite3FkCheck(
  733. Parse *pParse, /* Parse context */
  734. Table *pTab, /* Row is being deleted from this table */
  735. int regOld, /* Previous row data is stored here */
  736. int regNew, /* New row data is stored here */
  737. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  738. int bChngRowid /* True if rowid is UPDATEd */
  739. ){
  740. sqlite3 *db = pParse->db; /* Database handle */
  741. FKey *pFKey; /* Used to iterate through FKs */
  742. int iDb; /* Index of database containing pTab */
  743. const char *zDb; /* Name of database containing pTab */
  744. int isIgnoreErrors = pParse->disableTriggers;
  745. /* Exactly one of regOld and regNew should be non-zero. */
  746. assert( (regOld==0)!=(regNew==0) );
  747. /* If foreign-keys are disabled, this function is a no-op. */
  748. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  749. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  750. zDb = db->aDb[iDb].zName;
  751. /* Loop through all the foreign key constraints for which pTab is the
  752. ** child table (the table that the foreign key definition is part of). */
  753. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  754. Table *pTo; /* Parent table of foreign key pFKey */
  755. Index *pIdx = 0; /* Index on key columns in pTo */
  756. int *aiFree = 0;
  757. int *aiCol;
  758. int iCol;
  759. int i;
  760. int isIgnore = 0;
  761. if( aChange
  762. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  763. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  764. ){
  765. continue;
  766. }
  767. /* Find the parent table of this foreign key. Also find a unique index
  768. ** on the parent key columns in the parent table. If either of these
  769. ** schema items cannot be located, set an error in pParse and return
  770. ** early. */
  771. if( pParse->disableTriggers ){
  772. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  773. }else{
  774. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  775. }
  776. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  777. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  778. if( !isIgnoreErrors || db->mallocFailed ) return;
  779. if( pTo==0 ){
  780. /* If isIgnoreErrors is true, then a table is being dropped. In this
  781. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  782. ** before actually dropping it in order to check FK constraints.
  783. ** If the parent table of an FK constraint on the current table is
  784. ** missing, behave as if it is empty. i.e. decrement the relevant
  785. ** FK counter for each row of the current table with non-NULL keys.
  786. */
  787. Vdbe *v = sqlite3GetVdbe(pParse);
  788. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  789. for(i=0; i<pFKey->nCol; i++){
  790. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  791. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  792. }
  793. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  794. }
  795. continue;
  796. }
  797. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  798. if( aiFree ){
  799. aiCol = aiFree;
  800. }else{
  801. iCol = pFKey->aCol[0].iFrom;
  802. aiCol = &iCol;
  803. }
  804. for(i=0; i<pFKey->nCol; i++){
  805. if( aiCol[i]==pTab->iPKey ){
  806. aiCol[i] = -1;
  807. }
  808. #ifndef SQLITE_OMIT_AUTHORIZATION
  809. /* Request permission to read the parent key columns. If the
  810. ** authorization callback returns SQLITE_IGNORE, behave as if any
  811. ** values read from the parent table are NULL. */
  812. if( db->xAuth ){
  813. int rcauth;
  814. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  815. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  816. isIgnore = (rcauth==SQLITE_IGNORE);
  817. }
  818. #endif
  819. }
  820. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  821. ** a cursor to use to search the unique index on the parent key columns
  822. ** in the parent table. */
  823. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  824. pParse->nTab++;
  825. if( regOld!=0 ){
  826. /* A row is being removed from the child table. Search for the parent.
  827. ** If the parent does not exist, removing the child row resolves an
  828. ** outstanding foreign key constraint violation. */
  829. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  830. }
  831. if( regNew!=0 ){
  832. /* A row is being added to the child table. If a parent row cannot
  833. ** be found, adding the child row has violated the FK constraint. */
  834. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  835. }
  836. sqlite3DbFree(db, aiFree);
  837. }
  838. /* Loop through all the foreign key constraints that refer to this table */
  839. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  840. Index *pIdx = 0; /* Foreign key index for pFKey */
  841. SrcList *pSrc;
  842. int *aiCol = 0;
  843. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  844. continue;
  845. }
  846. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  847. && !pParse->pToplevel && !pParse->isMultiWrite
  848. ){
  849. assert( regOld==0 && regNew!=0 );
  850. /* Inserting a single row into a parent table cannot cause an immediate
  851. ** foreign key violation. So do nothing in this case. */
  852. continue;
  853. }
  854. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  855. if( !isIgnoreErrors || db->mallocFailed ) return;
  856. continue;
  857. }
  858. assert( aiCol || pFKey->nCol==1 );
  859. /* Create a SrcList structure containing a single table (the table
  860. ** the foreign key that refers to this table is attached to). This
  861. ** is required for the sqlite3WhereXXX() interface. */
  862. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  863. if( pSrc ){
  864. struct SrcList_item *pItem = pSrc->a;
  865. pItem->pTab = pFKey->pFrom;
  866. pItem->zName = pFKey->pFrom->zName;
  867. pItem->pTab->nRef++;
  868. pItem->iCursor = pParse->nTab++;
  869. if( regNew!=0 ){
  870. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  871. }
  872. if( regOld!=0 ){
  873. /* If there is a RESTRICT action configured for the current operation
  874. ** on the parent table of this FK, then throw an exception
  875. ** immediately if the FK constraint is violated, even if this is a
  876. ** deferred trigger. That's what RESTRICT means. To defer checking
  877. ** the constraint, the FK should specify NO ACTION (represented
  878. ** using OE_None). NO ACTION is the default. */
  879. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  880. }
  881. pItem->zName = 0;
  882. sqlite3SrcListDelete(db, pSrc);
  883. }
  884. sqlite3DbFree(db, aiCol);
  885. }
  886. }
  887. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  888. /*
  889. ** This function is called before generating code to update or delete a
  890. ** row contained in table pTab.
  891. */
  892. u32 sqlite3FkOldmask(
  893. Parse *pParse, /* Parse context */
  894. Table *pTab /* Table being modified */
  895. ){
  896. u32 mask = 0;
  897. if( pParse->db->flags&SQLITE_ForeignKeys ){
  898. FKey *p;
  899. int i;
  900. for(p=pTab->pFKey; p; p=p->pNextFrom){
  901. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  902. }
  903. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  904. Index *pIdx = 0;
  905. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  906. if( pIdx ){
  907. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  908. }
  909. }
  910. }
  911. return mask;
  912. }
  913. /*
  914. ** This function is called before generating code to update or delete a
  915. ** row contained in table pTab. If the operation is a DELETE, then
  916. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  917. ** to an array of size N, where N is the number of columns in table pTab.
  918. ** If the i'th column is not modified by the UPDATE, then the corresponding
  919. ** entry in the aChange[] array is set to -1. If the column is modified,
  920. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  921. ** UPDATE statement modifies the rowid fields of the table.
  922. **
  923. ** If any foreign key processing will be required, this function returns
  924. ** true. If there is no foreign key related processing, this function
  925. ** returns false.
  926. */
  927. int sqlite3FkRequired(
  928. Parse *pParse, /* Parse context */
  929. Table *pTab, /* Table being modified */
  930. int *aChange, /* Non-NULL for UPDATE operations */
  931. int chngRowid /* True for UPDATE that affects rowid */
  932. ){
  933. if( pParse->db->flags&SQLITE_ForeignKeys ){
  934. if( !aChange ){
  935. /* A DELETE operation. Foreign key processing is required if the
  936. ** table in question is either the child or parent table for any
  937. ** foreign key constraint. */
  938. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  939. }else{
  940. /* This is an UPDATE. Foreign key processing is only required if the
  941. ** operation modifies one or more child or parent key columns. */
  942. FKey *p;
  943. /* Check if any child key columns are being modified. */
  944. for(p=pTab->pFKey; p; p=p->pNextFrom){
  945. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  946. }
  947. /* Check if any parent key columns are being modified. */
  948. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  949. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  950. }
  951. }
  952. }
  953. return 0;
  954. }
  955. /*
  956. ** This function is called when an UPDATE or DELETE operation is being
  957. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  958. ** If the current operation is an UPDATE, then the pChanges parameter is
  959. ** passed a pointer to the list of columns being modified. If it is a
  960. ** DELETE, pChanges is passed a NULL pointer.
  961. **
  962. ** It returns a pointer to a Trigger structure containing a trigger
  963. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  964. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  965. ** returned (these actions require no special handling by the triggers
  966. ** sub-system, code for them is created by fkScanChildren()).
  967. **
  968. ** For example, if pFKey is the foreign key and pTab is table "p" in
  969. ** the following schema:
  970. **
  971. ** CREATE TABLE p(pk PRIMARY KEY);
  972. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  973. **
  974. ** then the returned trigger structure is equivalent to:
  975. **
  976. ** CREATE TRIGGER ... DELETE ON p BEGIN
  977. ** DELETE FROM c WHERE ck = old.pk;
  978. ** END;
  979. **
  980. ** The returned pointer is cached as part of the foreign key object. It
  981. ** is eventually freed along with the rest of the foreign key object by
  982. ** sqlite3FkDelete().
  983. */
  984. static Trigger *fkActionTrigger(
  985. Parse *pParse, /* Parse context */
  986. Table *pTab, /* Table being updated or deleted from */
  987. FKey *pFKey, /* Foreign key to get action for */
  988. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  989. ){
  990. sqlite3 *db = pParse->db; /* Database handle */
  991. int action; /* One of OE_None, OE_Cascade etc. */
  992. Trigger *pTrigger; /* Trigger definition to return */
  993. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  994. action = pFKey->aAction[iAction];
  995. pTrigger = pFKey->apTrigger[iAction];
  996. if( action!=OE_None && !pTrigger ){
  997. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  998. char const *zFrom; /* Name of child table */
  999. int nFrom; /* Length in bytes of zFrom */
  1000. Index *pIdx = 0; /* Parent key index for this FK */
  1001. int *aiCol = 0; /* child table cols -> parent key cols */
  1002. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  1003. Expr *pWhere = 0; /* WHERE clause of trigger step */
  1004. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  1005. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  1006. int i; /* Iterator variable */
  1007. Expr *pWhen = 0; /* WHEN clause for the trigger */
  1008. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  1009. assert( aiCol || pFKey->nCol==1 );
  1010. for(i=0; i<pFKey->nCol; i++){
  1011. Token tOld = { "old", 3 }; /* Literal "old" token */
  1012. Token tNew = { "new", 3 }; /* Literal "new" token */
  1013. Token tFromCol; /* Name of column in child table */
  1014. Token tToCol; /* Name of column in parent table */
  1015. int iFromCol; /* Idx of column in child table */
  1016. Expr *pEq; /* tFromCol = OLD.tToCol */
  1017. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  1018. assert( iFromCol>=0 );
  1019. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  1020. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  1021. tToCol.n = sqlite3Strlen30(tToCol.z);
  1022. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  1023. /* Create the expression "OLD.zToCol = zFromCol". It is important
  1024. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  1025. ** that the affinity and collation sequence associated with the
  1026. ** parent table are used for the comparison. */
  1027. pEq = sqlite3PExpr(pParse, TK_EQ,
  1028. sqlite3PExpr(pParse, TK_DOT,
  1029. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  1030. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  1031. , 0),
  1032. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  1033. , 0);
  1034. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  1035. /* For ON UPDATE, construct the next term of the WHEN clause.
  1036. ** The final WHEN clause will be like this:
  1037. **
  1038. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  1039. */
  1040. if( pChanges ){
  1041. pEq = sqlite3PExpr(pParse, TK_IS,
  1042. sqlite3PExpr(pParse, TK_DOT,
  1043. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  1044. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  1045. 0),
  1046. sqlite3PExpr(pParse, TK_DOT,
  1047. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  1048. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  1049. 0),
  1050. 0);
  1051. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  1052. }
  1053. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  1054. Expr *pNew;
  1055. if( action==OE_Cascade ){
  1056. pNew = sqlite3PExpr(pParse, TK_DOT,
  1057. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  1058. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  1059. , 0);
  1060. }else if( action==OE_SetDflt ){
  1061. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  1062. if( pDflt ){
  1063. pNew = sqlite3ExprDup(db, pDflt, 0);
  1064. }else{
  1065. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  1066. }
  1067. }else{
  1068. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  1069. }
  1070. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  1071. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  1072. }
  1073. }
  1074. sqlite3DbFree(db, aiCol);
  1075. zFrom = pFKey->pFrom->zName;
  1076. nFrom = sqlite3Strlen30(zFrom);
  1077. if( action==OE_Restrict ){
  1078. Token tFrom;
  1079. Expr *pRaise;
  1080. tFrom.z = zFrom;
  1081. tFrom.n = nFrom;
  1082. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  1083. if( pRaise ){
  1084. pRaise->affinity = OE_Abort;
  1085. }
  1086. pSelect = sqlite3SelectNew(pParse,
  1087. sqlite3ExprListAppend(pParse, 0, pRaise),
  1088. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  1089. pWhere,
  1090. 0, 0, 0, 0, 0, 0
  1091. );
  1092. pWhere = 0;
  1093. }
  1094. /* Disable lookaside memory allocation */
  1095. enableLookaside = db->lookaside.bEnabled;
  1096. db->lookaside.bEnabled = 0;
  1097. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  1098. sizeof(Trigger) + /* struct Trigger */
  1099. sizeof(TriggerStep) + /* Single step in trigger program */
  1100. nFrom + 1 /* Space for pStep->target.z */
  1101. );
  1102. if( pTrigger ){
  1103. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  1104. pStep->target.z = (char *)&pStep[1];
  1105. pStep->target.n = nFrom;
  1106. memcpy((char *)pStep->target.z, zFrom, nFrom);
  1107. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  1108. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  1109. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  1110. if( pWhen ){
  1111. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  1112. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  1113. }
  1114. }
  1115. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  1116. db->lookaside.bEnabled = enableLookaside;
  1117. sqlite3ExprDelete(db, pWhere);
  1118. sqlite3ExprDelete(db, pWhen);
  1119. sqlite3ExprListDelete(db, pList);
  1120. sqlite3SelectDelete(db, pSelect);
  1121. if( db->mallocFailed==1 ){
  1122. fkTriggerDelete(db, pTrigger);
  1123. return 0;
  1124. }
  1125. assert( pStep!=0 );
  1126. switch( action ){
  1127. case OE_Restrict:
  1128. pStep->op = TK_SELECT;
  1129. break;
  1130. case OE_Cascade:
  1131. if( !pChanges ){
  1132. pStep->op = TK_DELETE;
  1133. break;
  1134. }
  1135. default:
  1136. pStep->op = TK_UPDATE;
  1137. }
  1138. pStep->pTrig = pTrigger;
  1139. pTrigger->pSchema = pTab->pSchema;
  1140. pTrigger->pTabSchema = pTab->pSchema;
  1141. pFKey->apTrigger[iAction] = pTrigger;
  1142. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  1143. }
  1144. return pTrigger;
  1145. }
  1146. /*
  1147. ** This function is called when deleting or updating a row to implement
  1148. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  1149. */
  1150. void sqlite3FkActions(
  1151. Parse *pParse, /* Parse context */
  1152. Table *pTab, /* Table being updated or deleted from */
  1153. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  1154. int regOld, /* Address of array containing old row */
  1155. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  1156. int bChngRowid /* True if rowid is UPDATEd */
  1157. ){
  1158. /* If foreign-key support is enabled, iterate through all FKs that
  1159. ** refer to table pTab. If there is an action associated with the FK
  1160. ** for this operation (either update or delete), invoke the associated
  1161. ** trigger sub-program. */
  1162. if( pParse->db->flags&SQLITE_ForeignKeys ){
  1163. FKey *pFKey; /* Iterator variable */
  1164. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  1165. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  1166. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  1167. if( pAct ){
  1168. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  1175. /*
  1176. ** Free all memory associated with foreign key definitions attached to
  1177. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  1178. ** hash table.
  1179. */
  1180. void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  1181. FKey *pFKey; /* Iterator variable */
  1182. FKey *pNext; /* Copy of pFKey->pNextFrom */
  1183. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  1184. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  1185. /* Remove the FK from the fkeyHash hash table. */
  1186. if( !db || db->pnBytesFreed==0 ){
  1187. if( pFKey->pPrevTo ){
  1188. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  1189. }else{
  1190. void *p = (void *)pFKey->pNextTo;
  1191. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  1192. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  1193. }
  1194. if( pFKey->pNextTo ){
  1195. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  1196. }
  1197. }
  1198. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  1199. ** classified as either immediate or deferred.
  1200. */
  1201. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  1202. /* Delete any triggers created to implement actions for this FK. */
  1203. #ifndef SQLITE_OMIT_TRIGGER
  1204. fkTriggerDelete(db, pFKey->apTrigger[0]);
  1205. fkTriggerDelete(db, pFKey->apTrigger[1]);
  1206. #endif
  1207. pNext = pFKey->pNextFrom;
  1208. sqlite3DbFree(db, pFKey);
  1209. }
  1210. }
  1211. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */