xref: /sqlite-3.40.0/src/delete.c (revision 06ae6792)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** in order to generate code for DELETE FROM statements.
14 */
15 #include "sqliteInt.h"
16 
17 /*
18 ** Look up every table that is named in pSrc.  If any table is not found,
19 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
20 ** are found, return a pointer to the last table.
21 */
22 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
23   struct SrcList_item *pItem = pSrc->a;
24   Table *pTab;
25   assert( pItem && pSrc->nSrc==1 );
26   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
27   sqlite3DeleteTable(pParse->db, pItem->pTab);
28   pItem->pTab = pTab;
29   if( pTab ){
30     pTab->nRef++;
31   }
32   if( sqlite3IndexedByLookup(pParse, pItem) ){
33     pTab = 0;
34   }
35   return pTab;
36 }
37 
38 /*
39 ** Check to make sure the given table is writable.  If it is not
40 ** writable, generate an error message and return 1.  If it is
41 ** writable return 0;
42 */
43 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
44   /* A table is not writable under the following circumstances:
45   **
46   **   1) It is a virtual table and no implementation of the xUpdate method
47   **      has been provided, or
48   **   2) It is a system table (i.e. sqlite_master), this call is not
49   **      part of a nested parse and writable_schema pragma has not
50   **      been specified.
51   **
52   ** In either case leave an error message in pParse and return non-zero.
53   */
54   if( ( IsVirtual(pTab)
55      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
56    || ( (pTab->tabFlags & TF_Readonly)!=0
57      && (pParse->db->flags & SQLITE_WriteSchema)==0
58      && pParse->nested==0 )
59   ){
60     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
61     return 1;
62   }
63 
64 #ifndef SQLITE_OMIT_VIEW
65   if( !viewOk && pTab->pSelect ){
66     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
67     return 1;
68   }
69 #endif
70   return 0;
71 }
72 
73 
74 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
75 /*
76 ** Evaluate a view and store its result in an ephemeral table.  The
77 ** pWhere argument is an optional WHERE clause that restricts the
78 ** set of rows in the view that are to be added to the ephemeral table.
79 */
80 void sqlite3MaterializeView(
81   Parse *pParse,       /* Parsing context */
82   Table *pView,        /* View definition */
83   Expr *pWhere,        /* Optional WHERE clause to be added */
84   int iCur             /* Cursor number for ephemerial table */
85 ){
86   SelectDest dest;
87   Select *pDup;
88   sqlite3 *db = pParse->db;
89 
90   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
91   if( pWhere ){
92     SrcList *pFrom;
93 
94     pWhere = sqlite3ExprDup(db, pWhere, 0);
95     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
96     if( pFrom ){
97       assert( pFrom->nSrc==1 );
98       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
99       pFrom->a[0].pSelect = pDup;
100       assert( pFrom->a[0].pOn==0 );
101       assert( pFrom->a[0].pUsing==0 );
102     }else{
103       sqlite3SelectDelete(db, pDup);
104     }
105     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
106   }
107   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
108   sqlite3Select(pParse, pDup, &dest);
109   sqlite3SelectDelete(db, pDup);
110 }
111 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
112 
113 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
114 /*
115 ** Generate an expression tree to implement the WHERE, ORDER BY,
116 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
117 **
118 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
119 **                            \__________________________/
120 **                               pLimitWhere (pInClause)
121 */
122 Expr *sqlite3LimitWhere(
123   Parse *pParse,               /* The parser context */
124   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
125   Expr *pWhere,                /* The WHERE clause.  May be null */
126   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
127   Expr *pLimit,                /* The LIMIT clause.  May be null */
128   Expr *pOffset,               /* The OFFSET clause.  May be null */
129   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
130 ){
131   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
132   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
133   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
134   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
135   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
136   Select *pSelect = NULL;      /* Complete SELECT tree */
137 
138   /* Check that there isn't an ORDER BY without a LIMIT clause.
139   */
140   if( pOrderBy && (pLimit == 0) ) {
141     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
142     pParse->parseError = 1;
143     goto limit_where_cleanup_2;
144   }
145 
146   /* We only need to generate a select expression if there
147   ** is a limit/offset term to enforce.
148   */
149   if( pLimit == 0 ) {
150     /* if pLimit is null, pOffset will always be null as well. */
151     assert( pOffset == 0 );
152     return pWhere;
153   }
154 
155   /* Generate a select expression tree to enforce the limit/offset
156   ** term for the DELETE or UPDATE statement.  For example:
157   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
158   ** becomes:
159   **   DELETE FROM table_a WHERE rowid IN (
160   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
161   **   );
162   */
163 
164   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
165   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
166   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
167   if( pEList == 0 ) goto limit_where_cleanup_2;
168 
169   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
170   ** and the SELECT subtree. */
171   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
172   if( pSelectSrc == 0 ) {
173     sqlite3ExprListDelete(pParse->db, pEList);
174     goto limit_where_cleanup_2;
175   }
176 
177   /* generate the SELECT expression tree. */
178   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
179                              pOrderBy,0,pLimit,pOffset);
180   if( pSelect == 0 ) return 0;
181 
182   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
183   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
184   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
185   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
186   if( pInClause == 0 ) goto limit_where_cleanup_1;
187 
188   pInClause->x.pSelect = pSelect;
189   pInClause->flags |= EP_xIsSelect;
190   sqlite3ExprSetHeight(pParse, pInClause);
191   return pInClause;
192 
193   /* something went wrong. clean up anything allocated. */
194 limit_where_cleanup_1:
195   sqlite3SelectDelete(pParse->db, pSelect);
196   return 0;
197 
198 limit_where_cleanup_2:
199   sqlite3ExprDelete(pParse->db, pWhere);
200   sqlite3ExprListDelete(pParse->db, pOrderBy);
201   sqlite3ExprDelete(pParse->db, pLimit);
202   sqlite3ExprDelete(pParse->db, pOffset);
203   return 0;
204 }
205 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
206 
207 /*
208 ** Generate code for a DELETE FROM statement.
209 **
210 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
211 **                 \________/       \________________/
212 **                  pTabList              pWhere
213 */
214 void sqlite3DeleteFrom(
215   Parse *pParse,         /* The parser context */
216   SrcList *pTabList,     /* The table from which we should delete things */
217   Expr *pWhere           /* The WHERE clause.  May be null */
218 ){
219   Vdbe *v;               /* The virtual database engine */
220   Table *pTab;           /* The table from which records will be deleted */
221   const char *zDb;       /* Name of database holding pTab */
222   int end, addr = 0;     /* A couple addresses of generated code */
223   int i;                 /* Loop counter */
224   WhereInfo *pWInfo;     /* Information about the WHERE clause */
225   Index *pIdx;           /* For looping over indices of the table */
226   int iCur;              /* VDBE Cursor number for pTab */
227   sqlite3 *db;           /* Main database structure */
228   AuthContext sContext;  /* Authorization context */
229   NameContext sNC;       /* Name context to resolve expressions in */
230   int iDb;               /* Database number */
231   int memCnt = -1;       /* Memory cell used for change counting */
232   int rcauth;            /* Value returned by authorization callback */
233 
234 #ifndef SQLITE_OMIT_TRIGGER
235   int isView;                  /* True if attempting to delete from a view */
236   Trigger *pTrigger;           /* List of table triggers, if required */
237 #endif
238 
239   memset(&sContext, 0, sizeof(sContext));
240   db = pParse->db;
241   if( pParse->nErr || db->mallocFailed ){
242     goto delete_from_cleanup;
243   }
244   assert( pTabList->nSrc==1 );
245 
246   /* Locate the table which we want to delete.  This table has to be
247   ** put in an SrcList structure because some of the subroutines we
248   ** will be calling are designed to work with multiple tables and expect
249   ** an SrcList* parameter instead of just a Table* parameter.
250   */
251   pTab = sqlite3SrcListLookup(pParse, pTabList);
252   if( pTab==0 )  goto delete_from_cleanup;
253 
254   /* Figure out if we have any triggers and if the table being
255   ** deleted from is a view
256   */
257 #ifndef SQLITE_OMIT_TRIGGER
258   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
259   isView = pTab->pSelect!=0;
260 #else
261 # define pTrigger 0
262 # define isView 0
263 #endif
264 #ifdef SQLITE_OMIT_VIEW
265 # undef isView
266 # define isView 0
267 #endif
268 
269   /* If pTab is really a view, make sure it has been initialized.
270   */
271   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
272     goto delete_from_cleanup;
273   }
274 
275   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
276     goto delete_from_cleanup;
277   }
278   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
279   assert( iDb<db->nDb );
280   zDb = db->aDb[iDb].zName;
281   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
282   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
283   if( rcauth==SQLITE_DENY ){
284     goto delete_from_cleanup;
285   }
286   assert(!isView || pTrigger);
287 
288   /* Assign  cursor number to the table and all its indices.
289   */
290   assert( pTabList->nSrc==1 );
291   iCur = pTabList->a[0].iCursor = pParse->nTab++;
292   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
293     pParse->nTab++;
294   }
295 
296   /* Start the view context
297   */
298   if( isView ){
299     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
300   }
301 
302   /* Begin generating code.
303   */
304   v = sqlite3GetVdbe(pParse);
305   if( v==0 ){
306     goto delete_from_cleanup;
307   }
308   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
309   sqlite3BeginWriteOperation(pParse, 1, iDb);
310 
311   /* If we are trying to delete from a view, realize that view into
312   ** a ephemeral table.
313   */
314 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
315   if( isView ){
316     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
317   }
318 #endif
319 
320   /* Resolve the column names in the WHERE clause.
321   */
322   memset(&sNC, 0, sizeof(sNC));
323   sNC.pParse = pParse;
324   sNC.pSrcList = pTabList;
325   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
326     goto delete_from_cleanup;
327   }
328 
329   /* Initialize the counter of the number of rows deleted, if
330   ** we are counting rows.
331   */
332   if( db->flags & SQLITE_CountRows ){
333     memCnt = ++pParse->nMem;
334     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
335   }
336 
337 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
338   /* Special case: A DELETE without a WHERE clause deletes everything.
339   ** It is easier just to erase the whole table. Prior to version 3.6.5,
340   ** this optimization caused the row change count (the value returned by
341   ** API function sqlite3_count_changes) to be set incorrectly.  */
342   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
343    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
344   ){
345     assert( !isView );
346     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
347                       pTab->zName, P4_STATIC);
348     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
349       assert( pIdx->pSchema==pTab->pSchema );
350       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
351     }
352   }else
353 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
354   /* The usual case: There is a WHERE clause so we have to scan through
355   ** the table and pick which records to delete.
356   */
357   {
358     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
359     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
360     int regRowid;                   /* Actual register containing rowids */
361 
362     /* Collect rowids of every row to be deleted.
363     */
364     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
365     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
366     if( pWInfo==0 ) goto delete_from_cleanup;
367     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
368     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
369     if( db->flags & SQLITE_CountRows ){
370       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
371     }
372     sqlite3WhereEnd(pWInfo);
373 
374     /* Delete every item whose key was written to the list during the
375     ** database scan.  We have to delete items after the scan is complete
376     ** because deleting an item can change the scan order.  */
377     end = sqlite3VdbeMakeLabel(v);
378 
379     /* Unless this is a view, open cursors for the table we are
380     ** deleting from and all its indices. If this is a view, then the
381     ** only effect this statement has is to fire the INSTEAD OF
382     ** triggers.  */
383     if( !isView ){
384       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
385     }
386 
387     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
388 
389     /* Delete the row */
390 #ifndef SQLITE_OMIT_VIRTUALTABLE
391     if( IsVirtual(pTab) ){
392       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
393       sqlite3VtabMakeWritable(pParse, pTab);
394       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
395       sqlite3MayAbort(pParse);
396     }else
397 #endif
398     {
399       int count = (pParse->nested==0);    /* True to count changes */
400       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
401     }
402 
403     /* End of the delete loop */
404     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
405     sqlite3VdbeResolveLabel(v, end);
406 
407     /* Close the cursors open on the table and its indexes. */
408     if( !isView && !IsVirtual(pTab) ){
409       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
410         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
411       }
412       sqlite3VdbeAddOp1(v, OP_Close, iCur);
413     }
414   }
415 
416   /* Update the sqlite_sequence table by storing the content of the
417   ** maximum rowid counter values recorded while inserting into
418   ** autoincrement tables.
419   */
420   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
421     sqlite3AutoincrementEnd(pParse);
422   }
423 
424   /* Return the number of rows that were deleted. If this routine is
425   ** generating code because of a call to sqlite3NestedParse(), do not
426   ** invoke the callback function.
427   */
428   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
429     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
430     sqlite3VdbeSetNumCols(v, 1);
431     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
432   }
433 
434 delete_from_cleanup:
435   sqlite3AuthContextPop(&sContext);
436   sqlite3SrcListDelete(db, pTabList);
437   sqlite3ExprDelete(db, pWhere);
438   return;
439 }
440 /* Make sure "isView" and other macros defined above are undefined. Otherwise
441 ** thely may interfere with compilation of other functions in this file
442 ** (or in another file, if this file becomes part of the amalgamation).  */
443 #ifdef isView
444  #undef isView
445 #endif
446 #ifdef pTrigger
447  #undef pTrigger
448 #endif
449 
450 /*
451 ** This routine generates VDBE code that causes a single row of a
452 ** single table to be deleted.
453 **
454 ** The VDBE must be in a particular state when this routine is called.
455 ** These are the requirements:
456 **
457 **   1.  A read/write cursor pointing to pTab, the table containing the row
458 **       to be deleted, must be opened as cursor number $iCur.
459 **
460 **   2.  Read/write cursors for all indices of pTab must be open as
461 **       cursor number base+i for the i-th index.
462 **
463 **   3.  The record number of the row to be deleted must be stored in
464 **       memory cell iRowid.
465 **
466 ** This routine generates code to remove both the table record and all
467 ** index entries that point to that record.
468 */
469 void sqlite3GenerateRowDelete(
470   Parse *pParse,     /* Parsing context */
471   Table *pTab,       /* Table containing the row to be deleted */
472   int iCur,          /* Cursor number for the table */
473   int iRowid,        /* Memory cell that contains the rowid to delete */
474   int count,         /* If non-zero, increment the row change counter */
475   Trigger *pTrigger, /* List of triggers to (potentially) fire */
476   int onconf         /* Default ON CONFLICT policy for triggers */
477 ){
478   Vdbe *v = pParse->pVdbe;        /* Vdbe */
479   int iOld = 0;                   /* First register in OLD.* array */
480   int iLabel;                     /* Label resolved to end of generated code */
481 
482   /* Vdbe is guaranteed to have been allocated by this stage. */
483   assert( v );
484 
485   /* Seek cursor iCur to the row to delete. If this row no longer exists
486   ** (this can happen if a trigger program has already deleted it), do
487   ** not attempt to delete it or fire any DELETE triggers.  */
488   iLabel = sqlite3VdbeMakeLabel(v);
489   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
490 
491   /* If there are any triggers to fire, allocate a range of registers to
492   ** use for the old.* references in the triggers.  */
493   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
494     u32 mask;                     /* Mask of OLD.* columns in use */
495     int iCol;                     /* Iterator used while populating OLD.* */
496 
497     /* TODO: Could use temporary registers here. Also could attempt to
498     ** avoid copying the contents of the rowid register.  */
499     mask = sqlite3TriggerColmask(
500         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
501     );
502     mask |= sqlite3FkOldmask(pParse, pTab);
503     iOld = pParse->nMem+1;
504     pParse->nMem += (1 + pTab->nCol);
505 
506     /* Populate the OLD.* pseudo-table register array. These values will be
507     ** used by any BEFORE and AFTER triggers that exist.  */
508     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
509     for(iCol=0; iCol<pTab->nCol; iCol++){
510       if( mask==0xffffffff || mask&(1<<iCol) ){
511         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
512       }
513     }
514 
515     /* Invoke BEFORE DELETE trigger programs. */
516     sqlite3CodeRowTrigger(pParse, pTrigger,
517         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
518     );
519 
520     /* Seek the cursor to the row to be deleted again. It may be that
521     ** the BEFORE triggers coded above have already removed the row
522     ** being deleted. Do not attempt to delete the row a second time, and
523     ** do not fire AFTER triggers.  */
524     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
525 
526     /* Do FK processing. This call checks that any FK constraints that
527     ** refer to this table (i.e. constraints attached to other tables)
528     ** are not violated by deleting this row.  */
529     sqlite3FkCheck(pParse, pTab, iOld, 0);
530   }
531 
532   /* Delete the index and table entries. Skip this step if pTab is really
533   ** a view (in which case the only effect of the DELETE statement is to
534   ** fire the INSTEAD OF triggers).  */
535   if( pTab->pSelect==0 ){
536     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
537     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
538     if( count ){
539       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
540     }
541   }
542 
543   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
544   ** handle rows (possibly in other tables) that refer via a foreign key
545   ** to the row just deleted. */
546   sqlite3FkActions(pParse, pTab, 0, iOld);
547 
548   /* Invoke AFTER DELETE trigger programs. */
549   sqlite3CodeRowTrigger(pParse, pTrigger,
550       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
551   );
552 
553   /* Jump here if the row had already been deleted before any BEFORE
554   ** trigger programs were invoked. Or if a trigger program throws a
555   ** RAISE(IGNORE) exception.  */
556   sqlite3VdbeResolveLabel(v, iLabel);
557 }
558 
559 /*
560 ** This routine generates VDBE code that causes the deletion of all
561 ** index entries associated with a single row of a single table.
562 **
563 ** The VDBE must be in a particular state when this routine is called.
564 ** These are the requirements:
565 **
566 **   1.  A read/write cursor pointing to pTab, the table containing the row
567 **       to be deleted, must be opened as cursor number "iCur".
568 **
569 **   2.  Read/write cursors for all indices of pTab must be open as
570 **       cursor number iCur+i for the i-th index.
571 **
572 **   3.  The "iCur" cursor must be pointing to the row that is to be
573 **       deleted.
574 */
575 void sqlite3GenerateRowIndexDelete(
576   Parse *pParse,     /* Parsing and code generating context */
577   Table *pTab,       /* Table containing the row to be deleted */
578   int iCur,          /* Cursor number for the table */
579   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
580 ){
581   int i;
582   Index *pIdx;
583   int r1;
584 
585   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
586     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
587     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
588     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
589   }
590 }
591 
592 /*
593 ** Generate code that will assemble an index key and put it in register
594 ** regOut.  The key with be for index pIdx which is an index on pTab.
595 ** iCur is the index of a cursor open on the pTab table and pointing to
596 ** the entry that needs indexing.
597 **
598 ** Return a register number which is the first in a block of
599 ** registers that holds the elements of the index key.  The
600 ** block of registers has already been deallocated by the time
601 ** this routine returns.
602 */
603 int sqlite3GenerateIndexKey(
604   Parse *pParse,     /* Parsing context */
605   Index *pIdx,       /* The index for which to generate a key */
606   int iCur,          /* Cursor number for the pIdx->pTable table */
607   int regOut,        /* Write the new index key to this register */
608   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
609 ){
610   Vdbe *v = pParse->pVdbe;
611   int j;
612   Table *pTab = pIdx->pTable;
613   int regBase;
614   int nCol;
615 
616   nCol = pIdx->nColumn;
617   regBase = sqlite3GetTempRange(pParse, nCol+1);
618   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
619   for(j=0; j<nCol; j++){
620     int idx = pIdx->aiColumn[j];
621     if( idx==pTab->iPKey ){
622       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
623     }else{
624       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
625       sqlite3ColumnDefault(v, pTab, idx, -1);
626     }
627   }
628   if( doMakeRec ){
629     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
630     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
631   }
632   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
633   return regBase;
634 }
635