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