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