xref: /sqlite-3.40.0/src/insert.c (revision 5fdb9a35)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17cce7d176Sdrh /*
1826198bb4Sdrh ** Generate code that will
19dd9930efSdrh **
2026198bb4Sdrh **   (1) acquire a lock for table pTab then
2126198bb4Sdrh **   (2) open pTab as cursor iCur.
2226198bb4Sdrh **
2326198bb4Sdrh ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
2426198bb4Sdrh ** for that table that is actually opened.
25bbb5e4e0Sdrh */
sqlite3OpenTable(Parse * pParse,int iCur,int iDb,Table * pTab,int opcode)26bbb5e4e0Sdrh void sqlite3OpenTable(
272ec2fb22Sdrh   Parse *pParse,  /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
35289a0c84Sdrh   assert( pParse->pVdbe!=0 );
36289a0c84Sdrh   v = pParse->pVdbe;
37bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
382ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
392ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
40ec95c441Sdrh   if( HasRowid(pTab) ){
410b0b3a95Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
42bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
4326198bb4Sdrh   }else{
44dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
45dd9930efSdrh     assert( pPk!=0 );
4639075608Sdrh     assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
472ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
482ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
49bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
50bbb5e4e0Sdrh   }
51bbb5e4e0Sdrh }
52bbb5e4e0Sdrh 
53bbb5e4e0Sdrh /*
5469f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5569f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5669f8bb9cSdan ** the table, according to the affinity of the column:
573d1bfeaaSdanielk1977 **
583d1bfeaaSdanielk1977 **  Character      Column affinity
593d1bfeaaSdanielk1977 **  ------------------------------
6005883a34Sdrh **  'A'            BLOB
614583c37cSdrh **  'B'            TEXT
624583c37cSdrh **  'C'            NUMERIC
634583c37cSdrh **  'D'            INTEGER
644583c37cSdrh **  'F'            REAL
652d401ab8Sdrh **
664583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the
672d401ab8Sdrh ** rowid that appears as the last column in every index.
6869f8bb9cSdan **
6969f8bb9cSdan ** Memory for the buffer containing the column index affinity string
7069f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7169f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
723d1bfeaaSdanielk1977 */
sqlite3IndexAffinityStr(sqlite3 * db,Index * pIdx)73e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
74a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
75e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
76a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
77e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
78a37cdde0Sdanielk1977     **
79a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
80e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
81a37cdde0Sdanielk1977     ** up.
82a37cdde0Sdanielk1977     */
83a37cdde0Sdanielk1977     int n;
84a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
85ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
86a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
874a642b60Sdrh       sqlite3OomFault(db);
8869f8bb9cSdan       return 0;
89a37cdde0Sdanielk1977     }
90a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
91ad124329Sdrh       i16 x = pIdx->aiColumn[n];
926860e6faSdrh       char aff;
9381506b88Sdrh       if( x>=0 ){
9481506b88Sdrh         aff = pTab->aCol[x].affinity;
9581506b88Sdrh       }else if( x==XN_ROWID ){
9681506b88Sdrh         aff = SQLITE_AFF_INTEGER;
9781506b88Sdrh       }else{
984b92f98cSdrh         assert( x==XN_EXPR );
994bc1cc18Sdrh         assert( pIdx->bHasExpr );
1001f9ca2c8Sdrh         assert( pIdx->aColExpr!=0 );
1016860e6faSdrh         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
10281506b88Sdrh       }
10396fb16eeSdrh       if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
1047314495fSdrh       if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
1056860e6faSdrh       pIdx->zColAff[n] = aff;
1061f9ca2c8Sdrh     }
1072d401ab8Sdrh     pIdx->zColAff[n] = 0;
108a37cdde0Sdanielk1977   }
1093d1bfeaaSdanielk1977 
11069f8bb9cSdan   return pIdx->zColAff;
111a37cdde0Sdanielk1977 }
112a37cdde0Sdanielk1977 
113a37cdde0Sdanielk1977 /*
114*5fdb9a35Sdrh ** Compute an affinity string for a table.   Space is obtained
115*5fdb9a35Sdrh ** from sqlite3DbMalloc().  The caller is responsible for freeing
116*5fdb9a35Sdrh ** the space when done.
117*5fdb9a35Sdrh */
sqlite3TableAffinityStr(sqlite3 * db,const Table * pTab)118*5fdb9a35Sdrh char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
119*5fdb9a35Sdrh   char *zColAff;
120*5fdb9a35Sdrh   zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
121*5fdb9a35Sdrh   if( zColAff ){
122*5fdb9a35Sdrh     int i, j;
123*5fdb9a35Sdrh     for(i=j=0; i<pTab->nCol; i++){
124*5fdb9a35Sdrh       if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
125*5fdb9a35Sdrh         zColAff[j++] = pTab->aCol[i].affinity;
126*5fdb9a35Sdrh       }
127*5fdb9a35Sdrh     }
128*5fdb9a35Sdrh     do{
129*5fdb9a35Sdrh       zColAff[j--] = 0;
130*5fdb9a35Sdrh     }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
131*5fdb9a35Sdrh   }
132*5fdb9a35Sdrh   return zColAff;
133*5fdb9a35Sdrh }
134*5fdb9a35Sdrh 
135*5fdb9a35Sdrh /*
13671c770fbSdrh ** Make changes to the evolving bytecode to do affinity transformations
13771c770fbSdrh ** of values that are about to be gathered into a row for table pTab.
13871c770fbSdrh **
13971c770fbSdrh ** For ordinary (legacy, non-strict) tables:
14071c770fbSdrh ** -----------------------------------------
14171c770fbSdrh **
14257bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been
14305883a34Sdrh ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
14457bf4a8eSdrh **
14571c770fbSdrh ** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
14671c770fbSdrh ** which were then optimized out) then this routine becomes a no-op.
14771c770fbSdrh **
14871c770fbSdrh ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
14971c770fbSdrh ** affinities for register iReg and following.  Or if iReg==0,
15057bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should  be
15157bf4a8eSdrh ** an OP_MakeRecord) to the affinity string.
15257bf4a8eSdrh **
153b6e8fd10Sdrh ** A column affinity string has one character per column:
154a37cdde0Sdanielk1977 **
155a37cdde0Sdanielk1977 **    Character      Column affinity
15671c770fbSdrh **    ---------      ---------------
15705883a34Sdrh **    'A'            BLOB
1584583c37cSdrh **    'B'            TEXT
1594583c37cSdrh **    'C'            NUMERIC
1604583c37cSdrh **    'D'            INTEGER
1614583c37cSdrh **    'E'            REAL
16271c770fbSdrh **
16371c770fbSdrh ** For STRICT tables:
16471c770fbSdrh ** ------------------
16571c770fbSdrh **
16671c770fbSdrh ** Generate an appropropriate OP_TypeCheck opcode that will verify the
16771c770fbSdrh ** datatypes against the column definitions in pTab.  If iReg==0, that
16871c770fbSdrh ** means an OP_MakeRecord opcode has already been generated and should be
16971c770fbSdrh ** the last opcode generated.  The new OP_TypeCheck needs to be inserted
17071c770fbSdrh ** before the OP_MakeRecord.  The new OP_TypeCheck should use the same
17171c770fbSdrh ** register set as the OP_MakeRecord.  If iReg>0 then register iReg is
17271c770fbSdrh ** the first of a series of registers that will form the new record.
17371c770fbSdrh ** Apply the type checking to that array of registers.
174a37cdde0Sdanielk1977 */
sqlite3TableAffinity(Vdbe * v,Table * pTab,int iReg)17557bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
176*5fdb9a35Sdrh   int i;
17772532f52Sdrh   char *zColAff;
17872532f52Sdrh   if( pTab->tabFlags & TF_Strict ){
17972532f52Sdrh     if( iReg==0 ){
18072532f52Sdrh       /* Move the previous opcode (which should be OP_MakeRecord) forward
18172532f52Sdrh       ** by one slot and insert a new OP_TypeCheck where the current
18272532f52Sdrh       ** OP_MakeRecord is found */
18372532f52Sdrh       VdbeOp *pPrev;
18472532f52Sdrh       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
185058e9950Sdrh       pPrev = sqlite3VdbeGetLastOp(v);
18671c770fbSdrh       assert( pPrev!=0 );
18771c770fbSdrh       assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
18872532f52Sdrh       pPrev->opcode = OP_TypeCheck;
18972532f52Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
19072532f52Sdrh     }else{
19172532f52Sdrh       /* Insert an isolated OP_Typecheck */
19272532f52Sdrh       sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
19372532f52Sdrh       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
19472532f52Sdrh     }
19572532f52Sdrh     return;
19672532f52Sdrh   }
19772532f52Sdrh   zColAff = pTab->zColAff;
19857bf4a8eSdrh   if( zColAff==0 ){
199*5fdb9a35Sdrh     zColAff = sqlite3TableAffinityStr(0, pTab);
2003d1bfeaaSdanielk1977     if( !zColAff ){
201*5fdb9a35Sdrh       sqlite3OomFault(sqlite3VdbeDb(v));
202a37cdde0Sdanielk1977       return;
2033d1bfeaaSdanielk1977     }
2043d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
2053d1bfeaaSdanielk1977   }
2067301e774Sdrh   assert( zColAff!=0 );
2077301e774Sdrh   i = sqlite3Strlen30NN(zColAff);
20857bf4a8eSdrh   if( i ){
20957bf4a8eSdrh     if( iReg ){
21057bf4a8eSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
21157bf4a8eSdrh     }else{
212058e9950Sdrh       assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
21371c770fbSdrh               || sqlite3VdbeDb(v)->mallocFailed );
21457bf4a8eSdrh       sqlite3VdbeChangeP4(v, -1, zColAff, i);
21557bf4a8eSdrh     }
21657bf4a8eSdrh   }
2173d1bfeaaSdanielk1977 }
2183d1bfeaaSdanielk1977 
2194d88778bSdanielk1977 /*
22048d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
221b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if
22248d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
223b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT.
2244d88778bSdanielk1977 */
readsTable(Parse * p,int iDb,Table * pTab)22505a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){
226595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
2274d88778bSdanielk1977   int i;
22848d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
229595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
230595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
231595a523aSdanielk1977 #endif
232595a523aSdanielk1977 
23305a86c5cSdrh   for(i=1; i<iEnd; i++){
23448d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
235ef0bea92Sdrh     assert( pOp!=0 );
236207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
23748d1178aSdrh       Index *pIndex;
2388deae5adSdrh       Pgno tnum = pOp->p2;
23948d1178aSdrh       if( tnum==pTab->tnum ){
24048d1178aSdrh         return 1;
24148d1178aSdrh       }
24248d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
24348d1178aSdrh         if( tnum==pIndex->tnum ){
24448d1178aSdrh           return 1;
24548d1178aSdrh         }
24648d1178aSdrh       }
24748d1178aSdrh     }
248543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
249595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
2502dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
25166a5167bSdrh       assert( pOp->p4type==P4_VTAB );
25248d1178aSdrh       return 1;
2534d88778bSdanielk1977     }
254543165efSdrh #endif
2554d88778bSdanielk1977   }
2564d88778bSdanielk1977   return 0;
2574d88778bSdanielk1977 }
2583d1bfeaaSdanielk1977 
259dfa15270Sdrh /* This walker callback will compute the union of colFlags flags for all
2607dc76d8bSdrh ** referenced columns in a CHECK constraint or generated column expression.
261dfa15270Sdrh */
exprColumnFlagUnion(Walker * pWalker,Expr * pExpr)262dfa15270Sdrh static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
2637dc76d8bSdrh   if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
2647dc76d8bSdrh     assert( pExpr->iColumn < pWalker->u.pTab->nCol );
265dfa15270Sdrh     pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
266dfa15270Sdrh   }
267dfa15270Sdrh   return WRC_Continue;
268dfa15270Sdrh }
269dfa15270Sdrh 
270c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
271c1431144Sdrh /*
272c1431144Sdrh ** All regular columns for table pTab have been puts into registers
273c1431144Sdrh ** starting with iRegStore.  The registers that correspond to STORED
274dd6cc9b5Sdrh ** or VIRTUAL columns have not yet been initialized.  This routine goes
275dd6cc9b5Sdrh ** back and computes the values for those columns based on the previously
276dd6cc9b5Sdrh ** computed normal columns.
277c1431144Sdrh */
sqlite3ComputeGeneratedColumns(Parse * pParse,int iRegStore,Table * pTab)278dd6cc9b5Sdrh void sqlite3ComputeGeneratedColumns(
279c1431144Sdrh   Parse *pParse,    /* Parsing context */
280c1431144Sdrh   int iRegStore,    /* Register holding the first column */
281c1431144Sdrh   Table *pTab       /* The table */
282c1431144Sdrh ){
283c1431144Sdrh   int i;
284dfa15270Sdrh   Walker w;
285dfa15270Sdrh   Column *pRedo;
286dfa15270Sdrh   int eProgress;
287b5f6243fSdrh   VdbeOp *pOp;
288b5f6243fSdrh 
289b5f6243fSdrh   assert( pTab->tabFlags & TF_HasGenerated );
290b5f6243fSdrh   testcase( pTab->tabFlags & TF_HasVirtual );
291b5f6243fSdrh   testcase( pTab->tabFlags & TF_HasStored );
292b5f6243fSdrh 
293b5f6243fSdrh   /* Before computing generated columns, first go through and make sure
294b5f6243fSdrh   ** that appropriate affinity has been applied to the regular columns
295b5f6243fSdrh   */
296b5f6243fSdrh   sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
297926aac51Sdrh   if( (pTab->tabFlags & TF_HasStored)!=0 ){
298058e9950Sdrh     pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
299926aac51Sdrh     if( pOp->opcode==OP_Affinity ){
300b5f6243fSdrh       /* Change the OP_Affinity argument to '@' (NONE) for all stored
301b5f6243fSdrh       ** columns.  '@' is the no-op affinity and those columns have not
302b5f6243fSdrh       ** yet been computed. */
303b5f6243fSdrh       int ii, jj;
304b5f6243fSdrh       char *zP4 = pOp->p4.z;
305b5f6243fSdrh       assert( zP4!=0 );
306b5f6243fSdrh       assert( pOp->p4type==P4_DYNAMIC );
307b5f6243fSdrh       for(ii=jj=0; zP4[jj]; ii++){
308b5f6243fSdrh         if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
309b5f6243fSdrh           continue;
310b5f6243fSdrh         }
311b5f6243fSdrh         if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
312b5f6243fSdrh           zP4[jj] = SQLITE_AFF_NONE;
313b5f6243fSdrh         }
314b5f6243fSdrh         jj++;
315b5f6243fSdrh       }
316926aac51Sdrh     }else if( pOp->opcode==OP_TypeCheck ){
317926aac51Sdrh       /* If an OP_TypeCheck was generated because the table is STRICT,
318926aac51Sdrh       ** then set the P3 operand to indicate that generated columns should
319926aac51Sdrh       ** not be checked */
320926aac51Sdrh       pOp->p3 = 1;
321926aac51Sdrh     }
322b5f6243fSdrh   }
323dfa15270Sdrh 
324dd6cc9b5Sdrh   /* Because there can be multiple generated columns that refer to one another,
325dd6cc9b5Sdrh   ** this is a two-pass algorithm.  On the first pass, mark all generated
326dd6cc9b5Sdrh   ** columns as "not available".
3279942ef0dSdrh   */
3289942ef0dSdrh   for(i=0; i<pTab->nCol; i++){
329dd6cc9b5Sdrh     if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
330ab0992f0Sdrh       testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
331ab0992f0Sdrh       testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
3329942ef0dSdrh       pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
3339942ef0dSdrh     }
3349942ef0dSdrh   }
335dfa15270Sdrh 
336dfa15270Sdrh   w.u.pTab = pTab;
337dfa15270Sdrh   w.xExprCallback = exprColumnFlagUnion;
338dfa15270Sdrh   w.xSelectCallback = 0;
339dfa15270Sdrh   w.xSelectCallback2 = 0;
340dfa15270Sdrh 
3419942ef0dSdrh   /* On the second pass, compute the value of each NOT-AVAILABLE column.
3429942ef0dSdrh   ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
3439942ef0dSdrh   ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
3449942ef0dSdrh   ** they are needed.
3459942ef0dSdrh   */
346c1431144Sdrh   pParse->iSelfTab = -iRegStore;
347dfa15270Sdrh   do{
348dfa15270Sdrh     eProgress = 0;
349dfa15270Sdrh     pRedo = 0;
350dfa15270Sdrh     for(i=0; i<pTab->nCol; i++){
351dfa15270Sdrh       Column *pCol = pTab->aCol + i;
352dfa15270Sdrh       if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
353dfa15270Sdrh         int x;
354dfa15270Sdrh         pCol->colFlags |= COLFLAG_BUSY;
355dfa15270Sdrh         w.eCode = 0;
35679cf2b71Sdrh         sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
357dfa15270Sdrh         pCol->colFlags &= ~COLFLAG_BUSY;
358dfa15270Sdrh         if( w.eCode & COLFLAG_NOTAVAIL ){
359dfa15270Sdrh           pRedo = pCol;
360dfa15270Sdrh           continue;
361dd6cc9b5Sdrh         }
362dfa15270Sdrh         eProgress = 1;
363dfa15270Sdrh         assert( pCol->colFlags & COLFLAG_GENERATED );
364dfa15270Sdrh         x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
36579cf2b71Sdrh         sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
366dfa15270Sdrh         pCol->colFlags &= ~COLFLAG_NOTAVAIL;
367c1431144Sdrh       }
368dfa15270Sdrh     }
369dfa15270Sdrh   }while( pRedo && eProgress );
370dfa15270Sdrh   if( pRedo ){
371cf9d36d1Sdrh     sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
372c1431144Sdrh   }
373c1431144Sdrh   pParse->iSelfTab = 0;
374c1431144Sdrh }
375c1431144Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
376c1431144Sdrh 
377c1431144Sdrh 
3789d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
3799d9cf229Sdrh /*
3800b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
3810b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
3829ef5e770Sdrh ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
3839ef5e770Sdrh ** table.  (Also return zero when doing a VACUUM since we do not want to
3849ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.)
3859d9cf229Sdrh **
3860b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
3870b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
3880b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
3890b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
3900b9f50d8Sdrh ** AutoincInfo structure is used.
3919d9cf229Sdrh **
392c8abbc11Sdrh ** Four consecutive registers are allocated:
3930b9f50d8Sdrh **
394c8abbc11Sdrh **   (1)  The name of the pTab table.
395c8abbc11Sdrh **   (2)  The maximum ROWID of pTab.
396c8abbc11Sdrh **   (3)  The rowid in sqlite_sequence of pTab
397c8abbc11Sdrh **   (4)  The original value of the max ROWID in pTab, or NULL if none
3980b9f50d8Sdrh **
3990b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
4000b9f50d8Sdrh ** insert routine needs to know about.
4019d9cf229Sdrh */
autoIncBegin(Parse * pParse,int iDb,Table * pTab)4029d9cf229Sdrh static int autoIncBegin(
4039d9cf229Sdrh   Parse *pParse,      /* Parsing context */
4049d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
4059d9cf229Sdrh   Table *pTab         /* The table we are writing to */
4069d9cf229Sdrh ){
4076a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
408186ebd41Sdrh   assert( pParse->db->aDb[iDb].pSchema!=0 );
4099ef5e770Sdrh   if( (pTab->tabFlags & TF_Autoincrement)!=0
4108257aa8dSdrh    && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
4119ef5e770Sdrh   ){
41265a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
4130b9f50d8Sdrh     AutoincInfo *pInfo;
414186ebd41Sdrh     Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
415186ebd41Sdrh 
416186ebd41Sdrh     /* Verify that the sqlite_sequence table exists and is an ordinary
417186ebd41Sdrh     ** rowid table with exactly two columns.
418186ebd41Sdrh     ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
419186ebd41Sdrh     if( pSeqTab==0
420186ebd41Sdrh      || !HasRowid(pSeqTab)
4210003d878Sdrh      || NEVER(IsVirtual(pSeqTab))
422186ebd41Sdrh      || pSeqTab->nCol!=2
423186ebd41Sdrh     ){
424186ebd41Sdrh       pParse->nErr++;
425186ebd41Sdrh       pParse->rc = SQLITE_CORRUPT_SEQUENCE;
426186ebd41Sdrh       return 0;
427186ebd41Sdrh     }
4280b9f50d8Sdrh 
42965a7cd16Sdan     pInfo = pToplevel->pAinc;
4300b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
4310b9f50d8Sdrh     if( pInfo==0 ){
432575fad65Sdrh       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
43321d4f5b5Sdrh       sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
43421d4f5b5Sdrh       testcase( pParse->earlyCleanup );
43521d4f5b5Sdrh       if( pParse->db->mallocFailed ) return 0;
43665a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
43765a7cd16Sdan       pToplevel->pAinc = pInfo;
4380b9f50d8Sdrh       pInfo->pTab = pTab;
4390b9f50d8Sdrh       pInfo->iDb = iDb;
44065a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
44165a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
442c8abbc11Sdrh       pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
4430b9f50d8Sdrh     }
4440b9f50d8Sdrh     memId = pInfo->regCtr;
4459d9cf229Sdrh   }
4469d9cf229Sdrh   return memId;
4479d9cf229Sdrh }
4489d9cf229Sdrh 
4499d9cf229Sdrh /*
4500b9f50d8Sdrh ** This routine generates code that will initialize all of the
4510b9f50d8Sdrh ** register used by the autoincrement tracker.
4520b9f50d8Sdrh */
sqlite3AutoincrementBegin(Parse * pParse)4530b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
4540b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
4550b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
4560b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
4570b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
4580b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
4590b9f50d8Sdrh 
460345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
461345ba7dbSdrh   ** only called from the top-level */
462345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
463c149f18fSdrh   assert( sqlite3IsToplevel(pParse) );
46476d462eeSdan 
4650b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
4660b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
4671b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
4681b32554bSdrh     static const VdbeOpList autoInc[] = {
4691b32554bSdrh       /* 0  */ {OP_Null,    0,  0, 0},
470c8abbc11Sdrh       /* 1  */ {OP_Rewind,  0, 10, 0},
4711b32554bSdrh       /* 2  */ {OP_Column,  0,  0, 0},
472c8abbc11Sdrh       /* 3  */ {OP_Ne,      0,  9, 0},
4731b32554bSdrh       /* 4  */ {OP_Rowid,   0,  0, 0},
4741b32554bSdrh       /* 5  */ {OP_Column,  0,  1, 0},
475c8abbc11Sdrh       /* 6  */ {OP_AddImm,  0,  0, 0},
476c8abbc11Sdrh       /* 7  */ {OP_Copy,    0,  0, 0},
477c8abbc11Sdrh       /* 8  */ {OP_Goto,    0, 11, 0},
478c8abbc11Sdrh       /* 9  */ {OP_Next,    0,  2, 0},
479c8abbc11Sdrh       /* 10 */ {OP_Integer, 0,  0, 0},
480c8abbc11Sdrh       /* 11 */ {OP_Close,   0,  0, 0}
4811b32554bSdrh     };
4821b32554bSdrh     VdbeOp *aOp;
4830b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
4840b9f50d8Sdrh     memId = p->regCtr;
4852120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
4860b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
487076e85f5Sdrh     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
4881b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
4891b32554bSdrh     if( aOp==0 ) break;
4901b32554bSdrh     aOp[0].p2 = memId;
491c8abbc11Sdrh     aOp[0].p3 = memId+2;
4921b32554bSdrh     aOp[2].p3 = memId;
4931b32554bSdrh     aOp[3].p1 = memId-1;
4941b32554bSdrh     aOp[3].p3 = memId;
4951b32554bSdrh     aOp[3].p5 = SQLITE_JUMPIFNULL;
4961b32554bSdrh     aOp[4].p2 = memId+1;
4971b32554bSdrh     aOp[5].p3 = memId;
498c8abbc11Sdrh     aOp[6].p1 = memId;
499c8abbc11Sdrh     aOp[7].p2 = memId+2;
500c8abbc11Sdrh     aOp[7].p1 = memId;
501c8abbc11Sdrh     aOp[10].p2 = memId;
50204ab586bSdrh     if( pParse->nTab==0 ) pParse->nTab = 1;
5030b9f50d8Sdrh   }
5040b9f50d8Sdrh }
5050b9f50d8Sdrh 
5060b9f50d8Sdrh /*
5079d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
5089d9cf229Sdrh **
5091b32554bSdrh ** This routine should be called when the regRowid register holds a
5109d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
5119d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
5121b32554bSdrh ** memory cell is updated.
5139d9cf229Sdrh */
autoIncStep(Parse * pParse,int memId,int regRowid)5146a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
5159d9cf229Sdrh   if( memId>0 ){
5166a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
5179d9cf229Sdrh   }
5189d9cf229Sdrh }
5199d9cf229Sdrh 
5209d9cf229Sdrh /*
5210b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
5220b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
5230b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
5240b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
5250b9f50d8Sdrh ** routine just before the "exit" code.
5269d9cf229Sdrh */
autoIncrementEnd(Parse * pParse)5271b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
5280b9f50d8Sdrh   AutoincInfo *p;
5299d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
5300b9f50d8Sdrh   sqlite3 *db = pParse->db;
5316a288a33Sdrh 
5329d9cf229Sdrh   assert( v );
5330b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
5341b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
5351b32554bSdrh     static const VdbeOpList autoIncEnd[] = {
5361b32554bSdrh       /* 0 */ {OP_NotNull,     0, 2, 0},
5371b32554bSdrh       /* 1 */ {OP_NewRowid,    0, 0, 0},
5381b32554bSdrh       /* 2 */ {OP_MakeRecord,  0, 2, 0},
5391b32554bSdrh       /* 3 */ {OP_Insert,      0, 0, 0},
5401b32554bSdrh       /* 4 */ {OP_Close,       0, 0, 0}
5411b32554bSdrh     };
5421b32554bSdrh     VdbeOp *aOp;
5430b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
5440b9f50d8Sdrh     int iRec;
5450b9f50d8Sdrh     int memId = p->regCtr;
5460b9f50d8Sdrh 
5470b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
5482120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
549c8abbc11Sdrh     sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
550c8abbc11Sdrh     VdbeCoverage(v);
5510b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
5521b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
5531b32554bSdrh     if( aOp==0 ) break;
5541b32554bSdrh     aOp[0].p1 = memId+1;
5551b32554bSdrh     aOp[1].p2 = memId+1;
5561b32554bSdrh     aOp[2].p1 = memId-1;
5571b32554bSdrh     aOp[2].p3 = iRec;
5581b32554bSdrh     aOp[3].p2 = iRec;
5591b32554bSdrh     aOp[3].p3 = memId+1;
5601b32554bSdrh     aOp[3].p5 = OPFLAG_APPEND;
5610b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
5629d9cf229Sdrh   }
5639d9cf229Sdrh }
sqlite3AutoincrementEnd(Parse * pParse)5641b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){
5651b32554bSdrh   if( pParse->pAinc ) autoIncrementEnd(pParse);
5661b32554bSdrh }
5679d9cf229Sdrh #else
5689d9cf229Sdrh /*
5699d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
5709d9cf229Sdrh ** above are all no-ops
5719d9cf229Sdrh */
5729d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
573287fb61cSdanielk1977 # define autoIncStep(A,B,C)
5749d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
5759d9cf229Sdrh 
5769d9cf229Sdrh 
5779d9cf229Sdrh /* Forward declaration */
5789d9cf229Sdrh static int xferOptimization(
5799d9cf229Sdrh   Parse *pParse,        /* Parser context */
5809d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
5819d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5829d9cf229Sdrh   int onError,          /* How to handle constraint errors */
5839d9cf229Sdrh   int iDbDest           /* The database of pDest */
5849d9cf229Sdrh );
5859d9cf229Sdrh 
5863d1bfeaaSdanielk1977 /*
587d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
588cce7d176Sdrh **
589a21f78b9Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
5901ccde15dSdrh **    insert into TABLE (IDLIST) select
591a21f78b9Sdrh **    insert into TABLE (IDLIST) default values
592cce7d176Sdrh **
5931ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
594a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted.
595a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
596a21f78b9Sdrh ** is omitted.
5971ccde15dSdrh **
598a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the
599a21f78b9Sdrh ** first two forms shown above.  A VALUES clause is really just short-hand
600a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else
601a21f78b9Sdrh ** that follows.  If the pSelect parameter is NULL, that means that the
602a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended.
603142e30dfSdrh **
6049d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
605a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes
606e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
607e00ee6ebSdrh ** the "1st template"):
608142e30dfSdrh **
609142e30dfSdrh **         open write cursor to <table> and its indices
610ec95c441Sdrh **         put VALUES clause expressions into registers
611142e30dfSdrh **         write the resulting record into <table>
612142e30dfSdrh **         cleanup
613142e30dfSdrh **
6149d9cf229Sdrh ** The three remaining templates assume the statement is of the form
615142e30dfSdrh **
616142e30dfSdrh **   INSERT INTO <table> SELECT ...
617142e30dfSdrh **
6189d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
6199d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
6209d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
6219d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
6229d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
6239d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
6249d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
625e00ee6ebSdrh ** template.  This is the 2nd template.
6269d9cf229Sdrh **
6279d9cf229Sdrh **         open a write cursor to <table>
6289d9cf229Sdrh **         open read cursor on <table2>
6299d9cf229Sdrh **         transfer all records in <table2> over to <table>
6309d9cf229Sdrh **         close cursors
6319d9cf229Sdrh **         foreach index on <table>
6329d9cf229Sdrh **           open a write cursor on the <table> index
6339d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
6349d9cf229Sdrh **           transfer all records from the read to the write cursors
6359d9cf229Sdrh **           close cursors
6369d9cf229Sdrh **         end foreach
6379d9cf229Sdrh **
638e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
6399d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
6409d9cf229Sdrh ** The generated code follows this template:
641142e30dfSdrh **
642e00ee6ebSdrh **         X <- A
643142e30dfSdrh **         goto B
644142e30dfSdrh **      A: setup for the SELECT
6459d9cf229Sdrh **         loop over the rows in the SELECT
646e00ee6ebSdrh **           load values into registers R..R+n
647e00ee6ebSdrh **           yield X
648142e30dfSdrh **         end loop
649142e30dfSdrh **         cleanup after the SELECT
65081cf13ecSdrh **         end-coroutine X
651e00ee6ebSdrh **      B: open write cursor to <table> and its indices
65281cf13ecSdrh **      C: yield X, at EOF goto D
653e00ee6ebSdrh **         insert the select result into <table> from R..R+n
654e00ee6ebSdrh **         goto C
655142e30dfSdrh **      D: cleanup
656142e30dfSdrh **
657e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
658142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
659142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
66060ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of
661142e30dfSdrh ** the select.  The template is like this:
662142e30dfSdrh **
663e00ee6ebSdrh **         X <- A
664142e30dfSdrh **         goto B
665142e30dfSdrh **      A: setup for the SELECT
666142e30dfSdrh **         loop over the tables in the SELECT
667e00ee6ebSdrh **           load value into register R..R+n
668e00ee6ebSdrh **           yield X
669142e30dfSdrh **         end loop
670142e30dfSdrh **         cleanup after the SELECT
67181cf13ecSdrh **         end co-routine R
672e00ee6ebSdrh **      B: open temp table
67381cf13ecSdrh **      L: yield X, at EOF goto M
674e00ee6ebSdrh **         insert row from R..R+n into temp table
675e00ee6ebSdrh **         goto L
676e00ee6ebSdrh **      M: open write cursor to <table> and its indices
677e00ee6ebSdrh **         rewind temp table
678e00ee6ebSdrh **      C: loop over rows of intermediate table
679142e30dfSdrh **           transfer values form intermediate table into <table>
680e00ee6ebSdrh **         end loop
681e00ee6ebSdrh **      D: cleanup
682cce7d176Sdrh */
sqlite3Insert(Parse * pParse,SrcList * pTabList,Select * pSelect,IdList * pColumn,int onError,Upsert * pUpsert)6834adee20fSdanielk1977 void sqlite3Insert(
684cce7d176Sdrh   Parse *pParse,        /* Parser context */
685113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
6865974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
687f5f1915dSdrh   IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */
6882c2e844aSdrh   int onError,          /* How to handle constraint errors */
68946d2e5c3Sdrh   Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
690cce7d176Sdrh ){
6916a288a33Sdrh   sqlite3 *db;          /* The main database structure */
6926a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
69360ffc807Sdrh   int i, j;             /* Loop counters */
6945974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
6955974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
696967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
6976a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
69826198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
69926198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
700d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
7010ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
702cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
703e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
704e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
7052eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
7066a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
70705a86c5cSdrh   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
70805a86c5cSdrh   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
70905a86c5cSdrh   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
710a21f78b9Sdrh   u8 bIdListInOrder;    /* True if IDLIST is in table order */
71175593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
712c27ea2aeSdrh   int iRegStore;        /* Register in which to store next column */
713cce7d176Sdrh 
7146a288a33Sdrh   /* Register allocations */
7151bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
7166a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
7176a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
7186a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
7196a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
7206a288a33Sdrh   int regData;          /* register holding first column to insert */
721aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
7226a288a33Sdrh 
723798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
724798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
7252f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
7262f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
727798da52cSdrh #endif
728c3f9bad2Sdanielk1977 
72917435752Sdrh   db = pParse->db;
7300c7d3d39Sdrh   assert( db->pParse==pParse );
7310c7d3d39Sdrh   if( pParse->nErr ){
7326f7adc8aSdrh     goto insert_cleanup;
7336f7adc8aSdrh   }
7340c7d3d39Sdrh   assert( db->mallocFailed==0 );
7354c883487Sdrh   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
736daffd0e5Sdrh 
73775593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
738a21f78b9Sdrh   ** single row (the common case) then keep that one row of values
739a21f78b9Sdrh   ** and discard the other (unused) parts of the pSelect object
74075593d96Sdrh   */
74175593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
74275593d96Sdrh     pList = pSelect->pEList;
74375593d96Sdrh     pSelect->pEList = 0;
74475593d96Sdrh     sqlite3SelectDelete(db, pSelect);
74575593d96Sdrh     pSelect = 0;
74675593d96Sdrh   }
74775593d96Sdrh 
7481ccde15dSdrh   /* Locate the table into which we will be inserting new information.
7491ccde15dSdrh   */
750113088ecSdrh   assert( pTabList->nSrc==1 );
7514adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
752c3f9bad2Sdanielk1977   if( pTab==0 ){
753c3f9bad2Sdanielk1977     goto insert_cleanup;
754c3f9bad2Sdanielk1977   }
755da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
756da184236Sdanielk1977   assert( iDb<db->nDb );
757a0daa751Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
758a0daa751Sdrh                        db->aDb[iDb].zDbSName) ){
7591962bda7Sdrh     goto insert_cleanup;
7601962bda7Sdrh   }
761ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
762c3f9bad2Sdanielk1977 
763b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
764b7f9164eSdrh   ** inserted into is a view
765b7f9164eSdrh   */
766b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
7672f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
768f38524d2Sdrh   isView = IsView(pTab);
769b7f9164eSdrh #else
7702f886d1dSdanielk1977 # define pTrigger 0
7712f886d1dSdanielk1977 # define tmask 0
772b7f9164eSdrh # define isView 0
773b7f9164eSdrh #endif
774b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
775b7f9164eSdrh # undef isView
776b7f9164eSdrh # define isView 0
777b7f9164eSdrh #endif
7782f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
779b7f9164eSdrh 
7802a7dcbfbSdrh #if TREETRACE_ENABLED
7812a7dcbfbSdrh   if( sqlite3TreeTrace & 0x10000 ){
7822a7dcbfbSdrh     sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
783c2d0df95Sdrh     sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
7842a7dcbfbSdrh                           onError, pUpsert, pTrigger);
7852a7dcbfbSdrh   }
7862a7dcbfbSdrh #endif
7872a7dcbfbSdrh 
788f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
789d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
790f573c99bSdrh   */
791b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
792f573c99bSdrh     goto insert_cleanup;
793f573c99bSdrh   }
794f573c99bSdrh 
795d82b5021Sdrh   /* Cannot insert into a read-only table.
796595a523aSdanielk1977   */
797595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
798595a523aSdanielk1977     goto insert_cleanup;
799595a523aSdanielk1977   }
800595a523aSdanielk1977 
8011ccde15dSdrh   /* Allocate a VDBE
8021ccde15dSdrh   */
8034adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
8045974a30fSdrh   if( v==0 ) goto insert_cleanup;
8054794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
8062f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
8071ccde15dSdrh 
8089d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
8099d9cf229Sdrh   /* If the statement is of the form
8109d9cf229Sdrh   **
8119d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
8129d9cf229Sdrh   **
8139d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
8149d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
815e00ee6ebSdrh   **
816e00ee6ebSdrh   ** This is the 2nd template.
8179d9cf229Sdrh   */
818935c3722Sdrh   if( pColumn==0
819935c3722Sdrh    && pSelect!=0
820935c3722Sdrh    && pTrigger==0
821935c3722Sdrh    && xferOptimization(pParse, pTab, pSelect, onError, iDb)
822935c3722Sdrh   ){
8232f886d1dSdanielk1977     assert( !pTrigger );
8249d9cf229Sdrh     assert( pList==0 );
8250b9f50d8Sdrh     goto insert_end;
8269d9cf229Sdrh   }
8279d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
8289d9cf229Sdrh 
8292958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
8306a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
8312958a4e6Sdrh   */
8326a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
8332958a4e6Sdrh 
834f5f1915dSdrh   /* Allocate a block registers to hold the rowid and the values
835f5f1915dSdrh   ** for all columns of the new row.
8361ccde15dSdrh   */
83705a86c5cSdrh   regRowid = regIns = pParse->nMem+1;
83805a86c5cSdrh   pParse->nMem += pTab->nCol + 1;
839034ca14fSdanielk1977   if( IsVirtual(pTab) ){
84005a86c5cSdrh     regRowid++;
84105a86c5cSdrh     pParse->nMem++;
842034ca14fSdanielk1977   }
84305a86c5cSdrh   regData = regRowid+1;
8441ccde15dSdrh 
8451ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
8461ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
8471ccde15dSdrh   ** remember the column indices.
848c8392586Sdrh   **
849c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
850d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
851d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
852c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
853d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
854f5f1915dSdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)  After this
855f5f1915dSdrh   ** loop, if ipkColumn==(-1), that means that integer primary key
856f5f1915dSdrh   ** is unspecified, and hence the table is either WITHOUT ROWID or
857f5f1915dSdrh   ** it will automatically generated an integer primary key.
858f5f1915dSdrh   **
859f5f1915dSdrh   ** bIdListInOrder is true if the columns in IDLIST are in storage
860f5f1915dSdrh   ** order.  This enables an optimization that avoids shuffling the
861f5f1915dSdrh   ** columns into storage order.  False negatives are harmless,
862f5f1915dSdrh   ** but false positives will cause database corruption.
8631ccde15dSdrh   */
864d4cd292cSdrh   bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
865967e8b73Sdrh   if( pColumn ){
866a99e3254Sdrh     assert( pColumn->eU4!=EU4_EXPR );
867a99e3254Sdrh     pColumn->eU4 = EU4_IDX;
868967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
869a99e3254Sdrh       pColumn->a[i].u4.idx = -1;
870cce7d176Sdrh     }
871967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
872cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
873cf9d36d1Sdrh         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
874a99e3254Sdrh           pColumn->a[i].u4.idx = j;
87505a86c5cSdrh           if( i!=j ) bIdListInOrder = 0;
8764a32431cSdrh           if( j==pTab->iPKey ){
877d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
8784a32431cSdrh           }
8797e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
8807e508f1eSdrh           if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
8817e508f1eSdrh             sqlite3ErrorMsg(pParse,
8827e508f1eSdrh                "cannot INSERT into generated column \"%s\"",
883cf9d36d1Sdrh                pTab->aCol[j].zCnName);
8847e508f1eSdrh             goto insert_cleanup;
8857e508f1eSdrh           }
8867e508f1eSdrh #endif
887cce7d176Sdrh           break;
888cce7d176Sdrh         }
889cce7d176Sdrh       }
890cce7d176Sdrh       if( j>=pTab->nCol ){
891ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
892d82b5021Sdrh           ipkColumn = i;
893e48ae715Sdrh           bIdListInOrder = 0;
894a0217ba7Sdrh         }else{
8954adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
896a979993bSdrh               pTabList->a, pColumn->a[i].zName);
8971db95106Sdan           pParse->checkSchema = 1;
898cce7d176Sdrh           goto insert_cleanup;
899cce7d176Sdrh         }
900cce7d176Sdrh       }
901cce7d176Sdrh     }
902a0217ba7Sdrh   }
9031ccde15dSdrh 
904cce7d176Sdrh   /* Figure out how many columns of data are supplied.  If the data
905cce7d176Sdrh   ** is coming from a SELECT statement, then generate a co-routine that
906cce7d176Sdrh   ** produces a single row of the SELECT on each invocation.  The
907cce7d176Sdrh   ** co-routine is the common header to the 3rd and 4th templates.
908cce7d176Sdrh   */
9095f085269Sdrh   if( pSelect ){
910a21f78b9Sdrh     /* Data is coming from a SELECT or from a multi-row VALUES clause.
911a21f78b9Sdrh     ** Generate a co-routine to run the SELECT. */
91205a86c5cSdrh     int regYield;       /* Register holding co-routine entry-point */
91305a86c5cSdrh     int addrTop;        /* Top of the co-routine */
91405a86c5cSdrh     int rc;             /* Result code */
915cce7d176Sdrh 
91605a86c5cSdrh     regYield = ++pParse->nMem;
91705a86c5cSdrh     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
91805a86c5cSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
91905a86c5cSdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
92005a86c5cSdrh     dest.iSdst = bIdListInOrder ? regData : 0;
92105a86c5cSdrh     dest.nSdst = pTab->nCol;
92205a86c5cSdrh     rc = sqlite3Select(pParse, pSelect, &dest);
9232b596da8Sdrh     regFromSelect = dest.iSdst;
9240c7d3d39Sdrh     assert( db->pParse==pParse );
9250c7d3d39Sdrh     if( rc || pParse->nErr ) goto insert_cleanup;
9260c7d3d39Sdrh     assert( db->mallocFailed==0 );
9272fade2f7Sdrh     sqlite3VdbeEndCoroutine(v, regYield);
92805a86c5cSdrh     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
929cce7d176Sdrh     assert( pSelect->pEList );
930cce7d176Sdrh     nColumn = pSelect->pEList->nExpr;
931cce7d176Sdrh 
932cce7d176Sdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
933cce7d176Sdrh     ** should be written into a temporary table (template 4).  Set to
934cce7d176Sdrh     ** FALSE if each output row of the SELECT can be written directly into
935cce7d176Sdrh     ** the destination table (template 3).
936cce7d176Sdrh     **
937cce7d176Sdrh     ** A temp table must be used if the table being updated is also one
938cce7d176Sdrh     ** of the tables being read by the SELECT statement.  Also use a
939cce7d176Sdrh     ** temp table in the case of row triggers.
940cce7d176Sdrh     */
94105a86c5cSdrh     if( pTrigger || readsTable(pParse, iDb, pTab) ){
942cce7d176Sdrh       useTempTable = 1;
943cce7d176Sdrh     }
944cce7d176Sdrh 
945cce7d176Sdrh     if( useTempTable ){
946cce7d176Sdrh       /* Invoke the coroutine to extract information from the SELECT
947cce7d176Sdrh       ** and add it to a transient table srcTab.  The code generated
948cce7d176Sdrh       ** here is from the 4th template:
949cce7d176Sdrh       **
950cce7d176Sdrh       **      B: open temp table
95181cf13ecSdrh       **      L: yield X, goto M at EOF
952cce7d176Sdrh       **         insert row from R..R+n into temp table
953cce7d176Sdrh       **         goto L
954cce7d176Sdrh       **      M: ...
955cce7d176Sdrh       */
956cce7d176Sdrh       int regRec;          /* Register to hold packed record */
957cce7d176Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
95806280ee5Sdrh       int addrL;           /* Label "L" */
959cce7d176Sdrh 
960cce7d176Sdrh       srcTab = pParse->nTab++;
961cce7d176Sdrh       regRec = sqlite3GetTempReg(pParse);
962cce7d176Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
963cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
96406280ee5Sdrh       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
965cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
966cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
967cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
968076e85f5Sdrh       sqlite3VdbeGoto(v, addrL);
96906280ee5Sdrh       sqlite3VdbeJumpHere(v, addrL);
970cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
971cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
972cce7d176Sdrh     }
973cce7d176Sdrh   }else{
974a21f78b9Sdrh     /* This is the case if the data for the INSERT is coming from a
975a21f78b9Sdrh     ** single-row VALUES clause
976cce7d176Sdrh     */
977cce7d176Sdrh     NameContext sNC;
978cce7d176Sdrh     memset(&sNC, 0, sizeof(sNC));
979cce7d176Sdrh     sNC.pParse = pParse;
980cce7d176Sdrh     srcTab = -1;
981cce7d176Sdrh     assert( useTempTable==0 );
982fea870beSdrh     if( pList ){
983fea870beSdrh       nColumn = pList->nExpr;
984fea870beSdrh       if( sqlite3ResolveExprListNames(&sNC, pList) ){
985cce7d176Sdrh         goto insert_cleanup;
986cce7d176Sdrh       }
987fea870beSdrh     }else{
988fea870beSdrh       nColumn = 0;
989cce7d176Sdrh     }
990cce7d176Sdrh   }
991cce7d176Sdrh 
992aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
993d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
994d82b5021Sdrh   ** column index in the original table definition.
9954a32431cSdrh   */
996147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
997d82b5021Sdrh     ipkColumn = pTab->iPKey;
998427b96aeSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
9996ab61d70Sdrh     if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1000427b96aeSdrh       testcase( pTab->tabFlags & TF_HasVirtual );
10016ab61d70Sdrh       testcase( pTab->tabFlags & TF_HasStored );
1002427b96aeSdrh       for(i=ipkColumn-1; i>=0; i--){
1003427b96aeSdrh         if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1004427b96aeSdrh           testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
10056ab61d70Sdrh           testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1006427b96aeSdrh           ipkColumn--;
1007427b96aeSdrh         }
1008427b96aeSdrh       }
1009427b96aeSdrh     }
1010427b96aeSdrh #endif
10114a32431cSdrh 
1012cce7d176Sdrh     /* Make sure the number of columns in the source data matches the number
1013cce7d176Sdrh     ** of columns to be inserted into the table.
1014cce7d176Sdrh     */
10156f6e60ddSdrh     assert( TF_HasHidden==COLFLAG_HIDDEN );
10166f6e60ddSdrh     assert( TF_HasGenerated==COLFLAG_GENERATED );
10176f6e60ddSdrh     assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
10186f6e60ddSdrh     if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
1019cce7d176Sdrh       for(i=0; i<pTab->nCol; i++){
10207e508f1eSdrh         if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1021cce7d176Sdrh       }
1022c7e93f58Sdrh     }
1023c7e93f58Sdrh     if( nColumn!=(pTab->nCol-nHidden) ){
1024cce7d176Sdrh       sqlite3ErrorMsg(pParse,
1025cce7d176Sdrh          "table %S has %d columns but %d values were supplied",
1026a979993bSdrh          pTabList->a, pTab->nCol-nHidden, nColumn);
1027cce7d176Sdrh      goto insert_cleanup;
1028cce7d176Sdrh     }
1029c7e93f58Sdrh   }
1030cce7d176Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
1031cce7d176Sdrh     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1032cce7d176Sdrh     goto insert_cleanup;
1033cce7d176Sdrh   }
1034cce7d176Sdrh 
1035c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
10361ccde15dSdrh   */
103779636913Sdrh   if( (db->flags & SQLITE_CountRows)!=0
103879636913Sdrh    && !pParse->nested
103979636913Sdrh    && !pParse->pTriggerTab
1040d086aa0aSdrh    && !pParse->bReturning
104179636913Sdrh   ){
10426a288a33Sdrh     regRowCount = ++pParse->nMem;
10436a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1044c3f9bad2Sdanielk1977   }
1045c3f9bad2Sdanielk1977 
1046e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
1047e448dc4aSdanielk1977   if( !isView ){
1048aa9b8963Sdrh     int nIdx;
1049fd261ec6Sdan     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
105026198bb4Sdrh                                       &iDataCur, &iIdxCur);
1051a7c3b93fSdrh     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1052aa9b8963Sdrh     if( aRegIdx==0 ){
1053aa9b8963Sdrh       goto insert_cleanup;
1054aa9b8963Sdrh     }
10552c4dfc30Sdrh     for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
10562c4dfc30Sdrh       assert( pIdx );
1057aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
10582c4dfc30Sdrh       pParse->nMem += pIdx->nColumn;
1059aa9b8963Sdrh     }
1060a7c3b93fSdrh     aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */
1061feeb1394Sdrh   }
1062788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT
10630b30a116Sdrh   if( pUpsert ){
106420b86324Sdrh     Upsert *pNx;
1065b042d921Sdrh     if( IsVirtual(pTab) ){
1066b042d921Sdrh       sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1067b042d921Sdrh               pTab->zName);
1068b042d921Sdrh       goto insert_cleanup;
1069b042d921Sdrh     }
1070f38524d2Sdrh     if( IsView(pTab) ){
1071c6b24ab1Sdrh       sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1072c6b24ab1Sdrh       goto insert_cleanup;
1073c6b24ab1Sdrh     }
10749105fd51Sdan     if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
10759105fd51Sdan       goto insert_cleanup;
10769105fd51Sdan     }
1077788d55aaSdrh     pTabList->a[0].iCursor = iDataCur;
107820b86324Sdrh     pNx = pUpsert;
107920b86324Sdrh     do{
108020b86324Sdrh       pNx->pUpsertSrc = pTabList;
108120b86324Sdrh       pNx->regData = regData;
108220b86324Sdrh       pNx->iDataCur = iDataCur;
108320b86324Sdrh       pNx->iIdxCur = iIdxCur;
108420b86324Sdrh       if( pNx->pUpsertTarget ){
108593eb9064Sdan         if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx) ){
108693eb9064Sdan           goto insert_cleanup;
108793eb9064Sdan         }
1088788d55aaSdrh       }
108920b86324Sdrh       pNx = pNx->pNextUpsert;
109020b86324Sdrh     }while( pNx!=0 );
10910b30a116Sdrh   }
1092788d55aaSdrh #endif
1093788d55aaSdrh 
1094feeb1394Sdrh 
1095e00ee6ebSdrh   /* This is the top of the main insertion loop */
1096142e30dfSdrh   if( useTempTable ){
1097e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
1098e00ee6ebSdrh     ** following pseudocode (template 4):
1099e00ee6ebSdrh     **
110081cf13ecSdrh     **         rewind temp table, if empty goto D
1101e00ee6ebSdrh     **      C: loop over rows of intermediate table
1102e00ee6ebSdrh     **           transfer values form intermediate table into <table>
1103e00ee6ebSdrh     **         end loop
1104e00ee6ebSdrh     **      D: ...
1105e00ee6ebSdrh     */
1106688852abSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1107e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
1108142e30dfSdrh   }else if( pSelect ){
1109e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
1110e00ee6ebSdrh     ** following pseudocode (template 3):
1111e00ee6ebSdrh     **
111281cf13ecSdrh     **      C: yield X, at EOF goto D
1113e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
1114e00ee6ebSdrh     **         goto C
1115e00ee6ebSdrh     **      D: ...
1116e00ee6ebSdrh     */
11173aef2fb1Sdrh     sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
111881cf13ecSdrh     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1119688852abSdrh     VdbeCoverage(v);
1120f5f1915dSdrh     if( ipkColumn>=0 ){
1121f5f1915dSdrh       /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1122f5f1915dSdrh       ** SELECT, go ahead and copy the value into the rowid slot now, so that
1123f5f1915dSdrh       ** the value does not get overwritten by a NULL at tag-20191021-002. */
1124f5f1915dSdrh       sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1125bed8690fSdrh     }
1126f5f1915dSdrh   }
1127f5f1915dSdrh 
1128f5f1915dSdrh   /* Compute data for ordinary columns of the new entry.  Values
1129f5f1915dSdrh   ** are written in storage order into registers starting with regData.
1130f5f1915dSdrh   ** Only ordinary columns are computed in this loop. The rowid
1131f5f1915dSdrh   ** (if there is one) is computed later and generated columns are
1132f5f1915dSdrh   ** computed after the rowid since they might depend on the value
1133f5f1915dSdrh   ** of the rowid.
1134f5f1915dSdrh   */
1135f5f1915dSdrh   nHidden = 0;
1136f5f1915dSdrh   iRegStore = regData;  assert( regData==regRowid+1 );
1137f5f1915dSdrh   for(i=0; i<pTab->nCol; i++, iRegStore++){
1138f5f1915dSdrh     int k;
1139f5f1915dSdrh     u32 colFlags;
1140f5f1915dSdrh     assert( i>=nHidden );
1141f5f1915dSdrh     if( i==pTab->iPKey ){
1142f5f1915dSdrh       /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1143f5f1915dSdrh       ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1144f5f1915dSdrh       ** using excess space.  The file format definition requires this extra
1145f5f1915dSdrh       ** NULL - we cannot optimize further by skipping the column completely */
1146f5f1915dSdrh       sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1147f5f1915dSdrh       continue;
1148f5f1915dSdrh     }
1149f5f1915dSdrh     if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1150f5f1915dSdrh       nHidden++;
1151f5f1915dSdrh       if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1152f5f1915dSdrh         /* Virtual columns do not participate in OP_MakeRecord.  So back up
1153f5f1915dSdrh         ** iRegStore by one slot to compensate for the iRegStore++ in the
1154f5f1915dSdrh         ** outer for() loop */
1155f5f1915dSdrh         iRegStore--;
1156f5f1915dSdrh         continue;
1157f5f1915dSdrh       }else if( (colFlags & COLFLAG_STORED)!=0 ){
1158f5f1915dSdrh         /* Stored columns are computed later.  But if there are BEFORE
1159f5f1915dSdrh         ** triggers, the slots used for stored columns will be OP_Copy-ed
1160f5f1915dSdrh         ** to a second block of registers, so the register needs to be
1161f5f1915dSdrh         ** initialized to NULL to avoid an uninitialized register read */
1162f5f1915dSdrh         if( tmask & TRIGGER_BEFORE ){
1163f5f1915dSdrh           sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1164f5f1915dSdrh         }
1165f5f1915dSdrh         continue;
1166f5f1915dSdrh       }else if( pColumn==0 ){
1167f5f1915dSdrh         /* Hidden columns that are not explicitly named in the INSERT
1168f5f1915dSdrh         ** get there default value */
116979cf2b71Sdrh         sqlite3ExprCodeFactorable(pParse,
117079cf2b71Sdrh             sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
117179cf2b71Sdrh             iRegStore);
1172f5f1915dSdrh         continue;
1173f5f1915dSdrh       }
1174f5f1915dSdrh     }
1175f5f1915dSdrh     if( pColumn ){
1176a99e3254Sdrh       assert( pColumn->eU4==EU4_IDX );
1177a99e3254Sdrh       for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
1178f5f1915dSdrh       if( j>=pColumn->nId ){
1179f5f1915dSdrh         /* A column not named in the insert column list gets its
1180f5f1915dSdrh         ** default value */
118179cf2b71Sdrh         sqlite3ExprCodeFactorable(pParse,
118279cf2b71Sdrh             sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
118379cf2b71Sdrh             iRegStore);
1184f5f1915dSdrh         continue;
1185f5f1915dSdrh       }
1186f5f1915dSdrh       k = j;
1187f5f1915dSdrh     }else if( nColumn==0 ){
1188f5f1915dSdrh       /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
118979cf2b71Sdrh       sqlite3ExprCodeFactorable(pParse,
119079cf2b71Sdrh           sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
119179cf2b71Sdrh           iRegStore);
1192f5f1915dSdrh       continue;
1193f5f1915dSdrh     }else{
1194f5f1915dSdrh       k = i - nHidden;
1195f5f1915dSdrh     }
1196f5f1915dSdrh 
1197f5f1915dSdrh     if( useTempTable ){
1198f5f1915dSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1199f5f1915dSdrh     }else if( pSelect ){
1200f5f1915dSdrh       if( regFromSelect!=regData ){
1201f5f1915dSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1202f5f1915dSdrh       }
1203f5f1915dSdrh     }else{
12042d2e528eSdrh       Expr *pX = pList->a[k].pExpr;
12052d2e528eSdrh       int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
12062d2e528eSdrh       if( y!=iRegStore ){
12072d2e528eSdrh         sqlite3VdbeAddOp2(v,
12082d2e528eSdrh           ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
12092d2e528eSdrh       }
1210f5f1915dSdrh     }
1211f5f1915dSdrh   }
1212f5f1915dSdrh 
12131ccde15dSdrh 
12145cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
121570ce3f0cSdrh   */
1216ec4ccdbcSdrh   endOfLoop = sqlite3VdbeMakeLabel(pParse);
12172f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
121876d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1219c3f9bad2Sdanielk1977 
122070ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
122170ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
122270ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
122370ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
122470ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
122570ce3f0cSdrh     */
1226d82b5021Sdrh     if( ipkColumn<0 ){
122776d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
122870ce3f0cSdrh     }else{
1229728e0f91Sdrh       int addr1;
1230ec95c441Sdrh       assert( !withoutRowid );
12317fe45908Sdrh       if( useTempTable ){
1232d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
12337fe45908Sdrh       }else{
1234d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
1235d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
12367fe45908Sdrh       }
1237728e0f91Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
123876d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1239728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
1240688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
124170ce3f0cSdrh     }
124270ce3f0cSdrh 
1243f5f1915dSdrh     /* Copy the new data already generated. */
1244f5f1915dSdrh     assert( pTab->nNVCol>0 );
1245f5f1915dSdrh     sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1246f5f1915dSdrh 
1247f5f1915dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1248f5f1915dSdrh     /* Compute the new value for generated columns after all other
1249f5f1915dSdrh     ** columns have already been computed.  This must be done after
1250f5f1915dSdrh     ** computing the ROWID in case one of the generated columns
1251f5f1915dSdrh     ** refers to the ROWID. */
1252427b96aeSdrh     if( pTab->tabFlags & TF_HasGenerated ){
1253427b96aeSdrh       testcase( pTab->tabFlags & TF_HasVirtual );
1254427b96aeSdrh       testcase( pTab->tabFlags & TF_HasStored );
1255f5f1915dSdrh       sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1256c3f9bad2Sdanielk1977     }
1257f5f1915dSdrh #endif
1258a37cdde0Sdanielk1977 
1259a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1260a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
1261a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
1262a37cdde0Sdanielk1977     ** table column affinities.
1263a37cdde0Sdanielk1977     */
1264a37cdde0Sdanielk1977     if( !isView ){
126557bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regCols+1);
1266a37cdde0Sdanielk1977     }
1267c3f9bad2Sdanielk1977 
12685cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
1269165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
127094d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1271165921a7Sdan 
127276d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
127370ce3f0cSdrh   }
1274c3f9bad2Sdanielk1977 
12755cf590c1Sdrh   if( !isView ){
12764cbdda9eSdrh     if( IsVirtual(pTab) ){
12774cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
12786a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
12794cbdda9eSdrh     }
1280d82b5021Sdrh     if( ipkColumn>=0 ){
1281f5f1915dSdrh       /* Compute the new rowid */
1282142e30dfSdrh       if( useTempTable ){
1283d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1284142e30dfSdrh       }else if( pSelect ){
1285f5f1915dSdrh         /* Rowid already initialized at tag-20191021-001 */
12864a32431cSdrh       }else{
128704fcef00Sdrh         Expr *pIpk = pList->a[ipkColumn].pExpr;
128804fcef00Sdrh         if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
128904fcef00Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1290e4d90813Sdrh           appendFlag = 1;
129104fcef00Sdrh         }else{
129204fcef00Sdrh           sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1293e4d90813Sdrh         }
129427a32783Sdrh       }
1295f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1296e1e68f49Sdrh       ** to generate a unique primary key value.
1297e1e68f49Sdrh       */
1298e4d90813Sdrh       if( !appendFlag ){
1299728e0f91Sdrh         int addr1;
1300bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
1301728e0f91Sdrh           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
130226198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1303728e0f91Sdrh           sqlite3VdbeJumpHere(v, addr1);
1304bb50e7adSdanielk1977         }else{
1305728e0f91Sdrh           addr1 = sqlite3VdbeCurrentAddr(v);
1306728e0f91Sdrh           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1307bb50e7adSdanielk1977         }
1308688852abSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1309e4d90813Sdrh       }
1310ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
13116a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
13124a32431cSdrh     }else{
131326198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1314e4d90813Sdrh       appendFlag = 1;
13154a32431cSdrh     }
13166a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
13174a32431cSdrh 
1318c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1319dd6cc9b5Sdrh     /* Compute the new value for generated columns after all other
1320f5f1915dSdrh     ** columns have already been computed.  This must be done after
1321f5f1915dSdrh     ** computing the ROWID in case one of the generated columns
1322b5f6243fSdrh     ** is derived from the INTEGER PRIMARY KEY. */
1323427b96aeSdrh     if( pTab->tabFlags & TF_HasGenerated ){
1324dd6cc9b5Sdrh       sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
13254a32431cSdrh     }
1326c1431144Sdrh #endif
13271ccde15dSdrh 
13280ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
13290ca3e24bSdrh     ** do the insertion.
13304a32431cSdrh     */
13314cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
13324cbdda9eSdrh     if( IsVirtual(pTab) ){
1333595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
13344f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1335595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1336b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1337e0af83acSdan       sqlite3MayAbort(pParse);
13384cbdda9eSdrh     }else
13394cbdda9eSdrh #endif
13404cbdda9eSdrh     {
134111fbee24Sdan       int isReplace = 0;/* Set to true if constraints may cause a replace */
13423b908d41Sdan       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
1343f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1344788d55aaSdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
134504adf416Sdrh       );
1346509a6303Sdrh       if( db->flags & SQLITE_ForeignKeys ){
13478ff2d956Sdan         sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1348509a6303Sdrh       }
13493b908d41Sdan 
13503b908d41Sdan       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
13513b908d41Sdan       ** constraints or (b) there are no triggers and this table is not a
13523b908d41Sdan       ** parent table in a foreign key constraint. It is safe to set the
13533b908d41Sdan       ** flag in the second case as if any REPLACE constraint is hit, an
13543b908d41Sdan       ** OP_Delete or OP_IdxDelete instruction will be executed on each
13553b908d41Sdan       ** cursor that is disturbed. And these instructions both clear the
13563b908d41Sdan       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
13573b908d41Sdan       ** functionality.  */
135806baba54Sdrh       bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
135926198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
13603b908d41Sdan           regIns, aRegIdx, 0, appendFlag, bUseSeek
13613b908d41Sdan       );
13625cf590c1Sdrh     }
13636e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
13642a1aeaa3Sdan   }else if( pParse->bReturning ){
13652a1aeaa3Sdan     /* If there is a RETURNING clause, populate the rowid register with
13662a1aeaa3Sdan     ** constant value -1, in case one or more of the returned expressions
13672a1aeaa3Sdan     ** refer to the "rowid" of the view.  */
13682a1aeaa3Sdan     sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
13696e5020e8Sdrh #endif
13704cbdda9eSdrh   }
13711bee3d7bSdrh 
1372feeb1394Sdrh   /* Update the count of rows that are inserted
13731bee3d7bSdrh   */
137479636913Sdrh   if( regRowCount ){
13756a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
13761bee3d7bSdrh   }
1377c3f9bad2Sdanielk1977 
13782f886d1dSdanielk1977   if( pTrigger ){
1379c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1380165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
138194d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1382c3f9bad2Sdanielk1977   }
13831bee3d7bSdrh 
1384e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1385e00ee6ebSdrh   ** is a SELECT statement.
13861ccde15dSdrh   */
13874adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1388142e30dfSdrh   if( useTempTable ){
1389688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1390e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
13912eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1392142e30dfSdrh   }else if( pSelect ){
1393076e85f5Sdrh     sqlite3VdbeGoto(v, addrCont);
1394d9670abbSdrh #ifdef SQLITE_DEBUG
1395d9670abbSdrh     /* If we are jumping back to an OP_Yield that is preceded by an
1396d9670abbSdrh     ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1397d9670abbSdrh     ** OP_ReleaseReg will be included in the loop. */
1398d9670abbSdrh     if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1399d9670abbSdrh       assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1400d9670abbSdrh       sqlite3VdbeChangeP5(v, 1);
1401d9670abbSdrh     }
1402d9670abbSdrh #endif
1403e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
14046b56344dSdrh   }
1405c3f9bad2Sdanielk1977 
1406d6665c51Smistachkin #ifndef SQLITE_OMIT_XFER_OPT
14070b9f50d8Sdrh insert_end:
1408d6665c51Smistachkin #endif /* SQLITE_OMIT_XFER_OPT */
1409f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
14100b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
14110b9f50d8Sdrh   ** autoincrement tables.
14122958a4e6Sdrh   */
1413165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
14140b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
14150b9f50d8Sdrh   }
14162958a4e6Sdrh 
14171bee3d7bSdrh   /*
1418e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1419e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1420e7de6f25Sdanielk1977   ** invoke the callback function.
14211bee3d7bSdrh   */
142279636913Sdrh   if( regRowCount ){
14233b26b2b5Sdrh     sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
14241bee3d7bSdrh   }
1425cce7d176Sdrh 
1426cce7d176Sdrh insert_cleanup:
1427633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1428633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
142946d2e5c3Sdrh   sqlite3UpsertDelete(db, pUpsert);
1430633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1431633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
143241ce47c4Sdrh   if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
1433cce7d176Sdrh }
14349cfcf5d4Sdrh 
143575cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
143660ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
143775cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
143875cbd984Sdan #ifdef isView
143975cbd984Sdan  #undef isView
144075cbd984Sdan #endif
144175cbd984Sdan #ifdef pTrigger
144275cbd984Sdan  #undef pTrigger
144375cbd984Sdan #endif
144475cbd984Sdan #ifdef tmask
144575cbd984Sdan  #undef tmask
144675cbd984Sdan #endif
144775cbd984Sdan 
14489cfcf5d4Sdrh /*
1449e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for
1450e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn()
145198bfa16dSdrh */
145298bfa16dSdrh #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
145398bfa16dSdrh #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
145498bfa16dSdrh 
1455e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1456e9816d82Sdrh *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1457e9816d82Sdrh ** expression node references any of the
14582a0b527bSdrh ** columns that are being modifed by an UPDATE statement.
14592a0b527bSdrh */
checkConstraintExprNode(Walker * pWalker,Expr * pExpr)14602a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
146198bfa16dSdrh   if( pExpr->op==TK_COLUMN ){
146298bfa16dSdrh     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
146398bfa16dSdrh     if( pExpr->iColumn>=0 ){
146498bfa16dSdrh       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
146598bfa16dSdrh         pWalker->eCode |= CKCNSTRNT_COLUMN;
146698bfa16dSdrh       }
146798bfa16dSdrh     }else{
146898bfa16dSdrh       pWalker->eCode |= CKCNSTRNT_ROWID;
146998bfa16dSdrh     }
14702a0b527bSdrh   }
14712a0b527bSdrh   return WRC_Continue;
14722a0b527bSdrh }
14732a0b527bSdrh 
14742a0b527bSdrh /*
14752a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
14762a0b527bSdrh ** only columns that are modified by the UPDATE are those for which
147798bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
147898bfa16dSdrh **
1479e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the
148098bfa16dSdrh ** changing columns (or the rowid if it is changing).  In other words,
1481e9816d82Sdrh ** return true if this CHECK constraint must be validated for
148298bfa16dSdrh ** the new row in the UPDATE statement.
1483e9816d82Sdrh **
1484e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1485e9816d82Sdrh ** The operation of this routine is the same - return true if an only if
1486e9816d82Sdrh ** the expression uses one or more of columns identified by the second and
1487e9816d82Sdrh ** third arguments.
14882a0b527bSdrh */
sqlite3ExprReferencesUpdatedColumn(Expr * pExpr,int * aiChng,int chngRowid)1489e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn(
1490e9816d82Sdrh   Expr *pExpr,    /* The expression to be checked */
1491e9816d82Sdrh   int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
1492e9816d82Sdrh   int chngRowid   /* True if UPDATE changes the rowid */
1493e9816d82Sdrh ){
14942a0b527bSdrh   Walker w;
14952a0b527bSdrh   memset(&w, 0, sizeof(w));
149698bfa16dSdrh   w.eCode = 0;
14972a0b527bSdrh   w.xExprCallback = checkConstraintExprNode;
14982a0b527bSdrh   w.u.aiCol = aiChng;
14992a0b527bSdrh   sqlite3WalkExpr(&w, pExpr);
150005723a9eSdrh   if( !chngRowid ){
150105723a9eSdrh     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
150205723a9eSdrh     w.eCode &= ~CKCNSTRNT_ROWID;
150305723a9eSdrh   }
150405723a9eSdrh   testcase( w.eCode==0 );
150505723a9eSdrh   testcase( w.eCode==CKCNSTRNT_COLUMN );
150605723a9eSdrh   testcase( w.eCode==CKCNSTRNT_ROWID );
150705723a9eSdrh   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1508e9816d82Sdrh   return w.eCode!=0;
15092a0b527bSdrh }
15102a0b527bSdrh 
151111e85273Sdrh /*
1512daf2761cSdrh ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1513daf2761cSdrh ** the indexes of a table in the order provided in the Table->pIndex list.
1514daf2761cSdrh ** However, sometimes (rarely - when there is an upsert) it wants to visit
1515daf2761cSdrh ** the indexes in a different order.  The following data structures accomplish
1516daf2761cSdrh ** this.
1517daf2761cSdrh **
1518daf2761cSdrh ** The IndexIterator object is used to walk through all of the indexes
1519daf2761cSdrh ** of a table in either Index.pNext order, or in some other order established
1520daf2761cSdrh ** by an array of IndexListTerm objects.
1521daf2761cSdrh */
1522daf2761cSdrh typedef struct IndexListTerm IndexListTerm;
1523daf2761cSdrh typedef struct IndexIterator IndexIterator;
1524daf2761cSdrh struct IndexIterator {
1525daf2761cSdrh   int eType;    /* 0 for Index.pNext list.  1 for an array of IndexListTerm */
1526daf2761cSdrh   int i;        /* Index of the current item from the list */
1527daf2761cSdrh   union {
1528daf2761cSdrh     struct {    /* Use this object for eType==0: A Index.pNext list */
1529daf2761cSdrh       Index *pIdx;   /* The current Index */
1530daf2761cSdrh     } lx;
1531daf2761cSdrh     struct {    /* Use this object for eType==1; Array of IndexListTerm */
1532daf2761cSdrh       int nIdx;               /* Size of the array */
1533daf2761cSdrh       IndexListTerm *aIdx;    /* Array of IndexListTerms */
1534daf2761cSdrh     } ax;
1535daf2761cSdrh   } u;
1536daf2761cSdrh };
1537daf2761cSdrh 
1538daf2761cSdrh /* When IndexIterator.eType==1, then each index is an array of instances
1539daf2761cSdrh ** of the following object
1540daf2761cSdrh */
1541daf2761cSdrh struct IndexListTerm {
1542daf2761cSdrh   Index *p;  /* The index */
1543daf2761cSdrh   int ix;    /* Which entry in the original Table.pIndex list is this index*/
1544daf2761cSdrh };
1545daf2761cSdrh 
1546daf2761cSdrh /* Return the first index on the list */
indexIteratorFirst(IndexIterator * pIter,int * pIx)1547daf2761cSdrh static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1548ed4c5469Sdrh   assert( pIter->i==0 );
1549ed4c5469Sdrh   if( pIter->eType ){
1550ed4c5469Sdrh     *pIx = pIter->u.ax.aIdx[0].ix;
1551ed4c5469Sdrh     return pIter->u.ax.aIdx[0].p;
1552ed4c5469Sdrh   }else{
1553ed4c5469Sdrh     *pIx = 0;
1554ed4c5469Sdrh     return pIter->u.lx.pIdx;
1555ed4c5469Sdrh   }
1556daf2761cSdrh }
1557daf2761cSdrh 
1558daf2761cSdrh /* Return the next index from the list.  Return NULL when out of indexes */
indexIteratorNext(IndexIterator * pIter,int * pIx)1559daf2761cSdrh static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1560daf2761cSdrh   if( pIter->eType ){
1561d3e21a10Sdrh     int i = ++pIter->i;
156261e280adSdrh     if( i>=pIter->u.ax.nIdx ){
156361e280adSdrh       *pIx = i;
156461e280adSdrh       return 0;
156561e280adSdrh     }
1566daf2761cSdrh     *pIx = pIter->u.ax.aIdx[i].ix;
1567daf2761cSdrh     return pIter->u.ax.aIdx[i].p;
1568daf2761cSdrh   }else{
1569d3e21a10Sdrh     ++(*pIx);
1570daf2761cSdrh     pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1571daf2761cSdrh     return pIter->u.lx.pIdx;
1572daf2761cSdrh   }
1573daf2761cSdrh }
1574daf2761cSdrh 
1575daf2761cSdrh /*
15766934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
15776934fc7bSdrh ** on table pTab.
15789cfcf5d4Sdrh **
15796934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
15806934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
15816934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
15826934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
15836934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
15846934fc7bSdrh ** contain the content of the first table column.  The third register will
15856934fc7bSdrh ** contain the content of the second table column.  And so forth.
15860ca3e24bSdrh **
1587f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1588f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1589f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1590f8ffb278Sdrh ** checking regOldData for zero.
15910ca3e24bSdrh **
1592f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1593f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1594f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1595f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
15960ca3e24bSdrh **
1597f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1598f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1599f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1600f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1601f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1602f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
16030ca3e24bSdrh **
16046934fc7bSdrh ** The code generated by this routine will store new index entries into
1605aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1606aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1607aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
16086934fc7bSdrh ** at pTab->pIndex.
16096934fc7bSdrh **
1610a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the
1611a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the
1612a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first
1613a7c3b93fSdrh ** entry of aRegIdx[] past the last index.  It is important that the
1614a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes
1615a7c3b93fSdrh ** to the register content that occur after constraint checks but before
1616a7c3b93fSdrh ** the new record is inserted.
1617a7c3b93fSdrh **
16186934fc7bSdrh ** The caller must have already opened writeable cursors on the main
16196934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
16206934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
16216934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
16226934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
16236934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
16246934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
16259cfcf5d4Sdrh **
16269cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
16279cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
16281c92853dSdrh ** then the appropriate action is performed.  There are five possible
16291c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
16309cfcf5d4Sdrh **
16319cfcf5d4Sdrh **  Constraint type  Action       What Happens
16329cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
16331c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
16346934fc7bSdrh **                                sqlite3_step() returns immediately with a
16359cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
16369cfcf5d4Sdrh **
16371c92853dSdrh **  any              ABORT        Back out changes from the current command
16381c92853dSdrh **                                only (do not do a complete rollback) then
16396934fc7bSdrh **                                cause sqlite3_step() to return immediately
16401c92853dSdrh **                                with SQLITE_CONSTRAINT.
16411c92853dSdrh **
16426934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
16431c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
16441c92853dSdrh **                                transaction is not rolled back and any
16456934fc7bSdrh **                                changes to prior rows are retained.
16461c92853dSdrh **
16476934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
16486934fc7bSdrh **                                row is skipped, without throwing an error.
16496934fc7bSdrh **                                Processing continues with the next row.
16506934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
16519cfcf5d4Sdrh **
16529cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
16539cfcf5d4Sdrh **                                value for that column.  If the default value
16549cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
16559cfcf5d4Sdrh **
16569cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
16579cfcf5d4Sdrh **                                being inserted is removed.
16589cfcf5d4Sdrh **
16599cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
16609cfcf5d4Sdrh **
16611c92853dSdrh ** Which action to take is determined by the overrideError parameter.
16621c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
16631c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
16641c92853dSdrh ** for the constraint is used.
16659cfcf5d4Sdrh */
sqlite3GenerateConstraintChecks(Parse * pParse,Table * pTab,int * aRegIdx,int iDataCur,int iIdxCur,int regNewData,int regOldData,u8 pkChng,u8 overrideError,int ignoreDest,int * pbMayReplace,int * aiChng,Upsert * pUpsert)16664adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
16679cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
16686934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1669f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
16706934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
167126198bb4Sdrh   int iIdxCur,         /* First index cursor */
16726934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1673f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1674f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1675f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1676de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1677bdb00225Sdrh   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1678788d55aaSdrh   int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
1679788d55aaSdrh   Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
16809cfcf5d4Sdrh ){
16811b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
16821b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
1683e84ad92fSdrh   Index *pPk = 0;      /* The PRIMARY KEY index for WITHOUT ROWID tables */
16842938f924Sdrh   sqlite3 *db;         /* Database connection */
1685f8ffb278Sdrh   int i;               /* loop counter */
1686f8ffb278Sdrh   int ix;              /* Index loop counter */
16879cfcf5d4Sdrh   int nCol;            /* Number of columns */
16889cfcf5d4Sdrh   int onError;         /* Conflict resolution strategy */
16891b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
16906fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
169161e280adSdrh   Upsert *pUpsertClause = 0;  /* The specific ON CONFLICT clause for pIdx */
16928d1b82e4Sdrh   u8 isUpdate;           /* True if this is an UPDATE operation */
169357bf4a8eSdrh   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
169461e280adSdrh   int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
169561e280adSdrh   int upsertIpkDelay = 0;  /* Address of Goto to bypass initial IPK check */
169684304506Sdrh   int ipkTop = 0;        /* Top of the IPK uniqueness check */
169784304506Sdrh   int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
1698a407eccbSdrh   /* Variables associated with retesting uniqueness constraints after
1699a407eccbSdrh   ** replace triggers fire have run */
1700a407eccbSdrh   int regTrigCnt;       /* Register used to count replace trigger invocations */
1701a407eccbSdrh   int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */
1702a407eccbSdrh   int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1703a407eccbSdrh   Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
1704a407eccbSdrh   int nReplaceTrig = 0; /* Number of replace triggers coded */
170561e280adSdrh   IndexIterator sIdxIter;  /* Index iterator */
17069cfcf5d4Sdrh 
1707f8ffb278Sdrh   isUpdate = regOldData!=0;
17082938f924Sdrh   db = pParse->db;
1709f0b41745Sdrh   v = pParse->pVdbe;
17109cfcf5d4Sdrh   assert( v!=0 );
1711f38524d2Sdrh   assert( !IsView(pTab) );  /* This table is not a VIEW */
17129cfcf5d4Sdrh   nCol = pTab->nCol;
1713aa9b8963Sdrh 
17146934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
17156934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
17166934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
17176934fc7bSdrh   ** number of fields in the true primary key of the table. */
171826198bb4Sdrh   if( HasRowid(pTab) ){
171926198bb4Sdrh     pPk = 0;
172026198bb4Sdrh     nPkField = 1;
172126198bb4Sdrh   }else{
172226198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
172326198bb4Sdrh     nPkField = pPk->nKeyCol;
172426198bb4Sdrh   }
17256fbe41acSdrh 
17266fbe41acSdrh   /* Record that this module has started */
17276fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
17286934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
17299cfcf5d4Sdrh 
17309cfcf5d4Sdrh   /* Test all NOT NULL constraints.
17319cfcf5d4Sdrh   */
1732cbda9c7aSdrh   if( pTab->tabFlags & TF_HasNotNull ){
1733ad5f1577Sdrh     int b2ndPass = 0;         /* True if currently running 2nd pass */
1734ad5f1577Sdrh     int nSeenReplace = 0;     /* Number of ON CONFLICT REPLACE operations */
1735ad5f1577Sdrh     int nGenerated = 0;       /* Number of generated columns with NOT NULL */
1736ad5f1577Sdrh     while(1){  /* Make 2 passes over columns. Exit loop via "break" */
17379cfcf5d4Sdrh       for(i=0; i<nCol; i++){
1738ad5f1577Sdrh         int iReg;                        /* Register holding column value */
1739ad5f1577Sdrh         Column *pCol = &pTab->aCol[i];   /* The column to check for NOT NULL */
1740ad5f1577Sdrh         int isGenerated;                 /* non-zero if column is generated */
1741ad5f1577Sdrh         onError = pCol->notNull;
1742cbda9c7aSdrh         if( onError==OE_None ) continue; /* No NOT NULL on this column */
17430ca3e24bSdrh         if( i==pTab->iPKey ){
1744bdb00225Sdrh           continue;        /* ROWID is never NULL */
1745bdb00225Sdrh         }
1746ad5f1577Sdrh         isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1747ad5f1577Sdrh         if( isGenerated && !b2ndPass ){
1748ad5f1577Sdrh           nGenerated++;
1749ad5f1577Sdrh           continue;        /* Generated columns processed on 2nd pass */
1750ad5f1577Sdrh         }
1751ad5f1577Sdrh         if( aiChng && aiChng[i]<0 && !isGenerated ){
1752ad5f1577Sdrh           /* Do not check NOT NULL on columns that do not change */
17530ca3e24bSdrh           continue;
17540ca3e24bSdrh         }
17559cfcf5d4Sdrh         if( overrideError!=OE_Default ){
17569cfcf5d4Sdrh           onError = overrideError;
1757a996e477Sdrh         }else if( onError==OE_Default ){
1758a996e477Sdrh           onError = OE_Abort;
17599cfcf5d4Sdrh         }
1760ad5f1577Sdrh         if( onError==OE_Replace ){
1761ad5f1577Sdrh           if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */
176279cf2b71Sdrh            || pCol->iDflt==0  /* REPLACE is ABORT if no DEFAULT value */
1763ad5f1577Sdrh           ){
1764ad5f1577Sdrh             testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1765ad5f1577Sdrh             testcase( pCol->colFlags & COLFLAG_STORED );
1766ad5f1577Sdrh             testcase( pCol->colFlags & COLFLAG_GENERATED );
17679cfcf5d4Sdrh             onError = OE_Abort;
1768ad5f1577Sdrh           }else{
1769ad5f1577Sdrh             assert( !isGenerated );
1770ad5f1577Sdrh           }
1771ad5f1577Sdrh         }else if( b2ndPass && !isGenerated ){
1772ad5f1577Sdrh           continue;
17739cfcf5d4Sdrh         }
1774b84f96f8Sdanielk1977         assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1775b84f96f8Sdanielk1977             || onError==OE_Ignore || onError==OE_Replace );
1776c5f808d8Sdrh         testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1777b9bcf7caSdrh         iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
17789cfcf5d4Sdrh         switch( onError ){
17799bfb0794Sdrh           case OE_Replace: {
1780ad5f1577Sdrh             int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
17819bfb0794Sdrh             VdbeCoverage(v);
1782ad5f1577Sdrh             assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
1783ad5f1577Sdrh             nSeenReplace++;
178479cf2b71Sdrh             sqlite3ExprCodeCopy(pParse,
178579cf2b71Sdrh                sqlite3ColumnExpr(pTab, pCol), iReg);
1786ad5f1577Sdrh             sqlite3VdbeJumpHere(v, addr1);
1787ad5f1577Sdrh             break;
17889bfb0794Sdrh           }
17891c92853dSdrh           case OE_Abort:
1790e0af83acSdan             sqlite3MayAbort(pParse);
179108b92086Sdrh             /* no break */ deliberate_fall_through
1792e0af83acSdan           case OE_Rollback:
17931c92853dSdrh           case OE_Fail: {
1794f9c8ce3cSdrh             char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1795cf9d36d1Sdrh                                         pCol->zCnName);
1796cbda9c7aSdrh             sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
1797a88c8c1aSdrh                               onError, iReg);
17982700acaaSdrh             sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1799f9c8ce3cSdrh             sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1800688852abSdrh             VdbeCoverage(v);
18019cfcf5d4Sdrh             break;
18029cfcf5d4Sdrh           }
1803098d1684Sdrh           default: {
18049bfb0794Sdrh             assert( onError==OE_Ignore );
18058e10d74bSdrh             sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
1806728e0f91Sdrh             VdbeCoverage(v);
18079cfcf5d4Sdrh             break;
18089cfcf5d4Sdrh           }
1809ad5f1577Sdrh         } /* end switch(onError) */
1810ad5f1577Sdrh       } /* end loop i over columns */
1811ad5f1577Sdrh       if( nGenerated==0 && nSeenReplace==0 ){
1812ad5f1577Sdrh         /* If there are no generated columns with NOT NULL constraints
1813ad5f1577Sdrh         ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
1814ad5f1577Sdrh         ** pass is sufficient */
1815ad5f1577Sdrh         break;
18169cfcf5d4Sdrh       }
1817ad5f1577Sdrh       if( b2ndPass ) break;  /* Never need more than 2 passes */
1818ad5f1577Sdrh       b2ndPass = 1;
1819ef9f719dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1820ad5f1577Sdrh       if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1821ad5f1577Sdrh         /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
1822ad5f1577Sdrh         ** first pass, recomputed values for all generated columns, as
1823ad5f1577Sdrh         ** those values might depend on columns affected by the REPLACE.
1824ad5f1577Sdrh         */
1825ad5f1577Sdrh         sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
18269cfcf5d4Sdrh       }
1827ef9f719dSdrh #endif
1828ad5f1577Sdrh     } /* end of 2-pass loop */
1829ad5f1577Sdrh   } /* end if( has-not-null-constraints ) */
18309cfcf5d4Sdrh 
18319cfcf5d4Sdrh   /* Test all CHECK constraints
18329cfcf5d4Sdrh   */
1833ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
18342938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
18352938f924Sdrh     ExprList *pCheck = pTab->pCheck;
18366e97f8ecSdrh     pParse->iSelfTab = -(regNewData+1);
1837aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
18382938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
183905723a9eSdrh       int allOk;
18405cf1b611Sdrh       Expr *pCopy;
18412a0b527bSdrh       Expr *pExpr = pCheck->a[i].pExpr;
1842e9816d82Sdrh       if( aiChng
1843e9816d82Sdrh        && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
1844e9816d82Sdrh       ){
1845e9816d82Sdrh         /* The check constraints do not reference any of the columns being
1846e9816d82Sdrh         ** updated so there is no point it verifying the check constraint */
1847e9816d82Sdrh         continue;
1848e9816d82Sdrh       }
18499dce0ef4Sdrh       if( bAffinityDone==0 ){
18509dce0ef4Sdrh         sqlite3TableAffinity(v, pTab, regNewData+1);
18519dce0ef4Sdrh         bAffinityDone = 1;
18529dce0ef4Sdrh       }
1853ec4ccdbcSdrh       allOk = sqlite3VdbeMakeLabel(pParse);
18544031bafaSdrh       sqlite3VdbeVerifyAbortable(v, onError);
18555cf1b611Sdrh       pCopy = sqlite3ExprDup(db, pExpr, 0);
18565cf1b611Sdrh       if( !db->mallocFailed ){
18575cf1b611Sdrh         sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
18585cf1b611Sdrh       }
18595cf1b611Sdrh       sqlite3ExprDelete(db, pCopy);
18602e06c67cSdrh       if( onError==OE_Ignore ){
1861076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
1862aa01c7e2Sdrh       }else{
186341cee668Sdrh         char *zName = pCheck->a[i].zEName;
1864e2678b93Sdrh         assert( zName!=0 || pParse->db->mallocFailed );
18650ce974d1Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
1866d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1867f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1868f9c8ce3cSdrh                               P5_ConstraintCheck);
1869aa01c7e2Sdrh       }
1870ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1871ffe07b2dSdrh     }
18726e97f8ecSdrh     pParse->iSelfTab = 0;
18732938f924Sdrh   }
1874ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
18759cfcf5d4Sdrh 
1876096fd476Sdrh   /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1877096fd476Sdrh   ** order:
1878096fd476Sdrh   **
187984304506Sdrh   **   (1)  OE_Update
188084304506Sdrh   **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1881096fd476Sdrh   **   (3)  OE_Replace
1882096fd476Sdrh   **
1883096fd476Sdrh   ** OE_Fail and OE_Ignore must happen before any changes are made.
1884096fd476Sdrh   ** OE_Update guarantees that only a single row will change, so it
1885096fd476Sdrh   ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
1886096fd476Sdrh   ** could happen in any order, but they are grouped up front for
1887096fd476Sdrh   ** convenience.
1888096fd476Sdrh   **
188984304506Sdrh   ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
189084304506Sdrh   ** The order of constraints used to have OE_Update as (2) and OE_Abort
189184304506Sdrh   ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
189284304506Sdrh   ** constraint before any others, so it had to be moved.
189384304506Sdrh   **
1894096fd476Sdrh   ** Constraint checking code is generated in this order:
1895096fd476Sdrh   **   (A)  The rowid constraint
1896096fd476Sdrh   **   (B)  Unique index constraints that do not have OE_Replace as their
1897096fd476Sdrh   **        default conflict resolution strategy
1898096fd476Sdrh   **   (C)  Unique index that do use OE_Replace by default.
1899096fd476Sdrh   **
1900096fd476Sdrh   ** The ordering of (2) and (3) is accomplished by making sure the linked
1901096fd476Sdrh   ** list of indexes attached to a table puts all OE_Replace indexes last
1902096fd476Sdrh   ** in the list.  See sqlite3CreateIndex() for where that happens.
1903096fd476Sdrh   */
190461e280adSdrh   sIdxIter.eType = 0;
190561e280adSdrh   sIdxIter.i = 0;
1906d3e21a10Sdrh   sIdxIter.u.ax.aIdx = 0;  /* Silence harmless compiler warning */
190761e280adSdrh   sIdxIter.u.lx.pIdx = pTab->pIndex;
1908096fd476Sdrh   if( pUpsert ){
1909096fd476Sdrh     if( pUpsert->pUpsertTarget==0 ){
191061e280adSdrh       /* There is just on ON CONFLICT clause and it has no constraint-target */
191161e280adSdrh       assert( pUpsert->pNextUpsert==0 );
1912255c1c15Sdrh       if( pUpsert->isDoUpdate==0 ){
191361e280adSdrh         /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
1914096fd476Sdrh         ** Make all unique constraint resolution be OE_Ignore */
1915096fd476Sdrh         overrideError = OE_Ignore;
1916096fd476Sdrh         pUpsert = 0;
191761e280adSdrh       }else{
191861e280adSdrh         /* A single ON CONFLICT DO UPDATE.  Make all resolutions OE_Update */
191961e280adSdrh         overrideError = OE_Update;
192061e280adSdrh       }
192161e280adSdrh     }else if( pTab->pIndex!=0 ){
192261e280adSdrh       /* Otherwise, we'll need to run the IndexListTerm array version of the
192361e280adSdrh       ** iterator to ensure that all of the ON CONFLICT conditions are
192461e280adSdrh       ** checked first and in order. */
192561e280adSdrh       int nIdx, jj;
192661e280adSdrh       u64 nByte;
192761e280adSdrh       Upsert *pTerm;
192861e280adSdrh       u8 *bUsed;
192961e280adSdrh       for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
193061e280adSdrh          assert( aRegIdx[nIdx]>0 );
193161e280adSdrh       }
193261e280adSdrh       sIdxIter.eType = 1;
193361e280adSdrh       sIdxIter.u.ax.nIdx = nIdx;
193461e280adSdrh       nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
193561e280adSdrh       sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
193661e280adSdrh       if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
193761e280adSdrh       bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
193861e280adSdrh       pUpsert->pToFree = sIdxIter.u.ax.aIdx;
193961e280adSdrh       for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
194061e280adSdrh         if( pTerm->pUpsertTarget==0 ) break;
194161e280adSdrh         if( pTerm->pUpsertIdx==0 ) continue;  /* Skip ON CONFLICT for the IPK */
194261e280adSdrh         jj = 0;
194361e280adSdrh         pIdx = pTab->pIndex;
194461e280adSdrh         while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
194561e280adSdrh            pIdx = pIdx->pNext;
194661e280adSdrh            jj++;
194761e280adSdrh         }
194861e280adSdrh         if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
194961e280adSdrh         bUsed[jj] = 1;
195061e280adSdrh         sIdxIter.u.ax.aIdx[i].p = pIdx;
195161e280adSdrh         sIdxIter.u.ax.aIdx[i].ix = jj;
195261e280adSdrh         i++;
195361e280adSdrh       }
195461e280adSdrh       for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
195561e280adSdrh         if( bUsed[jj] ) continue;
195661e280adSdrh         sIdxIter.u.ax.aIdx[i].p = pIdx;
195761e280adSdrh         sIdxIter.u.ax.aIdx[i].ix = jj;
195861e280adSdrh         i++;
195961e280adSdrh       }
196061e280adSdrh       assert( i==nIdx );
1961096fd476Sdrh     }
1962096fd476Sdrh   }
1963096fd476Sdrh 
1964a407eccbSdrh   /* Determine if it is possible that triggers (either explicitly coded
1965a407eccbSdrh   ** triggers or FK resolution actions) might run as a result of deletes
1966a407eccbSdrh   ** that happen when OE_Replace conflict resolution occurs. (Call these
1967a407eccbSdrh   ** "replace triggers".)  If any replace triggers run, we will need to
1968a407eccbSdrh   ** recheck all of the uniqueness constraints after they have all run.
1969a407eccbSdrh   ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
1970a407eccbSdrh   **
1971a407eccbSdrh   ** If replace triggers are a possibility, then
1972a407eccbSdrh   **
1973a407eccbSdrh   **   (1) Allocate register regTrigCnt and initialize it to zero.
1974a407eccbSdrh   **       That register will count the number of replace triggers that
1975d3c468b7Sdrh   **       fire.  Constraint recheck only occurs if the number is positive.
1976d3c468b7Sdrh   **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
1977a407eccbSdrh   **   (3) Initialize addrRecheck and lblRecheckOk
1978a407eccbSdrh   **
1979a407eccbSdrh   ** The uniqueness rechecking code will create a series of tests to run
1980a407eccbSdrh   ** in a second pass.  The addrRecheck and lblRecheckOk variables are
1981a407eccbSdrh   ** used to link together these tests which are separated from each other
1982a407eccbSdrh   ** in the generate bytecode.
1983a407eccbSdrh   */
1984a407eccbSdrh   if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
1985a407eccbSdrh     /* There are not DELETE triggers nor FK constraints.  No constraint
1986a407eccbSdrh     ** rechecks are needed. */
1987a407eccbSdrh     pTrigger = 0;
1988a407eccbSdrh     regTrigCnt = 0;
1989a407eccbSdrh   }else{
1990a407eccbSdrh     if( db->flags&SQLITE_RecTriggers ){
1991a407eccbSdrh       pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1992a407eccbSdrh       regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
1993a407eccbSdrh     }else{
1994a407eccbSdrh       pTrigger = 0;
1995a407eccbSdrh       regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
1996a407eccbSdrh     }
1997a407eccbSdrh     if( regTrigCnt ){
1998a407eccbSdrh       /* Replace triggers might exist.  Allocate the counter and
1999a407eccbSdrh       ** initialize it to zero. */
2000a407eccbSdrh       regTrigCnt = ++pParse->nMem;
2001a407eccbSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2002a407eccbSdrh       VdbeComment((v, "trigger count"));
2003a407eccbSdrh       lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2004a407eccbSdrh       addrRecheck = lblRecheckOk;
2005a407eccbSdrh     }
2006a407eccbSdrh   }
2007a407eccbSdrh 
2008f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
2009f8ffb278Sdrh   ** exist in the table.
20109cfcf5d4Sdrh   */
20116fbe41acSdrh   if( pkChng && pPk==0 ){
2012ec4ccdbcSdrh     int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
201311e85273Sdrh 
2014f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
20150ca3e24bSdrh     onError = pTab->keyConf;
20160ca3e24bSdrh     if( overrideError!=OE_Default ){
20170ca3e24bSdrh       onError = overrideError;
2018a996e477Sdrh     }else if( onError==OE_Default ){
2019a996e477Sdrh       onError = OE_Abort;
20200ca3e24bSdrh     }
2021a0217ba7Sdrh 
2022c8a0c90bSdrh     /* figure out whether or not upsert applies in this case */
202361e280adSdrh     if( pUpsert ){
202461e280adSdrh       pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
202561e280adSdrh       if( pUpsertClause!=0 ){
2026255c1c15Sdrh         if( pUpsertClause->isDoUpdate==0 ){
2027c8a0c90bSdrh           onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
2028c8a0c90bSdrh         }else{
2029c8a0c90bSdrh           onError = OE_Update;  /* DO UPDATE */
2030c8a0c90bSdrh         }
2031c8a0c90bSdrh       }
203261e280adSdrh       if( pUpsertClause!=pUpsert ){
203361e280adSdrh         /* The first ON CONFLICT clause has a conflict target other than
203461e280adSdrh         ** the IPK.  We have to jump ahead to that first ON CONFLICT clause
203561e280adSdrh         ** and then come back here and deal with the IPK afterwards */
203661e280adSdrh         upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
203761e280adSdrh       }
203861e280adSdrh     }
2039c8a0c90bSdrh 
20408d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
20418d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
20428d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
20438d1b82e4Sdrh     ** the UNIQUE constraints have run.
20448d1b82e4Sdrh     */
204584304506Sdrh     if( onError==OE_Replace      /* IPK rule is REPLACE */
20469a60e716Smistachkin      && onError!=overrideError   /* Rules for other constraints are different */
204784304506Sdrh      && pTab->pIndex             /* There exist other constraints */
204866306d86Sdrh      && !upsertIpkDelay          /* IPK check already deferred by UPSERT */
2049096fd476Sdrh     ){
205084304506Sdrh       ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
205184304506Sdrh       VdbeComment((v, "defer IPK REPLACE until last"));
20528d1b82e4Sdrh     }
20538d1b82e4Sdrh 
2054bb6b1ca7Sdrh     if( isUpdate ){
2055bb6b1ca7Sdrh       /* pkChng!=0 does not mean that the rowid has changed, only that
2056bb6b1ca7Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
2057bb6b1ca7Sdrh       ** is unchanged. */
2058bb6b1ca7Sdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2059bb6b1ca7Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2060bb6b1ca7Sdrh       VdbeCoverage(v);
2061bb6b1ca7Sdrh     }
2062bb6b1ca7Sdrh 
2063f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
2064f8ffb278Sdrh     ** the following conflict logic if it does not. */
20657f5f306bSdrh     VdbeNoopComment((v, "uniqueness check for ROWID"));
20664031bafaSdrh     sqlite3VdbeVerifyAbortable(v, onError);
20676934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2068688852abSdrh     VdbeCoverage(v);
2069f8ffb278Sdrh 
20700ca3e24bSdrh     switch( onError ){
2071a0217ba7Sdrh       default: {
2072a0217ba7Sdrh         onError = OE_Abort;
207308b92086Sdrh         /* no break */ deliberate_fall_through
2074a0217ba7Sdrh       }
20751c92853dSdrh       case OE_Rollback:
20761c92853dSdrh       case OE_Abort:
20771c92853dSdrh       case OE_Fail: {
20789916048bSdrh         testcase( onError==OE_Rollback );
20799916048bSdrh         testcase( onError==OE_Abort );
20809916048bSdrh         testcase( onError==OE_Fail );
2081f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
20820ca3e24bSdrh         break;
20830ca3e24bSdrh       }
20845383ae5cSdrh       case OE_Replace: {
20852283d46cSdan         /* If there are DELETE triggers on this table and the
20862283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
2087d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
20882283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
20892283d46cSdan         **
20902283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
2091da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
2092da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
2093da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
2094da730f6eSdan         ** when it is inserted.
2095da730f6eSdan         **
2096da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2097da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
2098da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
2099da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2100da730f6eSdan         ** but being more selective here allows statements like:
2101da730f6eSdan         **
2102da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
2103da730f6eSdan         **
2104da730f6eSdan         ** to run without a statement journal if there are no indexes on the
2105da730f6eSdan         ** table.
2106da730f6eSdan         */
2107a407eccbSdrh         if( regTrigCnt ){
2108da730f6eSdan           sqlite3MultiWrite(pParse);
210926198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2110438b8815Sdan                                    regNewData, 1, 0, OE_Replace, 1, -1);
2111a407eccbSdrh           sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2112a407eccbSdrh           nReplaceTrig++;
211346c47d46Sdan         }else{
21149b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
211554f2cd90Sdrh           assert( HasRowid(pTab) );
211646c47d46Sdan           /* This OP_Delete opcode fires the pre-update-hook only. It does
211746c47d46Sdan           ** not modify the b-tree. It is more efficient to let the coming
211846c47d46Sdan           ** OP_Insert replace the existing entry than it is to delete the
211946c47d46Sdan           ** existing entry and then insert a new one. */
2120cbf1b8efSdrh           sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2121f14b7fb7Sdrh           sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
21229b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
212346c47d46Sdan           if( pTab->pIndex ){
2124da730f6eSdan             sqlite3MultiWrite(pParse);
2125f0ee1d3cSdan             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
21262283d46cSdan           }
212746c47d46Sdan         }
21285383ae5cSdrh         seenReplace = 1;
21295383ae5cSdrh         break;
21305383ae5cSdrh       }
21319eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
21329eddacadSdrh       case OE_Update: {
21332cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
213408b92086Sdrh         /* no break */ deliberate_fall_through
21359eddacadSdrh       }
21369eddacadSdrh #endif
21370ca3e24bSdrh       case OE_Ignore: {
21389916048bSdrh         testcase( onError==OE_Ignore );
2139076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
21400ca3e24bSdrh         break;
21410ca3e24bSdrh       }
21420ca3e24bSdrh     }
214311e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
214461e280adSdrh     if( pUpsert && pUpsertClause!=pUpsert ){
214561e280adSdrh       upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
214661e280adSdrh     }else if( ipkTop ){
214784304506Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
214884304506Sdrh       sqlite3VdbeJumpHere(v, ipkTop-1);
2149a05a722fSdrh     }
21500ca3e24bSdrh   }
21510bd1f4eaSdrh 
21520bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
21530bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
215411e85273Sdrh   ** Compute the revised record entries for indices as we go.
2155f8ffb278Sdrh   **
2156f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
2157f8ffb278Sdrh   ** WITHOUT ROWID table.
21580bd1f4eaSdrh   */
215961e280adSdrh   for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2160daf2761cSdrh       pIdx;
216161e280adSdrh       pIdx = indexIteratorNext(&sIdxIter, &ix)
2162daf2761cSdrh   ){
21636934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
21646934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
21656934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
21666934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
2167a407eccbSdrh     int addrConflictCk;  /* First opcode in the conflict check logic */
21682184fc75Sdrh 
216926198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
217061e280adSdrh     if( pUpsert ){
217161e280adSdrh       pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
217261e280adSdrh       if( upsertIpkDelay && pUpsertClause==pUpsert ){
217361e280adSdrh         sqlite3VdbeJumpHere(v, upsertIpkDelay);
21747f5f306bSdrh       }
217561e280adSdrh     }
217661e280adSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
217761e280adSdrh     if( bAffinityDone==0 ){
217884304506Sdrh       sqlite3TableAffinity(v, pTab, regNewData+1);
217984304506Sdrh       bAffinityDone = 1;
218084304506Sdrh     }
21818e50d65aSdrh     VdbeNoopComment((v, "prep index %s", pIdx->zName));
21826934fc7bSdrh     iThisCur = iIdxCur+ix;
21837f5f306bSdrh 
2184b2fe7d8cSdrh 
2185f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
2186b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
218726198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
21886e97f8ecSdrh       pParse->iSelfTab = -(regNewData+1);
218972bc8208Sdrh       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2190b2b9d3d7Sdrh                             SQLITE_JUMPIFNULL);
21916e97f8ecSdrh       pParse->iSelfTab = 0;
2192b2b9d3d7Sdrh     }
2193b2b9d3d7Sdrh 
21946934fc7bSdrh     /* Create a record for this index entry as it should appear after
2195f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
2196f8ffb278Sdrh     */
2197bf2f5739Sdrh     regIdx = aRegIdx[ix]+1;
21989cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
21996934fc7bSdrh       int iField = pIdx->aiColumn[i];
2200f82b9afcSdrh       int x;
22014b92f98cSdrh       if( iField==XN_EXPR ){
22026e97f8ecSdrh         pParse->iSelfTab = -(regNewData+1);
22031c75c9d7Sdrh         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
22046e97f8ecSdrh         pParse->iSelfTab = 0;
22051f9ca2c8Sdrh         VdbeComment((v, "%s column %d", pIdx->zName, i));
2206463e76ffSdrh       }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2207f82b9afcSdrh         x = regNewData;
2208463e76ffSdrh         sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2209463e76ffSdrh         VdbeComment((v, "rowid"));
22109cfcf5d4Sdrh       }else{
2211c5f808d8Sdrh         testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2212b9bcf7caSdrh         x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2213463e76ffSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2214cf9d36d1Sdrh         VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
22159cfcf5d4Sdrh       }
22161f9ca2c8Sdrh     }
221726198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
221826198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
22197e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
22209df385ecSdrh     if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
22219df385ecSdrh       sqlite3SetMakeRecordP5(v, pIdx->pTable);
22229df385ecSdrh     }
22237e4acf7bSdrh #endif
22243aef2fb1Sdrh     sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2225b2fe7d8cSdrh 
2226f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
2227f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
2228f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
2229f8ffb278Sdrh     ** logic below can all be skipped. */
223000012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
2231da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2232da475b8dSdrh       continue;
2233da475b8dSdrh     }
2234f8ffb278Sdrh 
22356934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
22369cfcf5d4Sdrh     onError = pIdx->onError;
2237de630353Sdanielk1977     if( onError==OE_None ){
223811e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2239de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
2240de630353Sdanielk1977     }
22419cfcf5d4Sdrh     if( overrideError!=OE_Default ){
22429cfcf5d4Sdrh       onError = overrideError;
2243a996e477Sdrh     }else if( onError==OE_Default ){
2244a996e477Sdrh       onError = OE_Abort;
22459cfcf5d4Sdrh     }
22465383ae5cSdrh 
2247c8a0c90bSdrh     /* Figure out if the upsert clause applies to this index */
224861e280adSdrh     if( pUpsertClause ){
2249255c1c15Sdrh       if( pUpsertClause->isDoUpdate==0 ){
2250c8a0c90bSdrh         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
2251c8a0c90bSdrh       }else{
2252c8a0c90bSdrh         onError = OE_Update;  /* DO UPDATE */
2253c8a0c90bSdrh       }
2254c8a0c90bSdrh     }
2255c8a0c90bSdrh 
2256801f55d8Sdrh     /* Collision detection may be omitted if all of the following are true:
2257801f55d8Sdrh     **   (1) The conflict resolution algorithm is REPLACE
2258801f55d8Sdrh     **   (2) The table is a WITHOUT ROWID table
2259801f55d8Sdrh     **   (3) There are no secondary indexes on the table
2260801f55d8Sdrh     **   (4) No delete triggers need to be fired if there is a conflict
2261f9a12a10Sdan     **   (5) No FK constraint counters need to be updated if a conflict occurs.
2262418454c6Sdan     **
2263418454c6Sdan     ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2264418454c6Sdan     ** must be explicitly deleted in order to ensure any pre-update hook
2265418454c6Sdan     ** is invoked.  */
226678b2fa86Sdrh     assert( IsOrdinaryTable(pTab) );
2267418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2268801f55d8Sdrh     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
2269801f55d8Sdrh      && pPk==pIdx                                   /* Condition 2 */
2270801f55d8Sdrh      && onError==OE_Replace                         /* Condition 1 */
2271801f55d8Sdrh      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
2272801f55d8Sdrh           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2273f9a12a10Sdan      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
2274f38524d2Sdrh          (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
22754e1f0efbSdan     ){
2276c6c9e158Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2277c6c9e158Sdrh       continue;
2278c6c9e158Sdrh     }
2279418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2280c6c9e158Sdrh 
2281b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
22824031bafaSdrh     sqlite3VdbeVerifyAbortable(v, onError);
2283a407eccbSdrh     addrConflictCk =
228426198bb4Sdrh       sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2285688852abSdrh                            regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2286f8ffb278Sdrh 
2287f8ffb278Sdrh     /* Generate code to handle collisions */
2288d3e21a10Sdrh     regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
228946d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
229011e85273Sdrh       if( HasRowid(pTab) ){
22916934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
22920978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
22930978d4ffSdrh         ** is different from old-rowid */
2294f8ffb278Sdrh         if( isUpdate ){
22956934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
22963d77dee9Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2297688852abSdrh           VdbeCoverage(v);
2298f8ffb278Sdrh         }
229926198bb4Sdrh       }else{
2300ccc79f02Sdrh         int x;
230126198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
2302da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
2303a021f121Sdrh         if( pIdx!=pPk ){
230426198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
23054b92f98cSdrh             assert( pPk->aiColumn[i]>=0 );
2306b9bcf7caSdrh             x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
230726198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
230826198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
2309cf9d36d1Sdrh                          pTab->aCol[pPk->aiColumn[i]].zCnName));
231026198bb4Sdrh           }
2311da475b8dSdrh         }
2312da475b8dSdrh         if( isUpdate ){
2313e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2314e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
23155a1f7612Sdrh           ** different from the old.  See TH3 withoutrowid04.test.
2316e83267daSdan           **
2317e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2318e83267daSdan           ** of the matched index row are different from the original PRIMARY
2319e83267daSdan           ** KEY values of this row before the update.  */
2320e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2321e83267daSdan           int op = OP_Ne;
232248dd1d8eSdrh           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2323e83267daSdan 
2324e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
2325e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2326ccc79f02Sdrh             x = pPk->aiColumn[i];
23274b92f98cSdrh             assert( x>=0 );
2328e83267daSdan             if( i==(pPk->nKeyCol-1) ){
2329e83267daSdan               addrJump = addrUniqueOk;
2330e83267daSdan               op = OP_Eq;
233111e85273Sdrh             }
2332b6d861e5Sdrh             x = sqlite3TableColumnToStorage(pTab, x);
2333e83267daSdan             sqlite3VdbeAddOp4(v, op,
2334e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2335e83267daSdan             );
23363d77dee9Sdrh             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
23373d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Eq);
23383d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Ne);
2339da475b8dSdrh           }
234011e85273Sdrh         }
234126198bb4Sdrh       }
234246d03fcbSdrh     }
2343b2fe7d8cSdrh 
2344b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
2345b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
23469eddacadSdrh         || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
23479cfcf5d4Sdrh     switch( onError ){
23481c92853dSdrh       case OE_Rollback:
23491c92853dSdrh       case OE_Abort:
23501c92853dSdrh       case OE_Fail: {
23519916048bSdrh         testcase( onError==OE_Rollback );
23529916048bSdrh         testcase( onError==OE_Abort );
23539916048bSdrh         testcase( onError==OE_Fail );
2354f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
23559cfcf5d4Sdrh         break;
23569cfcf5d4Sdrh       }
23579eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
23589eddacadSdrh       case OE_Update: {
23592cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
236008b92086Sdrh         /* no break */ deliberate_fall_through
23619eddacadSdrh       }
23629eddacadSdrh #endif
23639cfcf5d4Sdrh       case OE_Ignore: {
23649916048bSdrh         testcase( onError==OE_Ignore );
2365076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
23669cfcf5d4Sdrh         break;
23679cfcf5d4Sdrh       }
2368098d1684Sdrh       default: {
2369a407eccbSdrh         int nConflictCk;   /* Number of opcodes in conflict check logic */
2370a407eccbSdrh 
2371098d1684Sdrh         assert( onError==OE_Replace );
2372a407eccbSdrh         nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2373362c1819Sdrh         assert( nConflictCk>0 || db->mallocFailed );
2374362c1819Sdrh         testcase( nConflictCk<=0 );
2375d3c468b7Sdrh         testcase( nConflictCk>1 );
2376a407eccbSdrh         if( regTrigCnt ){
2377fecfb318Sdan           sqlite3MultiWrite(pParse);
2378a407eccbSdrh           nReplaceTrig++;
2379fecfb318Sdan         }
23807b14b65dSdrh         if( pTrigger && isUpdate ){
23817b14b65dSdrh           sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
23827b14b65dSdrh         }
238326198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2384b0264eecSdrh             regR, nPkField, 0, OE_Replace,
238568116939Sdrh             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
23867b14b65dSdrh         if( pTrigger && isUpdate ){
23877b14b65dSdrh           sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
23887b14b65dSdrh         }
2389a407eccbSdrh         if( regTrigCnt ){
2390a407eccbSdrh           int addrBypass;  /* Jump destination to bypass recheck logic */
2391a407eccbSdrh 
2392a407eccbSdrh           sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2393a407eccbSdrh           addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */
2394a407eccbSdrh           VdbeComment((v, "bypass recheck"));
2395a407eccbSdrh 
2396a407eccbSdrh           /* Here we insert code that will be invoked after all constraint
2397a407eccbSdrh           ** checks have run, if and only if one or more replace triggers
2398a407eccbSdrh           ** fired. */
2399a407eccbSdrh           sqlite3VdbeResolveLabel(v, lblRecheckOk);
2400a407eccbSdrh           lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2401a407eccbSdrh           if( pIdx->pPartIdxWhere ){
2402a407eccbSdrh             /* Bypass the recheck if this partial index is not defined
2403a407eccbSdrh             ** for the current row */
24040660884eSdrh             sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2405a407eccbSdrh             VdbeCoverage(v);
2406a407eccbSdrh           }
2407a407eccbSdrh           /* Copy the constraint check code from above, except change
2408a407eccbSdrh           ** the constraint-ok jump destination to be the address of
2409a407eccbSdrh           ** the next retest block */
2410d3c468b7Sdrh           while( nConflictCk>0 ){
2411d901b168Sdrh             VdbeOp x;    /* Conflict check opcode to copy */
2412d901b168Sdrh             /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2413d901b168Sdrh             ** Hence, make a complete copy of the opcode, rather than using
2414d901b168Sdrh             ** a pointer to the opcode. */
2415d901b168Sdrh             x = *sqlite3VdbeGetOp(v, addrConflictCk);
2416d901b168Sdrh             if( x.opcode!=OP_IdxRowid ){
2417d901b168Sdrh               int p2;      /* New P2 value for copied conflict check opcode */
2418b9f2e5f7Sdrh               const char *zP4;
2419d901b168Sdrh               if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2420a407eccbSdrh                 p2 = lblRecheckOk;
2421a407eccbSdrh               }else{
2422d901b168Sdrh                 p2 = x.p2;
2423a407eccbSdrh               }
2424b9f2e5f7Sdrh               zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2425b9f2e5f7Sdrh               sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2426d901b168Sdrh               sqlite3VdbeChangeP5(v, x.p5);
2427d901b168Sdrh               VdbeCoverageIf(v, p2!=x.p2);
2428a407eccbSdrh             }
2429a407eccbSdrh             nConflictCk--;
2430d901b168Sdrh             addrConflictCk++;
2431a407eccbSdrh           }
2432a407eccbSdrh           /* If the retest fails, issue an abort */
24332da8d6feSdrh           sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2434a407eccbSdrh 
2435a407eccbSdrh           sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
24362da8d6feSdrh         }
24370ca3e24bSdrh         seenReplace = 1;
24389cfcf5d4Sdrh         break;
24399cfcf5d4Sdrh       }
24409cfcf5d4Sdrh     }
244111e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
2442392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2443ed4c5469Sdrh     if( pUpsertClause
2444ed4c5469Sdrh      && upsertIpkReturn
2445ed4c5469Sdrh      && sqlite3UpsertNextIsIPK(pUpsertClause)
2446ed4c5469Sdrh     ){
244761e280adSdrh       sqlite3VdbeGoto(v, upsertIpkDelay+1);
244861e280adSdrh       sqlite3VdbeJumpHere(v, upsertIpkReturn);
244958b18a47Sdrh       upsertIpkReturn = 0;
245061e280adSdrh     }
24519cfcf5d4Sdrh   }
245284304506Sdrh 
245384304506Sdrh   /* If the IPK constraint is a REPLACE, run it last */
245484304506Sdrh   if( ipkTop ){
24556214d939Sdrh     sqlite3VdbeGoto(v, ipkTop);
245684304506Sdrh     VdbeComment((v, "Do IPK REPLACE"));
245766306d86Sdrh     assert( ipkBottom>0 );
245884304506Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
245984304506Sdrh   }
2460de630353Sdanielk1977 
2461a407eccbSdrh   /* Recheck all uniqueness constraints after replace triggers have run */
2462a407eccbSdrh   testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2463d3c468b7Sdrh   assert( regTrigCnt!=0 || nReplaceTrig==0 );
2464a407eccbSdrh   if( nReplaceTrig ){
2465a407eccbSdrh     sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2466a407eccbSdrh     if( !pPk ){
2467a407eccbSdrh       if( isUpdate ){
2468a407eccbSdrh         sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2469a407eccbSdrh         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2470a407eccbSdrh         VdbeCoverage(v);
2471a407eccbSdrh       }
2472a407eccbSdrh       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2473a407eccbSdrh       VdbeCoverage(v);
2474a407eccbSdrh       sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2475a407eccbSdrh     }else{
2476a407eccbSdrh       sqlite3VdbeGoto(v, addrRecheck);
2477a407eccbSdrh     }
2478a407eccbSdrh     sqlite3VdbeResolveLabel(v, lblRecheckOk);
2479a407eccbSdrh   }
2480a407eccbSdrh 
2481a7c3b93fSdrh   /* Generate the table record */
2482a7c3b93fSdrh   if( HasRowid(pTab) ){
2483a7c3b93fSdrh     int regRec = aRegIdx[ix];
24840b0b3a95Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2485a7c3b93fSdrh     sqlite3SetMakeRecordP5(v, pTab);
2486a7c3b93fSdrh     if( !bAffinityDone ){
2487a7c3b93fSdrh       sqlite3TableAffinity(v, pTab, 0);
2488a7c3b93fSdrh     }
2489a7c3b93fSdrh   }
2490a7c3b93fSdrh 
2491de630353Sdanielk1977   *pbMayReplace = seenReplace;
2492ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
24939cfcf5d4Sdrh }
24940ca3e24bSdrh 
2495d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
24960ca3e24bSdrh /*
2497585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2498585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed.
2499585ce192Sdrh **
2500585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2501585ce192Sdrh */
sqlite3SetMakeRecordP5(Vdbe * v,Table * pTab)2502585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2503585ce192Sdrh   u16 i;
2504585ce192Sdrh 
2505585ce192Sdrh   /* Records with omitted columns are only allowed for schema format
2506585ce192Sdrh   ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2507585ce192Sdrh   if( pTab->pSchema->file_format<2 ) return;
2508585ce192Sdrh 
25097e4acf7bSdrh   for(i=pTab->nCol-1; i>0; i--){
251079cf2b71Sdrh     if( pTab->aCol[i].iDflt!=0 ) break;
25117e4acf7bSdrh     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
25127e4acf7bSdrh   }
25137e4acf7bSdrh   sqlite3VdbeChangeP5(v, i+1);
2514585ce192Sdrh }
2515d447dcedSdrh #endif
2516585ce192Sdrh 
25170ca3e24bSdrh /*
2518fadc0e34Sdan ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2519fadc0e34Sdan ** number is iCur, and register regData contains the new record for the
2520fadc0e34Sdan ** PK index. This function adds code to invoke the pre-update hook,
2521fadc0e34Sdan ** if one is registered.
2522fadc0e34Sdan */
2523fadc0e34Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
codeWithoutRowidPreupdate(Parse * pParse,Table * pTab,int iCur,int regData)2524fadc0e34Sdan static void codeWithoutRowidPreupdate(
2525fadc0e34Sdan   Parse *pParse,                  /* Parse context */
2526fadc0e34Sdan   Table *pTab,                    /* Table being updated */
2527fadc0e34Sdan   int iCur,                       /* Cursor number for table */
2528fadc0e34Sdan   int regData                     /* Data containing new record */
2529fadc0e34Sdan ){
2530fadc0e34Sdan   Vdbe *v = pParse->pVdbe;
2531fadc0e34Sdan   int r = sqlite3GetTempReg(pParse);
2532fadc0e34Sdan   assert( !HasRowid(pTab) );
2533d01206ffSdrh   assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2534fadc0e34Sdan   sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2535fadc0e34Sdan   sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2536fadc0e34Sdan   sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2537fadc0e34Sdan   sqlite3ReleaseTempReg(pParse, r);
2538fadc0e34Sdan }
2539fadc0e34Sdan #else
2540fadc0e34Sdan # define codeWithoutRowidPreupdate(a,b,c,d)
2541fadc0e34Sdan #endif
2542fadc0e34Sdan 
2543fadc0e34Sdan /*
25440ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
25454adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
25466934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
254704adf416Sdrh ** rowid and the content to be inserted.
25480ca3e24bSdrh **
2549b419a926Sdrh ** The arguments to this routine should be the same as the first six
25504adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
25510ca3e24bSdrh */
sqlite3CompleteInsertion(Parse * pParse,Table * pTab,int iDataCur,int iIdxCur,int regNewData,int * aRegIdx,int update_flags,int appendBias,int useSeekResult)25524adee20fSdanielk1977 void sqlite3CompleteInsertion(
25530ca3e24bSdrh   Parse *pParse,      /* The parser context */
25540ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
255526198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
255626198bb4Sdrh   int iIdxCur,        /* First index cursor */
25576934fc7bSdrh   int regNewData,     /* Range of content */
2558aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
2559f91c1318Sdan   int update_flags,   /* True for UPDATE, False for INSERT */
2560de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
2561de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
25620ca3e24bSdrh ){
25636934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
25646934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
25656934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
25666934fc7bSdrh   int i;              /* Loop counter */
25670ca3e24bSdrh 
2568f91c1318Sdan   assert( update_flags==0
2569f91c1318Sdan        || update_flags==OPFLAG_ISUPDATE
2570f91c1318Sdan        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2571f91c1318Sdan   );
2572f91c1318Sdan 
2573f0b41745Sdrh   v = pParse->pVdbe;
25740ca3e24bSdrh   assert( v!=0 );
2575f38524d2Sdrh   assert( !IsView(pTab) );  /* This table is not a VIEW */
2576b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2577d35bdd6cSdrh     /* All REPLACE indexes are at the end of the list */
2578d35bdd6cSdrh     assert( pIdx->onError!=OE_Replace
2579d35bdd6cSdrh          || pIdx->pNext==0
2580d35bdd6cSdrh          || pIdx->pNext->onError==OE_Replace );
2581aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
2582b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
2583b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2584688852abSdrh       VdbeCoverage(v);
2585b2b9d3d7Sdrh     }
2586cb9a3643Sdan     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
258748dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
25886546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
2589f91c1318Sdan       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2590cb9a3643Sdan       if( update_flags==0 ){
2591fadc0e34Sdan         codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2592de630353Sdanielk1977       }
2593cb9a3643Sdan     }
2594cb9a3643Sdan     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2595cb9a3643Sdan                          aRegIdx[i]+1,
2596cb9a3643Sdan                          pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
25979b34abeeSdrh     sqlite3VdbeChangeP5(v, pik_flags);
25980ca3e24bSdrh   }
2599ec95c441Sdrh   if( !HasRowid(pTab) ) return;
26004794f735Sdrh   if( pParse->nested ){
26014794f735Sdrh     pik_flags = 0;
26024794f735Sdrh   }else{
260394eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
2604f91c1318Sdan     pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
26054794f735Sdrh   }
2606e4d90813Sdrh   if( appendBias ){
2607e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
2608e4d90813Sdrh   }
2609de630353Sdanielk1977   if( useSeekResult ){
2610de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
2611de630353Sdanielk1977   }
2612a7c3b93fSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
261394eb6a14Sdanielk1977   if( !pParse->nested ){
2614f14b7fb7Sdrh     sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
261594eb6a14Sdanielk1977   }
2616b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
26170ca3e24bSdrh }
2618cd44690aSdrh 
2619cd44690aSdrh /*
262026198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
262126198bb4Sdrh ** code to open and initialized those cursors.
2622aa9b8963Sdrh **
262326198bb4Sdrh ** The cursor for the object that contains the complete data (normally
262426198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
262526198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
262626198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
262726198bb4Sdrh **
262826198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
262926198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
263026198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
263126198bb4Sdrh **
263226198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
263326198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
263426198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
263526198bb4Sdrh ** pTab->pIndex list.
2636b6b4b79fSdrh **
2637b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the
2638b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized.
2639cd44690aSdrh */
sqlite3OpenTableAndIndices(Parse * pParse,Table * pTab,int op,u8 p5,int iBase,u8 * aToOpen,int * piDataCur,int * piIdxCur)2640aa9b8963Sdrh int sqlite3OpenTableAndIndices(
2641290c1948Sdrh   Parse *pParse,   /* Parsing context */
2642290c1948Sdrh   Table *pTab,     /* Table to be opened */
264326198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
2644b89aeb6aSdrh   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
264526198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
26466a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
264726198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
264826198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
2649290c1948Sdrh ){
2650cd44690aSdrh   int i;
26514cbdda9eSdrh   int iDb;
26526a53499aSdrh   int iDataCur;
2653cd44690aSdrh   Index *pIdx;
26544cbdda9eSdrh   Vdbe *v;
26554cbdda9eSdrh 
265626198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
2657fd261ec6Sdan   assert( op==OP_OpenWrite || p5==0 );
265826198bb4Sdrh   if( IsVirtual(pTab) ){
2659b6b4b79fSdrh     /* This routine is a no-op for virtual tables. Leave the output
266033d28ab4Sdrh     ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
266133d28ab4Sdrh     ** for improved error detection. */
266233d28ab4Sdrh     *piDataCur = *piIdxCur = -999;
266326198bb4Sdrh     return 0;
266426198bb4Sdrh   }
26654cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2666f0b41745Sdrh   v = pParse->pVdbe;
2667cd44690aSdrh   assert( v!=0 );
266826198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
26696a53499aSdrh   iDataCur = iBase++;
26706a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
26716a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
26726a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
26736fbe41acSdrh   }else{
267426198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
26756fbe41acSdrh   }
26766a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
267726198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
267826198bb4Sdrh     int iIdxCur = iBase++;
2679da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
268061441c34Sdan     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
268161441c34Sdan       if( piDataCur ) *piDataCur = iIdxCur;
268261441c34Sdan       p5 = 0;
268361441c34Sdan     }
26846a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
26852ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
26862ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2687b89aeb6aSdrh       sqlite3VdbeChangeP5(v, p5);
268861441c34Sdan       VdbeComment((v, "%s", pIdx->zName));
2689b89aeb6aSdrh     }
26906a53499aSdrh   }
269126198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
269226198bb4Sdrh   return i;
2693cd44690aSdrh }
26949d9cf229Sdrh 
269591c58e23Sdrh 
269691c58e23Sdrh #ifdef SQLITE_TEST
269791c58e23Sdrh /*
269891c58e23Sdrh ** The following global variable is incremented whenever the
269991c58e23Sdrh ** transfer optimization is used.  This is used for testing
270091c58e23Sdrh ** purposes only - to make sure the transfer optimization really
270160ec914cSpeter.d.reid ** is happening when it is supposed to.
270291c58e23Sdrh */
270391c58e23Sdrh int sqlite3_xferopt_count;
270491c58e23Sdrh #endif /* SQLITE_TEST */
270591c58e23Sdrh 
270691c58e23Sdrh 
27079d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
27089d9cf229Sdrh /*
27099d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
27109d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
27119d9cf229Sdrh ** for a compatible index:
27129d9cf229Sdrh **
27139d9cf229Sdrh **    *   The index is over the same set of columns
27149d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
27159d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
27169d9cf229Sdrh **    *   The same collating sequence on each column
2717b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
27189d9cf229Sdrh */
xferCompatibleIndex(Index * pDest,Index * pSrc)27199d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
27209d9cf229Sdrh   int i;
27219d9cf229Sdrh   assert( pDest && pSrc );
27229d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
27231e7c00e6Sdrh   if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
27249d9cf229Sdrh     return 0;   /* Different number of columns */
27259d9cf229Sdrh   }
27269d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
27279d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
27289d9cf229Sdrh   }
2729bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
27309d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
27319d9cf229Sdrh       return 0;   /* Different columns indexed */
27329d9cf229Sdrh     }
27334b92f98cSdrh     if( pSrc->aiColumn[i]==XN_EXPR ){
27341f9ca2c8Sdrh       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
27355aa550cfSdan       if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
27361f9ca2c8Sdrh                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
27371f9ca2c8Sdrh         return 0;   /* Different expressions in the index */
27381f9ca2c8Sdrh       }
27391f9ca2c8Sdrh     }
27409d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
27419d9cf229Sdrh       return 0;   /* Different sort orders */
27429d9cf229Sdrh     }
27430472af91Sdrh     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
274460a713c6Sdrh       return 0;   /* Different collating sequences */
27459d9cf229Sdrh     }
27469d9cf229Sdrh   }
27475aa550cfSdan   if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2748b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
2749b2b9d3d7Sdrh   }
27509d9cf229Sdrh 
27519d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
27529d9cf229Sdrh   return 1;
27539d9cf229Sdrh }
27549d9cf229Sdrh 
27559d9cf229Sdrh /*
27569d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
27579d9cf229Sdrh **
27589d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
27599d9cf229Sdrh **
2760ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
276160ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves
2762ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
27639d9cf229Sdrh **
2764ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2765ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
2766ccdf1baeSdrh ** embedded in the code for details.
27679d9cf229Sdrh **
2768ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
2769ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
2770ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
2771ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
2772ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
2773ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
2774ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
2775ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
2776ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
27779d9cf229Sdrh **
2778ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
27799d9cf229Sdrh */
xferOptimization(Parse * pParse,Table * pDest,Select * pSelect,int onError,int iDbDest)27809d9cf229Sdrh static int xferOptimization(
27819d9cf229Sdrh   Parse *pParse,        /* Parser context */
27829d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
27839d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
27849d9cf229Sdrh   int onError,          /* How to handle constraint errors */
27859d9cf229Sdrh   int iDbDest           /* The database of pDest */
27869d9cf229Sdrh ){
2787e34162b1Sdan   sqlite3 *db = pParse->db;
27889d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
27899d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
27909d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
27917601294aSdrh   SrcItem *pItem;                  /* An element of pSelect->pSrc */
27929d9cf229Sdrh   int i;                           /* Loop counter */
27939d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
27949d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
27959d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
2796da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
2797da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
27989d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
27996a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
2800f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
2801b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
28029d9cf229Sdrh 
2803935c3722Sdrh   assert( pSelect!=0 );
2804ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
2805ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
2806ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
2807ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
2808ebbf08a0Sdan     return 0;
2809ebbf08a0Sdan   }
28109d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
281144266ec6Sdrh   if( IsVirtual(pDest) ){
28129d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
28139d9cf229Sdrh   }
28149d9cf229Sdrh #endif
28159d9cf229Sdrh   if( onError==OE_Default ){
2816e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2817e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
28189d9cf229Sdrh   }
28195ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
28209d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
28219d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
28229d9cf229Sdrh   }
28239d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
28249d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
28259d9cf229Sdrh   }
28269d9cf229Sdrh   if( pSelect->pWhere ){
28279d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
28289d9cf229Sdrh   }
28299d9cf229Sdrh   if( pSelect->pOrderBy ){
28309d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
28319d9cf229Sdrh   }
28328103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
28338103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
28349d9cf229Sdrh   if( pSelect->pGroupBy ){
28359d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
28369d9cf229Sdrh   }
28379d9cf229Sdrh   if( pSelect->pLimit ){
28389d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
28399d9cf229Sdrh   }
28409d9cf229Sdrh   if( pSelect->pPrior ){
28419d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
28429d9cf229Sdrh   }
28437d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
28449d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
28459d9cf229Sdrh   }
28469d9cf229Sdrh   pEList = pSelect->pEList;
28479d9cf229Sdrh   assert( pEList!=0 );
28489d9cf229Sdrh   if( pEList->nExpr!=1 ){
28499d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
28509d9cf229Sdrh   }
28519d9cf229Sdrh   assert( pEList->a[0].pExpr );
28521a1d3cd2Sdrh   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
28539d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
28549d9cf229Sdrh   }
28559d9cf229Sdrh 
28569d9cf229Sdrh   /* At this point we have established that the statement is of the
28579d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
28589d9cf229Sdrh   ** we have to check the semantics.
28599d9cf229Sdrh   */
28609d9cf229Sdrh   pItem = pSelect->pSrc->a;
286141fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
28629d9cf229Sdrh   if( pSrc==0 ){
28639d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
28649d9cf229Sdrh   }
286521908b21Sdrh   if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
28661e32bed3Sdrh     testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
28679d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
28689d9cf229Sdrh   }
286955548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
287055548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
287155548273Sdrh   }
2872f38524d2Sdrh   if( !IsOrdinaryTable(pSrc) ){
2873f38524d2Sdrh     return 0;   /* tab2 may not be a view or virtual table */
28749d9cf229Sdrh   }
28759d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
28769d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
28779d9cf229Sdrh   }
28789d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
28799d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
28809d9cf229Sdrh   }
28817b4b74acSdrh   if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
28827b4b74acSdrh     return 0;   /* Cannot feed from a non-strict into a strict table */
28837b4b74acSdrh   }
28849d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
28859940e2aaSdan     Column *pDestCol = &pDest->aCol[i];
28869940e2aaSdan     Column *pSrcCol = &pSrc->aCol[i];
2887ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
28888257aa8dSdrh     if( (db->mDbFlags & DBFLAG_Vacuum)==0
2889aaea3143Sdan      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2890aaea3143Sdan     ){
2891ba68f8f3Sdan       return 0;    /* Neither table may have __hidden__ columns */
2892ba68f8f3Sdan     }
2893ba68f8f3Sdan #endif
28946ab61d70Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
28956ab61d70Sdrh     /* Even if tables t1 and t2 have identical schemas, if they contain
28966ab61d70Sdrh     ** generated columns, then this statement is semantically incorrect:
28976ab61d70Sdrh     **
28986ab61d70Sdrh     **     INSERT INTO t2 SELECT * FROM t1;
28996ab61d70Sdrh     **
29006ab61d70Sdrh     ** The reason is that generated column values are returned by the
29016ab61d70Sdrh     ** the SELECT statement on the right but the INSERT statement on the
29026ab61d70Sdrh     ** left wants them to be omitted.
29036ab61d70Sdrh     **
29046ab61d70Sdrh     ** Nevertheless, this is a useful notational shorthand to tell SQLite
29056ab61d70Sdrh     ** to do a bulk transfer all of the content from t1 over to t2.
29066ab61d70Sdrh     **
29076ab61d70Sdrh     ** We could, in theory, disable this (except for internal use by the
29086ab61d70Sdrh     ** VACUUM command where it is actually needed).  But why do that?  It
29096ab61d70Sdrh     ** seems harmless enough, and provides a useful service.
29106ab61d70Sdrh     */
2911ae3977a8Sdrh     if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
2912ae3977a8Sdrh         (pSrcCol->colFlags & COLFLAG_GENERATED) ){
29136ab61d70Sdrh       return 0;    /* Both columns have the same generated-column type */
2914ae3977a8Sdrh     }
29156ab61d70Sdrh     /* But the transfer is only allowed if both the source and destination
29166ab61d70Sdrh     ** tables have the exact same expressions for generated columns.
29176ab61d70Sdrh     ** This requirement could be relaxed for VIRTUAL columns, I suppose.
29186ab61d70Sdrh     */
29196ab61d70Sdrh     if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
292079cf2b71Sdrh       if( sqlite3ExprCompare(0,
292179cf2b71Sdrh              sqlite3ColumnExpr(pSrc, pSrcCol),
292279cf2b71Sdrh              sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
29236ab61d70Sdrh         testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
29246ab61d70Sdrh         testcase( pDestCol->colFlags & COLFLAG_STORED );
29256ab61d70Sdrh         return 0;  /* Different generator expressions */
29266ab61d70Sdrh       }
29276ab61d70Sdrh     }
29286ab61d70Sdrh #endif
29299940e2aaSdan     if( pDestCol->affinity!=pSrcCol->affinity ){
29309d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
29319d9cf229Sdrh     }
293265b40093Sdrh     if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
293365b40093Sdrh                         sqlite3ColumnColl(pSrcCol))!=0 ){
29349d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
29359d9cf229Sdrh     }
29369940e2aaSdan     if( pDestCol->notNull && !pSrcCol->notNull ){
29379d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
29389d9cf229Sdrh     }
2939453e0261Sdrh     /* Default values for second and subsequent columns need to match. */
2940ae3977a8Sdrh     if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
294179cf2b71Sdrh       Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
294279cf2b71Sdrh       Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
294379cf2b71Sdrh       assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
2944f9751074Sdrh       assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
294579cf2b71Sdrh       assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
2946f9751074Sdrh       assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
294779cf2b71Sdrh       if( (pDestExpr==0)!=(pSrcExpr==0)
294879cf2b71Sdrh        || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
294979cf2b71Sdrh                                        pSrcExpr->u.zToken)!=0)
29509940e2aaSdan       ){
29519940e2aaSdan         return 0;    /* Default values must be the same for all columns */
29529940e2aaSdan       }
29539d9cf229Sdrh     }
295494fa9c41Sdrh   }
29559d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
29565f1d1d9cSdrh     if( IsUniqueIndex(pDestIdx) ){
2957f33c9fadSdrh       destHasUniqueIdx = 1;
2958f33c9fadSdrh     }
29599d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
29609d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
29619d9cf229Sdrh     }
29629d9cf229Sdrh     if( pSrcIdx==0 ){
29639d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
29649d9cf229Sdrh     }
2965e3bd232eSdrh     if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
2966e3bd232eSdrh          && sqlite3FaultSim(411)==SQLITE_OK ){
2967e3bd232eSdrh       /* The sqlite3FaultSim() call allows this corruption test to be
2968e3bd232eSdrh       ** bypassed during testing, in order to exercise other corruption tests
2969e3bd232eSdrh       ** further downstream. */
297086223e8dSdrh       return 0;   /* Corrupt schema - two indexes on the same btree */
297186223e8dSdrh     }
29729d9cf229Sdrh   }
29737fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
2974619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
29758103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
29768103b7d2Sdrh   }
29777fc2f41bSdrh #endif
2978713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
2979713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
2980713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
2981713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
2982713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
2983713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
2984713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2985713de341Sdrh   */
298678b2fa86Sdrh   assert( IsOrdinaryTable(pDest) );
2987f38524d2Sdrh   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
2988713de341Sdrh     return 0;
2989713de341Sdrh   }
2990713de341Sdrh #endif
2991e34162b1Sdan   if( (db->flags & SQLITE_CountRows)!=0 ){
2992ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
29931696124dSdan   }
29949d9cf229Sdrh 
2995ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
2996ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
2997ccdf1baeSdrh   ** table (tab1) is initially empty.
29989d9cf229Sdrh   */
2999dd73521bSdrh #ifdef SQLITE_TEST
3000dd73521bSdrh   sqlite3_xferopt_count++;
3001dd73521bSdrh #endif
3002e34162b1Sdan   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
30039d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
3004f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
30059d9cf229Sdrh   iSrc = pParse->nTab++;
30069d9cf229Sdrh   iDest = pParse->nTab++;
30076a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
300855548273Sdrh   regData = sqlite3GetTempReg(pParse);
30097aae7358Sdan   sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
301055548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
30119d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
3012427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
30138257aa8dSdrh   if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
3014e34162b1Sdan       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
3015ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
3016ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
3017e34162b1Sdan   )){
3018ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
3019e34162b1Sdan     ** only if the destination table is initially empty. Unless the
30208257aa8dSdrh     ** DBFLAG_Vacuum flag is set, this block generates code to make
30218257aa8dSdrh     ** that determination. If DBFLAG_Vacuum is set, then the destination
3022e34162b1Sdan     ** table is always empty.
3023e34162b1Sdan     **
3024e34162b1Sdan     ** Conditions under which the destination must be empty:
3025f33c9fadSdrh     **
3026ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3027ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
3028ccdf1baeSdrh     **     of index entries might need to change.)
3029ccdf1baeSdrh     **
3030ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
3031ccdf1baeSdrh     **     is unable to test uniqueness.)
3032ccdf1baeSdrh     **
3033ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
30349d9cf229Sdrh     */
3035688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
30362991ba05Sdrh     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
30379d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
30389d9cf229Sdrh   }
3039427ebba1Sdan   if( HasRowid(pSrc) ){
3040c9b9deaeSdrh     u8 insFlags;
30419d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3042688852abSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
304342242dedSdrh     if( pDest->iPKey>=0 ){
3044b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3045036e0675Sdan       if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
30464031bafaSdrh         sqlite3VdbeVerifyAbortable(v, onError);
3047b7654111Sdrh         addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3048688852abSdrh         VdbeCoverage(v);
3049f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pDest);
30509d9cf229Sdrh         sqlite3VdbeJumpHere(v, addr2);
3051036e0675Sdan       }
3052b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
30534e61e883Sdrh     }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3054b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
305595bad4c7Sdrh     }else{
3056b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
30577d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
305895bad4c7Sdrh     }
30597aae7358Sdan 
30608257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
306186b40dfdSdrh       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
30627aae7358Sdan       insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3063c9b9deaeSdrh     }else{
30647aae7358Sdan       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
30657aae7358Sdan     }
30667aae7358Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3067a55a839aSdan     if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
306851f37b2bSdrh       sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
30697aae7358Sdan       insFlags &= ~OPFLAG_PREFORMAT;
3070a55a839aSdan     }else
3071fadc0e34Sdan #endif
3072a55a839aSdan     {
3073a55a839aSdan       sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3074a55a839aSdan     }
3075a55a839aSdan     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3076a55a839aSdan     if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3077a55a839aSdan       sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3078a55a839aSdan     }
3079c9b9deaeSdrh     sqlite3VdbeChangeP5(v, insFlags);
30807aae7358Sdan 
3081688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
308255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
308355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3084da475b8dSdrh   }else{
3085da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3086da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
308755548273Sdrh   }
30889d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
308941b9ca25Sdrh     u8 idxInsFlags = 0;
30901b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
30919d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
30929d9cf229Sdrh     }
30939d9cf229Sdrh     assert( pSrcIdx );
30942ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
30952ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3096d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
30972ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
30982ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
309959885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3100207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
3101688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
31028257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
3103e34162b1Sdan       /* This INSERT command is part of a VACUUM operation, which guarantees
3104e34162b1Sdan       ** that the destination table is empty. If all indexed columns use
3105e34162b1Sdan       ** collation sequence BINARY, then it can also be assumed that the
3106e34162b1Sdan       ** index will be populated by inserting keys in strictly sorted
3107e34162b1Sdan       ** order. In this case, instead of seeking within the b-tree as part
310886b40dfdSdrh       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3109e34162b1Sdan       ** OP_IdxInsert to seek to the point within the b-tree where each key
3110e34162b1Sdan       ** should be inserted. This is faster.
3111e34162b1Sdan       **
3112e34162b1Sdan       ** If any of the indexed columns use a collation sequence other than
3113e34162b1Sdan       ** BINARY, this optimization is disabled. This is because the user
3114e34162b1Sdan       ** might change the definition of a collation sequence and then run
3115e34162b1Sdan       ** a VACUUM command. In that case keys may not be written in strictly
3116e34162b1Sdan       ** sorted order.  */
3117e34162b1Sdan       for(i=0; i<pSrcIdx->nColumn; i++){
3118f19aa5faSdrh         const char *zColl = pSrcIdx->azColl[i];
3119f19aa5faSdrh         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3120e34162b1Sdan       }
3121e34162b1Sdan       if( i==pSrcIdx->nColumn ){
31227aae7358Sdan         idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
312386b40dfdSdrh         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3124a06eafc8Sdrh         sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3125e34162b1Sdan       }
3126c84ad318Sdrh     }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
312741b9ca25Sdrh       idxInsFlags |= OPFLAG_NCHANGE;
312841b9ca25Sdrh     }
31297aae7358Sdan     if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
313051f37b2bSdrh       sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3131a55a839aSdan       if( (db->mDbFlags & DBFLAG_Vacuum)==0
3132a55a839aSdan        && !HasRowid(pDest)
3133a55a839aSdan        && IsPrimaryKeyIndex(pDestIdx)
3134a55a839aSdan       ){
3135fadc0e34Sdan         codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3136fadc0e34Sdan       }
31377aae7358Sdan     }
31389b4eaebcSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
31399b4eaebcSdrh     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3140688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
31419d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
314255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
314355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
31449d9cf229Sdrh   }
3145aceb31b1Sdrh   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3146b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
3147b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
31489d9cf229Sdrh   if( emptyDestTest ){
31491dd518cfSdrh     sqlite3AutoincrementEnd(pParse);
315066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
31519d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
315266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
31539d9cf229Sdrh     return 0;
31549d9cf229Sdrh   }else{
31559d9cf229Sdrh     return 1;
31569d9cf229Sdrh   }
31579d9cf229Sdrh }
31589d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
3159