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