xref: /sqlite-3.40.0/src/insert.c (revision 9bccde3d)
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 ** to handle INSERT statements in SQLite.
14 */
15 #include "sqliteInt.h"
16 
17 /*
18 ** Generate code that will
19 **
20 **   (1) acquire a lock for table pTab then
21 **   (2) open pTab as cursor iCur.
22 **
23 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
24 ** for that table that is actually opened.
25 */
26 void sqlite3OpenTable(
27   Parse *pParse,  /* Generate code into this VDBE */
28   int iCur,       /* The cursor number of the table */
29   int iDb,        /* The database index in sqlite3.aDb[] */
30   Table *pTab,    /* The table to be opened */
31   int opcode      /* OP_OpenRead or OP_OpenWrite */
32 ){
33   Vdbe *v;
34   assert( !IsVirtual(pTab) );
35   v = sqlite3GetVdbe(pParse);
36   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
37   sqlite3TableLock(pParse, iDb, pTab->tnum,
38                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
39   if( HasRowid(pTab) ){
40     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
41     VdbeComment((v, "%s", pTab->zName));
42   }else{
43     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44     assert( pPk!=0 );
45     assert( pPk->tnum==pTab->tnum );
46     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
47     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
48     VdbeComment((v, "%s", pTab->zName));
49   }
50 }
51 
52 /*
53 ** Return a pointer to the column affinity string associated with index
54 ** pIdx. A column affinity string has one character for each column in
55 ** the table, according to the affinity of the column:
56 **
57 **  Character      Column affinity
58 **  ------------------------------
59 **  'A'            BLOB
60 **  'B'            TEXT
61 **  'C'            NUMERIC
62 **  'D'            INTEGER
63 **  'F'            REAL
64 **
65 ** An extra 'D' is appended to the end of the string to cover the
66 ** rowid that appears as the last column in every index.
67 **
68 ** Memory for the buffer containing the column index affinity string
69 ** is managed along with the rest of the Index structure. It will be
70 ** released when sqlite3DeleteIndex() is called.
71 */
72 const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
73   if( !pIdx->zColAff ){
74     /* The first time a column affinity string for a particular index is
75     ** required, it is allocated and populated here. It is then stored as
76     ** a member of the Index structure for subsequent use.
77     **
78     ** The column affinity string will eventually be deleted by
79     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80     ** up.
81     */
82     int n;
83     Table *pTab = pIdx->pTable;
84     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85     if( !pIdx->zColAff ){
86       sqlite3OomFault(db);
87       return 0;
88     }
89     for(n=0; n<pIdx->nColumn; n++){
90       i16 x = pIdx->aiColumn[n];
91       if( x>=0 ){
92         pIdx->zColAff[n] = pTab->aCol[x].affinity;
93       }else if( x==XN_ROWID ){
94         pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
95       }else{
96         char aff;
97         assert( x==XN_EXPR );
98         assert( pIdx->aColExpr!=0 );
99         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
100         if( aff==0 ) aff = SQLITE_AFF_BLOB;
101         pIdx->zColAff[n] = aff;
102       }
103     }
104     pIdx->zColAff[n] = 0;
105   }
106 
107   return pIdx->zColAff;
108 }
109 
110 /*
111 ** Compute the affinity string for table pTab, if it has not already been
112 ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
113 **
114 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
115 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
116 ** for register iReg and following.  Or if affinities exists and iReg==0,
117 ** then just set the P4 operand of the previous opcode (which should  be
118 ** an OP_MakeRecord) to the affinity string.
119 **
120 ** A column affinity string has one character per column:
121 **
122 **  Character      Column affinity
123 **  ------------------------------
124 **  'A'            BLOB
125 **  'B'            TEXT
126 **  'C'            NUMERIC
127 **  'D'            INTEGER
128 **  'E'            REAL
129 */
130 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
131   int i;
132   char *zColAff = pTab->zColAff;
133   if( zColAff==0 ){
134     sqlite3 *db = sqlite3VdbeDb(v);
135     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
136     if( !zColAff ){
137       sqlite3OomFault(db);
138       return;
139     }
140 
141     for(i=0; i<pTab->nCol; i++){
142       zColAff[i] = pTab->aCol[i].affinity;
143     }
144     do{
145       zColAff[i--] = 0;
146     }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
147     pTab->zColAff = zColAff;
148   }
149   i = sqlite3Strlen30(zColAff);
150   if( i ){
151     if( iReg ){
152       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
153     }else{
154       sqlite3VdbeChangeP4(v, -1, zColAff, i);
155     }
156   }
157 }
158 
159 /*
160 ** Return non-zero if the table pTab in database iDb or any of its indices
161 ** have been opened at any point in the VDBE program. This is used to see if
162 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
163 ** run without using a temporary table for the results of the SELECT.
164 */
165 static int readsTable(Parse *p, int iDb, Table *pTab){
166   Vdbe *v = sqlite3GetVdbe(p);
167   int i;
168   int iEnd = sqlite3VdbeCurrentAddr(v);
169 #ifndef SQLITE_OMIT_VIRTUALTABLE
170   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
171 #endif
172 
173   for(i=1; i<iEnd; i++){
174     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
175     assert( pOp!=0 );
176     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
177       Index *pIndex;
178       int tnum = pOp->p2;
179       if( tnum==pTab->tnum ){
180         return 1;
181       }
182       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
183         if( tnum==pIndex->tnum ){
184           return 1;
185         }
186       }
187     }
188 #ifndef SQLITE_OMIT_VIRTUALTABLE
189     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
190       assert( pOp->p4.pVtab!=0 );
191       assert( pOp->p4type==P4_VTAB );
192       return 1;
193     }
194 #endif
195   }
196   return 0;
197 }
198 
199 #ifndef SQLITE_OMIT_AUTOINCREMENT
200 /*
201 ** Locate or create an AutoincInfo structure associated with table pTab
202 ** which is in database iDb.  Return the register number for the register
203 ** that holds the maximum rowid.
204 **
205 ** There is at most one AutoincInfo structure per table even if the
206 ** same table is autoincremented multiple times due to inserts within
207 ** triggers.  A new AutoincInfo structure is created if this is the
208 ** first use of table pTab.  On 2nd and subsequent uses, the original
209 ** AutoincInfo structure is used.
210 **
211 ** Three memory locations are allocated:
212 **
213 **   (1)  Register to hold the name of the pTab table.
214 **   (2)  Register to hold the maximum ROWID of pTab.
215 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
216 **
217 ** The 2nd register is the one that is returned.  That is all the
218 ** insert routine needs to know about.
219 */
220 static int autoIncBegin(
221   Parse *pParse,      /* Parsing context */
222   int iDb,            /* Index of the database holding pTab */
223   Table *pTab         /* The table we are writing to */
224 ){
225   int memId = 0;      /* Register holding maximum rowid */
226   if( pTab->tabFlags & TF_Autoincrement ){
227     Parse *pToplevel = sqlite3ParseToplevel(pParse);
228     AutoincInfo *pInfo;
229 
230     pInfo = pToplevel->pAinc;
231     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
232     if( pInfo==0 ){
233       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
234       if( pInfo==0 ) return 0;
235       pInfo->pNext = pToplevel->pAinc;
236       pToplevel->pAinc = pInfo;
237       pInfo->pTab = pTab;
238       pInfo->iDb = iDb;
239       pToplevel->nMem++;                  /* Register to hold name of table */
240       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
241       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
242     }
243     memId = pInfo->regCtr;
244   }
245   return memId;
246 }
247 
248 /*
249 ** This routine generates code that will initialize all of the
250 ** register used by the autoincrement tracker.
251 */
252 void sqlite3AutoincrementBegin(Parse *pParse){
253   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
254   sqlite3 *db = pParse->db;  /* The database connection */
255   Db *pDb;                   /* Database only autoinc table */
256   int memId;                 /* Register holding max rowid */
257   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
258 
259   /* This routine is never called during trigger-generation.  It is
260   ** only called from the top-level */
261   assert( pParse->pTriggerTab==0 );
262   assert( sqlite3IsToplevel(pParse) );
263 
264   assert( v );   /* We failed long ago if this is not so */
265   for(p = pParse->pAinc; p; p = p->pNext){
266     static const int iLn = VDBE_OFFSET_LINENO(2);
267     static const VdbeOpList autoInc[] = {
268       /* 0  */ {OP_Null,    0,  0, 0},
269       /* 1  */ {OP_Rewind,  0,  9, 0},
270       /* 2  */ {OP_Column,  0,  0, 0},
271       /* 3  */ {OP_Ne,      0,  7, 0},
272       /* 4  */ {OP_Rowid,   0,  0, 0},
273       /* 5  */ {OP_Column,  0,  1, 0},
274       /* 6  */ {OP_Goto,    0,  9, 0},
275       /* 7  */ {OP_Next,    0,  2, 0},
276       /* 8  */ {OP_Integer, 0,  0, 0},
277       /* 9  */ {OP_Close,   0,  0, 0}
278     };
279     VdbeOp *aOp;
280     pDb = &db->aDb[p->iDb];
281     memId = p->regCtr;
282     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
283     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
284     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
285     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
286     if( aOp==0 ) break;
287     aOp[0].p2 = memId;
288     aOp[0].p3 = memId+1;
289     aOp[2].p3 = memId;
290     aOp[3].p1 = memId-1;
291     aOp[3].p3 = memId;
292     aOp[3].p5 = SQLITE_JUMPIFNULL;
293     aOp[4].p2 = memId+1;
294     aOp[5].p3 = memId;
295     aOp[8].p2 = memId;
296   }
297 }
298 
299 /*
300 ** Update the maximum rowid for an autoincrement calculation.
301 **
302 ** This routine should be called when the regRowid register holds a
303 ** new rowid that is about to be inserted.  If that new rowid is
304 ** larger than the maximum rowid in the memId memory cell, then the
305 ** memory cell is updated.
306 */
307 static void autoIncStep(Parse *pParse, int memId, int regRowid){
308   if( memId>0 ){
309     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
310   }
311 }
312 
313 /*
314 ** This routine generates the code needed to write autoincrement
315 ** maximum rowid values back into the sqlite_sequence register.
316 ** Every statement that might do an INSERT into an autoincrement
317 ** table (either directly or through triggers) needs to call this
318 ** routine just before the "exit" code.
319 */
320 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
321   AutoincInfo *p;
322   Vdbe *v = pParse->pVdbe;
323   sqlite3 *db = pParse->db;
324 
325   assert( v );
326   for(p = pParse->pAinc; p; p = p->pNext){
327     static const int iLn = VDBE_OFFSET_LINENO(2);
328     static const VdbeOpList autoIncEnd[] = {
329       /* 0 */ {OP_NotNull,     0, 2, 0},
330       /* 1 */ {OP_NewRowid,    0, 0, 0},
331       /* 2 */ {OP_MakeRecord,  0, 2, 0},
332       /* 3 */ {OP_Insert,      0, 0, 0},
333       /* 4 */ {OP_Close,       0, 0, 0}
334     };
335     VdbeOp *aOp;
336     Db *pDb = &db->aDb[p->iDb];
337     int iRec;
338     int memId = p->regCtr;
339 
340     iRec = sqlite3GetTempReg(pParse);
341     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
342     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
343     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
344     if( aOp==0 ) break;
345     aOp[0].p1 = memId+1;
346     aOp[1].p2 = memId+1;
347     aOp[2].p1 = memId-1;
348     aOp[2].p3 = iRec;
349     aOp[3].p2 = iRec;
350     aOp[3].p3 = memId+1;
351     aOp[3].p5 = OPFLAG_APPEND;
352     sqlite3ReleaseTempReg(pParse, iRec);
353   }
354 }
355 void sqlite3AutoincrementEnd(Parse *pParse){
356   if( pParse->pAinc ) autoIncrementEnd(pParse);
357 }
358 #else
359 /*
360 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
361 ** above are all no-ops
362 */
363 # define autoIncBegin(A,B,C) (0)
364 # define autoIncStep(A,B,C)
365 #endif /* SQLITE_OMIT_AUTOINCREMENT */
366 
367 
368 /* Forward declaration */
369 static int xferOptimization(
370   Parse *pParse,        /* Parser context */
371   Table *pDest,         /* The table we are inserting into */
372   Select *pSelect,      /* A SELECT statement to use as the data source */
373   int onError,          /* How to handle constraint errors */
374   int iDbDest           /* The database of pDest */
375 );
376 
377 /*
378 ** This routine is called to handle SQL of the following forms:
379 **
380 **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
381 **    insert into TABLE (IDLIST) select
382 **    insert into TABLE (IDLIST) default values
383 **
384 ** The IDLIST following the table name is always optional.  If omitted,
385 ** then a list of all (non-hidden) columns for the table is substituted.
386 ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
387 ** is omitted.
388 **
389 ** For the pSelect parameter holds the values to be inserted for the
390 ** first two forms shown above.  A VALUES clause is really just short-hand
391 ** for a SELECT statement that omits the FROM clause and everything else
392 ** that follows.  If the pSelect parameter is NULL, that means that the
393 ** DEFAULT VALUES form of the INSERT statement is intended.
394 **
395 ** The code generated follows one of four templates.  For a simple
396 ** insert with data coming from a single-row VALUES clause, the code executes
397 ** once straight down through.  Pseudo-code follows (we call this
398 ** the "1st template"):
399 **
400 **         open write cursor to <table> and its indices
401 **         put VALUES clause expressions into registers
402 **         write the resulting record into <table>
403 **         cleanup
404 **
405 ** The three remaining templates assume the statement is of the form
406 **
407 **   INSERT INTO <table> SELECT ...
408 **
409 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
410 ** in other words if the SELECT pulls all columns from a single table
411 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
412 ** if <table2> and <table1> are distinct tables but have identical
413 ** schemas, including all the same indices, then a special optimization
414 ** is invoked that copies raw records from <table2> over to <table1>.
415 ** See the xferOptimization() function for the implementation of this
416 ** template.  This is the 2nd template.
417 **
418 **         open a write cursor to <table>
419 **         open read cursor on <table2>
420 **         transfer all records in <table2> over to <table>
421 **         close cursors
422 **         foreach index on <table>
423 **           open a write cursor on the <table> index
424 **           open a read cursor on the corresponding <table2> index
425 **           transfer all records from the read to the write cursors
426 **           close cursors
427 **         end foreach
428 **
429 ** The 3rd template is for when the second template does not apply
430 ** and the SELECT clause does not read from <table> at any time.
431 ** The generated code follows this template:
432 **
433 **         X <- A
434 **         goto B
435 **      A: setup for the SELECT
436 **         loop over the rows in the SELECT
437 **           load values into registers R..R+n
438 **           yield X
439 **         end loop
440 **         cleanup after the SELECT
441 **         end-coroutine X
442 **      B: open write cursor to <table> and its indices
443 **      C: yield X, at EOF goto D
444 **         insert the select result into <table> from R..R+n
445 **         goto C
446 **      D: cleanup
447 **
448 ** The 4th template is used if the insert statement takes its
449 ** values from a SELECT but the data is being inserted into a table
450 ** that is also read as part of the SELECT.  In the third form,
451 ** we have to use an intermediate table to store the results of
452 ** the select.  The template is like this:
453 **
454 **         X <- A
455 **         goto B
456 **      A: setup for the SELECT
457 **         loop over the tables in the SELECT
458 **           load value into register R..R+n
459 **           yield X
460 **         end loop
461 **         cleanup after the SELECT
462 **         end co-routine R
463 **      B: open temp table
464 **      L: yield X, at EOF goto M
465 **         insert row from R..R+n into temp table
466 **         goto L
467 **      M: open write cursor to <table> and its indices
468 **         rewind temp table
469 **      C: loop over rows of intermediate table
470 **           transfer values form intermediate table into <table>
471 **         end loop
472 **      D: cleanup
473 */
474 void sqlite3Insert(
475   Parse *pParse,        /* Parser context */
476   SrcList *pTabList,    /* Name of table into which we are inserting */
477   Select *pSelect,      /* A SELECT statement to use as the data source */
478   IdList *pColumn,      /* Column names corresponding to IDLIST. */
479   int onError           /* How to handle constraint errors */
480 ){
481   sqlite3 *db;          /* The main database structure */
482   Table *pTab;          /* The table to insert into.  aka TABLE */
483   char *zTab;           /* Name of the table into which we are inserting */
484   const char *zDb;      /* Name of the database holding this table */
485   int i, j, idx;        /* Loop counters */
486   Vdbe *v;              /* Generate code into this virtual machine */
487   Index *pIdx;          /* For looping over indices of the table */
488   int nColumn;          /* Number of columns in the data */
489   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
490   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
491   int iIdxCur = 0;      /* First index cursor */
492   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
493   int endOfLoop;        /* Label for the end of the insertion loop */
494   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
495   int addrInsTop = 0;   /* Jump to label "D" */
496   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
497   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
498   int iDb;              /* Index of database holding TABLE */
499   Db *pDb;              /* The database containing table being inserted into */
500   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
501   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
502   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
503   u8 bIdListInOrder;    /* True if IDLIST is in table order */
504   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
505 
506   /* Register allocations */
507   int regFromSelect = 0;/* Base register for data coming from SELECT */
508   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
509   int regRowCount = 0;  /* Memory cell used for the row counter */
510   int regIns;           /* Block of regs holding rowid+data being inserted */
511   int regRowid;         /* registers holding insert rowid */
512   int regData;          /* register holding first column to insert */
513   int *aRegIdx = 0;     /* One register allocated to each index */
514 
515 #ifndef SQLITE_OMIT_TRIGGER
516   int isView;                 /* True if attempting to insert into a view */
517   Trigger *pTrigger;          /* List of triggers on pTab, if required */
518   int tmask;                  /* Mask of trigger times */
519 #endif
520 
521   db = pParse->db;
522   memset(&dest, 0, sizeof(dest));
523   if( pParse->nErr || db->mallocFailed ){
524     goto insert_cleanup;
525   }
526 
527   /* If the Select object is really just a simple VALUES() list with a
528   ** single row (the common case) then keep that one row of values
529   ** and discard the other (unused) parts of the pSelect object
530   */
531   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
532     pList = pSelect->pEList;
533     pSelect->pEList = 0;
534     sqlite3SelectDelete(db, pSelect);
535     pSelect = 0;
536   }
537 
538   /* Locate the table into which we will be inserting new information.
539   */
540   assert( pTabList->nSrc==1 );
541   zTab = pTabList->a[0].zName;
542   if( NEVER(zTab==0) ) goto insert_cleanup;
543   pTab = sqlite3SrcListLookup(pParse, pTabList);
544   if( pTab==0 ){
545     goto insert_cleanup;
546   }
547   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
548   assert( iDb<db->nDb );
549   pDb = &db->aDb[iDb];
550   zDb = pDb->zName;
551   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
552     goto insert_cleanup;
553   }
554   withoutRowid = !HasRowid(pTab);
555 
556   /* Figure out if we have any triggers and if the table being
557   ** inserted into is a view
558   */
559 #ifndef SQLITE_OMIT_TRIGGER
560   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
561   isView = pTab->pSelect!=0;
562 #else
563 # define pTrigger 0
564 # define tmask 0
565 # define isView 0
566 #endif
567 #ifdef SQLITE_OMIT_VIEW
568 # undef isView
569 # define isView 0
570 #endif
571   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
572 
573   /* If pTab is really a view, make sure it has been initialized.
574   ** ViewGetColumnNames() is a no-op if pTab is not a view.
575   */
576   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
577     goto insert_cleanup;
578   }
579 
580   /* Cannot insert into a read-only table.
581   */
582   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
583     goto insert_cleanup;
584   }
585 
586   /* Allocate a VDBE
587   */
588   v = sqlite3GetVdbe(pParse);
589   if( v==0 ) goto insert_cleanup;
590   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
591   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
592 
593 #ifndef SQLITE_OMIT_XFER_OPT
594   /* If the statement is of the form
595   **
596   **       INSERT INTO <table1> SELECT * FROM <table2>;
597   **
598   ** Then special optimizations can be applied that make the transfer
599   ** very fast and which reduce fragmentation of indices.
600   **
601   ** This is the 2nd template.
602   */
603   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
604     assert( !pTrigger );
605     assert( pList==0 );
606     goto insert_end;
607   }
608 #endif /* SQLITE_OMIT_XFER_OPT */
609 
610   /* If this is an AUTOINCREMENT table, look up the sequence number in the
611   ** sqlite_sequence table and store it in memory cell regAutoinc.
612   */
613   regAutoinc = autoIncBegin(pParse, iDb, pTab);
614 
615   /* Allocate registers for holding the rowid of the new row,
616   ** the content of the new row, and the assembled row record.
617   */
618   regRowid = regIns = pParse->nMem+1;
619   pParse->nMem += pTab->nCol + 1;
620   if( IsVirtual(pTab) ){
621     regRowid++;
622     pParse->nMem++;
623   }
624   regData = regRowid+1;
625 
626   /* If the INSERT statement included an IDLIST term, then make sure
627   ** all elements of the IDLIST really are columns of the table and
628   ** remember the column indices.
629   **
630   ** If the table has an INTEGER PRIMARY KEY column and that column
631   ** is named in the IDLIST, then record in the ipkColumn variable
632   ** the index into IDLIST of the primary key column.  ipkColumn is
633   ** the index of the primary key as it appears in IDLIST, not as
634   ** is appears in the original table.  (The index of the INTEGER
635   ** PRIMARY KEY in the original table is pTab->iPKey.)
636   */
637   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
638   if( pColumn ){
639     for(i=0; i<pColumn->nId; i++){
640       pColumn->a[i].idx = -1;
641     }
642     for(i=0; i<pColumn->nId; i++){
643       for(j=0; j<pTab->nCol; j++){
644         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
645           pColumn->a[i].idx = j;
646           if( i!=j ) bIdListInOrder = 0;
647           if( j==pTab->iPKey ){
648             ipkColumn = i;  assert( !withoutRowid );
649           }
650           break;
651         }
652       }
653       if( j>=pTab->nCol ){
654         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
655           ipkColumn = i;
656           bIdListInOrder = 0;
657         }else{
658           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
659               pTabList, 0, pColumn->a[i].zName);
660           pParse->checkSchema = 1;
661           goto insert_cleanup;
662         }
663       }
664     }
665   }
666 
667   /* Figure out how many columns of data are supplied.  If the data
668   ** is coming from a SELECT statement, then generate a co-routine that
669   ** produces a single row of the SELECT on each invocation.  The
670   ** co-routine is the common header to the 3rd and 4th templates.
671   */
672   if( pSelect ){
673     /* Data is coming from a SELECT or from a multi-row VALUES clause.
674     ** Generate a co-routine to run the SELECT. */
675     int regYield;       /* Register holding co-routine entry-point */
676     int addrTop;        /* Top of the co-routine */
677     int rc;             /* Result code */
678 
679     regYield = ++pParse->nMem;
680     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
681     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
682     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
683     dest.iSdst = bIdListInOrder ? regData : 0;
684     dest.nSdst = pTab->nCol;
685     rc = sqlite3Select(pParse, pSelect, &dest);
686     regFromSelect = dest.iSdst;
687     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
688     sqlite3VdbeEndCoroutine(v, regYield);
689     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
690     assert( pSelect->pEList );
691     nColumn = pSelect->pEList->nExpr;
692 
693     /* Set useTempTable to TRUE if the result of the SELECT statement
694     ** should be written into a temporary table (template 4).  Set to
695     ** FALSE if each output row of the SELECT can be written directly into
696     ** the destination table (template 3).
697     **
698     ** A temp table must be used if the table being updated is also one
699     ** of the tables being read by the SELECT statement.  Also use a
700     ** temp table in the case of row triggers.
701     */
702     if( pTrigger || readsTable(pParse, iDb, pTab) ){
703       useTempTable = 1;
704     }
705 
706     if( useTempTable ){
707       /* Invoke the coroutine to extract information from the SELECT
708       ** and add it to a transient table srcTab.  The code generated
709       ** here is from the 4th template:
710       **
711       **      B: open temp table
712       **      L: yield X, goto M at EOF
713       **         insert row from R..R+n into temp table
714       **         goto L
715       **      M: ...
716       */
717       int regRec;          /* Register to hold packed record */
718       int regTempRowid;    /* Register to hold temp table ROWID */
719       int addrL;           /* Label "L" */
720 
721       srcTab = pParse->nTab++;
722       regRec = sqlite3GetTempReg(pParse);
723       regTempRowid = sqlite3GetTempReg(pParse);
724       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
725       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
726       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
727       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
728       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
729       sqlite3VdbeGoto(v, addrL);
730       sqlite3VdbeJumpHere(v, addrL);
731       sqlite3ReleaseTempReg(pParse, regRec);
732       sqlite3ReleaseTempReg(pParse, regTempRowid);
733     }
734   }else{
735     /* This is the case if the data for the INSERT is coming from a
736     ** single-row VALUES clause
737     */
738     NameContext sNC;
739     memset(&sNC, 0, sizeof(sNC));
740     sNC.pParse = pParse;
741     srcTab = -1;
742     assert( useTempTable==0 );
743     if( pList ){
744       nColumn = pList->nExpr;
745       if( sqlite3ResolveExprListNames(&sNC, pList) ){
746         goto insert_cleanup;
747       }
748     }else{
749       nColumn = 0;
750     }
751   }
752 
753   /* If there is no IDLIST term but the table has an integer primary
754   ** key, the set the ipkColumn variable to the integer primary key
755   ** column index in the original table definition.
756   */
757   if( pColumn==0 && nColumn>0 ){
758     ipkColumn = pTab->iPKey;
759   }
760 
761   /* Make sure the number of columns in the source data matches the number
762   ** of columns to be inserted into the table.
763   */
764   for(i=0; i<pTab->nCol; i++){
765     nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
766   }
767   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
768     sqlite3ErrorMsg(pParse,
769        "table %S has %d columns but %d values were supplied",
770        pTabList, 0, pTab->nCol-nHidden, nColumn);
771     goto insert_cleanup;
772   }
773   if( pColumn!=0 && nColumn!=pColumn->nId ){
774     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
775     goto insert_cleanup;
776   }
777 
778   /* Initialize the count of rows to be inserted
779   */
780   if( db->flags & SQLITE_CountRows ){
781     regRowCount = ++pParse->nMem;
782     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
783   }
784 
785   /* If this is not a view, open the table and and all indices */
786   if( !isView ){
787     int nIdx;
788     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
789                                       &iDataCur, &iIdxCur);
790     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
791     if( aRegIdx==0 ){
792       goto insert_cleanup;
793     }
794     for(i=0; i<nIdx; i++){
795       aRegIdx[i] = ++pParse->nMem;
796     }
797   }
798 
799   /* This is the top of the main insertion loop */
800   if( useTempTable ){
801     /* This block codes the top of loop only.  The complete loop is the
802     ** following pseudocode (template 4):
803     **
804     **         rewind temp table, if empty goto D
805     **      C: loop over rows of intermediate table
806     **           transfer values form intermediate table into <table>
807     **         end loop
808     **      D: ...
809     */
810     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
811     addrCont = sqlite3VdbeCurrentAddr(v);
812   }else if( pSelect ){
813     /* This block codes the top of loop only.  The complete loop is the
814     ** following pseudocode (template 3):
815     **
816     **      C: yield X, at EOF goto D
817     **         insert the select result into <table> from R..R+n
818     **         goto C
819     **      D: ...
820     */
821     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
822     VdbeCoverage(v);
823   }
824 
825   /* Run the BEFORE and INSTEAD OF triggers, if there are any
826   */
827   endOfLoop = sqlite3VdbeMakeLabel(v);
828   if( tmask & TRIGGER_BEFORE ){
829     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
830 
831     /* build the NEW.* reference row.  Note that if there is an INTEGER
832     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
833     ** translated into a unique ID for the row.  But on a BEFORE trigger,
834     ** we do not know what the unique ID will be (because the insert has
835     ** not happened yet) so we substitute a rowid of -1
836     */
837     if( ipkColumn<0 ){
838       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
839     }else{
840       int addr1;
841       assert( !withoutRowid );
842       if( useTempTable ){
843         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
844       }else{
845         assert( pSelect==0 );  /* Otherwise useTempTable is true */
846         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
847       }
848       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
849       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
850       sqlite3VdbeJumpHere(v, addr1);
851       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
852     }
853 
854     /* Cannot have triggers on a virtual table. If it were possible,
855     ** this block would have to account for hidden column.
856     */
857     assert( !IsVirtual(pTab) );
858 
859     /* Create the new column data
860     */
861     for(i=j=0; i<pTab->nCol; i++){
862       if( pColumn ){
863         for(j=0; j<pColumn->nId; j++){
864           if( pColumn->a[j].idx==i ) break;
865         }
866       }
867       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
868             || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
869         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
870       }else if( useTempTable ){
871         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
872       }else{
873         assert( pSelect==0 ); /* Otherwise useTempTable is true */
874         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
875       }
876       if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
877     }
878 
879     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
880     ** do not attempt any conversions before assembling the record.
881     ** If this is a real table, attempt conversions as required by the
882     ** table column affinities.
883     */
884     if( !isView ){
885       sqlite3TableAffinity(v, pTab, regCols+1);
886     }
887 
888     /* Fire BEFORE or INSTEAD OF triggers */
889     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
890         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
891 
892     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
893   }
894 
895   /* Compute the content of the next row to insert into a range of
896   ** registers beginning at regIns.
897   */
898   if( !isView ){
899     if( IsVirtual(pTab) ){
900       /* The row that the VUpdate opcode will delete: none */
901       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
902     }
903     if( ipkColumn>=0 ){
904       if( useTempTable ){
905         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
906       }else if( pSelect ){
907         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
908       }else{
909         VdbeOp *pOp;
910         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
911         pOp = sqlite3VdbeGetOp(v, -1);
912         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
913           appendFlag = 1;
914           pOp->opcode = OP_NewRowid;
915           pOp->p1 = iDataCur;
916           pOp->p2 = regRowid;
917           pOp->p3 = regAutoinc;
918         }
919       }
920       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
921       ** to generate a unique primary key value.
922       */
923       if( !appendFlag ){
924         int addr1;
925         if( !IsVirtual(pTab) ){
926           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
927           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
928           sqlite3VdbeJumpHere(v, addr1);
929         }else{
930           addr1 = sqlite3VdbeCurrentAddr(v);
931           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
932         }
933         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
934       }
935     }else if( IsVirtual(pTab) || withoutRowid ){
936       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
937     }else{
938       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
939       appendFlag = 1;
940     }
941     autoIncStep(pParse, regAutoinc, regRowid);
942 
943     /* Compute data for all columns of the new entry, beginning
944     ** with the first column.
945     */
946     nHidden = 0;
947     for(i=0; i<pTab->nCol; i++){
948       int iRegStore = regRowid+1+i;
949       if( i==pTab->iPKey ){
950         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
951         ** Whenever this column is read, the rowid will be substituted
952         ** in its place.  Hence, fill this column with a NULL to avoid
953         ** taking up data space with information that will never be used.
954         ** As there may be shallow copies of this value, make it a soft-NULL */
955         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
956         continue;
957       }
958       if( pColumn==0 ){
959         if( IsHiddenColumn(&pTab->aCol[i]) ){
960           j = -1;
961           nHidden++;
962         }else{
963           j = i - nHidden;
964         }
965       }else{
966         for(j=0; j<pColumn->nId; j++){
967           if( pColumn->a[j].idx==i ) break;
968         }
969       }
970       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
971         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
972       }else if( useTempTable ){
973         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
974       }else if( pSelect ){
975         if( regFromSelect!=regData ){
976           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
977         }
978       }else{
979         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
980       }
981     }
982 
983     /* Generate code to check constraints and generate index keys and
984     ** do the insertion.
985     */
986 #ifndef SQLITE_OMIT_VIRTUALTABLE
987     if( IsVirtual(pTab) ){
988       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
989       sqlite3VtabMakeWritable(pParse, pTab);
990       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
991       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
992       sqlite3MayAbort(pParse);
993     }else
994 #endif
995     {
996       int isReplace;    /* Set to true if constraints may cause a replace */
997       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
998           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
999       );
1000       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1001       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1002                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
1003     }
1004   }
1005 
1006   /* Update the count of rows that are inserted
1007   */
1008   if( (db->flags & SQLITE_CountRows)!=0 ){
1009     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1010   }
1011 
1012   if( pTrigger ){
1013     /* Code AFTER triggers */
1014     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1015         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1016   }
1017 
1018   /* The bottom of the main insertion loop, if the data source
1019   ** is a SELECT statement.
1020   */
1021   sqlite3VdbeResolveLabel(v, endOfLoop);
1022   if( useTempTable ){
1023     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1024     sqlite3VdbeJumpHere(v, addrInsTop);
1025     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1026   }else if( pSelect ){
1027     sqlite3VdbeGoto(v, addrCont);
1028     sqlite3VdbeJumpHere(v, addrInsTop);
1029   }
1030 
1031   if( !IsVirtual(pTab) && !isView ){
1032     /* Close all tables opened */
1033     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
1034     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
1035       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
1036     }
1037   }
1038 
1039 insert_end:
1040   /* Update the sqlite_sequence table by storing the content of the
1041   ** maximum rowid counter values recorded while inserting into
1042   ** autoincrement tables.
1043   */
1044   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1045     sqlite3AutoincrementEnd(pParse);
1046   }
1047 
1048   /*
1049   ** Return the number of rows inserted. If this routine is
1050   ** generating code because of a call to sqlite3NestedParse(), do not
1051   ** invoke the callback function.
1052   */
1053   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
1054     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
1055     sqlite3VdbeSetNumCols(v, 1);
1056     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
1057   }
1058 
1059 insert_cleanup:
1060   sqlite3SrcListDelete(db, pTabList);
1061   sqlite3ExprListDelete(db, pList);
1062   sqlite3SelectDelete(db, pSelect);
1063   sqlite3IdListDelete(db, pColumn);
1064   sqlite3DbFree(db, aRegIdx);
1065 }
1066 
1067 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1068 ** they may interfere with compilation of other functions in this file
1069 ** (or in another file, if this file becomes part of the amalgamation).  */
1070 #ifdef isView
1071  #undef isView
1072 #endif
1073 #ifdef pTrigger
1074  #undef pTrigger
1075 #endif
1076 #ifdef tmask
1077  #undef tmask
1078 #endif
1079 
1080 /*
1081 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
1082 */
1083 #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
1084 #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
1085 
1086 /* This is the Walker callback from checkConstraintUnchanged().  Set
1087 ** bit 0x01 of pWalker->eCode if
1088 ** pWalker->eCode to 0 if this expression node references any of the
1089 ** columns that are being modifed by an UPDATE statement.
1090 */
1091 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1092   if( pExpr->op==TK_COLUMN ){
1093     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1094     if( pExpr->iColumn>=0 ){
1095       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1096         pWalker->eCode |= CKCNSTRNT_COLUMN;
1097       }
1098     }else{
1099       pWalker->eCode |= CKCNSTRNT_ROWID;
1100     }
1101   }
1102   return WRC_Continue;
1103 }
1104 
1105 /*
1106 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
1107 ** only columns that are modified by the UPDATE are those for which
1108 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1109 **
1110 ** Return true if CHECK constraint pExpr does not use any of the
1111 ** changing columns (or the rowid if it is changing).  In other words,
1112 ** return true if this CHECK constraint can be skipped when validating
1113 ** the new row in the UPDATE statement.
1114 */
1115 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
1116   Walker w;
1117   memset(&w, 0, sizeof(w));
1118   w.eCode = 0;
1119   w.xExprCallback = checkConstraintExprNode;
1120   w.u.aiCol = aiChng;
1121   sqlite3WalkExpr(&w, pExpr);
1122   if( !chngRowid ){
1123     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1124     w.eCode &= ~CKCNSTRNT_ROWID;
1125   }
1126   testcase( w.eCode==0 );
1127   testcase( w.eCode==CKCNSTRNT_COLUMN );
1128   testcase( w.eCode==CKCNSTRNT_ROWID );
1129   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1130   return !w.eCode;
1131 }
1132 
1133 /*
1134 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1135 ** on table pTab.
1136 **
1137 ** The regNewData parameter is the first register in a range that contains
1138 ** the data to be inserted or the data after the update.  There will be
1139 ** pTab->nCol+1 registers in this range.  The first register (the one
1140 ** that regNewData points to) will contain the new rowid, or NULL in the
1141 ** case of a WITHOUT ROWID table.  The second register in the range will
1142 ** contain the content of the first table column.  The third register will
1143 ** contain the content of the second table column.  And so forth.
1144 **
1145 ** The regOldData parameter is similar to regNewData except that it contains
1146 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1147 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1148 ** checking regOldData for zero.
1149 **
1150 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1151 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1152 ** might be modified by the UPDATE.  If pkChng is false, then the key of
1153 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1154 **
1155 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1156 ** was explicitly specified as part of the INSERT statement.  If pkChng
1157 ** is zero, it means that the either rowid is computed automatically or
1158 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1159 ** pkChng will only be true if the INSERT statement provides an integer
1160 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1161 **
1162 ** The code generated by this routine will store new index entries into
1163 ** registers identified by aRegIdx[].  No index entry is created for
1164 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1165 ** the same as the order of indices on the linked list of indices
1166 ** at pTab->pIndex.
1167 **
1168 ** The caller must have already opened writeable cursors on the main
1169 ** table and all applicable indices (that is to say, all indices for which
1170 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
1171 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1172 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
1173 ** for the first index in the pTab->pIndex list.  Cursors for other indices
1174 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1175 **
1176 ** This routine also generates code to check constraints.  NOT NULL,
1177 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
1178 ** then the appropriate action is performed.  There are five possible
1179 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1180 **
1181 **  Constraint type  Action       What Happens
1182 **  ---------------  ----------   ----------------------------------------
1183 **  any              ROLLBACK     The current transaction is rolled back and
1184 **                                sqlite3_step() returns immediately with a
1185 **                                return code of SQLITE_CONSTRAINT.
1186 **
1187 **  any              ABORT        Back out changes from the current command
1188 **                                only (do not do a complete rollback) then
1189 **                                cause sqlite3_step() to return immediately
1190 **                                with SQLITE_CONSTRAINT.
1191 **
1192 **  any              FAIL         Sqlite3_step() returns immediately with a
1193 **                                return code of SQLITE_CONSTRAINT.  The
1194 **                                transaction is not rolled back and any
1195 **                                changes to prior rows are retained.
1196 **
1197 **  any              IGNORE       The attempt in insert or update the current
1198 **                                row is skipped, without throwing an error.
1199 **                                Processing continues with the next row.
1200 **                                (There is an immediate jump to ignoreDest.)
1201 **
1202 **  NOT NULL         REPLACE      The NULL value is replace by the default
1203 **                                value for that column.  If the default value
1204 **                                is NULL, the action is the same as ABORT.
1205 **
1206 **  UNIQUE           REPLACE      The other row that conflicts with the row
1207 **                                being inserted is removed.
1208 **
1209 **  CHECK            REPLACE      Illegal.  The results in an exception.
1210 **
1211 ** Which action to take is determined by the overrideError parameter.
1212 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1213 ** is used.  Or if pParse->onError==OE_Default then the onError value
1214 ** for the constraint is used.
1215 */
1216 void sqlite3GenerateConstraintChecks(
1217   Parse *pParse,       /* The parser context */
1218   Table *pTab,         /* The table being inserted or updated */
1219   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
1220   int iDataCur,        /* Canonical data cursor (main table or PK index) */
1221   int iIdxCur,         /* First index cursor */
1222   int regNewData,      /* First register in a range holding values to insert */
1223   int regOldData,      /* Previous content.  0 for INSERTs */
1224   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1225   u8 overrideError,    /* Override onError to this if not OE_Default */
1226   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1227   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1228   int *aiChng          /* column i is unchanged if aiChng[i]<0 */
1229 ){
1230   Vdbe *v;             /* VDBE under constrution */
1231   Index *pIdx;         /* Pointer to one of the indices */
1232   Index *pPk = 0;      /* The PRIMARY KEY index */
1233   sqlite3 *db;         /* Database connection */
1234   int i;               /* loop counter */
1235   int ix;              /* Index loop counter */
1236   int nCol;            /* Number of columns */
1237   int onError;         /* Conflict resolution strategy */
1238   int addr1;           /* Address of jump instruction */
1239   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1240   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1241   int ipkTop = 0;      /* Top of the rowid change constraint check */
1242   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
1243   u8 isUpdate;         /* True if this is an UPDATE operation */
1244   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
1245   int regRowid = -1;   /* Register holding ROWID value */
1246 
1247   isUpdate = regOldData!=0;
1248   db = pParse->db;
1249   v = sqlite3GetVdbe(pParse);
1250   assert( v!=0 );
1251   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1252   nCol = pTab->nCol;
1253 
1254   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1255   ** normal rowid tables.  nPkField is the number of key fields in the
1256   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
1257   ** number of fields in the true primary key of the table. */
1258   if( HasRowid(pTab) ){
1259     pPk = 0;
1260     nPkField = 1;
1261   }else{
1262     pPk = sqlite3PrimaryKeyIndex(pTab);
1263     nPkField = pPk->nKeyCol;
1264   }
1265 
1266   /* Record that this module has started */
1267   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1268                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1269 
1270   /* Test all NOT NULL constraints.
1271   */
1272   for(i=0; i<nCol; i++){
1273     if( i==pTab->iPKey ){
1274       continue;        /* ROWID is never NULL */
1275     }
1276     if( aiChng && aiChng[i]<0 ){
1277       /* Don't bother checking for NOT NULL on columns that do not change */
1278       continue;
1279     }
1280     onError = pTab->aCol[i].notNull;
1281     if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
1282     if( overrideError!=OE_Default ){
1283       onError = overrideError;
1284     }else if( onError==OE_Default ){
1285       onError = OE_Abort;
1286     }
1287     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
1288       onError = OE_Abort;
1289     }
1290     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1291         || onError==OE_Ignore || onError==OE_Replace );
1292     switch( onError ){
1293       case OE_Abort:
1294         sqlite3MayAbort(pParse);
1295         /* Fall through */
1296       case OE_Rollback:
1297       case OE_Fail: {
1298         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1299                                     pTab->aCol[i].zName);
1300         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1301                           regNewData+1+i, zMsg, P4_DYNAMIC);
1302         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1303         VdbeCoverage(v);
1304         break;
1305       }
1306       case OE_Ignore: {
1307         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
1308         VdbeCoverage(v);
1309         break;
1310       }
1311       default: {
1312         assert( onError==OE_Replace );
1313         addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
1314            VdbeCoverage(v);
1315         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
1316         sqlite3VdbeJumpHere(v, addr1);
1317         break;
1318       }
1319     }
1320   }
1321 
1322   /* Test all CHECK constraints
1323   */
1324 #ifndef SQLITE_OMIT_CHECK
1325   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1326     ExprList *pCheck = pTab->pCheck;
1327     pParse->ckBase = regNewData+1;
1328     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1329     for(i=0; i<pCheck->nExpr; i++){
1330       int allOk;
1331       Expr *pExpr = pCheck->a[i].pExpr;
1332       if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
1333       allOk = sqlite3VdbeMakeLabel(v);
1334       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
1335       if( onError==OE_Ignore ){
1336         sqlite3VdbeGoto(v, ignoreDest);
1337       }else{
1338         char *zName = pCheck->a[i].zName;
1339         if( zName==0 ) zName = pTab->zName;
1340         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1341         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1342                               onError, zName, P4_TRANSIENT,
1343                               P5_ConstraintCheck);
1344       }
1345       sqlite3VdbeResolveLabel(v, allOk);
1346     }
1347   }
1348 #endif /* !defined(SQLITE_OMIT_CHECK) */
1349 
1350   /* If rowid is changing, make sure the new rowid does not previously
1351   ** exist in the table.
1352   */
1353   if( pkChng && pPk==0 ){
1354     int addrRowidOk = sqlite3VdbeMakeLabel(v);
1355 
1356     /* Figure out what action to take in case of a rowid collision */
1357     onError = pTab->keyConf;
1358     if( overrideError!=OE_Default ){
1359       onError = overrideError;
1360     }else if( onError==OE_Default ){
1361       onError = OE_Abort;
1362     }
1363 
1364     if( isUpdate ){
1365       /* pkChng!=0 does not mean that the rowid has change, only that
1366       ** it might have changed.  Skip the conflict logic below if the rowid
1367       ** is unchanged. */
1368       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
1369       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1370       VdbeCoverage(v);
1371     }
1372 
1373     /* If the response to a rowid conflict is REPLACE but the response
1374     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
1375     ** to defer the running of the rowid conflict checking until after
1376     ** the UNIQUE constraints have run.
1377     */
1378     if( onError==OE_Replace && overrideError!=OE_Replace ){
1379       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1380         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
1381           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
1382           break;
1383         }
1384       }
1385     }
1386 
1387     /* Check to see if the new rowid already exists in the table.  Skip
1388     ** the following conflict logic if it does not. */
1389     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1390     VdbeCoverage(v);
1391 
1392     /* Generate code that deals with a rowid collision */
1393     switch( onError ){
1394       default: {
1395         onError = OE_Abort;
1396         /* Fall thru into the next case */
1397       }
1398       case OE_Rollback:
1399       case OE_Abort:
1400       case OE_Fail: {
1401         sqlite3RowidConstraint(pParse, onError, pTab);
1402         break;
1403       }
1404       case OE_Replace: {
1405         /* If there are DELETE triggers on this table and the
1406         ** recursive-triggers flag is set, call GenerateRowDelete() to
1407         ** remove the conflicting row from the table. This will fire
1408         ** the triggers and remove both the table and index b-tree entries.
1409         **
1410         ** Otherwise, if there are no triggers or the recursive-triggers
1411         ** flag is not set, but the table has one or more indexes, call
1412         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1413         ** only. The table b-tree entry will be replaced by the new entry
1414         ** when it is inserted.
1415         **
1416         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1417         ** also invoke MultiWrite() to indicate that this VDBE may require
1418         ** statement rollback (if the statement is aborted after the delete
1419         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1420         ** but being more selective here allows statements like:
1421         **
1422         **   REPLACE INTO t(rowid) VALUES($newrowid)
1423         **
1424         ** to run without a statement journal if there are no indexes on the
1425         ** table.
1426         */
1427         Trigger *pTrigger = 0;
1428         if( db->flags&SQLITE_RecTriggers ){
1429           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1430         }
1431         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1432           sqlite3MultiWrite(pParse);
1433           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1434                                    regNewData, 1, 0, OE_Replace,
1435                                    ONEPASS_SINGLE, -1);
1436         }else{
1437           if( pTab->pIndex ){
1438             sqlite3MultiWrite(pParse);
1439             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
1440           }
1441         }
1442         seenReplace = 1;
1443         break;
1444       }
1445       case OE_Ignore: {
1446         /*assert( seenReplace==0 );*/
1447         sqlite3VdbeGoto(v, ignoreDest);
1448         break;
1449       }
1450     }
1451     sqlite3VdbeResolveLabel(v, addrRowidOk);
1452     if( ipkTop ){
1453       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
1454       sqlite3VdbeJumpHere(v, ipkTop);
1455     }
1456   }
1457 
1458   /* Test all UNIQUE constraints by creating entries for each UNIQUE
1459   ** index and making sure that duplicate entries do not already exist.
1460   ** Compute the revised record entries for indices as we go.
1461   **
1462   ** This loop also handles the case of the PRIMARY KEY index for a
1463   ** WITHOUT ROWID table.
1464   */
1465   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
1466     int regIdx;          /* Range of registers hold conent for pIdx */
1467     int regR;            /* Range of registers holding conflicting PK */
1468     int iThisCur;        /* Cursor for this UNIQUE index */
1469     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
1470 
1471     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
1472     if( bAffinityDone==0 ){
1473       sqlite3TableAffinity(v, pTab, regNewData+1);
1474       bAffinityDone = 1;
1475     }
1476     iThisCur = iIdxCur+ix;
1477     addrUniqueOk = sqlite3VdbeMakeLabel(v);
1478 
1479     /* Skip partial indices for which the WHERE clause is not true */
1480     if( pIdx->pPartIdxWhere ){
1481       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
1482       pParse->ckBase = regNewData+1;
1483       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1484                             SQLITE_JUMPIFNULL);
1485       pParse->ckBase = 0;
1486     }
1487 
1488     /* Create a record for this index entry as it should appear after
1489     ** the insert or update.  Store that record in the aRegIdx[ix] register
1490     */
1491     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
1492     for(i=0; i<pIdx->nColumn; i++){
1493       int iField = pIdx->aiColumn[i];
1494       int x;
1495       if( iField==XN_EXPR ){
1496         pParse->ckBase = regNewData+1;
1497         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
1498         pParse->ckBase = 0;
1499         VdbeComment((v, "%s column %d", pIdx->zName, i));
1500       }else{
1501         if( iField==XN_ROWID || iField==pTab->iPKey ){
1502           if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
1503           x = regNewData;
1504           regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
1505         }else{
1506           x = iField + regNewData + 1;
1507         }
1508         sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
1509         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
1510       }
1511     }
1512     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
1513     VdbeComment((v, "for %s", pIdx->zName));
1514     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1515 
1516     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1517     ** of a WITHOUT ROWID table and there has been no change the
1518     ** primary key, then no collision is possible.  The collision detection
1519     ** logic below can all be skipped. */
1520     if( isUpdate && pPk==pIdx && pkChng==0 ){
1521       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1522       continue;
1523     }
1524 
1525     /* Find out what action to take in case there is a uniqueness conflict */
1526     onError = pIdx->onError;
1527     if( onError==OE_None ){
1528       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1529       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1530       continue;  /* pIdx is not a UNIQUE index */
1531     }
1532     if( overrideError!=OE_Default ){
1533       onError = overrideError;
1534     }else if( onError==OE_Default ){
1535       onError = OE_Abort;
1536     }
1537 
1538     /* Check to see if the new index entry will be unique */
1539     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
1540                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
1541 
1542     /* Generate code to handle collisions */
1543     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
1544     if( isUpdate || onError==OE_Replace ){
1545       if( HasRowid(pTab) ){
1546         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
1547         /* Conflict only if the rowid of the existing index entry
1548         ** is different from old-rowid */
1549         if( isUpdate ){
1550           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
1551           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1552           VdbeCoverage(v);
1553         }
1554       }else{
1555         int x;
1556         /* Extract the PRIMARY KEY from the end of the index entry and
1557         ** store it in registers regR..regR+nPk-1 */
1558         if( pIdx!=pPk ){
1559           for(i=0; i<pPk->nKeyCol; i++){
1560             assert( pPk->aiColumn[i]>=0 );
1561             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
1562             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
1563             VdbeComment((v, "%s.%s", pTab->zName,
1564                          pTab->aCol[pPk->aiColumn[i]].zName));
1565           }
1566         }
1567         if( isUpdate ){
1568           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1569           ** table, only conflict if the new PRIMARY KEY values are actually
1570           ** different from the old.
1571           **
1572           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1573           ** of the matched index row are different from the original PRIMARY
1574           ** KEY values of this row before the update.  */
1575           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1576           int op = OP_Ne;
1577           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
1578 
1579           for(i=0; i<pPk->nKeyCol; i++){
1580             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1581             x = pPk->aiColumn[i];
1582             assert( x>=0 );
1583             if( i==(pPk->nKeyCol-1) ){
1584               addrJump = addrUniqueOk;
1585               op = OP_Eq;
1586             }
1587             sqlite3VdbeAddOp4(v, op,
1588                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1589             );
1590             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1591             VdbeCoverageIf(v, op==OP_Eq);
1592             VdbeCoverageIf(v, op==OP_Ne);
1593           }
1594         }
1595       }
1596     }
1597 
1598     /* Generate code that executes if the new index entry is not unique */
1599     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1600         || onError==OE_Ignore || onError==OE_Replace );
1601     switch( onError ){
1602       case OE_Rollback:
1603       case OE_Abort:
1604       case OE_Fail: {
1605         sqlite3UniqueConstraint(pParse, onError, pIdx);
1606         break;
1607       }
1608       case OE_Ignore: {
1609         sqlite3VdbeGoto(v, ignoreDest);
1610         break;
1611       }
1612       default: {
1613         Trigger *pTrigger = 0;
1614         assert( onError==OE_Replace );
1615         sqlite3MultiWrite(pParse);
1616         if( db->flags&SQLITE_RecTriggers ){
1617           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1618         }
1619         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1620             regR, nPkField, 0, OE_Replace,
1621             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
1622         seenReplace = 1;
1623         break;
1624       }
1625     }
1626     sqlite3VdbeResolveLabel(v, addrUniqueOk);
1627     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1628     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
1629   }
1630   if( ipkTop ){
1631     sqlite3VdbeGoto(v, ipkTop+1);
1632     sqlite3VdbeJumpHere(v, ipkBottom);
1633   }
1634 
1635   *pbMayReplace = seenReplace;
1636   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
1637 }
1638 
1639 /*
1640 ** This routine generates code to finish the INSERT or UPDATE operation
1641 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1642 ** A consecutive range of registers starting at regNewData contains the
1643 ** rowid and the content to be inserted.
1644 **
1645 ** The arguments to this routine should be the same as the first six
1646 ** arguments to sqlite3GenerateConstraintChecks.
1647 */
1648 void sqlite3CompleteInsertion(
1649   Parse *pParse,      /* The parser context */
1650   Table *pTab,        /* the table into which we are inserting */
1651   int iDataCur,       /* Cursor of the canonical data source */
1652   int iIdxCur,        /* First index cursor */
1653   int regNewData,     /* Range of content */
1654   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1655   int isUpdate,       /* True for UPDATE, False for INSERT */
1656   int appendBias,     /* True if this is likely to be an append */
1657   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
1658 ){
1659   Vdbe *v;            /* Prepared statements under construction */
1660   Index *pIdx;        /* An index being inserted or updated */
1661   u8 pik_flags;       /* flag values passed to the btree insert */
1662   int regData;        /* Content registers (after the rowid) */
1663   int regRec;         /* Register holding assembled record for the table */
1664   int i;              /* Loop counter */
1665   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
1666 
1667   v = sqlite3GetVdbe(pParse);
1668   assert( v!=0 );
1669   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1670   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1671     if( aRegIdx[i]==0 ) continue;
1672     bAffinityDone = 1;
1673     if( pIdx->pPartIdxWhere ){
1674       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1675       VdbeCoverage(v);
1676     }
1677     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
1678     pik_flags = 0;
1679     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
1680     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
1681       assert( pParse->nested==0 );
1682       pik_flags |= OPFLAG_NCHANGE;
1683     }
1684     sqlite3VdbeChangeP5(v, pik_flags);
1685   }
1686   if( !HasRowid(pTab) ) return;
1687   regData = regNewData + 1;
1688   regRec = sqlite3GetTempReg(pParse);
1689   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1690   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
1691   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1692   if( pParse->nested ){
1693     pik_flags = 0;
1694   }else{
1695     pik_flags = OPFLAG_NCHANGE;
1696     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
1697   }
1698   if( appendBias ){
1699     pik_flags |= OPFLAG_APPEND;
1700   }
1701   if( useSeekResult ){
1702     pik_flags |= OPFLAG_USESEEKRESULT;
1703   }
1704   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
1705   if( !pParse->nested ){
1706     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
1707   }
1708   sqlite3VdbeChangeP5(v, pik_flags);
1709 }
1710 
1711 /*
1712 ** Allocate cursors for the pTab table and all its indices and generate
1713 ** code to open and initialized those cursors.
1714 **
1715 ** The cursor for the object that contains the complete data (normally
1716 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
1717 ** ROWID table) is returned in *piDataCur.  The first index cursor is
1718 ** returned in *piIdxCur.  The number of indices is returned.
1719 **
1720 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
1721 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
1722 ** If iBase is negative, then allocate the next available cursor.
1723 **
1724 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
1725 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
1726 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
1727 ** pTab->pIndex list.
1728 **
1729 ** If pTab is a virtual table, then this routine is a no-op and the
1730 ** *piDataCur and *piIdxCur values are left uninitialized.
1731 */
1732 int sqlite3OpenTableAndIndices(
1733   Parse *pParse,   /* Parsing context */
1734   Table *pTab,     /* Table to be opened */
1735   int op,          /* OP_OpenRead or OP_OpenWrite */
1736   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
1737   int iBase,       /* Use this for the table cursor, if there is one */
1738   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
1739   int *piDataCur,  /* Write the database source cursor number here */
1740   int *piIdxCur    /* Write the first index cursor number here */
1741 ){
1742   int i;
1743   int iDb;
1744   int iDataCur;
1745   Index *pIdx;
1746   Vdbe *v;
1747 
1748   assert( op==OP_OpenRead || op==OP_OpenWrite );
1749   assert( op==OP_OpenWrite || p5==0 );
1750   if( IsVirtual(pTab) ){
1751     /* This routine is a no-op for virtual tables. Leave the output
1752     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
1753     ** can detect if they are used by mistake in the caller. */
1754     return 0;
1755   }
1756   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1757   v = sqlite3GetVdbe(pParse);
1758   assert( v!=0 );
1759   if( iBase<0 ) iBase = pParse->nTab;
1760   iDataCur = iBase++;
1761   if( piDataCur ) *piDataCur = iDataCur;
1762   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
1763     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
1764   }else{
1765     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
1766   }
1767   if( piIdxCur ) *piIdxCur = iBase;
1768   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1769     int iIdxCur = iBase++;
1770     assert( pIdx->pSchema==pTab->pSchema );
1771     if( aToOpen==0 || aToOpen[i+1] ){
1772       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
1773       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1774       VdbeComment((v, "%s", pIdx->zName));
1775     }
1776     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
1777       if( piDataCur ) *piDataCur = iIdxCur;
1778     }else{
1779       sqlite3VdbeChangeP5(v, p5);
1780     }
1781   }
1782   if( iBase>pParse->nTab ) pParse->nTab = iBase;
1783   return i;
1784 }
1785 
1786 
1787 #ifdef SQLITE_TEST
1788 /*
1789 ** The following global variable is incremented whenever the
1790 ** transfer optimization is used.  This is used for testing
1791 ** purposes only - to make sure the transfer optimization really
1792 ** is happening when it is supposed to.
1793 */
1794 int sqlite3_xferopt_count;
1795 #endif /* SQLITE_TEST */
1796 
1797 
1798 #ifndef SQLITE_OMIT_XFER_OPT
1799 /*
1800 ** Check to see if index pSrc is compatible as a source of data
1801 ** for index pDest in an insert transfer optimization.  The rules
1802 ** for a compatible index:
1803 **
1804 **    *   The index is over the same set of columns
1805 **    *   The same DESC and ASC markings occurs on all columns
1806 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
1807 **    *   The same collating sequence on each column
1808 **    *   The index has the exact same WHERE clause
1809 */
1810 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1811   int i;
1812   assert( pDest && pSrc );
1813   assert( pDest->pTable!=pSrc->pTable );
1814   if( pDest->nKeyCol!=pSrc->nKeyCol ){
1815     return 0;   /* Different number of columns */
1816   }
1817   if( pDest->onError!=pSrc->onError ){
1818     return 0;   /* Different conflict resolution strategies */
1819   }
1820   for(i=0; i<pSrc->nKeyCol; i++){
1821     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1822       return 0;   /* Different columns indexed */
1823     }
1824     if( pSrc->aiColumn[i]==XN_EXPR ){
1825       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
1826       if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
1827                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
1828         return 0;   /* Different expressions in the index */
1829       }
1830     }
1831     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1832       return 0;   /* Different sort orders */
1833     }
1834     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
1835       return 0;   /* Different collating sequences */
1836     }
1837   }
1838   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1839     return 0;     /* Different WHERE clauses */
1840   }
1841 
1842   /* If no test above fails then the indices must be compatible */
1843   return 1;
1844 }
1845 
1846 /*
1847 ** Attempt the transfer optimization on INSERTs of the form
1848 **
1849 **     INSERT INTO tab1 SELECT * FROM tab2;
1850 **
1851 ** The xfer optimization transfers raw records from tab2 over to tab1.
1852 ** Columns are not decoded and reassembled, which greatly improves
1853 ** performance.  Raw index records are transferred in the same way.
1854 **
1855 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1856 ** There are lots of rules for determining compatibility - see comments
1857 ** embedded in the code for details.
1858 **
1859 ** This routine returns TRUE if the optimization is guaranteed to be used.
1860 ** Sometimes the xfer optimization will only work if the destination table
1861 ** is empty - a factor that can only be determined at run-time.  In that
1862 ** case, this routine generates code for the xfer optimization but also
1863 ** does a test to see if the destination table is empty and jumps over the
1864 ** xfer optimization code if the test fails.  In that case, this routine
1865 ** returns FALSE so that the caller will know to go ahead and generate
1866 ** an unoptimized transfer.  This routine also returns FALSE if there
1867 ** is no chance that the xfer optimization can be applied.
1868 **
1869 ** This optimization is particularly useful at making VACUUM run faster.
1870 */
1871 static int xferOptimization(
1872   Parse *pParse,        /* Parser context */
1873   Table *pDest,         /* The table we are inserting into */
1874   Select *pSelect,      /* A SELECT statement to use as the data source */
1875   int onError,          /* How to handle constraint errors */
1876   int iDbDest           /* The database of pDest */
1877 ){
1878   sqlite3 *db = pParse->db;
1879   ExprList *pEList;                /* The result set of the SELECT */
1880   Table *pSrc;                     /* The table in the FROM clause of SELECT */
1881   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
1882   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
1883   int i;                           /* Loop counter */
1884   int iDbSrc;                      /* The database of pSrc */
1885   int iSrc, iDest;                 /* Cursors from source and destination */
1886   int addr1, addr2;                /* Loop addresses */
1887   int emptyDestTest = 0;           /* Address of test for empty pDest */
1888   int emptySrcTest = 0;            /* Address of test for empty pSrc */
1889   Vdbe *v;                         /* The VDBE we are building */
1890   int regAutoinc;                  /* Memory register used by AUTOINC */
1891   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1892   int regData, regRowid;           /* Registers holding data and rowid */
1893 
1894   if( pSelect==0 ){
1895     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
1896   }
1897   if( pParse->pWith || pSelect->pWith ){
1898     /* Do not attempt to process this query if there are an WITH clauses
1899     ** attached to it. Proceeding may generate a false "no such table: xxx"
1900     ** error if pSelect reads from a CTE named "xxx".  */
1901     return 0;
1902   }
1903   if( sqlite3TriggerList(pParse, pDest) ){
1904     return 0;   /* tab1 must not have triggers */
1905   }
1906 #ifndef SQLITE_OMIT_VIRTUALTABLE
1907   if( pDest->tabFlags & TF_Virtual ){
1908     return 0;   /* tab1 must not be a virtual table */
1909   }
1910 #endif
1911   if( onError==OE_Default ){
1912     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1913     if( onError==OE_Default ) onError = OE_Abort;
1914   }
1915   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
1916   if( pSelect->pSrc->nSrc!=1 ){
1917     return 0;   /* FROM clause must have exactly one term */
1918   }
1919   if( pSelect->pSrc->a[0].pSelect ){
1920     return 0;   /* FROM clause cannot contain a subquery */
1921   }
1922   if( pSelect->pWhere ){
1923     return 0;   /* SELECT may not have a WHERE clause */
1924   }
1925   if( pSelect->pOrderBy ){
1926     return 0;   /* SELECT may not have an ORDER BY clause */
1927   }
1928   /* Do not need to test for a HAVING clause.  If HAVING is present but
1929   ** there is no ORDER BY, we will get an error. */
1930   if( pSelect->pGroupBy ){
1931     return 0;   /* SELECT may not have a GROUP BY clause */
1932   }
1933   if( pSelect->pLimit ){
1934     return 0;   /* SELECT may not have a LIMIT clause */
1935   }
1936   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
1937   if( pSelect->pPrior ){
1938     return 0;   /* SELECT may not be a compound query */
1939   }
1940   if( pSelect->selFlags & SF_Distinct ){
1941     return 0;   /* SELECT may not be DISTINCT */
1942   }
1943   pEList = pSelect->pEList;
1944   assert( pEList!=0 );
1945   if( pEList->nExpr!=1 ){
1946     return 0;   /* The result set must have exactly one column */
1947   }
1948   assert( pEList->a[0].pExpr );
1949   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
1950     return 0;   /* The result set must be the special operator "*" */
1951   }
1952 
1953   /* At this point we have established that the statement is of the
1954   ** correct syntactic form to participate in this optimization.  Now
1955   ** we have to check the semantics.
1956   */
1957   pItem = pSelect->pSrc->a;
1958   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
1959   if( pSrc==0 ){
1960     return 0;   /* FROM clause does not contain a real table */
1961   }
1962   if( pSrc==pDest ){
1963     return 0;   /* tab1 and tab2 may not be the same table */
1964   }
1965   if( HasRowid(pDest)!=HasRowid(pSrc) ){
1966     return 0;   /* source and destination must both be WITHOUT ROWID or not */
1967   }
1968 #ifndef SQLITE_OMIT_VIRTUALTABLE
1969   if( pSrc->tabFlags & TF_Virtual ){
1970     return 0;   /* tab2 must not be a virtual table */
1971   }
1972 #endif
1973   if( pSrc->pSelect ){
1974     return 0;   /* tab2 may not be a view */
1975   }
1976   if( pDest->nCol!=pSrc->nCol ){
1977     return 0;   /* Number of columns must be the same in tab1 and tab2 */
1978   }
1979   if( pDest->iPKey!=pSrc->iPKey ){
1980     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
1981   }
1982   for(i=0; i<pDest->nCol; i++){
1983     Column *pDestCol = &pDest->aCol[i];
1984     Column *pSrcCol = &pSrc->aCol[i];
1985 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
1986     if( (db->flags & SQLITE_Vacuum)==0
1987      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
1988     ){
1989       return 0;    /* Neither table may have __hidden__ columns */
1990     }
1991 #endif
1992     if( pDestCol->affinity!=pSrcCol->affinity ){
1993       return 0;    /* Affinity must be the same on all columns */
1994     }
1995     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
1996       return 0;    /* Collating sequence must be the same on all columns */
1997     }
1998     if( pDestCol->notNull && !pSrcCol->notNull ){
1999       return 0;    /* tab2 must be NOT NULL if tab1 is */
2000     }
2001     /* Default values for second and subsequent columns need to match. */
2002     if( i>0 ){
2003       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
2004       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
2005       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
2006        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
2007                                        pSrcCol->pDflt->u.zToken)!=0)
2008       ){
2009         return 0;    /* Default values must be the same for all columns */
2010       }
2011     }
2012   }
2013   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2014     if( IsUniqueIndex(pDestIdx) ){
2015       destHasUniqueIdx = 1;
2016     }
2017     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
2018       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2019     }
2020     if( pSrcIdx==0 ){
2021       return 0;    /* pDestIdx has no corresponding index in pSrc */
2022     }
2023   }
2024 #ifndef SQLITE_OMIT_CHECK
2025   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
2026     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
2027   }
2028 #endif
2029 #ifndef SQLITE_OMIT_FOREIGN_KEY
2030   /* Disallow the transfer optimization if the destination table constains
2031   ** any foreign key constraints.  This is more restrictive than necessary.
2032   ** But the main beneficiary of the transfer optimization is the VACUUM
2033   ** command, and the VACUUM command disables foreign key constraints.  So
2034   ** the extra complication to make this rule less restrictive is probably
2035   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2036   */
2037   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
2038     return 0;
2039   }
2040 #endif
2041   if( (db->flags & SQLITE_CountRows)!=0 ){
2042     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
2043   }
2044 
2045   /* If we get this far, it means that the xfer optimization is at
2046   ** least a possibility, though it might only work if the destination
2047   ** table (tab1) is initially empty.
2048   */
2049 #ifdef SQLITE_TEST
2050   sqlite3_xferopt_count++;
2051 #endif
2052   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
2053   v = sqlite3GetVdbe(pParse);
2054   sqlite3CodeVerifySchema(pParse, iDbSrc);
2055   iSrc = pParse->nTab++;
2056   iDest = pParse->nTab++;
2057   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
2058   regData = sqlite3GetTempReg(pParse);
2059   regRowid = sqlite3GetTempReg(pParse);
2060   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2061   assert( HasRowid(pDest) || destHasUniqueIdx );
2062   if( (db->flags & SQLITE_Vacuum)==0 && (
2063       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2064    || destHasUniqueIdx                              /* (2) */
2065    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2066   )){
2067     /* In some circumstances, we are able to run the xfer optimization
2068     ** only if the destination table is initially empty. Unless the
2069     ** SQLITE_Vacuum flag is set, this block generates code to make
2070     ** that determination. If SQLITE_Vacuum is set, then the destination
2071     ** table is always empty.
2072     **
2073     ** Conditions under which the destination must be empty:
2074     **
2075     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2076     **     (If the destination is not initially empty, the rowid fields
2077     **     of index entries might need to change.)
2078     **
2079     ** (2) The destination has a unique index.  (The xfer optimization
2080     **     is unable to test uniqueness.)
2081     **
2082     ** (3) onError is something other than OE_Abort and OE_Rollback.
2083     */
2084     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
2085     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
2086     sqlite3VdbeJumpHere(v, addr1);
2087   }
2088   if( HasRowid(pSrc) ){
2089     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
2090     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2091     if( pDest->iPKey>=0 ){
2092       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2093       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2094       VdbeCoverage(v);
2095       sqlite3RowidConstraint(pParse, onError, pDest);
2096       sqlite3VdbeJumpHere(v, addr2);
2097       autoIncStep(pParse, regAutoinc, regRowid);
2098     }else if( pDest->pIndex==0 ){
2099       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
2100     }else{
2101       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2102       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
2103     }
2104     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
2105     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
2106                       pDest->zName, 0);
2107     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
2108     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
2109     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2110     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2111   }else{
2112     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2113     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
2114   }
2115   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2116     u8 idxInsFlags = 0;
2117     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
2118       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2119     }
2120     assert( pSrcIdx );
2121     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
2122     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2123     VdbeComment((v, "%s", pSrcIdx->zName));
2124     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
2125     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
2126     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2127     VdbeComment((v, "%s", pDestIdx->zName));
2128     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2129     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2130     if( db->flags & SQLITE_Vacuum ){
2131       /* This INSERT command is part of a VACUUM operation, which guarantees
2132       ** that the destination table is empty. If all indexed columns use
2133       ** collation sequence BINARY, then it can also be assumed that the
2134       ** index will be populated by inserting keys in strictly sorted
2135       ** order. In this case, instead of seeking within the b-tree as part
2136       ** of every OP_IdxInsert opcode, an OP_Last is added before the
2137       ** OP_IdxInsert to seek to the point within the b-tree where each key
2138       ** should be inserted. This is faster.
2139       **
2140       ** If any of the indexed columns use a collation sequence other than
2141       ** BINARY, this optimization is disabled. This is because the user
2142       ** might change the definition of a collation sequence and then run
2143       ** a VACUUM command. In that case keys may not be written in strictly
2144       ** sorted order.  */
2145       for(i=0; i<pSrcIdx->nColumn; i++){
2146         const char *zColl = pSrcIdx->azColl[i];
2147         assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
2148                     || sqlite3StrBINARY==zColl );
2149         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
2150       }
2151       if( i==pSrcIdx->nColumn ){
2152         idxInsFlags = OPFLAG_USESEEKRESULT;
2153         sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
2154       }
2155     }
2156     if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
2157       idxInsFlags |= OPFLAG_NCHANGE;
2158     }
2159     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
2160     sqlite3VdbeChangeP5(v, idxInsFlags);
2161     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
2162     sqlite3VdbeJumpHere(v, addr1);
2163     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2164     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2165   }
2166   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2167   sqlite3ReleaseTempReg(pParse, regRowid);
2168   sqlite3ReleaseTempReg(pParse, regData);
2169   if( emptyDestTest ){
2170     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
2171     sqlite3VdbeJumpHere(v, emptyDestTest);
2172     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2173     return 0;
2174   }else{
2175     return 1;
2176   }
2177 }
2178 #endif /* SQLITE_OMIT_XFER_OPT */
2179