xref: /sqlite-3.40.0/src/insert.c (revision e99cb2da)
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->nNVCol);
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       char aff;
92       if( x>=0 ){
93         aff = pTab->aCol[x].affinity;
94       }else if( x==XN_ROWID ){
95         aff = SQLITE_AFF_INTEGER;
96       }else{
97         assert( x==XN_EXPR );
98         assert( pIdx->aColExpr!=0 );
99         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
100       }
101       if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
102       if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
103       pIdx->zColAff[n] = aff;
104     }
105     pIdx->zColAff[n] = 0;
106   }
107 
108   return pIdx->zColAff;
109 }
110 
111 /*
112 ** Compute the affinity string for table pTab, if it has not already been
113 ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
114 **
115 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
116 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
117 ** for register iReg and following.  Or if affinities exists and iReg==0,
118 ** then just set the P4 operand of the previous opcode (which should  be
119 ** an OP_MakeRecord) to the affinity string.
120 **
121 ** A column affinity string has one character per column:
122 **
123 **  Character      Column affinity
124 **  ------------------------------
125 **  'A'            BLOB
126 **  'B'            TEXT
127 **  'C'            NUMERIC
128 **  'D'            INTEGER
129 **  'E'            REAL
130 */
131 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
132   int i, j;
133   char *zColAff = pTab->zColAff;
134   if( zColAff==0 ){
135     sqlite3 *db = sqlite3VdbeDb(v);
136     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
137     if( !zColAff ){
138       sqlite3OomFault(db);
139       return;
140     }
141 
142     for(i=j=0; i<pTab->nCol; i++){
143       assert( pTab->aCol[i].affinity!=0 );
144       if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
145         zColAff[j++] = pTab->aCol[i].affinity;
146       }
147     }
148     do{
149       zColAff[j--] = 0;
150     }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
151     pTab->zColAff = zColAff;
152   }
153   assert( zColAff!=0 );
154   i = sqlite3Strlen30NN(zColAff);
155   if( i ){
156     if( iReg ){
157       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
158     }else{
159       sqlite3VdbeChangeP4(v, -1, zColAff, i);
160     }
161   }
162 }
163 
164 /*
165 ** Return non-zero if the table pTab in database iDb or any of its indices
166 ** have been opened at any point in the VDBE program. This is used to see if
167 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
168 ** run without using a temporary table for the results of the SELECT.
169 */
170 static int readsTable(Parse *p, int iDb, Table *pTab){
171   Vdbe *v = sqlite3GetVdbe(p);
172   int i;
173   int iEnd = sqlite3VdbeCurrentAddr(v);
174 #ifndef SQLITE_OMIT_VIRTUALTABLE
175   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
176 #endif
177 
178   for(i=1; i<iEnd; i++){
179     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
180     assert( pOp!=0 );
181     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
182       Index *pIndex;
183       int tnum = pOp->p2;
184       if( tnum==pTab->tnum ){
185         return 1;
186       }
187       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
188         if( tnum==pIndex->tnum ){
189           return 1;
190         }
191       }
192     }
193 #ifndef SQLITE_OMIT_VIRTUALTABLE
194     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
195       assert( pOp->p4.pVtab!=0 );
196       assert( pOp->p4type==P4_VTAB );
197       return 1;
198     }
199 #endif
200   }
201   return 0;
202 }
203 
204 /* This walker callback will compute the union of colFlags flags for all
205 ** referenced columns in a CHECK constraint or generated column expression.
206 */
207 static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
208   if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
209     assert( pExpr->iColumn < pWalker->u.pTab->nCol );
210     pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
211   }
212   return WRC_Continue;
213 }
214 
215 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
216 /*
217 ** All regular columns for table pTab have been puts into registers
218 ** starting with iRegStore.  The registers that correspond to STORED
219 ** or VIRTUAL columns have not yet been initialized.  This routine goes
220 ** back and computes the values for those columns based on the previously
221 ** computed normal columns.
222 */
223 void sqlite3ComputeGeneratedColumns(
224   Parse *pParse,    /* Parsing context */
225   int iRegStore,    /* Register holding the first column */
226   Table *pTab       /* The table */
227 ){
228   int i;
229   Walker w;
230   Column *pRedo;
231   int eProgress;
232   VdbeOp *pOp;
233 
234   assert( pTab->tabFlags & TF_HasGenerated );
235   testcase( pTab->tabFlags & TF_HasVirtual );
236   testcase( pTab->tabFlags & TF_HasStored );
237 
238   /* Before computing generated columns, first go through and make sure
239   ** that appropriate affinity has been applied to the regular columns
240   */
241   sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
242   if( (pTab->tabFlags & TF_HasStored)!=0
243    && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity
244   ){
245     /* Change the OP_Affinity argument to '@' (NONE) for all stored
246     ** columns.  '@' is the no-op affinity and those columns have not
247     ** yet been computed. */
248     int ii, jj;
249     char *zP4 = pOp->p4.z;
250     assert( zP4!=0 );
251     assert( pOp->p4type==P4_DYNAMIC );
252     for(ii=jj=0; zP4[jj]; ii++){
253       if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
254         continue;
255       }
256       if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
257         zP4[jj] = SQLITE_AFF_NONE;
258       }
259       jj++;
260     }
261   }
262 
263   /* Because there can be multiple generated columns that refer to one another,
264   ** this is a two-pass algorithm.  On the first pass, mark all generated
265   ** columns as "not available".
266   */
267   for(i=0; i<pTab->nCol; i++){
268     if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
269       testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
270       testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
271       pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
272     }
273   }
274 
275   w.u.pTab = pTab;
276   w.xExprCallback = exprColumnFlagUnion;
277   w.xSelectCallback = 0;
278   w.xSelectCallback2 = 0;
279 
280   /* On the second pass, compute the value of each NOT-AVAILABLE column.
281   ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
282   ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
283   ** they are needed.
284   */
285   pParse->iSelfTab = -iRegStore;
286   do{
287     eProgress = 0;
288     pRedo = 0;
289     for(i=0; i<pTab->nCol; i++){
290       Column *pCol = pTab->aCol + i;
291       if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
292         int x;
293         pCol->colFlags |= COLFLAG_BUSY;
294         w.eCode = 0;
295         sqlite3WalkExpr(&w, pCol->pDflt);
296         pCol->colFlags &= ~COLFLAG_BUSY;
297         if( w.eCode & COLFLAG_NOTAVAIL ){
298           pRedo = pCol;
299           continue;
300         }
301         eProgress = 1;
302         assert( pCol->colFlags & COLFLAG_GENERATED );
303         x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
304         sqlite3ExprCodeGeneratedColumn(pParse, pCol, x);
305         pCol->colFlags &= ~COLFLAG_NOTAVAIL;
306       }
307     }
308   }while( pRedo && eProgress );
309   if( pRedo ){
310     sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName);
311   }
312   pParse->iSelfTab = 0;
313 }
314 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
315 
316 
317 #ifndef SQLITE_OMIT_AUTOINCREMENT
318 /*
319 ** Locate or create an AutoincInfo structure associated with table pTab
320 ** which is in database iDb.  Return the register number for the register
321 ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
322 ** table.  (Also return zero when doing a VACUUM since we do not want to
323 ** update the AUTOINCREMENT counters during a VACUUM.)
324 **
325 ** There is at most one AutoincInfo structure per table even if the
326 ** same table is autoincremented multiple times due to inserts within
327 ** triggers.  A new AutoincInfo structure is created if this is the
328 ** first use of table pTab.  On 2nd and subsequent uses, the original
329 ** AutoincInfo structure is used.
330 **
331 ** Four consecutive registers are allocated:
332 **
333 **   (1)  The name of the pTab table.
334 **   (2)  The maximum ROWID of pTab.
335 **   (3)  The rowid in sqlite_sequence of pTab
336 **   (4)  The original value of the max ROWID in pTab, or NULL if none
337 **
338 ** The 2nd register is the one that is returned.  That is all the
339 ** insert routine needs to know about.
340 */
341 static int autoIncBegin(
342   Parse *pParse,      /* Parsing context */
343   int iDb,            /* Index of the database holding pTab */
344   Table *pTab         /* The table we are writing to */
345 ){
346   int memId = 0;      /* Register holding maximum rowid */
347   assert( pParse->db->aDb[iDb].pSchema!=0 );
348   if( (pTab->tabFlags & TF_Autoincrement)!=0
349    && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
350   ){
351     Parse *pToplevel = sqlite3ParseToplevel(pParse);
352     AutoincInfo *pInfo;
353     Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
354 
355     /* Verify that the sqlite_sequence table exists and is an ordinary
356     ** rowid table with exactly two columns.
357     ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
358     if( pSeqTab==0
359      || !HasRowid(pSeqTab)
360      || IsVirtual(pSeqTab)
361      || pSeqTab->nCol!=2
362     ){
363       pParse->nErr++;
364       pParse->rc = SQLITE_CORRUPT_SEQUENCE;
365       return 0;
366     }
367 
368     pInfo = pToplevel->pAinc;
369     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
370     if( pInfo==0 ){
371       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
372       if( pInfo==0 ) return 0;
373       pInfo->pNext = pToplevel->pAinc;
374       pToplevel->pAinc = pInfo;
375       pInfo->pTab = pTab;
376       pInfo->iDb = iDb;
377       pToplevel->nMem++;                  /* Register to hold name of table */
378       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
379       pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
380     }
381     memId = pInfo->regCtr;
382   }
383   return memId;
384 }
385 
386 /*
387 ** This routine generates code that will initialize all of the
388 ** register used by the autoincrement tracker.
389 */
390 void sqlite3AutoincrementBegin(Parse *pParse){
391   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
392   sqlite3 *db = pParse->db;  /* The database connection */
393   Db *pDb;                   /* Database only autoinc table */
394   int memId;                 /* Register holding max rowid */
395   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
396 
397   /* This routine is never called during trigger-generation.  It is
398   ** only called from the top-level */
399   assert( pParse->pTriggerTab==0 );
400   assert( sqlite3IsToplevel(pParse) );
401 
402   assert( v );   /* We failed long ago if this is not so */
403   for(p = pParse->pAinc; p; p = p->pNext){
404     static const int iLn = VDBE_OFFSET_LINENO(2);
405     static const VdbeOpList autoInc[] = {
406       /* 0  */ {OP_Null,    0,  0, 0},
407       /* 1  */ {OP_Rewind,  0, 10, 0},
408       /* 2  */ {OP_Column,  0,  0, 0},
409       /* 3  */ {OP_Ne,      0,  9, 0},
410       /* 4  */ {OP_Rowid,   0,  0, 0},
411       /* 5  */ {OP_Column,  0,  1, 0},
412       /* 6  */ {OP_AddImm,  0,  0, 0},
413       /* 7  */ {OP_Copy,    0,  0, 0},
414       /* 8  */ {OP_Goto,    0, 11, 0},
415       /* 9  */ {OP_Next,    0,  2, 0},
416       /* 10 */ {OP_Integer, 0,  0, 0},
417       /* 11 */ {OP_Close,   0,  0, 0}
418     };
419     VdbeOp *aOp;
420     pDb = &db->aDb[p->iDb];
421     memId = p->regCtr;
422     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
423     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
424     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
425     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
426     if( aOp==0 ) break;
427     aOp[0].p2 = memId;
428     aOp[0].p3 = memId+2;
429     aOp[2].p3 = memId;
430     aOp[3].p1 = memId-1;
431     aOp[3].p3 = memId;
432     aOp[3].p5 = SQLITE_JUMPIFNULL;
433     aOp[4].p2 = memId+1;
434     aOp[5].p3 = memId;
435     aOp[6].p1 = memId;
436     aOp[7].p2 = memId+2;
437     aOp[7].p1 = memId;
438     aOp[10].p2 = memId;
439     if( pParse->nTab==0 ) pParse->nTab = 1;
440   }
441 }
442 
443 /*
444 ** Update the maximum rowid for an autoincrement calculation.
445 **
446 ** This routine should be called when the regRowid register holds a
447 ** new rowid that is about to be inserted.  If that new rowid is
448 ** larger than the maximum rowid in the memId memory cell, then the
449 ** memory cell is updated.
450 */
451 static void autoIncStep(Parse *pParse, int memId, int regRowid){
452   if( memId>0 ){
453     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
454   }
455 }
456 
457 /*
458 ** This routine generates the code needed to write autoincrement
459 ** maximum rowid values back into the sqlite_sequence register.
460 ** Every statement that might do an INSERT into an autoincrement
461 ** table (either directly or through triggers) needs to call this
462 ** routine just before the "exit" code.
463 */
464 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
465   AutoincInfo *p;
466   Vdbe *v = pParse->pVdbe;
467   sqlite3 *db = pParse->db;
468 
469   assert( v );
470   for(p = pParse->pAinc; p; p = p->pNext){
471     static const int iLn = VDBE_OFFSET_LINENO(2);
472     static const VdbeOpList autoIncEnd[] = {
473       /* 0 */ {OP_NotNull,     0, 2, 0},
474       /* 1 */ {OP_NewRowid,    0, 0, 0},
475       /* 2 */ {OP_MakeRecord,  0, 2, 0},
476       /* 3 */ {OP_Insert,      0, 0, 0},
477       /* 4 */ {OP_Close,       0, 0, 0}
478     };
479     VdbeOp *aOp;
480     Db *pDb = &db->aDb[p->iDb];
481     int iRec;
482     int memId = p->regCtr;
483 
484     iRec = sqlite3GetTempReg(pParse);
485     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
486     sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
487     VdbeCoverage(v);
488     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
489     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
490     if( aOp==0 ) break;
491     aOp[0].p1 = memId+1;
492     aOp[1].p2 = memId+1;
493     aOp[2].p1 = memId-1;
494     aOp[2].p3 = iRec;
495     aOp[3].p2 = iRec;
496     aOp[3].p3 = memId+1;
497     aOp[3].p5 = OPFLAG_APPEND;
498     sqlite3ReleaseTempReg(pParse, iRec);
499   }
500 }
501 void sqlite3AutoincrementEnd(Parse *pParse){
502   if( pParse->pAinc ) autoIncrementEnd(pParse);
503 }
504 #else
505 /*
506 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
507 ** above are all no-ops
508 */
509 # define autoIncBegin(A,B,C) (0)
510 # define autoIncStep(A,B,C)
511 #endif /* SQLITE_OMIT_AUTOINCREMENT */
512 
513 
514 /* Forward declaration */
515 static int xferOptimization(
516   Parse *pParse,        /* Parser context */
517   Table *pDest,         /* The table we are inserting into */
518   Select *pSelect,      /* A SELECT statement to use as the data source */
519   int onError,          /* How to handle constraint errors */
520   int iDbDest           /* The database of pDest */
521 );
522 
523 /*
524 ** This routine is called to handle SQL of the following forms:
525 **
526 **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
527 **    insert into TABLE (IDLIST) select
528 **    insert into TABLE (IDLIST) default values
529 **
530 ** The IDLIST following the table name is always optional.  If omitted,
531 ** then a list of all (non-hidden) columns for the table is substituted.
532 ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
533 ** is omitted.
534 **
535 ** For the pSelect parameter holds the values to be inserted for the
536 ** first two forms shown above.  A VALUES clause is really just short-hand
537 ** for a SELECT statement that omits the FROM clause and everything else
538 ** that follows.  If the pSelect parameter is NULL, that means that the
539 ** DEFAULT VALUES form of the INSERT statement is intended.
540 **
541 ** The code generated follows one of four templates.  For a simple
542 ** insert with data coming from a single-row VALUES clause, the code executes
543 ** once straight down through.  Pseudo-code follows (we call this
544 ** the "1st template"):
545 **
546 **         open write cursor to <table> and its indices
547 **         put VALUES clause expressions into registers
548 **         write the resulting record into <table>
549 **         cleanup
550 **
551 ** The three remaining templates assume the statement is of the form
552 **
553 **   INSERT INTO <table> SELECT ...
554 **
555 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
556 ** in other words if the SELECT pulls all columns from a single table
557 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
558 ** if <table2> and <table1> are distinct tables but have identical
559 ** schemas, including all the same indices, then a special optimization
560 ** is invoked that copies raw records from <table2> over to <table1>.
561 ** See the xferOptimization() function for the implementation of this
562 ** template.  This is the 2nd template.
563 **
564 **         open a write cursor to <table>
565 **         open read cursor on <table2>
566 **         transfer all records in <table2> over to <table>
567 **         close cursors
568 **         foreach index on <table>
569 **           open a write cursor on the <table> index
570 **           open a read cursor on the corresponding <table2> index
571 **           transfer all records from the read to the write cursors
572 **           close cursors
573 **         end foreach
574 **
575 ** The 3rd template is for when the second template does not apply
576 ** and the SELECT clause does not read from <table> at any time.
577 ** The generated code follows this template:
578 **
579 **         X <- A
580 **         goto B
581 **      A: setup for the SELECT
582 **         loop over the rows in the SELECT
583 **           load values into registers R..R+n
584 **           yield X
585 **         end loop
586 **         cleanup after the SELECT
587 **         end-coroutine X
588 **      B: open write cursor to <table> and its indices
589 **      C: yield X, at EOF goto D
590 **         insert the select result into <table> from R..R+n
591 **         goto C
592 **      D: cleanup
593 **
594 ** The 4th template is used if the insert statement takes its
595 ** values from a SELECT but the data is being inserted into a table
596 ** that is also read as part of the SELECT.  In the third form,
597 ** we have to use an intermediate table to store the results of
598 ** the select.  The template is like this:
599 **
600 **         X <- A
601 **         goto B
602 **      A: setup for the SELECT
603 **         loop over the tables in the SELECT
604 **           load value into register R..R+n
605 **           yield X
606 **         end loop
607 **         cleanup after the SELECT
608 **         end co-routine R
609 **      B: open temp table
610 **      L: yield X, at EOF goto M
611 **         insert row from R..R+n into temp table
612 **         goto L
613 **      M: open write cursor to <table> and its indices
614 **         rewind temp table
615 **      C: loop over rows of intermediate table
616 **           transfer values form intermediate table into <table>
617 **         end loop
618 **      D: cleanup
619 */
620 void sqlite3Insert(
621   Parse *pParse,        /* Parser context */
622   SrcList *pTabList,    /* Name of table into which we are inserting */
623   Select *pSelect,      /* A SELECT statement to use as the data source */
624   IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */
625   int onError,          /* How to handle constraint errors */
626   Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
627 ){
628   sqlite3 *db;          /* The main database structure */
629   Table *pTab;          /* The table to insert into.  aka TABLE */
630   int i, j;             /* Loop counters */
631   Vdbe *v;              /* Generate code into this virtual machine */
632   Index *pIdx;          /* For looping over indices of the table */
633   int nColumn;          /* Number of columns in the data */
634   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
635   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
636   int iIdxCur = 0;      /* First index cursor */
637   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
638   int endOfLoop;        /* Label for the end of the insertion loop */
639   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
640   int addrInsTop = 0;   /* Jump to label "D" */
641   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
642   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
643   int iDb;              /* Index of database holding TABLE */
644   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
645   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
646   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
647   u8 bIdListInOrder;    /* True if IDLIST is in table order */
648   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
649   int iRegStore;        /* Register in which to store next column */
650 
651   /* Register allocations */
652   int regFromSelect = 0;/* Base register for data coming from SELECT */
653   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
654   int regRowCount = 0;  /* Memory cell used for the row counter */
655   int regIns;           /* Block of regs holding rowid+data being inserted */
656   int regRowid;         /* registers holding insert rowid */
657   int regData;          /* register holding first column to insert */
658   int *aRegIdx = 0;     /* One register allocated to each index */
659 
660 #ifndef SQLITE_OMIT_TRIGGER
661   int isView;                 /* True if attempting to insert into a view */
662   Trigger *pTrigger;          /* List of triggers on pTab, if required */
663   int tmask;                  /* Mask of trigger times */
664 #endif
665 
666   db = pParse->db;
667   if( pParse->nErr || db->mallocFailed ){
668     goto insert_cleanup;
669   }
670   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
671 
672   /* If the Select object is really just a simple VALUES() list with a
673   ** single row (the common case) then keep that one row of values
674   ** and discard the other (unused) parts of the pSelect object
675   */
676   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
677     pList = pSelect->pEList;
678     pSelect->pEList = 0;
679     sqlite3SelectDelete(db, pSelect);
680     pSelect = 0;
681   }
682 
683   /* Locate the table into which we will be inserting new information.
684   */
685   assert( pTabList->nSrc==1 );
686   pTab = sqlite3SrcListLookup(pParse, pTabList);
687   if( pTab==0 ){
688     goto insert_cleanup;
689   }
690   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
691   assert( iDb<db->nDb );
692   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
693                        db->aDb[iDb].zDbSName) ){
694     goto insert_cleanup;
695   }
696   withoutRowid = !HasRowid(pTab);
697 
698   /* Figure out if we have any triggers and if the table being
699   ** inserted into is a view
700   */
701 #ifndef SQLITE_OMIT_TRIGGER
702   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
703   isView = pTab->pSelect!=0;
704 #else
705 # define pTrigger 0
706 # define tmask 0
707 # define isView 0
708 #endif
709 #ifdef SQLITE_OMIT_VIEW
710 # undef isView
711 # define isView 0
712 #endif
713   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
714 
715   /* If pTab is really a view, make sure it has been initialized.
716   ** ViewGetColumnNames() is a no-op if pTab is not a view.
717   */
718   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
719     goto insert_cleanup;
720   }
721 
722   /* Cannot insert into a read-only table.
723   */
724   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
725     goto insert_cleanup;
726   }
727 
728   /* Allocate a VDBE
729   */
730   v = sqlite3GetVdbe(pParse);
731   if( v==0 ) goto insert_cleanup;
732   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
733   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
734 
735 #ifndef SQLITE_OMIT_XFER_OPT
736   /* If the statement is of the form
737   **
738   **       INSERT INTO <table1> SELECT * FROM <table2>;
739   **
740   ** Then special optimizations can be applied that make the transfer
741   ** very fast and which reduce fragmentation of indices.
742   **
743   ** This is the 2nd template.
744   */
745   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
746     assert( !pTrigger );
747     assert( pList==0 );
748     goto insert_end;
749   }
750 #endif /* SQLITE_OMIT_XFER_OPT */
751 
752   /* If this is an AUTOINCREMENT table, look up the sequence number in the
753   ** sqlite_sequence table and store it in memory cell regAutoinc.
754   */
755   regAutoinc = autoIncBegin(pParse, iDb, pTab);
756 
757   /* Allocate a block registers to hold the rowid and the values
758   ** for all columns of the new row.
759   */
760   regRowid = regIns = pParse->nMem+1;
761   pParse->nMem += pTab->nCol + 1;
762   if( IsVirtual(pTab) ){
763     regRowid++;
764     pParse->nMem++;
765   }
766   regData = regRowid+1;
767 
768   /* If the INSERT statement included an IDLIST term, then make sure
769   ** all elements of the IDLIST really are columns of the table and
770   ** remember the column indices.
771   **
772   ** If the table has an INTEGER PRIMARY KEY column and that column
773   ** is named in the IDLIST, then record in the ipkColumn variable
774   ** the index into IDLIST of the primary key column.  ipkColumn is
775   ** the index of the primary key as it appears in IDLIST, not as
776   ** is appears in the original table.  (The index of the INTEGER
777   ** PRIMARY KEY in the original table is pTab->iPKey.)  After this
778   ** loop, if ipkColumn==(-1), that means that integer primary key
779   ** is unspecified, and hence the table is either WITHOUT ROWID or
780   ** it will automatically generated an integer primary key.
781   **
782   ** bIdListInOrder is true if the columns in IDLIST are in storage
783   ** order.  This enables an optimization that avoids shuffling the
784   ** columns into storage order.  False negatives are harmless,
785   ** but false positives will cause database corruption.
786   */
787   bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
788   if( pColumn ){
789     for(i=0; i<pColumn->nId; i++){
790       pColumn->a[i].idx = -1;
791     }
792     for(i=0; i<pColumn->nId; i++){
793       for(j=0; j<pTab->nCol; j++){
794         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
795           pColumn->a[i].idx = j;
796           if( i!=j ) bIdListInOrder = 0;
797           if( j==pTab->iPKey ){
798             ipkColumn = i;  assert( !withoutRowid );
799           }
800 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
801           if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
802             sqlite3ErrorMsg(pParse,
803                "cannot INSERT into generated column \"%s\"",
804                pTab->aCol[j].zName);
805             goto insert_cleanup;
806           }
807 #endif
808           break;
809         }
810       }
811       if( j>=pTab->nCol ){
812         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
813           ipkColumn = i;
814           bIdListInOrder = 0;
815         }else{
816           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
817               pTabList, 0, pColumn->a[i].zName);
818           pParse->checkSchema = 1;
819           goto insert_cleanup;
820         }
821       }
822     }
823   }
824 
825   /* Figure out how many columns of data are supplied.  If the data
826   ** is coming from a SELECT statement, then generate a co-routine that
827   ** produces a single row of the SELECT on each invocation.  The
828   ** co-routine is the common header to the 3rd and 4th templates.
829   */
830   if( pSelect ){
831     /* Data is coming from a SELECT or from a multi-row VALUES clause.
832     ** Generate a co-routine to run the SELECT. */
833     int regYield;       /* Register holding co-routine entry-point */
834     int addrTop;        /* Top of the co-routine */
835     int rc;             /* Result code */
836 
837     regYield = ++pParse->nMem;
838     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
839     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
840     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
841     dest.iSdst = bIdListInOrder ? regData : 0;
842     dest.nSdst = pTab->nCol;
843     rc = sqlite3Select(pParse, pSelect, &dest);
844     regFromSelect = dest.iSdst;
845     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
846     sqlite3VdbeEndCoroutine(v, regYield);
847     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
848     assert( pSelect->pEList );
849     nColumn = pSelect->pEList->nExpr;
850 
851     /* Set useTempTable to TRUE if the result of the SELECT statement
852     ** should be written into a temporary table (template 4).  Set to
853     ** FALSE if each output row of the SELECT can be written directly into
854     ** the destination table (template 3).
855     **
856     ** A temp table must be used if the table being updated is also one
857     ** of the tables being read by the SELECT statement.  Also use a
858     ** temp table in the case of row triggers.
859     */
860     if( pTrigger || readsTable(pParse, iDb, pTab) ){
861       useTempTable = 1;
862     }
863 
864     if( useTempTable ){
865       /* Invoke the coroutine to extract information from the SELECT
866       ** and add it to a transient table srcTab.  The code generated
867       ** here is from the 4th template:
868       **
869       **      B: open temp table
870       **      L: yield X, goto M at EOF
871       **         insert row from R..R+n into temp table
872       **         goto L
873       **      M: ...
874       */
875       int regRec;          /* Register to hold packed record */
876       int regTempRowid;    /* Register to hold temp table ROWID */
877       int addrL;           /* Label "L" */
878 
879       srcTab = pParse->nTab++;
880       regRec = sqlite3GetTempReg(pParse);
881       regTempRowid = sqlite3GetTempReg(pParse);
882       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
883       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
884       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
885       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
886       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
887       sqlite3VdbeGoto(v, addrL);
888       sqlite3VdbeJumpHere(v, addrL);
889       sqlite3ReleaseTempReg(pParse, regRec);
890       sqlite3ReleaseTempReg(pParse, regTempRowid);
891     }
892   }else{
893     /* This is the case if the data for the INSERT is coming from a
894     ** single-row VALUES clause
895     */
896     NameContext sNC;
897     memset(&sNC, 0, sizeof(sNC));
898     sNC.pParse = pParse;
899     srcTab = -1;
900     assert( useTempTable==0 );
901     if( pList ){
902       nColumn = pList->nExpr;
903       if( sqlite3ResolveExprListNames(&sNC, pList) ){
904         goto insert_cleanup;
905       }
906     }else{
907       nColumn = 0;
908     }
909   }
910 
911   /* If there is no IDLIST term but the table has an integer primary
912   ** key, the set the ipkColumn variable to the integer primary key
913   ** column index in the original table definition.
914   */
915   if( pColumn==0 && nColumn>0 ){
916     ipkColumn = pTab->iPKey;
917 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
918     if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
919       testcase( pTab->tabFlags & TF_HasVirtual );
920       testcase( pTab->tabFlags & TF_HasStored );
921       for(i=ipkColumn-1; i>=0; i--){
922         if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
923           testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
924           testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
925           ipkColumn--;
926         }
927       }
928     }
929 #endif
930   }
931 
932   /* Make sure the number of columns in the source data matches the number
933   ** of columns to be inserted into the table.
934   */
935   for(i=0; i<pTab->nCol; i++){
936     if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
937   }
938   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
939     sqlite3ErrorMsg(pParse,
940        "table %S has %d columns but %d values were supplied",
941        pTabList, 0, pTab->nCol-nHidden, nColumn);
942     goto insert_cleanup;
943   }
944   if( pColumn!=0 && nColumn!=pColumn->nId ){
945     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
946     goto insert_cleanup;
947   }
948 
949   /* Initialize the count of rows to be inserted
950   */
951   if( (db->flags & SQLITE_CountRows)!=0
952    && !pParse->nested
953    && !pParse->pTriggerTab
954   ){
955     regRowCount = ++pParse->nMem;
956     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
957   }
958 
959   /* If this is not a view, open the table and and all indices */
960   if( !isView ){
961     int nIdx;
962     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
963                                       &iDataCur, &iIdxCur);
964     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
965     if( aRegIdx==0 ){
966       goto insert_cleanup;
967     }
968     for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
969       assert( pIdx );
970       aRegIdx[i] = ++pParse->nMem;
971       pParse->nMem += pIdx->nColumn;
972     }
973     aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */
974   }
975 #ifndef SQLITE_OMIT_UPSERT
976   if( pUpsert ){
977     if( IsVirtual(pTab) ){
978       sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
979               pTab->zName);
980       goto insert_cleanup;
981     }
982     if( pTab->pSelect ){
983       sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
984       goto insert_cleanup;
985     }
986     if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
987       goto insert_cleanup;
988     }
989     pTabList->a[0].iCursor = iDataCur;
990     pUpsert->pUpsertSrc = pTabList;
991     pUpsert->regData = regData;
992     pUpsert->iDataCur = iDataCur;
993     pUpsert->iIdxCur = iIdxCur;
994     if( pUpsert->pUpsertTarget ){
995       sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
996     }
997   }
998 #endif
999 
1000 
1001   /* This is the top of the main insertion loop */
1002   if( useTempTable ){
1003     /* This block codes the top of loop only.  The complete loop is the
1004     ** following pseudocode (template 4):
1005     **
1006     **         rewind temp table, if empty goto D
1007     **      C: loop over rows of intermediate table
1008     **           transfer values form intermediate table into <table>
1009     **         end loop
1010     **      D: ...
1011     */
1012     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1013     addrCont = sqlite3VdbeCurrentAddr(v);
1014   }else if( pSelect ){
1015     /* This block codes the top of loop only.  The complete loop is the
1016     ** following pseudocode (template 3):
1017     **
1018     **      C: yield X, at EOF goto D
1019     **         insert the select result into <table> from R..R+n
1020     **         goto C
1021     **      D: ...
1022     */
1023     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1024     VdbeCoverage(v);
1025     if( ipkColumn>=0 ){
1026       /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1027       ** SELECT, go ahead and copy the value into the rowid slot now, so that
1028       ** the value does not get overwritten by a NULL at tag-20191021-002. */
1029       sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1030     }
1031   }
1032 
1033   /* Compute data for ordinary columns of the new entry.  Values
1034   ** are written in storage order into registers starting with regData.
1035   ** Only ordinary columns are computed in this loop. The rowid
1036   ** (if there is one) is computed later and generated columns are
1037   ** computed after the rowid since they might depend on the value
1038   ** of the rowid.
1039   */
1040   nHidden = 0;
1041   iRegStore = regData;  assert( regData==regRowid+1 );
1042   for(i=0; i<pTab->nCol; i++, iRegStore++){
1043     int k;
1044     u32 colFlags;
1045     assert( i>=nHidden );
1046     if( i==pTab->iPKey ){
1047       /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1048       ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1049       ** using excess space.  The file format definition requires this extra
1050       ** NULL - we cannot optimize further by skipping the column completely */
1051       sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1052       continue;
1053     }
1054     if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1055       nHidden++;
1056       if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1057         /* Virtual columns do not participate in OP_MakeRecord.  So back up
1058         ** iRegStore by one slot to compensate for the iRegStore++ in the
1059         ** outer for() loop */
1060         iRegStore--;
1061         continue;
1062       }else if( (colFlags & COLFLAG_STORED)!=0 ){
1063         /* Stored columns are computed later.  But if there are BEFORE
1064         ** triggers, the slots used for stored columns will be OP_Copy-ed
1065         ** to a second block of registers, so the register needs to be
1066         ** initialized to NULL to avoid an uninitialized register read */
1067         if( tmask & TRIGGER_BEFORE ){
1068           sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1069         }
1070         continue;
1071       }else if( pColumn==0 ){
1072         /* Hidden columns that are not explicitly named in the INSERT
1073         ** get there default value */
1074         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
1075         continue;
1076       }
1077     }
1078     if( pColumn ){
1079       for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){}
1080       if( j>=pColumn->nId ){
1081         /* A column not named in the insert column list gets its
1082         ** default value */
1083         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
1084         continue;
1085       }
1086       k = j;
1087     }else if( nColumn==0 ){
1088       /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
1089       sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
1090       continue;
1091     }else{
1092       k = i - nHidden;
1093     }
1094 
1095     if( useTempTable ){
1096       sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1097     }else if( pSelect ){
1098       if( regFromSelect!=regData ){
1099         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1100       }
1101     }else{
1102       sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore);
1103     }
1104   }
1105 
1106 
1107   /* Run the BEFORE and INSTEAD OF triggers, if there are any
1108   */
1109   endOfLoop = sqlite3VdbeMakeLabel(pParse);
1110   if( tmask & TRIGGER_BEFORE ){
1111     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1112 
1113     /* build the NEW.* reference row.  Note that if there is an INTEGER
1114     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1115     ** translated into a unique ID for the row.  But on a BEFORE trigger,
1116     ** we do not know what the unique ID will be (because the insert has
1117     ** not happened yet) so we substitute a rowid of -1
1118     */
1119     if( ipkColumn<0 ){
1120       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1121     }else{
1122       int addr1;
1123       assert( !withoutRowid );
1124       if( useTempTable ){
1125         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
1126       }else{
1127         assert( pSelect==0 );  /* Otherwise useTempTable is true */
1128         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
1129       }
1130       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
1131       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1132       sqlite3VdbeJumpHere(v, addr1);
1133       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
1134     }
1135 
1136     /* Cannot have triggers on a virtual table. If it were possible,
1137     ** this block would have to account for hidden column.
1138     */
1139     assert( !IsVirtual(pTab) );
1140 
1141     /* Copy the new data already generated. */
1142     assert( pTab->nNVCol>0 );
1143     sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1144 
1145 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1146     /* Compute the new value for generated columns after all other
1147     ** columns have already been computed.  This must be done after
1148     ** computing the ROWID in case one of the generated columns
1149     ** refers to the ROWID. */
1150     if( pTab->tabFlags & TF_HasGenerated ){
1151       testcase( pTab->tabFlags & TF_HasVirtual );
1152       testcase( pTab->tabFlags & TF_HasStored );
1153       sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1154     }
1155 #endif
1156 
1157     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1158     ** do not attempt any conversions before assembling the record.
1159     ** If this is a real table, attempt conversions as required by the
1160     ** table column affinities.
1161     */
1162     if( !isView ){
1163       sqlite3TableAffinity(v, pTab, regCols+1);
1164     }
1165 
1166     /* Fire BEFORE or INSTEAD OF triggers */
1167     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
1168         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1169 
1170     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
1171   }
1172 
1173   if( !isView ){
1174     if( IsVirtual(pTab) ){
1175       /* The row that the VUpdate opcode will delete: none */
1176       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
1177     }
1178     if( ipkColumn>=0 ){
1179       /* Compute the new rowid */
1180       if( useTempTable ){
1181         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1182       }else if( pSelect ){
1183         /* Rowid already initialized at tag-20191021-001 */
1184       }else{
1185         Expr *pIpk = pList->a[ipkColumn].pExpr;
1186         if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1187           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1188           appendFlag = 1;
1189         }else{
1190           sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1191         }
1192       }
1193       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1194       ** to generate a unique primary key value.
1195       */
1196       if( !appendFlag ){
1197         int addr1;
1198         if( !IsVirtual(pTab) ){
1199           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
1200           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1201           sqlite3VdbeJumpHere(v, addr1);
1202         }else{
1203           addr1 = sqlite3VdbeCurrentAddr(v);
1204           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1205         }
1206         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1207       }
1208     }else if( IsVirtual(pTab) || withoutRowid ){
1209       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
1210     }else{
1211       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1212       appendFlag = 1;
1213     }
1214     autoIncStep(pParse, regAutoinc, regRowid);
1215 
1216 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1217     /* Compute the new value for generated columns after all other
1218     ** columns have already been computed.  This must be done after
1219     ** computing the ROWID in case one of the generated columns
1220     ** is derived from the INTEGER PRIMARY KEY. */
1221     if( pTab->tabFlags & TF_HasGenerated ){
1222       sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
1223     }
1224 #endif
1225 
1226     /* Generate code to check constraints and generate index keys and
1227     ** do the insertion.
1228     */
1229 #ifndef SQLITE_OMIT_VIRTUALTABLE
1230     if( IsVirtual(pTab) ){
1231       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1232       sqlite3VtabMakeWritable(pParse, pTab);
1233       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1234       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1235       sqlite3MayAbort(pParse);
1236     }else
1237 #endif
1238     {
1239       int isReplace;    /* Set to true if constraints may cause a replace */
1240       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
1241       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1242           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1243       );
1244       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1245 
1246       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1247       ** constraints or (b) there are no triggers and this table is not a
1248       ** parent table in a foreign key constraint. It is safe to set the
1249       ** flag in the second case as if any REPLACE constraint is hit, an
1250       ** OP_Delete or OP_IdxDelete instruction will be executed on each
1251       ** cursor that is disturbed. And these instructions both clear the
1252       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1253       ** functionality.  */
1254       bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
1255       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1256           regIns, aRegIdx, 0, appendFlag, bUseSeek
1257       );
1258     }
1259   }
1260 
1261   /* Update the count of rows that are inserted
1262   */
1263   if( regRowCount ){
1264     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1265   }
1266 
1267   if( pTrigger ){
1268     /* Code AFTER triggers */
1269     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1270         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1271   }
1272 
1273   /* The bottom of the main insertion loop, if the data source
1274   ** is a SELECT statement.
1275   */
1276   sqlite3VdbeResolveLabel(v, endOfLoop);
1277   if( useTempTable ){
1278     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1279     sqlite3VdbeJumpHere(v, addrInsTop);
1280     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1281   }else if( pSelect ){
1282     sqlite3VdbeGoto(v, addrCont);
1283     sqlite3VdbeJumpHere(v, addrInsTop);
1284   }
1285 
1286 insert_end:
1287   /* Update the sqlite_sequence table by storing the content of the
1288   ** maximum rowid counter values recorded while inserting into
1289   ** autoincrement tables.
1290   */
1291   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1292     sqlite3AutoincrementEnd(pParse);
1293   }
1294 
1295   /*
1296   ** Return the number of rows inserted. If this routine is
1297   ** generating code because of a call to sqlite3NestedParse(), do not
1298   ** invoke the callback function.
1299   */
1300   if( regRowCount ){
1301     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
1302     sqlite3VdbeSetNumCols(v, 1);
1303     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
1304   }
1305 
1306 insert_cleanup:
1307   sqlite3SrcListDelete(db, pTabList);
1308   sqlite3ExprListDelete(db, pList);
1309   sqlite3UpsertDelete(db, pUpsert);
1310   sqlite3SelectDelete(db, pSelect);
1311   sqlite3IdListDelete(db, pColumn);
1312   sqlite3DbFree(db, aRegIdx);
1313 }
1314 
1315 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1316 ** they may interfere with compilation of other functions in this file
1317 ** (or in another file, if this file becomes part of the amalgamation).  */
1318 #ifdef isView
1319  #undef isView
1320 #endif
1321 #ifdef pTrigger
1322  #undef pTrigger
1323 #endif
1324 #ifdef tmask
1325  #undef tmask
1326 #endif
1327 
1328 /*
1329 ** Meanings of bits in of pWalker->eCode for
1330 ** sqlite3ExprReferencesUpdatedColumn()
1331 */
1332 #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
1333 #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
1334 
1335 /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1336 *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1337 ** expression node references any of the
1338 ** columns that are being modifed by an UPDATE statement.
1339 */
1340 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1341   if( pExpr->op==TK_COLUMN ){
1342     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1343     if( pExpr->iColumn>=0 ){
1344       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1345         pWalker->eCode |= CKCNSTRNT_COLUMN;
1346       }
1347     }else{
1348       pWalker->eCode |= CKCNSTRNT_ROWID;
1349     }
1350   }
1351   return WRC_Continue;
1352 }
1353 
1354 /*
1355 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
1356 ** only columns that are modified by the UPDATE are those for which
1357 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1358 **
1359 ** Return true if CHECK constraint pExpr uses any of the
1360 ** changing columns (or the rowid if it is changing).  In other words,
1361 ** return true if this CHECK constraint must be validated for
1362 ** the new row in the UPDATE statement.
1363 **
1364 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1365 ** The operation of this routine is the same - return true if an only if
1366 ** the expression uses one or more of columns identified by the second and
1367 ** third arguments.
1368 */
1369 int sqlite3ExprReferencesUpdatedColumn(
1370   Expr *pExpr,    /* The expression to be checked */
1371   int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
1372   int chngRowid   /* True if UPDATE changes the rowid */
1373 ){
1374   Walker w;
1375   memset(&w, 0, sizeof(w));
1376   w.eCode = 0;
1377   w.xExprCallback = checkConstraintExprNode;
1378   w.u.aiCol = aiChng;
1379   sqlite3WalkExpr(&w, pExpr);
1380   if( !chngRowid ){
1381     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1382     w.eCode &= ~CKCNSTRNT_ROWID;
1383   }
1384   testcase( w.eCode==0 );
1385   testcase( w.eCode==CKCNSTRNT_COLUMN );
1386   testcase( w.eCode==CKCNSTRNT_ROWID );
1387   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1388   return w.eCode!=0;
1389 }
1390 
1391 /*
1392 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1393 ** on table pTab.
1394 **
1395 ** The regNewData parameter is the first register in a range that contains
1396 ** the data to be inserted or the data after the update.  There will be
1397 ** pTab->nCol+1 registers in this range.  The first register (the one
1398 ** that regNewData points to) will contain the new rowid, or NULL in the
1399 ** case of a WITHOUT ROWID table.  The second register in the range will
1400 ** contain the content of the first table column.  The third register will
1401 ** contain the content of the second table column.  And so forth.
1402 **
1403 ** The regOldData parameter is similar to regNewData except that it contains
1404 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1405 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1406 ** checking regOldData for zero.
1407 **
1408 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1409 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1410 ** might be modified by the UPDATE.  If pkChng is false, then the key of
1411 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1412 **
1413 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1414 ** was explicitly specified as part of the INSERT statement.  If pkChng
1415 ** is zero, it means that the either rowid is computed automatically or
1416 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1417 ** pkChng will only be true if the INSERT statement provides an integer
1418 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1419 **
1420 ** The code generated by this routine will store new index entries into
1421 ** registers identified by aRegIdx[].  No index entry is created for
1422 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1423 ** the same as the order of indices on the linked list of indices
1424 ** at pTab->pIndex.
1425 **
1426 ** (2019-05-07) The generated code also creates a new record for the
1427 ** main table, if pTab is a rowid table, and stores that record in the
1428 ** register identified by aRegIdx[nIdx] - in other words in the first
1429 ** entry of aRegIdx[] past the last index.  It is important that the
1430 ** record be generated during constraint checks to avoid affinity changes
1431 ** to the register content that occur after constraint checks but before
1432 ** the new record is inserted.
1433 **
1434 ** The caller must have already opened writeable cursors on the main
1435 ** table and all applicable indices (that is to say, all indices for which
1436 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
1437 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1438 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
1439 ** for the first index in the pTab->pIndex list.  Cursors for other indices
1440 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1441 **
1442 ** This routine also generates code to check constraints.  NOT NULL,
1443 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
1444 ** then the appropriate action is performed.  There are five possible
1445 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1446 **
1447 **  Constraint type  Action       What Happens
1448 **  ---------------  ----------   ----------------------------------------
1449 **  any              ROLLBACK     The current transaction is rolled back and
1450 **                                sqlite3_step() returns immediately with a
1451 **                                return code of SQLITE_CONSTRAINT.
1452 **
1453 **  any              ABORT        Back out changes from the current command
1454 **                                only (do not do a complete rollback) then
1455 **                                cause sqlite3_step() to return immediately
1456 **                                with SQLITE_CONSTRAINT.
1457 **
1458 **  any              FAIL         Sqlite3_step() returns immediately with a
1459 **                                return code of SQLITE_CONSTRAINT.  The
1460 **                                transaction is not rolled back and any
1461 **                                changes to prior rows are retained.
1462 **
1463 **  any              IGNORE       The attempt in insert or update the current
1464 **                                row is skipped, without throwing an error.
1465 **                                Processing continues with the next row.
1466 **                                (There is an immediate jump to ignoreDest.)
1467 **
1468 **  NOT NULL         REPLACE      The NULL value is replace by the default
1469 **                                value for that column.  If the default value
1470 **                                is NULL, the action is the same as ABORT.
1471 **
1472 **  UNIQUE           REPLACE      The other row that conflicts with the row
1473 **                                being inserted is removed.
1474 **
1475 **  CHECK            REPLACE      Illegal.  The results in an exception.
1476 **
1477 ** Which action to take is determined by the overrideError parameter.
1478 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1479 ** is used.  Or if pParse->onError==OE_Default then the onError value
1480 ** for the constraint is used.
1481 */
1482 void sqlite3GenerateConstraintChecks(
1483   Parse *pParse,       /* The parser context */
1484   Table *pTab,         /* The table being inserted or updated */
1485   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
1486   int iDataCur,        /* Canonical data cursor (main table or PK index) */
1487   int iIdxCur,         /* First index cursor */
1488   int regNewData,      /* First register in a range holding values to insert */
1489   int regOldData,      /* Previous content.  0 for INSERTs */
1490   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1491   u8 overrideError,    /* Override onError to this if not OE_Default */
1492   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1493   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1494   int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
1495   Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
1496 ){
1497   Vdbe *v;             /* VDBE under constrution */
1498   Index *pIdx;         /* Pointer to one of the indices */
1499   Index *pPk = 0;      /* The PRIMARY KEY index */
1500   sqlite3 *db;         /* Database connection */
1501   int i;               /* loop counter */
1502   int ix;              /* Index loop counter */
1503   int nCol;            /* Number of columns */
1504   int onError;         /* Conflict resolution strategy */
1505   int addr1;           /* Address of jump instruction */
1506   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1507   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1508   Index *pUpIdx = 0;   /* Index to which to apply the upsert */
1509   u8 isUpdate;         /* True if this is an UPDATE operation */
1510   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
1511   int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */
1512   int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */
1513   int ipkTop = 0;        /* Top of the IPK uniqueness check */
1514   int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
1515   /* Variables associated with retesting uniqueness constraints after
1516   ** replace triggers fire have run */
1517   int regTrigCnt;       /* Register used to count replace trigger invocations */
1518   int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */
1519   int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1520   Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
1521   int nReplaceTrig = 0; /* Number of replace triggers coded */
1522 
1523   isUpdate = regOldData!=0;
1524   db = pParse->db;
1525   v = sqlite3GetVdbe(pParse);
1526   assert( v!=0 );
1527   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1528   nCol = pTab->nCol;
1529 
1530   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1531   ** normal rowid tables.  nPkField is the number of key fields in the
1532   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
1533   ** number of fields in the true primary key of the table. */
1534   if( HasRowid(pTab) ){
1535     pPk = 0;
1536     nPkField = 1;
1537   }else{
1538     pPk = sqlite3PrimaryKeyIndex(pTab);
1539     nPkField = pPk->nKeyCol;
1540   }
1541 
1542   /* Record that this module has started */
1543   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1544                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1545 
1546   /* Test all NOT NULL constraints.
1547   */
1548   if( pTab->tabFlags & TF_HasNotNull ){
1549     for(i=0; i<nCol; i++){
1550       int iReg;
1551       onError = pTab->aCol[i].notNull;
1552       if( onError==OE_None ) continue; /* No NOT NULL on this column */
1553       if( i==pTab->iPKey ){
1554         continue;        /* ROWID is never NULL */
1555       }
1556       if( aiChng && aiChng[i]<0 ){
1557         /* Don't bother checking for NOT NULL on columns that do not change */
1558         continue;
1559       }
1560       if( overrideError!=OE_Default ){
1561         onError = overrideError;
1562       }else if( onError==OE_Default ){
1563         onError = OE_Abort;
1564       }
1565       if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
1566         onError = OE_Abort;
1567       }
1568       assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1569           || onError==OE_Ignore || onError==OE_Replace );
1570       addr1 = 0;
1571       testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1572       testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
1573       testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1574       iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
1575       switch( onError ){
1576         case OE_Replace: {
1577           assert( onError==OE_Replace );
1578           addr1 = sqlite3VdbeMakeLabel(pParse);
1579           sqlite3VdbeAddOp2(v, OP_NotNull, iReg, addr1);
1580             VdbeCoverage(v);
1581           if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ){
1582             sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
1583             sqlite3VdbeAddOp2(v, OP_NotNull, iReg, addr1);
1584               VdbeCoverage(v);
1585           }
1586           onError = OE_Abort;
1587           /* Fall through into the OE_Abort case to generate code that runs
1588           ** if both the input and the default value are NULL */
1589         }
1590         case OE_Abort:
1591           sqlite3MayAbort(pParse);
1592           /* Fall through */
1593         case OE_Rollback:
1594         case OE_Fail: {
1595           char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1596                                       pTab->aCol[i].zName);
1597           sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
1598                             onError, iReg);
1599           sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1600           sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1601           VdbeCoverage(v);
1602           if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
1603           break;
1604         }
1605         default: {
1606           assert( onError==OE_Ignore );
1607           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
1608           VdbeCoverage(v);
1609           break;
1610         }
1611       }
1612     }
1613   }
1614 
1615   /* Test all CHECK constraints
1616   */
1617 #ifndef SQLITE_OMIT_CHECK
1618   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1619     ExprList *pCheck = pTab->pCheck;
1620     pParse->iSelfTab = -(regNewData+1);
1621     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1622     for(i=0; i<pCheck->nExpr; i++){
1623       int allOk;
1624       Expr *pExpr = pCheck->a[i].pExpr;
1625       if( aiChng
1626        && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
1627       ){
1628         /* The check constraints do not reference any of the columns being
1629         ** updated so there is no point it verifying the check constraint */
1630         continue;
1631       }
1632       allOk = sqlite3VdbeMakeLabel(pParse);
1633       sqlite3VdbeVerifyAbortable(v, onError);
1634       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
1635       if( onError==OE_Ignore ){
1636         sqlite3VdbeGoto(v, ignoreDest);
1637       }else{
1638         char *zName = pCheck->a[i].zName;
1639         if( zName==0 ) zName = pTab->zName;
1640         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
1641         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1642                               onError, zName, P4_TRANSIENT,
1643                               P5_ConstraintCheck);
1644       }
1645       sqlite3VdbeResolveLabel(v, allOk);
1646     }
1647     pParse->iSelfTab = 0;
1648   }
1649 #endif /* !defined(SQLITE_OMIT_CHECK) */
1650 
1651   /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1652   ** order:
1653   **
1654   **   (1)  OE_Update
1655   **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1656   **   (3)  OE_Replace
1657   **
1658   ** OE_Fail and OE_Ignore must happen before any changes are made.
1659   ** OE_Update guarantees that only a single row will change, so it
1660   ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
1661   ** could happen in any order, but they are grouped up front for
1662   ** convenience.
1663   **
1664   ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
1665   ** The order of constraints used to have OE_Update as (2) and OE_Abort
1666   ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
1667   ** constraint before any others, so it had to be moved.
1668   **
1669   ** Constraint checking code is generated in this order:
1670   **   (A)  The rowid constraint
1671   **   (B)  Unique index constraints that do not have OE_Replace as their
1672   **        default conflict resolution strategy
1673   **   (C)  Unique index that do use OE_Replace by default.
1674   **
1675   ** The ordering of (2) and (3) is accomplished by making sure the linked
1676   ** list of indexes attached to a table puts all OE_Replace indexes last
1677   ** in the list.  See sqlite3CreateIndex() for where that happens.
1678   */
1679 
1680   if( pUpsert ){
1681     if( pUpsert->pUpsertTarget==0 ){
1682       /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
1683       ** Make all unique constraint resolution be OE_Ignore */
1684       assert( pUpsert->pUpsertSet==0 );
1685       overrideError = OE_Ignore;
1686       pUpsert = 0;
1687     }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
1688       /* If the constraint-target uniqueness check must be run first.
1689       ** Jump to that uniqueness check now */
1690       upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
1691       VdbeComment((v, "UPSERT constraint goes first"));
1692     }
1693   }
1694 
1695   /* Determine if it is possible that triggers (either explicitly coded
1696   ** triggers or FK resolution actions) might run as a result of deletes
1697   ** that happen when OE_Replace conflict resolution occurs. (Call these
1698   ** "replace triggers".)  If any replace triggers run, we will need to
1699   ** recheck all of the uniqueness constraints after they have all run.
1700   ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
1701   **
1702   ** If replace triggers are a possibility, then
1703   **
1704   **   (1) Allocate register regTrigCnt and initialize it to zero.
1705   **       That register will count the number of replace triggers that
1706   **       fire.  Constraint recheck only occurs if the number is positive.
1707   **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
1708   **   (3) Initialize addrRecheck and lblRecheckOk
1709   **
1710   ** The uniqueness rechecking code will create a series of tests to run
1711   ** in a second pass.  The addrRecheck and lblRecheckOk variables are
1712   ** used to link together these tests which are separated from each other
1713   ** in the generate bytecode.
1714   */
1715   if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
1716     /* There are not DELETE triggers nor FK constraints.  No constraint
1717     ** rechecks are needed. */
1718     pTrigger = 0;
1719     regTrigCnt = 0;
1720   }else{
1721     if( db->flags&SQLITE_RecTriggers ){
1722       pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1723       regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
1724     }else{
1725       pTrigger = 0;
1726       regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
1727     }
1728     if( regTrigCnt ){
1729       /* Replace triggers might exist.  Allocate the counter and
1730       ** initialize it to zero. */
1731       regTrigCnt = ++pParse->nMem;
1732       sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
1733       VdbeComment((v, "trigger count"));
1734       lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
1735       addrRecheck = lblRecheckOk;
1736     }
1737   }
1738 
1739   /* If rowid is changing, make sure the new rowid does not previously
1740   ** exist in the table.
1741   */
1742   if( pkChng && pPk==0 ){
1743     int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
1744 
1745     /* Figure out what action to take in case of a rowid collision */
1746     onError = pTab->keyConf;
1747     if( overrideError!=OE_Default ){
1748       onError = overrideError;
1749     }else if( onError==OE_Default ){
1750       onError = OE_Abort;
1751     }
1752 
1753     /* figure out whether or not upsert applies in this case */
1754     if( pUpsert && pUpsert->pUpsertIdx==0 ){
1755       if( pUpsert->pUpsertSet==0 ){
1756         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1757       }else{
1758         onError = OE_Update;  /* DO UPDATE */
1759       }
1760     }
1761 
1762     /* If the response to a rowid conflict is REPLACE but the response
1763     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
1764     ** to defer the running of the rowid conflict checking until after
1765     ** the UNIQUE constraints have run.
1766     */
1767     if( onError==OE_Replace      /* IPK rule is REPLACE */
1768      && onError!=overrideError   /* Rules for other contraints are different */
1769      && pTab->pIndex             /* There exist other constraints */
1770     ){
1771       ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
1772       VdbeComment((v, "defer IPK REPLACE until last"));
1773     }
1774 
1775     if( isUpdate ){
1776       /* pkChng!=0 does not mean that the rowid has changed, only that
1777       ** it might have changed.  Skip the conflict logic below if the rowid
1778       ** is unchanged. */
1779       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
1780       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1781       VdbeCoverage(v);
1782     }
1783 
1784     /* Check to see if the new rowid already exists in the table.  Skip
1785     ** the following conflict logic if it does not. */
1786     VdbeNoopComment((v, "uniqueness check for ROWID"));
1787     sqlite3VdbeVerifyAbortable(v, onError);
1788     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1789     VdbeCoverage(v);
1790 
1791     switch( onError ){
1792       default: {
1793         onError = OE_Abort;
1794         /* Fall thru into the next case */
1795       }
1796       case OE_Rollback:
1797       case OE_Abort:
1798       case OE_Fail: {
1799         testcase( onError==OE_Rollback );
1800         testcase( onError==OE_Abort );
1801         testcase( onError==OE_Fail );
1802         sqlite3RowidConstraint(pParse, onError, pTab);
1803         break;
1804       }
1805       case OE_Replace: {
1806         /* If there are DELETE triggers on this table and the
1807         ** recursive-triggers flag is set, call GenerateRowDelete() to
1808         ** remove the conflicting row from the table. This will fire
1809         ** the triggers and remove both the table and index b-tree entries.
1810         **
1811         ** Otherwise, if there are no triggers or the recursive-triggers
1812         ** flag is not set, but the table has one or more indexes, call
1813         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1814         ** only. The table b-tree entry will be replaced by the new entry
1815         ** when it is inserted.
1816         **
1817         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1818         ** also invoke MultiWrite() to indicate that this VDBE may require
1819         ** statement rollback (if the statement is aborted after the delete
1820         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1821         ** but being more selective here allows statements like:
1822         **
1823         **   REPLACE INTO t(rowid) VALUES($newrowid)
1824         **
1825         ** to run without a statement journal if there are no indexes on the
1826         ** table.
1827         */
1828         if( regTrigCnt ){
1829           sqlite3MultiWrite(pParse);
1830           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1831                                    regNewData, 1, 0, OE_Replace, 1, -1);
1832           sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
1833           nReplaceTrig++;
1834         }else{
1835 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1836           assert( HasRowid(pTab) );
1837           /* This OP_Delete opcode fires the pre-update-hook only. It does
1838           ** not modify the b-tree. It is more efficient to let the coming
1839           ** OP_Insert replace the existing entry than it is to delete the
1840           ** existing entry and then insert a new one. */
1841           sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
1842           sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
1843 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
1844           if( pTab->pIndex ){
1845             sqlite3MultiWrite(pParse);
1846             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
1847           }
1848         }
1849         seenReplace = 1;
1850         break;
1851       }
1852 #ifndef SQLITE_OMIT_UPSERT
1853       case OE_Update: {
1854         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
1855         /* Fall through */
1856       }
1857 #endif
1858       case OE_Ignore: {
1859         testcase( onError==OE_Ignore );
1860         sqlite3VdbeGoto(v, ignoreDest);
1861         break;
1862       }
1863     }
1864     sqlite3VdbeResolveLabel(v, addrRowidOk);
1865     if( ipkTop ){
1866       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
1867       sqlite3VdbeJumpHere(v, ipkTop-1);
1868     }
1869   }
1870 
1871   /* Test all UNIQUE constraints by creating entries for each UNIQUE
1872   ** index and making sure that duplicate entries do not already exist.
1873   ** Compute the revised record entries for indices as we go.
1874   **
1875   ** This loop also handles the case of the PRIMARY KEY index for a
1876   ** WITHOUT ROWID table.
1877   */
1878   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
1879     int regIdx;          /* Range of registers hold conent for pIdx */
1880     int regR;            /* Range of registers holding conflicting PK */
1881     int iThisCur;        /* Cursor for this UNIQUE index */
1882     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
1883     int addrConflictCk;  /* First opcode in the conflict check logic */
1884 
1885     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
1886     if( pUpIdx==pIdx ){
1887       addrUniqueOk = upsertJump+1;
1888       upsertBypass = sqlite3VdbeGoto(v, 0);
1889       VdbeComment((v, "Skip upsert subroutine"));
1890       sqlite3VdbeJumpHere(v, upsertJump);
1891     }else{
1892       addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
1893     }
1894     if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
1895       sqlite3TableAffinity(v, pTab, regNewData+1);
1896       bAffinityDone = 1;
1897     }
1898     VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
1899     iThisCur = iIdxCur+ix;
1900 
1901 
1902     /* Skip partial indices for which the WHERE clause is not true */
1903     if( pIdx->pPartIdxWhere ){
1904       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
1905       pParse->iSelfTab = -(regNewData+1);
1906       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1907                             SQLITE_JUMPIFNULL);
1908       pParse->iSelfTab = 0;
1909     }
1910 
1911     /* Create a record for this index entry as it should appear after
1912     ** the insert or update.  Store that record in the aRegIdx[ix] register
1913     */
1914     regIdx = aRegIdx[ix]+1;
1915     for(i=0; i<pIdx->nColumn; i++){
1916       int iField = pIdx->aiColumn[i];
1917       int x;
1918       if( iField==XN_EXPR ){
1919         pParse->iSelfTab = -(regNewData+1);
1920         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
1921         pParse->iSelfTab = 0;
1922         VdbeComment((v, "%s column %d", pIdx->zName, i));
1923       }else if( iField==XN_ROWID || iField==pTab->iPKey ){
1924         x = regNewData;
1925         sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
1926         VdbeComment((v, "rowid"));
1927       }else{
1928         testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
1929         x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
1930         sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
1931         VdbeComment((v, "%s", pTab->aCol[iField].zName));
1932       }
1933     }
1934     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
1935     VdbeComment((v, "for %s", pIdx->zName));
1936 #ifdef SQLITE_ENABLE_NULL_TRIM
1937     if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
1938       sqlite3SetMakeRecordP5(v, pIdx->pTable);
1939     }
1940 #endif
1941 
1942     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1943     ** of a WITHOUT ROWID table and there has been no change the
1944     ** primary key, then no collision is possible.  The collision detection
1945     ** logic below can all be skipped. */
1946     if( isUpdate && pPk==pIdx && pkChng==0 ){
1947       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1948       continue;
1949     }
1950 
1951     /* Find out what action to take in case there is a uniqueness conflict */
1952     onError = pIdx->onError;
1953     if( onError==OE_None ){
1954       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1955       continue;  /* pIdx is not a UNIQUE index */
1956     }
1957     if( overrideError!=OE_Default ){
1958       onError = overrideError;
1959     }else if( onError==OE_Default ){
1960       onError = OE_Abort;
1961     }
1962 
1963     /* Figure out if the upsert clause applies to this index */
1964     if( pUpIdx==pIdx ){
1965       if( pUpsert->pUpsertSet==0 ){
1966         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1967       }else{
1968         onError = OE_Update;  /* DO UPDATE */
1969       }
1970     }
1971 
1972     /* Collision detection may be omitted if all of the following are true:
1973     **   (1) The conflict resolution algorithm is REPLACE
1974     **   (2) The table is a WITHOUT ROWID table
1975     **   (3) There are no secondary indexes on the table
1976     **   (4) No delete triggers need to be fired if there is a conflict
1977     **   (5) No FK constraint counters need to be updated if a conflict occurs.
1978     **
1979     ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
1980     ** must be explicitly deleted in order to ensure any pre-update hook
1981     ** is invoked.  */
1982 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
1983     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
1984      && pPk==pIdx                                   /* Condition 2 */
1985      && onError==OE_Replace                         /* Condition 1 */
1986      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
1987           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
1988      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
1989          (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
1990     ){
1991       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1992       continue;
1993     }
1994 #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
1995 
1996     /* Check to see if the new index entry will be unique */
1997     sqlite3VdbeVerifyAbortable(v, onError);
1998     addrConflictCk =
1999       sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2000                            regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2001 
2002     /* Generate code to handle collisions */
2003     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
2004     if( isUpdate || onError==OE_Replace ){
2005       if( HasRowid(pTab) ){
2006         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2007         /* Conflict only if the rowid of the existing index entry
2008         ** is different from old-rowid */
2009         if( isUpdate ){
2010           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
2011           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2012           VdbeCoverage(v);
2013         }
2014       }else{
2015         int x;
2016         /* Extract the PRIMARY KEY from the end of the index entry and
2017         ** store it in registers regR..regR+nPk-1 */
2018         if( pIdx!=pPk ){
2019           for(i=0; i<pPk->nKeyCol; i++){
2020             assert( pPk->aiColumn[i]>=0 );
2021             x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
2022             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2023             VdbeComment((v, "%s.%s", pTab->zName,
2024                          pTab->aCol[pPk->aiColumn[i]].zName));
2025           }
2026         }
2027         if( isUpdate ){
2028           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2029           ** table, only conflict if the new PRIMARY KEY values are actually
2030           ** different from the old.
2031           **
2032           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2033           ** of the matched index row are different from the original PRIMARY
2034           ** KEY values of this row before the update.  */
2035           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2036           int op = OP_Ne;
2037           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2038 
2039           for(i=0; i<pPk->nKeyCol; i++){
2040             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2041             x = pPk->aiColumn[i];
2042             assert( x>=0 );
2043             if( i==(pPk->nKeyCol-1) ){
2044               addrJump = addrUniqueOk;
2045               op = OP_Eq;
2046             }
2047             x = sqlite3TableColumnToStorage(pTab, x);
2048             sqlite3VdbeAddOp4(v, op,
2049                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2050             );
2051             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2052             VdbeCoverageIf(v, op==OP_Eq);
2053             VdbeCoverageIf(v, op==OP_Ne);
2054           }
2055         }
2056       }
2057     }
2058 
2059     /* Generate code that executes if the new index entry is not unique */
2060     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2061         || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
2062     switch( onError ){
2063       case OE_Rollback:
2064       case OE_Abort:
2065       case OE_Fail: {
2066         testcase( onError==OE_Rollback );
2067         testcase( onError==OE_Abort );
2068         testcase( onError==OE_Fail );
2069         sqlite3UniqueConstraint(pParse, onError, pIdx);
2070         break;
2071       }
2072 #ifndef SQLITE_OMIT_UPSERT
2073       case OE_Update: {
2074         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
2075         /* Fall through */
2076       }
2077 #endif
2078       case OE_Ignore: {
2079         testcase( onError==OE_Ignore );
2080         sqlite3VdbeGoto(v, ignoreDest);
2081         break;
2082       }
2083       default: {
2084         int nConflictCk;   /* Number of opcodes in conflict check logic */
2085 
2086         assert( onError==OE_Replace );
2087         nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2088         assert( nConflictCk>0 );
2089         testcase( nConflictCk>1 );
2090         if( regTrigCnt ){
2091           sqlite3MultiWrite(pParse);
2092           nReplaceTrig++;
2093         }
2094         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2095             regR, nPkField, 0, OE_Replace,
2096             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
2097         if( regTrigCnt ){
2098           int addrBypass;  /* Jump destination to bypass recheck logic */
2099 
2100           sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2101           addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */
2102           VdbeComment((v, "bypass recheck"));
2103 
2104           /* Here we insert code that will be invoked after all constraint
2105           ** checks have run, if and only if one or more replace triggers
2106           ** fired. */
2107           sqlite3VdbeResolveLabel(v, lblRecheckOk);
2108           lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2109           if( pIdx->pPartIdxWhere ){
2110             /* Bypass the recheck if this partial index is not defined
2111             ** for the current row */
2112             sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2113             VdbeCoverage(v);
2114           }
2115           /* Copy the constraint check code from above, except change
2116           ** the constraint-ok jump destination to be the address of
2117           ** the next retest block */
2118           while( nConflictCk>0 ){
2119             VdbeOp x;    /* Conflict check opcode to copy */
2120             /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2121             ** Hence, make a complete copy of the opcode, rather than using
2122             ** a pointer to the opcode. */
2123             x = *sqlite3VdbeGetOp(v, addrConflictCk);
2124             if( x.opcode!=OP_IdxRowid ){
2125               int p2;      /* New P2 value for copied conflict check opcode */
2126               if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2127                 p2 = lblRecheckOk;
2128               }else{
2129                 p2 = x.p2;
2130               }
2131               sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, x.p4.z, x.p4type);
2132               sqlite3VdbeChangeP5(v, x.p5);
2133               VdbeCoverageIf(v, p2!=x.p2);
2134             }
2135             nConflictCk--;
2136             addrConflictCk++;
2137           }
2138           /* If the retest fails, issue an abort */
2139           sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2140 
2141           sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
2142         }
2143         seenReplace = 1;
2144         break;
2145       }
2146     }
2147     if( pUpIdx==pIdx ){
2148       sqlite3VdbeGoto(v, upsertJump+1);
2149       sqlite3VdbeJumpHere(v, upsertBypass);
2150     }else{
2151       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2152     }
2153     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2154   }
2155 
2156   /* If the IPK constraint is a REPLACE, run it last */
2157   if( ipkTop ){
2158     sqlite3VdbeGoto(v, ipkTop);
2159     VdbeComment((v, "Do IPK REPLACE"));
2160     sqlite3VdbeJumpHere(v, ipkBottom);
2161   }
2162 
2163   /* Recheck all uniqueness constraints after replace triggers have run */
2164   testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2165   assert( regTrigCnt!=0 || nReplaceTrig==0 );
2166   if( nReplaceTrig ){
2167     sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2168     if( !pPk ){
2169       if( isUpdate ){
2170         sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2171         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2172         VdbeCoverage(v);
2173       }
2174       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2175       VdbeCoverage(v);
2176       sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2177     }else{
2178       sqlite3VdbeGoto(v, addrRecheck);
2179     }
2180     sqlite3VdbeResolveLabel(v, lblRecheckOk);
2181   }
2182 
2183   /* Generate the table record */
2184   if( HasRowid(pTab) ){
2185     int regRec = aRegIdx[ix];
2186     sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2187     sqlite3SetMakeRecordP5(v, pTab);
2188     if( !bAffinityDone ){
2189       sqlite3TableAffinity(v, pTab, 0);
2190     }
2191   }
2192 
2193   *pbMayReplace = seenReplace;
2194   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
2195 }
2196 
2197 #ifdef SQLITE_ENABLE_NULL_TRIM
2198 /*
2199 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2200 ** to be the number of columns in table pTab that must not be NULL-trimmed.
2201 **
2202 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2203 */
2204 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2205   u16 i;
2206 
2207   /* Records with omitted columns are only allowed for schema format
2208   ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2209   if( pTab->pSchema->file_format<2 ) return;
2210 
2211   for(i=pTab->nCol-1; i>0; i--){
2212     if( pTab->aCol[i].pDflt!=0 ) break;
2213     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2214   }
2215   sqlite3VdbeChangeP5(v, i+1);
2216 }
2217 #endif
2218 
2219 /*
2220 ** This routine generates code to finish the INSERT or UPDATE operation
2221 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
2222 ** A consecutive range of registers starting at regNewData contains the
2223 ** rowid and the content to be inserted.
2224 **
2225 ** The arguments to this routine should be the same as the first six
2226 ** arguments to sqlite3GenerateConstraintChecks.
2227 */
2228 void sqlite3CompleteInsertion(
2229   Parse *pParse,      /* The parser context */
2230   Table *pTab,        /* the table into which we are inserting */
2231   int iDataCur,       /* Cursor of the canonical data source */
2232   int iIdxCur,        /* First index cursor */
2233   int regNewData,     /* Range of content */
2234   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
2235   int update_flags,   /* True for UPDATE, False for INSERT */
2236   int appendBias,     /* True if this is likely to be an append */
2237   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
2238 ){
2239   Vdbe *v;            /* Prepared statements under construction */
2240   Index *pIdx;        /* An index being inserted or updated */
2241   u8 pik_flags;       /* flag values passed to the btree insert */
2242   int i;              /* Loop counter */
2243 
2244   assert( update_flags==0
2245        || update_flags==OPFLAG_ISUPDATE
2246        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2247   );
2248 
2249   v = sqlite3GetVdbe(pParse);
2250   assert( v!=0 );
2251   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
2252   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2253     /* All REPLACE indexes are at the end of the list */
2254     assert( pIdx->onError!=OE_Replace
2255          || pIdx->pNext==0
2256          || pIdx->pNext->onError==OE_Replace );
2257     if( aRegIdx[i]==0 ) continue;
2258     if( pIdx->pPartIdxWhere ){
2259       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2260       VdbeCoverage(v);
2261     }
2262     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
2263     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2264       assert( pParse->nested==0 );
2265       pik_flags |= OPFLAG_NCHANGE;
2266       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2267 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2268       if( update_flags==0 ){
2269         int r = sqlite3GetTempReg(pParse);
2270         sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2271         sqlite3VdbeAddOp4(v, OP_Insert,
2272             iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
2273         );
2274         sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2275         sqlite3ReleaseTempReg(pParse, r);
2276       }
2277 #endif
2278     }
2279     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2280                          aRegIdx[i]+1,
2281                          pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
2282     sqlite3VdbeChangeP5(v, pik_flags);
2283   }
2284   if( !HasRowid(pTab) ) return;
2285   if( pParse->nested ){
2286     pik_flags = 0;
2287   }else{
2288     pik_flags = OPFLAG_NCHANGE;
2289     pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
2290   }
2291   if( appendBias ){
2292     pik_flags |= OPFLAG_APPEND;
2293   }
2294   if( useSeekResult ){
2295     pik_flags |= OPFLAG_USESEEKRESULT;
2296   }
2297   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
2298   if( !pParse->nested ){
2299     sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2300   }
2301   sqlite3VdbeChangeP5(v, pik_flags);
2302 }
2303 
2304 /*
2305 ** Allocate cursors for the pTab table and all its indices and generate
2306 ** code to open and initialized those cursors.
2307 **
2308 ** The cursor for the object that contains the complete data (normally
2309 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2310 ** ROWID table) is returned in *piDataCur.  The first index cursor is
2311 ** returned in *piIdxCur.  The number of indices is returned.
2312 **
2313 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
2314 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
2315 ** If iBase is negative, then allocate the next available cursor.
2316 **
2317 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2318 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2319 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2320 ** pTab->pIndex list.
2321 **
2322 ** If pTab is a virtual table, then this routine is a no-op and the
2323 ** *piDataCur and *piIdxCur values are left uninitialized.
2324 */
2325 int sqlite3OpenTableAndIndices(
2326   Parse *pParse,   /* Parsing context */
2327   Table *pTab,     /* Table to be opened */
2328   int op,          /* OP_OpenRead or OP_OpenWrite */
2329   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
2330   int iBase,       /* Use this for the table cursor, if there is one */
2331   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
2332   int *piDataCur,  /* Write the database source cursor number here */
2333   int *piIdxCur    /* Write the first index cursor number here */
2334 ){
2335   int i;
2336   int iDb;
2337   int iDataCur;
2338   Index *pIdx;
2339   Vdbe *v;
2340 
2341   assert( op==OP_OpenRead || op==OP_OpenWrite );
2342   assert( op==OP_OpenWrite || p5==0 );
2343   if( IsVirtual(pTab) ){
2344     /* This routine is a no-op for virtual tables. Leave the output
2345     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
2346     ** can detect if they are used by mistake in the caller. */
2347     return 0;
2348   }
2349   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2350   v = sqlite3GetVdbe(pParse);
2351   assert( v!=0 );
2352   if( iBase<0 ) iBase = pParse->nTab;
2353   iDataCur = iBase++;
2354   if( piDataCur ) *piDataCur = iDataCur;
2355   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2356     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2357   }else{
2358     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2359   }
2360   if( piIdxCur ) *piIdxCur = iBase;
2361   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2362     int iIdxCur = iBase++;
2363     assert( pIdx->pSchema==pTab->pSchema );
2364     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2365       if( piDataCur ) *piDataCur = iIdxCur;
2366       p5 = 0;
2367     }
2368     if( aToOpen==0 || aToOpen[i+1] ){
2369       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2370       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2371       sqlite3VdbeChangeP5(v, p5);
2372       VdbeComment((v, "%s", pIdx->zName));
2373     }
2374   }
2375   if( iBase>pParse->nTab ) pParse->nTab = iBase;
2376   return i;
2377 }
2378 
2379 
2380 #ifdef SQLITE_TEST
2381 /*
2382 ** The following global variable is incremented whenever the
2383 ** transfer optimization is used.  This is used for testing
2384 ** purposes only - to make sure the transfer optimization really
2385 ** is happening when it is supposed to.
2386 */
2387 int sqlite3_xferopt_count;
2388 #endif /* SQLITE_TEST */
2389 
2390 
2391 #ifndef SQLITE_OMIT_XFER_OPT
2392 /*
2393 ** Check to see if index pSrc is compatible as a source of data
2394 ** for index pDest in an insert transfer optimization.  The rules
2395 ** for a compatible index:
2396 **
2397 **    *   The index is over the same set of columns
2398 **    *   The same DESC and ASC markings occurs on all columns
2399 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
2400 **    *   The same collating sequence on each column
2401 **    *   The index has the exact same WHERE clause
2402 */
2403 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2404   int i;
2405   assert( pDest && pSrc );
2406   assert( pDest->pTable!=pSrc->pTable );
2407   if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
2408     return 0;   /* Different number of columns */
2409   }
2410   if( pDest->onError!=pSrc->onError ){
2411     return 0;   /* Different conflict resolution strategies */
2412   }
2413   for(i=0; i<pSrc->nKeyCol; i++){
2414     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2415       return 0;   /* Different columns indexed */
2416     }
2417     if( pSrc->aiColumn[i]==XN_EXPR ){
2418       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
2419       if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
2420                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2421         return 0;   /* Different expressions in the index */
2422       }
2423     }
2424     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2425       return 0;   /* Different sort orders */
2426     }
2427     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
2428       return 0;   /* Different collating sequences */
2429     }
2430   }
2431   if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2432     return 0;     /* Different WHERE clauses */
2433   }
2434 
2435   /* If no test above fails then the indices must be compatible */
2436   return 1;
2437 }
2438 
2439 /*
2440 ** Attempt the transfer optimization on INSERTs of the form
2441 **
2442 **     INSERT INTO tab1 SELECT * FROM tab2;
2443 **
2444 ** The xfer optimization transfers raw records from tab2 over to tab1.
2445 ** Columns are not decoded and reassembled, which greatly improves
2446 ** performance.  Raw index records are transferred in the same way.
2447 **
2448 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2449 ** There are lots of rules for determining compatibility - see comments
2450 ** embedded in the code for details.
2451 **
2452 ** This routine returns TRUE if the optimization is guaranteed to be used.
2453 ** Sometimes the xfer optimization will only work if the destination table
2454 ** is empty - a factor that can only be determined at run-time.  In that
2455 ** case, this routine generates code for the xfer optimization but also
2456 ** does a test to see if the destination table is empty and jumps over the
2457 ** xfer optimization code if the test fails.  In that case, this routine
2458 ** returns FALSE so that the caller will know to go ahead and generate
2459 ** an unoptimized transfer.  This routine also returns FALSE if there
2460 ** is no chance that the xfer optimization can be applied.
2461 **
2462 ** This optimization is particularly useful at making VACUUM run faster.
2463 */
2464 static int xferOptimization(
2465   Parse *pParse,        /* Parser context */
2466   Table *pDest,         /* The table we are inserting into */
2467   Select *pSelect,      /* A SELECT statement to use as the data source */
2468   int onError,          /* How to handle constraint errors */
2469   int iDbDest           /* The database of pDest */
2470 ){
2471   sqlite3 *db = pParse->db;
2472   ExprList *pEList;                /* The result set of the SELECT */
2473   Table *pSrc;                     /* The table in the FROM clause of SELECT */
2474   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
2475   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
2476   int i;                           /* Loop counter */
2477   int iDbSrc;                      /* The database of pSrc */
2478   int iSrc, iDest;                 /* Cursors from source and destination */
2479   int addr1, addr2;                /* Loop addresses */
2480   int emptyDestTest = 0;           /* Address of test for empty pDest */
2481   int emptySrcTest = 0;            /* Address of test for empty pSrc */
2482   Vdbe *v;                         /* The VDBE we are building */
2483   int regAutoinc;                  /* Memory register used by AUTOINC */
2484   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
2485   int regData, regRowid;           /* Registers holding data and rowid */
2486 
2487   if( pSelect==0 ){
2488     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
2489   }
2490   if( pParse->pWith || pSelect->pWith ){
2491     /* Do not attempt to process this query if there are an WITH clauses
2492     ** attached to it. Proceeding may generate a false "no such table: xxx"
2493     ** error if pSelect reads from a CTE named "xxx".  */
2494     return 0;
2495   }
2496   if( sqlite3TriggerList(pParse, pDest) ){
2497     return 0;   /* tab1 must not have triggers */
2498   }
2499 #ifndef SQLITE_OMIT_VIRTUALTABLE
2500   if( IsVirtual(pDest) ){
2501     return 0;   /* tab1 must not be a virtual table */
2502   }
2503 #endif
2504   if( onError==OE_Default ){
2505     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2506     if( onError==OE_Default ) onError = OE_Abort;
2507   }
2508   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
2509   if( pSelect->pSrc->nSrc!=1 ){
2510     return 0;   /* FROM clause must have exactly one term */
2511   }
2512   if( pSelect->pSrc->a[0].pSelect ){
2513     return 0;   /* FROM clause cannot contain a subquery */
2514   }
2515   if( pSelect->pWhere ){
2516     return 0;   /* SELECT may not have a WHERE clause */
2517   }
2518   if( pSelect->pOrderBy ){
2519     return 0;   /* SELECT may not have an ORDER BY clause */
2520   }
2521   /* Do not need to test for a HAVING clause.  If HAVING is present but
2522   ** there is no ORDER BY, we will get an error. */
2523   if( pSelect->pGroupBy ){
2524     return 0;   /* SELECT may not have a GROUP BY clause */
2525   }
2526   if( pSelect->pLimit ){
2527     return 0;   /* SELECT may not have a LIMIT clause */
2528   }
2529   if( pSelect->pPrior ){
2530     return 0;   /* SELECT may not be a compound query */
2531   }
2532   if( pSelect->selFlags & SF_Distinct ){
2533     return 0;   /* SELECT may not be DISTINCT */
2534   }
2535   pEList = pSelect->pEList;
2536   assert( pEList!=0 );
2537   if( pEList->nExpr!=1 ){
2538     return 0;   /* The result set must have exactly one column */
2539   }
2540   assert( pEList->a[0].pExpr );
2541   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
2542     return 0;   /* The result set must be the special operator "*" */
2543   }
2544 
2545   /* At this point we have established that the statement is of the
2546   ** correct syntactic form to participate in this optimization.  Now
2547   ** we have to check the semantics.
2548   */
2549   pItem = pSelect->pSrc->a;
2550   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
2551   if( pSrc==0 ){
2552     return 0;   /* FROM clause does not contain a real table */
2553   }
2554   if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
2555     testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
2556     return 0;   /* tab1 and tab2 may not be the same table */
2557   }
2558   if( HasRowid(pDest)!=HasRowid(pSrc) ){
2559     return 0;   /* source and destination must both be WITHOUT ROWID or not */
2560   }
2561 #ifndef SQLITE_OMIT_VIRTUALTABLE
2562   if( IsVirtual(pSrc) ){
2563     return 0;   /* tab2 must not be a virtual table */
2564   }
2565 #endif
2566   if( pSrc->pSelect ){
2567     return 0;   /* tab2 may not be a view */
2568   }
2569   if( pDest->nCol!=pSrc->nCol ){
2570     return 0;   /* Number of columns must be the same in tab1 and tab2 */
2571   }
2572   if( pDest->iPKey!=pSrc->iPKey ){
2573     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
2574   }
2575   for(i=0; i<pDest->nCol; i++){
2576     Column *pDestCol = &pDest->aCol[i];
2577     Column *pSrcCol = &pSrc->aCol[i];
2578 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
2579     if( (db->mDbFlags & DBFLAG_Vacuum)==0
2580      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2581     ){
2582       return 0;    /* Neither table may have __hidden__ columns */
2583     }
2584 #endif
2585 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2586     /* Even if tables t1 and t2 have identical schemas, if they contain
2587     ** generated columns, then this statement is semantically incorrect:
2588     **
2589     **     INSERT INTO t2 SELECT * FROM t1;
2590     **
2591     ** The reason is that generated column values are returned by the
2592     ** the SELECT statement on the right but the INSERT statement on the
2593     ** left wants them to be omitted.
2594     **
2595     ** Nevertheless, this is a useful notational shorthand to tell SQLite
2596     ** to do a bulk transfer all of the content from t1 over to t2.
2597     **
2598     ** We could, in theory, disable this (except for internal use by the
2599     ** VACUUM command where it is actually needed).  But why do that?  It
2600     ** seems harmless enough, and provides a useful service.
2601     */
2602     if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
2603         (pSrcCol->colFlags & COLFLAG_GENERATED) ){
2604       return 0;    /* Both columns have the same generated-column type */
2605     }
2606     /* But the transfer is only allowed if both the source and destination
2607     ** tables have the exact same expressions for generated columns.
2608     ** This requirement could be relaxed for VIRTUAL columns, I suppose.
2609     */
2610     if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
2611       if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){
2612         testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
2613         testcase( pDestCol->colFlags & COLFLAG_STORED );
2614         return 0;  /* Different generator expressions */
2615       }
2616     }
2617 #endif
2618     if( pDestCol->affinity!=pSrcCol->affinity ){
2619       return 0;    /* Affinity must be the same on all columns */
2620     }
2621     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
2622       return 0;    /* Collating sequence must be the same on all columns */
2623     }
2624     if( pDestCol->notNull && !pSrcCol->notNull ){
2625       return 0;    /* tab2 must be NOT NULL if tab1 is */
2626     }
2627     /* Default values for second and subsequent columns need to match. */
2628     if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
2629       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
2630       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
2631       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
2632        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
2633                                        pSrcCol->pDflt->u.zToken)!=0)
2634       ){
2635         return 0;    /* Default values must be the same for all columns */
2636       }
2637     }
2638   }
2639   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2640     if( IsUniqueIndex(pDestIdx) ){
2641       destHasUniqueIdx = 1;
2642     }
2643     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
2644       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2645     }
2646     if( pSrcIdx==0 ){
2647       return 0;    /* pDestIdx has no corresponding index in pSrc */
2648     }
2649     if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
2650          && sqlite3FaultSim(411)==SQLITE_OK ){
2651       /* The sqlite3FaultSim() call allows this corruption test to be
2652       ** bypassed during testing, in order to exercise other corruption tests
2653       ** further downstream. */
2654       return 0;   /* Corrupt schema - two indexes on the same btree */
2655     }
2656   }
2657 #ifndef SQLITE_OMIT_CHECK
2658   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
2659     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
2660   }
2661 #endif
2662 #ifndef SQLITE_OMIT_FOREIGN_KEY
2663   /* Disallow the transfer optimization if the destination table constains
2664   ** any foreign key constraints.  This is more restrictive than necessary.
2665   ** But the main beneficiary of the transfer optimization is the VACUUM
2666   ** command, and the VACUUM command disables foreign key constraints.  So
2667   ** the extra complication to make this rule less restrictive is probably
2668   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2669   */
2670   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
2671     return 0;
2672   }
2673 #endif
2674   if( (db->flags & SQLITE_CountRows)!=0 ){
2675     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
2676   }
2677 
2678   /* If we get this far, it means that the xfer optimization is at
2679   ** least a possibility, though it might only work if the destination
2680   ** table (tab1) is initially empty.
2681   */
2682 #ifdef SQLITE_TEST
2683   sqlite3_xferopt_count++;
2684 #endif
2685   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
2686   v = sqlite3GetVdbe(pParse);
2687   sqlite3CodeVerifySchema(pParse, iDbSrc);
2688   iSrc = pParse->nTab++;
2689   iDest = pParse->nTab++;
2690   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
2691   regData = sqlite3GetTempReg(pParse);
2692   regRowid = sqlite3GetTempReg(pParse);
2693   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2694   assert( HasRowid(pDest) || destHasUniqueIdx );
2695   if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
2696       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2697    || destHasUniqueIdx                              /* (2) */
2698    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2699   )){
2700     /* In some circumstances, we are able to run the xfer optimization
2701     ** only if the destination table is initially empty. Unless the
2702     ** DBFLAG_Vacuum flag is set, this block generates code to make
2703     ** that determination. If DBFLAG_Vacuum is set, then the destination
2704     ** table is always empty.
2705     **
2706     ** Conditions under which the destination must be empty:
2707     **
2708     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2709     **     (If the destination is not initially empty, the rowid fields
2710     **     of index entries might need to change.)
2711     **
2712     ** (2) The destination has a unique index.  (The xfer optimization
2713     **     is unable to test uniqueness.)
2714     **
2715     ** (3) onError is something other than OE_Abort and OE_Rollback.
2716     */
2717     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
2718     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
2719     sqlite3VdbeJumpHere(v, addr1);
2720   }
2721   if( HasRowid(pSrc) ){
2722     u8 insFlags;
2723     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
2724     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2725     if( pDest->iPKey>=0 ){
2726       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2727       sqlite3VdbeVerifyAbortable(v, onError);
2728       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2729       VdbeCoverage(v);
2730       sqlite3RowidConstraint(pParse, onError, pDest);
2731       sqlite3VdbeJumpHere(v, addr2);
2732       autoIncStep(pParse, regAutoinc, regRowid);
2733     }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
2734       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
2735     }else{
2736       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2737       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
2738     }
2739     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
2740     if( db->mDbFlags & DBFLAG_Vacuum ){
2741       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2742       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
2743                            OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
2744     }else{
2745       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
2746     }
2747     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
2748                       (char*)pDest, P4_TABLE);
2749     sqlite3VdbeChangeP5(v, insFlags);
2750     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
2751     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2752     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2753   }else{
2754     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2755     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
2756   }
2757   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2758     u8 idxInsFlags = 0;
2759     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
2760       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2761     }
2762     assert( pSrcIdx );
2763     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
2764     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2765     VdbeComment((v, "%s", pSrcIdx->zName));
2766     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
2767     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
2768     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2769     VdbeComment((v, "%s", pDestIdx->zName));
2770     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2771     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
2772     if( db->mDbFlags & DBFLAG_Vacuum ){
2773       /* This INSERT command is part of a VACUUM operation, which guarantees
2774       ** that the destination table is empty. If all indexed columns use
2775       ** collation sequence BINARY, then it can also be assumed that the
2776       ** index will be populated by inserting keys in strictly sorted
2777       ** order. In this case, instead of seeking within the b-tree as part
2778       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
2779       ** OP_IdxInsert to seek to the point within the b-tree where each key
2780       ** should be inserted. This is faster.
2781       **
2782       ** If any of the indexed columns use a collation sequence other than
2783       ** BINARY, this optimization is disabled. This is because the user
2784       ** might change the definition of a collation sequence and then run
2785       ** a VACUUM command. In that case keys may not be written in strictly
2786       ** sorted order.  */
2787       for(i=0; i<pSrcIdx->nColumn; i++){
2788         const char *zColl = pSrcIdx->azColl[i];
2789         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
2790       }
2791       if( i==pSrcIdx->nColumn ){
2792         idxInsFlags = OPFLAG_USESEEKRESULT;
2793         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2794       }
2795     }
2796     if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2797       idxInsFlags |= OPFLAG_NCHANGE;
2798     }
2799     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
2800     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
2801     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
2802     sqlite3VdbeJumpHere(v, addr1);
2803     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2804     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2805   }
2806   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2807   sqlite3ReleaseTempReg(pParse, regRowid);
2808   sqlite3ReleaseTempReg(pParse, regData);
2809   if( emptyDestTest ){
2810     sqlite3AutoincrementEnd(pParse);
2811     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
2812     sqlite3VdbeJumpHere(v, emptyDestTest);
2813     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2814     return 0;
2815   }else{
2816     return 1;
2817   }
2818 }
2819 #endif /* SQLITE_OMIT_XFER_OPT */
2820