xref: /sqlite-3.40.0/src/insert.c (revision c27ea2ae)
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 */
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) );
352ec2fb22Sdrh   v = sqlite3GetVdbe(pParse);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
372ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
382ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
39ec95c441Sdrh   if( HasRowid(pTab) ){
407e508f1eSdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb,
417e508f1eSdrh                          pTab->nCol - pTab->nVCol);
42bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
4326198bb4Sdrh   }else{
44dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
45dd9930efSdrh     assert( pPk!=0 );
46afe028a8Sdrh     assert( pPk->tnum==pTab->tnum );
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 */
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 );
991f9ca2c8Sdrh         assert( pIdx->aColExpr!=0 );
1006860e6faSdrh         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
10181506b88Sdrh       }
10296fb16eeSdrh       if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
1037314495fSdrh       if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
1046860e6faSdrh       pIdx->zColAff[n] = aff;
1051f9ca2c8Sdrh     }
1062d401ab8Sdrh     pIdx->zColAff[n] = 0;
107a37cdde0Sdanielk1977   }
1083d1bfeaaSdanielk1977 
10969f8bb9cSdan   return pIdx->zColAff;
110a37cdde0Sdanielk1977 }
111a37cdde0Sdanielk1977 
112a37cdde0Sdanielk1977 /*
11357bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been
11405883a34Sdrh ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
11557bf4a8eSdrh **
11605883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
11757bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
11857bf4a8eSdrh ** for register iReg and following.  Or if affinities exists and iReg==0,
11957bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should  be
12057bf4a8eSdrh ** an OP_MakeRecord) to the affinity string.
12157bf4a8eSdrh **
122b6e8fd10Sdrh ** A column affinity string has one character per column:
123a37cdde0Sdanielk1977 **
124a37cdde0Sdanielk1977 **  Character      Column affinity
125a37cdde0Sdanielk1977 **  ------------------------------
12605883a34Sdrh **  'A'            BLOB
1274583c37cSdrh **  'B'            TEXT
1284583c37cSdrh **  'C'            NUMERIC
1294583c37cSdrh **  'D'            INTEGER
1304583c37cSdrh **  'E'            REAL
131a37cdde0Sdanielk1977 */
13257bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
1333d1bfeaaSdanielk1977   int i;
13457bf4a8eSdrh   char *zColAff = pTab->zColAff;
13557bf4a8eSdrh   if( zColAff==0 ){
136abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
137b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1383d1bfeaaSdanielk1977     if( !zColAff ){
1394a642b60Sdrh       sqlite3OomFault(db);
140a37cdde0Sdanielk1977       return;
1413d1bfeaaSdanielk1977     }
1423d1bfeaaSdanielk1977 
1433d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
14496fb16eeSdrh       assert( pTab->aCol[i].affinity!=0 );
145a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1463d1bfeaaSdanielk1977     }
14757bf4a8eSdrh     do{
14857bf4a8eSdrh       zColAff[i--] = 0;
14996fb16eeSdrh     }while( i>=0 && zColAff[i]<=SQLITE_AFF_BLOB );
1503d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1513d1bfeaaSdanielk1977   }
1527301e774Sdrh   assert( zColAff!=0 );
1537301e774Sdrh   i = sqlite3Strlen30NN(zColAff);
15457bf4a8eSdrh   if( i ){
15557bf4a8eSdrh     if( iReg ){
15657bf4a8eSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
15757bf4a8eSdrh     }else{
15857bf4a8eSdrh       sqlite3VdbeChangeP4(v, -1, zColAff, i);
15957bf4a8eSdrh     }
16057bf4a8eSdrh   }
1613d1bfeaaSdanielk1977 }
1623d1bfeaaSdanielk1977 
1634d88778bSdanielk1977 /*
16448d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
165b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if
16648d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
167b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT.
1684d88778bSdanielk1977 */
16905a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){
170595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1714d88778bSdanielk1977   int i;
17248d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
173595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
174595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
175595a523aSdanielk1977 #endif
176595a523aSdanielk1977 
17705a86c5cSdrh   for(i=1; i<iEnd; i++){
17848d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
179ef0bea92Sdrh     assert( pOp!=0 );
180207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
18148d1178aSdrh       Index *pIndex;
182207872a4Sdanielk1977       int tnum = pOp->p2;
18348d1178aSdrh       if( tnum==pTab->tnum ){
18448d1178aSdrh         return 1;
18548d1178aSdrh       }
18648d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
18748d1178aSdrh         if( tnum==pIndex->tnum ){
18848d1178aSdrh           return 1;
18948d1178aSdrh         }
19048d1178aSdrh       }
19148d1178aSdrh     }
192543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
193595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1942dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
19566a5167bSdrh       assert( pOp->p4type==P4_VTAB );
19648d1178aSdrh       return 1;
1974d88778bSdanielk1977     }
198543165efSdrh #endif
1994d88778bSdanielk1977   }
2004d88778bSdanielk1977   return 0;
2014d88778bSdanielk1977 }
2023d1bfeaaSdanielk1977 
2039d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
2049d9cf229Sdrh /*
2050b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
2060b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
2079ef5e770Sdrh ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
2089ef5e770Sdrh ** table.  (Also return zero when doing a VACUUM since we do not want to
2099ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.)
2109d9cf229Sdrh **
2110b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
2120b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
2130b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
2140b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
2150b9f50d8Sdrh ** AutoincInfo structure is used.
2169d9cf229Sdrh **
217c8abbc11Sdrh ** Four consecutive registers are allocated:
2180b9f50d8Sdrh **
219c8abbc11Sdrh **   (1)  The name of the pTab table.
220c8abbc11Sdrh **   (2)  The maximum ROWID of pTab.
221c8abbc11Sdrh **   (3)  The rowid in sqlite_sequence of pTab
222c8abbc11Sdrh **   (4)  The original value of the max ROWID in pTab, or NULL if none
2230b9f50d8Sdrh **
2240b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2250b9f50d8Sdrh ** insert routine needs to know about.
2269d9cf229Sdrh */
2279d9cf229Sdrh static int autoIncBegin(
2289d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2299d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2309d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2319d9cf229Sdrh ){
2326a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
233186ebd41Sdrh   assert( pParse->db->aDb[iDb].pSchema!=0 );
2349ef5e770Sdrh   if( (pTab->tabFlags & TF_Autoincrement)!=0
2358257aa8dSdrh    && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
2369ef5e770Sdrh   ){
23765a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2380b9f50d8Sdrh     AutoincInfo *pInfo;
239186ebd41Sdrh     Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
240186ebd41Sdrh 
241186ebd41Sdrh     /* Verify that the sqlite_sequence table exists and is an ordinary
242186ebd41Sdrh     ** rowid table with exactly two columns.
243186ebd41Sdrh     ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
244186ebd41Sdrh     if( pSeqTab==0
245186ebd41Sdrh      || !HasRowid(pSeqTab)
246186ebd41Sdrh      || IsVirtual(pSeqTab)
247186ebd41Sdrh      || pSeqTab->nCol!=2
248186ebd41Sdrh     ){
249186ebd41Sdrh       pParse->nErr++;
250186ebd41Sdrh       pParse->rc = SQLITE_CORRUPT_SEQUENCE;
251186ebd41Sdrh       return 0;
252186ebd41Sdrh     }
2530b9f50d8Sdrh 
25465a7cd16Sdan     pInfo = pToplevel->pAinc;
2550b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2560b9f50d8Sdrh     if( pInfo==0 ){
257575fad65Sdrh       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
2580b9f50d8Sdrh       if( pInfo==0 ) return 0;
25965a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
26065a7cd16Sdan       pToplevel->pAinc = pInfo;
2610b9f50d8Sdrh       pInfo->pTab = pTab;
2620b9f50d8Sdrh       pInfo->iDb = iDb;
26365a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
26465a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
265c8abbc11Sdrh       pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
2660b9f50d8Sdrh     }
2670b9f50d8Sdrh     memId = pInfo->regCtr;
2689d9cf229Sdrh   }
2699d9cf229Sdrh   return memId;
2709d9cf229Sdrh }
2719d9cf229Sdrh 
2729d9cf229Sdrh /*
2730b9f50d8Sdrh ** This routine generates code that will initialize all of the
2740b9f50d8Sdrh ** register used by the autoincrement tracker.
2750b9f50d8Sdrh */
2760b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2770b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2780b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2790b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2800b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2810b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2820b9f50d8Sdrh 
283345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
284345ba7dbSdrh   ** only called from the top-level */
285345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
286c149f18fSdrh   assert( sqlite3IsToplevel(pParse) );
28776d462eeSdan 
2880b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2890b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2901b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
2911b32554bSdrh     static const VdbeOpList autoInc[] = {
2921b32554bSdrh       /* 0  */ {OP_Null,    0,  0, 0},
293c8abbc11Sdrh       /* 1  */ {OP_Rewind,  0, 10, 0},
2941b32554bSdrh       /* 2  */ {OP_Column,  0,  0, 0},
295c8abbc11Sdrh       /* 3  */ {OP_Ne,      0,  9, 0},
2961b32554bSdrh       /* 4  */ {OP_Rowid,   0,  0, 0},
2971b32554bSdrh       /* 5  */ {OP_Column,  0,  1, 0},
298c8abbc11Sdrh       /* 6  */ {OP_AddImm,  0,  0, 0},
299c8abbc11Sdrh       /* 7  */ {OP_Copy,    0,  0, 0},
300c8abbc11Sdrh       /* 8  */ {OP_Goto,    0, 11, 0},
301c8abbc11Sdrh       /* 9  */ {OP_Next,    0,  2, 0},
302c8abbc11Sdrh       /* 10 */ {OP_Integer, 0,  0, 0},
303c8abbc11Sdrh       /* 11 */ {OP_Close,   0,  0, 0}
3041b32554bSdrh     };
3051b32554bSdrh     VdbeOp *aOp;
3060b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
3070b9f50d8Sdrh     memId = p->regCtr;
3082120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3090b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
310076e85f5Sdrh     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
3111b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
3121b32554bSdrh     if( aOp==0 ) break;
3131b32554bSdrh     aOp[0].p2 = memId;
314c8abbc11Sdrh     aOp[0].p3 = memId+2;
3151b32554bSdrh     aOp[2].p3 = memId;
3161b32554bSdrh     aOp[3].p1 = memId-1;
3171b32554bSdrh     aOp[3].p3 = memId;
3181b32554bSdrh     aOp[3].p5 = SQLITE_JUMPIFNULL;
3191b32554bSdrh     aOp[4].p2 = memId+1;
3201b32554bSdrh     aOp[5].p3 = memId;
321c8abbc11Sdrh     aOp[6].p1 = memId;
322c8abbc11Sdrh     aOp[7].p2 = memId+2;
323c8abbc11Sdrh     aOp[7].p1 = memId;
324c8abbc11Sdrh     aOp[10].p2 = memId;
32504ab586bSdrh     if( pParse->nTab==0 ) pParse->nTab = 1;
3260b9f50d8Sdrh   }
3270b9f50d8Sdrh }
3280b9f50d8Sdrh 
3290b9f50d8Sdrh /*
3309d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
3319d9cf229Sdrh **
3321b32554bSdrh ** This routine should be called when the regRowid register holds a
3339d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
3349d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
3351b32554bSdrh ** memory cell is updated.
3369d9cf229Sdrh */
3376a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
3389d9cf229Sdrh   if( memId>0 ){
3396a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
3409d9cf229Sdrh   }
3419d9cf229Sdrh }
3429d9cf229Sdrh 
3439d9cf229Sdrh /*
3440b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
3450b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
3460b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
3470b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
3480b9f50d8Sdrh ** routine just before the "exit" code.
3499d9cf229Sdrh */
3501b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
3510b9f50d8Sdrh   AutoincInfo *p;
3529d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
3530b9f50d8Sdrh   sqlite3 *db = pParse->db;
3546a288a33Sdrh 
3559d9cf229Sdrh   assert( v );
3560b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3571b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
3581b32554bSdrh     static const VdbeOpList autoIncEnd[] = {
3591b32554bSdrh       /* 0 */ {OP_NotNull,     0, 2, 0},
3601b32554bSdrh       /* 1 */ {OP_NewRowid,    0, 0, 0},
3611b32554bSdrh       /* 2 */ {OP_MakeRecord,  0, 2, 0},
3621b32554bSdrh       /* 3 */ {OP_Insert,      0, 0, 0},
3631b32554bSdrh       /* 4 */ {OP_Close,       0, 0, 0}
3641b32554bSdrh     };
3651b32554bSdrh     VdbeOp *aOp;
3660b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3670b9f50d8Sdrh     int iRec;
3680b9f50d8Sdrh     int memId = p->regCtr;
3690b9f50d8Sdrh 
3700b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3712120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
372c8abbc11Sdrh     sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
373c8abbc11Sdrh     VdbeCoverage(v);
3740b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3751b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
3761b32554bSdrh     if( aOp==0 ) break;
3771b32554bSdrh     aOp[0].p1 = memId+1;
3781b32554bSdrh     aOp[1].p2 = memId+1;
3791b32554bSdrh     aOp[2].p1 = memId-1;
3801b32554bSdrh     aOp[2].p3 = iRec;
3811b32554bSdrh     aOp[3].p2 = iRec;
3821b32554bSdrh     aOp[3].p3 = memId+1;
3831b32554bSdrh     aOp[3].p5 = OPFLAG_APPEND;
3840b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3859d9cf229Sdrh   }
3869d9cf229Sdrh }
3871b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){
3881b32554bSdrh   if( pParse->pAinc ) autoIncrementEnd(pParse);
3891b32554bSdrh }
3909d9cf229Sdrh #else
3919d9cf229Sdrh /*
3929d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3939d9cf229Sdrh ** above are all no-ops
3949d9cf229Sdrh */
3959d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
396287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3979d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3989d9cf229Sdrh 
3999d9cf229Sdrh 
4009d9cf229Sdrh /* Forward declaration */
4019d9cf229Sdrh static int xferOptimization(
4029d9cf229Sdrh   Parse *pParse,        /* Parser context */
4039d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4049d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4059d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4069d9cf229Sdrh   int iDbDest           /* The database of pDest */
4079d9cf229Sdrh );
4089d9cf229Sdrh 
4093d1bfeaaSdanielk1977 /*
410d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
411cce7d176Sdrh **
412a21f78b9Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
4131ccde15dSdrh **    insert into TABLE (IDLIST) select
414a21f78b9Sdrh **    insert into TABLE (IDLIST) default values
415cce7d176Sdrh **
4161ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
417a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted.
418a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
419a21f78b9Sdrh ** is omitted.
4201ccde15dSdrh **
421a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the
422a21f78b9Sdrh ** first two forms shown above.  A VALUES clause is really just short-hand
423a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else
424a21f78b9Sdrh ** that follows.  If the pSelect parameter is NULL, that means that the
425a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended.
426142e30dfSdrh **
4279d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
428a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes
429e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
430e00ee6ebSdrh ** the "1st template"):
431142e30dfSdrh **
432142e30dfSdrh **         open write cursor to <table> and its indices
433ec95c441Sdrh **         put VALUES clause expressions into registers
434142e30dfSdrh **         write the resulting record into <table>
435142e30dfSdrh **         cleanup
436142e30dfSdrh **
4379d9cf229Sdrh ** The three remaining templates assume the statement is of the form
438142e30dfSdrh **
439142e30dfSdrh **   INSERT INTO <table> SELECT ...
440142e30dfSdrh **
4419d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4429d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4439d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4449d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4459d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4469d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4479d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
448e00ee6ebSdrh ** template.  This is the 2nd template.
4499d9cf229Sdrh **
4509d9cf229Sdrh **         open a write cursor to <table>
4519d9cf229Sdrh **         open read cursor on <table2>
4529d9cf229Sdrh **         transfer all records in <table2> over to <table>
4539d9cf229Sdrh **         close cursors
4549d9cf229Sdrh **         foreach index on <table>
4559d9cf229Sdrh **           open a write cursor on the <table> index
4569d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4579d9cf229Sdrh **           transfer all records from the read to the write cursors
4589d9cf229Sdrh **           close cursors
4599d9cf229Sdrh **         end foreach
4609d9cf229Sdrh **
461e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4629d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4639d9cf229Sdrh ** The generated code follows this template:
464142e30dfSdrh **
465e00ee6ebSdrh **         X <- A
466142e30dfSdrh **         goto B
467142e30dfSdrh **      A: setup for the SELECT
4689d9cf229Sdrh **         loop over the rows in the SELECT
469e00ee6ebSdrh **           load values into registers R..R+n
470e00ee6ebSdrh **           yield X
471142e30dfSdrh **         end loop
472142e30dfSdrh **         cleanup after the SELECT
47381cf13ecSdrh **         end-coroutine X
474e00ee6ebSdrh **      B: open write cursor to <table> and its indices
47581cf13ecSdrh **      C: yield X, at EOF goto D
476e00ee6ebSdrh **         insert the select result into <table> from R..R+n
477e00ee6ebSdrh **         goto C
478142e30dfSdrh **      D: cleanup
479142e30dfSdrh **
480e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
481142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
482142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
48360ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of
484142e30dfSdrh ** the select.  The template is like this:
485142e30dfSdrh **
486e00ee6ebSdrh **         X <- A
487142e30dfSdrh **         goto B
488142e30dfSdrh **      A: setup for the SELECT
489142e30dfSdrh **         loop over the tables in the SELECT
490e00ee6ebSdrh **           load value into register R..R+n
491e00ee6ebSdrh **           yield X
492142e30dfSdrh **         end loop
493142e30dfSdrh **         cleanup after the SELECT
49481cf13ecSdrh **         end co-routine R
495e00ee6ebSdrh **      B: open temp table
49681cf13ecSdrh **      L: yield X, at EOF goto M
497e00ee6ebSdrh **         insert row from R..R+n into temp table
498e00ee6ebSdrh **         goto L
499e00ee6ebSdrh **      M: open write cursor to <table> and its indices
500e00ee6ebSdrh **         rewind temp table
501e00ee6ebSdrh **      C: loop over rows of intermediate table
502142e30dfSdrh **           transfer values form intermediate table into <table>
503e00ee6ebSdrh **         end loop
504e00ee6ebSdrh **      D: cleanup
505cce7d176Sdrh */
5064adee20fSdanielk1977 void sqlite3Insert(
507cce7d176Sdrh   Parse *pParse,        /* Parser context */
508113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
5095974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5109cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5112c2e844aSdrh   int onError,          /* How to handle constraint errors */
51246d2e5c3Sdrh   Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
513cce7d176Sdrh ){
5146a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5156a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
51660ffc807Sdrh   int i, j;             /* Loop counters */
5175974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5185974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
519967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5206a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
52126198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
52226198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
523d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5240ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
525cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
526e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
527e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
5282eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5296a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
53005a86c5cSdrh   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
53105a86c5cSdrh   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
53205a86c5cSdrh   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
533a21f78b9Sdrh   u8 bIdListInOrder;    /* True if IDLIST is in table order */
53475593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
535*c27ea2aeSdrh   int iRegStore;        /* Register in which to store next column */
536cce7d176Sdrh 
5376a288a33Sdrh   /* Register allocations */
5381bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5396a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5406a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5416a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5426a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5436a288a33Sdrh   int regData;          /* register holding first column to insert */
544aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5456a288a33Sdrh 
546798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
547798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5482f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5492f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
550798da52cSdrh #endif
551c3f9bad2Sdanielk1977 
55217435752Sdrh   db = pParse->db;
55317435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5546f7adc8aSdrh     goto insert_cleanup;
5556f7adc8aSdrh   }
5564c883487Sdrh   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
557daffd0e5Sdrh 
55875593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
559a21f78b9Sdrh   ** single row (the common case) then keep that one row of values
560a21f78b9Sdrh   ** and discard the other (unused) parts of the pSelect object
56175593d96Sdrh   */
56275593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
56375593d96Sdrh     pList = pSelect->pEList;
56475593d96Sdrh     pSelect->pEList = 0;
56575593d96Sdrh     sqlite3SelectDelete(db, pSelect);
56675593d96Sdrh     pSelect = 0;
56775593d96Sdrh   }
56875593d96Sdrh 
5691ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5701ccde15dSdrh   */
571113088ecSdrh   assert( pTabList->nSrc==1 );
5724adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
573c3f9bad2Sdanielk1977   if( pTab==0 ){
574c3f9bad2Sdanielk1977     goto insert_cleanup;
575c3f9bad2Sdanielk1977   }
576da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
577da184236Sdanielk1977   assert( iDb<db->nDb );
578a0daa751Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
579a0daa751Sdrh                        db->aDb[iDb].zDbSName) ){
5801962bda7Sdrh     goto insert_cleanup;
5811962bda7Sdrh   }
582ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
583c3f9bad2Sdanielk1977 
584b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
585b7f9164eSdrh   ** inserted into is a view
586b7f9164eSdrh   */
587b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
5882f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
589b7f9164eSdrh   isView = pTab->pSelect!=0;
590b7f9164eSdrh #else
5912f886d1dSdanielk1977 # define pTrigger 0
5922f886d1dSdanielk1977 # define tmask 0
593b7f9164eSdrh # define isView 0
594b7f9164eSdrh #endif
595b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
596b7f9164eSdrh # undef isView
597b7f9164eSdrh # define isView 0
598b7f9164eSdrh #endif
5992f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
600b7f9164eSdrh 
601f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
602d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
603f573c99bSdrh   */
604b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
605f573c99bSdrh     goto insert_cleanup;
606f573c99bSdrh   }
607f573c99bSdrh 
608d82b5021Sdrh   /* Cannot insert into a read-only table.
609595a523aSdanielk1977   */
610595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
611595a523aSdanielk1977     goto insert_cleanup;
612595a523aSdanielk1977   }
613595a523aSdanielk1977 
6141ccde15dSdrh   /* Allocate a VDBE
6151ccde15dSdrh   */
6164adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6175974a30fSdrh   if( v==0 ) goto insert_cleanup;
6184794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6192f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6201ccde15dSdrh 
6219d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6229d9cf229Sdrh   /* If the statement is of the form
6239d9cf229Sdrh   **
6249d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6259d9cf229Sdrh   **
6269d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6279d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
628e00ee6ebSdrh   **
629e00ee6ebSdrh   ** This is the 2nd template.
6309d9cf229Sdrh   */
6319d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6322f886d1dSdanielk1977     assert( !pTrigger );
6339d9cf229Sdrh     assert( pList==0 );
6340b9f50d8Sdrh     goto insert_end;
6359d9cf229Sdrh   }
6369d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6379d9cf229Sdrh 
6382958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6396a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6402958a4e6Sdrh   */
6416a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6422958a4e6Sdrh 
64305a86c5cSdrh   /* Allocate registers for holding the rowid of the new row,
64460ec914cSpeter.d.reid   ** the content of the new row, and the assembled row record.
6451ccde15dSdrh   */
64605a86c5cSdrh   regRowid = regIns = pParse->nMem+1;
64705a86c5cSdrh   pParse->nMem += pTab->nCol + 1;
648034ca14fSdanielk1977   if( IsVirtual(pTab) ){
64905a86c5cSdrh     regRowid++;
65005a86c5cSdrh     pParse->nMem++;
651034ca14fSdanielk1977   }
65205a86c5cSdrh   regData = regRowid+1;
6531ccde15dSdrh 
6541ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6551ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6561ccde15dSdrh   ** remember the column indices.
657c8392586Sdrh   **
658c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
659d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
660d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
661c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
662d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
663d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
6641ccde15dSdrh   */
665a21f78b9Sdrh   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
666967e8b73Sdrh   if( pColumn ){
667967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
668967e8b73Sdrh       pColumn->a[i].idx = -1;
669cce7d176Sdrh     }
670967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
671cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6724adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
673967e8b73Sdrh           pColumn->a[i].idx = j;
67405a86c5cSdrh           if( i!=j ) bIdListInOrder = 0;
6754a32431cSdrh           if( j==pTab->iPKey ){
676d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
6774a32431cSdrh           }
6787e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
6797e508f1eSdrh           if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
6807e508f1eSdrh             sqlite3ErrorMsg(pParse,
6817e508f1eSdrh                "cannot INSERT into generated column \"%s\"",
6827e508f1eSdrh                pTab->aCol[j].zName);
6837e508f1eSdrh             goto insert_cleanup;
6847e508f1eSdrh           }
6857e508f1eSdrh #endif
686cce7d176Sdrh           break;
687cce7d176Sdrh         }
688cce7d176Sdrh       }
689cce7d176Sdrh       if( j>=pTab->nCol ){
690ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
691d82b5021Sdrh           ipkColumn = i;
692e48ae715Sdrh           bIdListInOrder = 0;
693a0217ba7Sdrh         }else{
6944adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
695da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
6961db95106Sdan           pParse->checkSchema = 1;
697cce7d176Sdrh           goto insert_cleanup;
698cce7d176Sdrh         }
699cce7d176Sdrh       }
700cce7d176Sdrh     }
701a0217ba7Sdrh   }
7021ccde15dSdrh 
703cce7d176Sdrh   /* Figure out how many columns of data are supplied.  If the data
704cce7d176Sdrh   ** is coming from a SELECT statement, then generate a co-routine that
705cce7d176Sdrh   ** produces a single row of the SELECT on each invocation.  The
706cce7d176Sdrh   ** co-routine is the common header to the 3rd and 4th templates.
707cce7d176Sdrh   */
7085f085269Sdrh   if( pSelect ){
709a21f78b9Sdrh     /* Data is coming from a SELECT or from a multi-row VALUES clause.
710a21f78b9Sdrh     ** Generate a co-routine to run the SELECT. */
71105a86c5cSdrh     int regYield;       /* Register holding co-routine entry-point */
71205a86c5cSdrh     int addrTop;        /* Top of the co-routine */
71305a86c5cSdrh     int rc;             /* Result code */
714cce7d176Sdrh 
71505a86c5cSdrh     regYield = ++pParse->nMem;
71605a86c5cSdrh     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
71705a86c5cSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
71805a86c5cSdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
71905a86c5cSdrh     dest.iSdst = bIdListInOrder ? regData : 0;
72005a86c5cSdrh     dest.nSdst = pTab->nCol;
72105a86c5cSdrh     rc = sqlite3Select(pParse, pSelect, &dest);
7222b596da8Sdrh     regFromSelect = dest.iSdst;
723992590beSdrh     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
7242fade2f7Sdrh     sqlite3VdbeEndCoroutine(v, regYield);
72505a86c5cSdrh     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
726cce7d176Sdrh     assert( pSelect->pEList );
727cce7d176Sdrh     nColumn = pSelect->pEList->nExpr;
728cce7d176Sdrh 
729cce7d176Sdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
730cce7d176Sdrh     ** should be written into a temporary table (template 4).  Set to
731cce7d176Sdrh     ** FALSE if each output row of the SELECT can be written directly into
732cce7d176Sdrh     ** the destination table (template 3).
733cce7d176Sdrh     **
734cce7d176Sdrh     ** A temp table must be used if the table being updated is also one
735cce7d176Sdrh     ** of the tables being read by the SELECT statement.  Also use a
736cce7d176Sdrh     ** temp table in the case of row triggers.
737cce7d176Sdrh     */
73805a86c5cSdrh     if( pTrigger || readsTable(pParse, iDb, pTab) ){
739cce7d176Sdrh       useTempTable = 1;
740cce7d176Sdrh     }
741cce7d176Sdrh 
742cce7d176Sdrh     if( useTempTable ){
743cce7d176Sdrh       /* Invoke the coroutine to extract information from the SELECT
744cce7d176Sdrh       ** and add it to a transient table srcTab.  The code generated
745cce7d176Sdrh       ** here is from the 4th template:
746cce7d176Sdrh       **
747cce7d176Sdrh       **      B: open temp table
74881cf13ecSdrh       **      L: yield X, goto M at EOF
749cce7d176Sdrh       **         insert row from R..R+n into temp table
750cce7d176Sdrh       **         goto L
751cce7d176Sdrh       **      M: ...
752cce7d176Sdrh       */
753cce7d176Sdrh       int regRec;          /* Register to hold packed record */
754cce7d176Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
75506280ee5Sdrh       int addrL;           /* Label "L" */
756cce7d176Sdrh 
757cce7d176Sdrh       srcTab = pParse->nTab++;
758cce7d176Sdrh       regRec = sqlite3GetTempReg(pParse);
759cce7d176Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
760cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
76106280ee5Sdrh       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
762cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
763cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
764cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
765076e85f5Sdrh       sqlite3VdbeGoto(v, addrL);
76606280ee5Sdrh       sqlite3VdbeJumpHere(v, addrL);
767cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
768cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
769cce7d176Sdrh     }
770cce7d176Sdrh   }else{
771a21f78b9Sdrh     /* This is the case if the data for the INSERT is coming from a
772a21f78b9Sdrh     ** single-row VALUES clause
773cce7d176Sdrh     */
774cce7d176Sdrh     NameContext sNC;
775cce7d176Sdrh     memset(&sNC, 0, sizeof(sNC));
776cce7d176Sdrh     sNC.pParse = pParse;
777cce7d176Sdrh     srcTab = -1;
778cce7d176Sdrh     assert( useTempTable==0 );
779fea870beSdrh     if( pList ){
780fea870beSdrh       nColumn = pList->nExpr;
781fea870beSdrh       if( sqlite3ResolveExprListNames(&sNC, pList) ){
782cce7d176Sdrh         goto insert_cleanup;
783cce7d176Sdrh       }
784fea870beSdrh     }else{
785fea870beSdrh       nColumn = 0;
786cce7d176Sdrh     }
787cce7d176Sdrh   }
788cce7d176Sdrh 
789aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
790d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
791d82b5021Sdrh   ** column index in the original table definition.
7924a32431cSdrh   */
793147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
794d82b5021Sdrh     ipkColumn = pTab->iPKey;
7954a32431cSdrh   }
7964a32431cSdrh 
797cce7d176Sdrh   /* Make sure the number of columns in the source data matches the number
798cce7d176Sdrh   ** of columns to be inserted into the table.
799cce7d176Sdrh   */
800cce7d176Sdrh   for(i=0; i<pTab->nCol; i++){
8017e508f1eSdrh     if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
802cce7d176Sdrh   }
803cce7d176Sdrh   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
804cce7d176Sdrh     sqlite3ErrorMsg(pParse,
805cce7d176Sdrh        "table %S has %d columns but %d values were supplied",
806cce7d176Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
807cce7d176Sdrh     goto insert_cleanup;
808cce7d176Sdrh   }
809cce7d176Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
810cce7d176Sdrh     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
811cce7d176Sdrh     goto insert_cleanup;
812cce7d176Sdrh   }
813cce7d176Sdrh 
814c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8151ccde15dSdrh   */
81679636913Sdrh   if( (db->flags & SQLITE_CountRows)!=0
81779636913Sdrh    && !pParse->nested
81879636913Sdrh    && !pParse->pTriggerTab
81979636913Sdrh   ){
8206a288a33Sdrh     regRowCount = ++pParse->nMem;
8216a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
822c3f9bad2Sdanielk1977   }
823c3f9bad2Sdanielk1977 
824e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
825e448dc4aSdanielk1977   if( !isView ){
826aa9b8963Sdrh     int nIdx;
827fd261ec6Sdan     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
82826198bb4Sdrh                                       &iDataCur, &iIdxCur);
829a7c3b93fSdrh     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
830aa9b8963Sdrh     if( aRegIdx==0 ){
831aa9b8963Sdrh       goto insert_cleanup;
832aa9b8963Sdrh     }
8332c4dfc30Sdrh     for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
8342c4dfc30Sdrh       assert( pIdx );
835aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
8362c4dfc30Sdrh       pParse->nMem += pIdx->nColumn;
837aa9b8963Sdrh     }
838a7c3b93fSdrh     aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */
839feeb1394Sdrh   }
840788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT
8410b30a116Sdrh   if( pUpsert ){
842b042d921Sdrh     if( IsVirtual(pTab) ){
843b042d921Sdrh       sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
844b042d921Sdrh               pTab->zName);
845b042d921Sdrh       goto insert_cleanup;
846b042d921Sdrh     }
8479105fd51Sdan     if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
8489105fd51Sdan       goto insert_cleanup;
8499105fd51Sdan     }
850788d55aaSdrh     pTabList->a[0].iCursor = iDataCur;
8510b30a116Sdrh     pUpsert->pUpsertSrc = pTabList;
852eac9fabbSdrh     pUpsert->regData = regData;
8537fc3aba8Sdrh     pUpsert->iDataCur = iDataCur;
8547fc3aba8Sdrh     pUpsert->iIdxCur = iIdxCur;
8550b30a116Sdrh     if( pUpsert->pUpsertTarget ){
856e9c2e772Sdrh       sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
857788d55aaSdrh     }
8580b30a116Sdrh   }
859788d55aaSdrh #endif
860788d55aaSdrh 
861feeb1394Sdrh 
862e00ee6ebSdrh   /* This is the top of the main insertion loop */
863142e30dfSdrh   if( useTempTable ){
864e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
865e00ee6ebSdrh     ** following pseudocode (template 4):
866e00ee6ebSdrh     **
86781cf13ecSdrh     **         rewind temp table, if empty goto D
868e00ee6ebSdrh     **      C: loop over rows of intermediate table
869e00ee6ebSdrh     **           transfer values form intermediate table into <table>
870e00ee6ebSdrh     **         end loop
871e00ee6ebSdrh     **      D: ...
872e00ee6ebSdrh     */
873688852abSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
874e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
875142e30dfSdrh   }else if( pSelect ){
876e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
877e00ee6ebSdrh     ** following pseudocode (template 3):
878e00ee6ebSdrh     **
87981cf13ecSdrh     **      C: yield X, at EOF goto D
880e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
881e00ee6ebSdrh     **         goto C
882e00ee6ebSdrh     **      D: ...
883e00ee6ebSdrh     */
88481cf13ecSdrh     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
885688852abSdrh     VdbeCoverage(v);
886bed8690fSdrh   }
8871ccde15dSdrh 
8885cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
88970ce3f0cSdrh   */
890ec4ccdbcSdrh   endOfLoop = sqlite3VdbeMakeLabel(pParse);
8912f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
89276d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
893c3f9bad2Sdanielk1977 
89470ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
89570ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89670ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89770ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
89870ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
89970ce3f0cSdrh     */
900d82b5021Sdrh     if( ipkColumn<0 ){
90176d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90270ce3f0cSdrh     }else{
903728e0f91Sdrh       int addr1;
904ec95c441Sdrh       assert( !withoutRowid );
9057fe45908Sdrh       if( useTempTable ){
906d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
9077fe45908Sdrh       }else{
908d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
909d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
9107fe45908Sdrh       }
911728e0f91Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
91276d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
913728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
914688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
91570ce3f0cSdrh     }
91670ce3f0cSdrh 
917034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
918034ca14fSdanielk1977     ** this block would have to account for hidden column.
919034ca14fSdanielk1977     */
920034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
921034ca14fSdanielk1977 
92270ce3f0cSdrh     /* Create the new column data
92370ce3f0cSdrh     */
924b1daa3f4Sdrh     for(i=j=0; i<pTab->nCol; i++){
925b1daa3f4Sdrh       if( pColumn ){
926c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
927c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
928c3f9bad2Sdanielk1977         }
929c3f9bad2Sdanielk1977       }
930b1daa3f4Sdrh       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
93103d69a68Sdrh             || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
93276d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
933142e30dfSdrh       }else if( useTempTable ){
93476d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
935c3f9bad2Sdanielk1977       }else{
936d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
93776d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
938c3f9bad2Sdanielk1977       }
93903d69a68Sdrh       if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
940c3f9bad2Sdanielk1977     }
941a37cdde0Sdanielk1977 
942a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
943a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
944a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
945a37cdde0Sdanielk1977     ** table column affinities.
946a37cdde0Sdanielk1977     */
947a37cdde0Sdanielk1977     if( !isView ){
94857bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regCols+1);
949a37cdde0Sdanielk1977     }
950c3f9bad2Sdanielk1977 
9515cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
952165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
95394d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
954165921a7Sdan 
95576d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
95670ce3f0cSdrh   }
957c3f9bad2Sdanielk1977 
958d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
959d82b5021Sdrh   ** registers beginning at regIns.
9601ccde15dSdrh   */
9615cf590c1Sdrh   if( !isView ){
9624cbdda9eSdrh     if( IsVirtual(pTab) ){
9634cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9646a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9654cbdda9eSdrh     }
966d82b5021Sdrh     if( ipkColumn>=0 ){
967142e30dfSdrh       if( useTempTable ){
968d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
969142e30dfSdrh       }else if( pSelect ){
97005a86c5cSdrh         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
9714a32431cSdrh       }else{
97204fcef00Sdrh         Expr *pIpk = pList->a[ipkColumn].pExpr;
97304fcef00Sdrh         if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
97404fcef00Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
975e4d90813Sdrh           appendFlag = 1;
97604fcef00Sdrh         }else{
97704fcef00Sdrh           sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
978e4d90813Sdrh         }
97927a32783Sdrh       }
980f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
981e1e68f49Sdrh       ** to generate a unique primary key value.
982e1e68f49Sdrh       */
983e4d90813Sdrh       if( !appendFlag ){
984728e0f91Sdrh         int addr1;
985bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
986728e0f91Sdrh           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
98726198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
988728e0f91Sdrh           sqlite3VdbeJumpHere(v, addr1);
989bb50e7adSdanielk1977         }else{
990728e0f91Sdrh           addr1 = sqlite3VdbeCurrentAddr(v);
991728e0f91Sdrh           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
992bb50e7adSdanielk1977         }
993688852abSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
994e4d90813Sdrh       }
995ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9966a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9974a32431cSdrh     }else{
99826198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
999e4d90813Sdrh       appendFlag = 1;
10004a32431cSdrh     }
10016a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
10024a32431cSdrh 
1003d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
10044a32431cSdrh     ** with the first column.
10054a32431cSdrh     */
1006034ca14fSdanielk1977     nHidden = 0;
1007*c27ea2aeSdrh     iRegStore = regRowid+1;
1008*c27ea2aeSdrh     for(i=0; i<pTab->nCol; i++, iRegStore++){
10094a32431cSdrh       if( i==pTab->iPKey ){
10104a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
1011d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
1012d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
101305a86c5cSdrh         ** taking up data space with information that will never be used.
101405a86c5cSdrh         ** As there may be shallow copies of this value, make it a soft-NULL */
101505a86c5cSdrh         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
10164a32431cSdrh         continue;
10174a32431cSdrh       }
1018967e8b73Sdrh       if( pColumn==0 ){
10197e508f1eSdrh         if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ){
1020034ca14fSdanielk1977           j = -1;
1021034ca14fSdanielk1977           nHidden++;
10227e508f1eSdrh           if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
1023*c27ea2aeSdrh             iRegStore--;
10247e508f1eSdrh             continue;
10257e508f1eSdrh           }
1026034ca14fSdanielk1977         }else{
1027034ca14fSdanielk1977           j = i - nHidden;
1028034ca14fSdanielk1977         }
1029cce7d176Sdrh       }else{
1030967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1031967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1032cce7d176Sdrh         }
1033cce7d176Sdrh       }
1034034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
103505a86c5cSdrh         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
1036142e30dfSdrh       }else if( useTempTable ){
1037287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1038142e30dfSdrh       }else if( pSelect ){
103905a86c5cSdrh         if( regFromSelect!=regData ){
1040b7654111Sdrh           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
104105a86c5cSdrh         }
1042cce7d176Sdrh       }else{
1043287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1044cce7d176Sdrh       }
1045cce7d176Sdrh     }
10461ccde15dSdrh 
10470ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10480ca3e24bSdrh     ** do the insertion.
10494a32431cSdrh     */
10504cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10514cbdda9eSdrh     if( IsVirtual(pTab) ){
1052595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10534f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1054595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1055b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1056e0af83acSdan       sqlite3MayAbort(pParse);
10574cbdda9eSdrh     }else
10584cbdda9eSdrh #endif
10594cbdda9eSdrh     {
1060de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
10613b908d41Sdan       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
1062f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1063788d55aaSdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
106404adf416Sdrh       );
10658ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
10663b908d41Sdan 
10673b908d41Sdan       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
10683b908d41Sdan       ** constraints or (b) there are no triggers and this table is not a
10693b908d41Sdan       ** parent table in a foreign key constraint. It is safe to set the
10703b908d41Sdan       ** flag in the second case as if any REPLACE constraint is hit, an
10713b908d41Sdan       ** OP_Delete or OP_IdxDelete instruction will be executed on each
10723b908d41Sdan       ** cursor that is disturbed. And these instructions both clear the
10733b908d41Sdan       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
10743b908d41Sdan       ** functionality.  */
10753b908d41Sdan       bUseSeek = (isReplace==0 || (pTrigger==0 &&
10763b908d41Sdan           ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
10773b908d41Sdan       ));
107826198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
10793b908d41Sdan           regIns, aRegIdx, 0, appendFlag, bUseSeek
10803b908d41Sdan       );
10815cf590c1Sdrh     }
10824cbdda9eSdrh   }
10831bee3d7bSdrh 
1084feeb1394Sdrh   /* Update the count of rows that are inserted
10851bee3d7bSdrh   */
108679636913Sdrh   if( regRowCount ){
10876a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10881bee3d7bSdrh   }
1089c3f9bad2Sdanielk1977 
10902f886d1dSdanielk1977   if( pTrigger ){
1091c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1092165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
109394d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1094c3f9bad2Sdanielk1977   }
10951bee3d7bSdrh 
1096e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1097e00ee6ebSdrh   ** is a SELECT statement.
10981ccde15dSdrh   */
10994adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1100142e30dfSdrh   if( useTempTable ){
1101688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1102e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
11032eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1104142e30dfSdrh   }else if( pSelect ){
1105076e85f5Sdrh     sqlite3VdbeGoto(v, addrCont);
1106e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
11076b56344dSdrh   }
1108c3f9bad2Sdanielk1977 
11090b9f50d8Sdrh insert_end:
1110f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
11110b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
11120b9f50d8Sdrh   ** autoincrement tables.
11132958a4e6Sdrh   */
1114165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
11150b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
11160b9f50d8Sdrh   }
11172958a4e6Sdrh 
11181bee3d7bSdrh   /*
1119e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1120e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1121e7de6f25Sdanielk1977   ** invoke the callback function.
11221bee3d7bSdrh   */
112379636913Sdrh   if( regRowCount ){
11246a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
112522322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
112610fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11271bee3d7bSdrh   }
1128cce7d176Sdrh 
1129cce7d176Sdrh insert_cleanup:
1130633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1131633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
113246d2e5c3Sdrh   sqlite3UpsertDelete(db, pUpsert);
1133633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1134633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1135633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1136cce7d176Sdrh }
11379cfcf5d4Sdrh 
113875cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
113960ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
114075cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
114175cbd984Sdan #ifdef isView
114275cbd984Sdan  #undef isView
114375cbd984Sdan #endif
114475cbd984Sdan #ifdef pTrigger
114575cbd984Sdan  #undef pTrigger
114675cbd984Sdan #endif
114775cbd984Sdan #ifdef tmask
114875cbd984Sdan  #undef tmask
114975cbd984Sdan #endif
115075cbd984Sdan 
11519cfcf5d4Sdrh /*
1152e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for
1153e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn()
115498bfa16dSdrh */
115598bfa16dSdrh #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
115698bfa16dSdrh #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
115798bfa16dSdrh 
1158e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1159e9816d82Sdrh *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1160e9816d82Sdrh ** expression node references any of the
11612a0b527bSdrh ** columns that are being modifed by an UPDATE statement.
11622a0b527bSdrh */
11632a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
116498bfa16dSdrh   if( pExpr->op==TK_COLUMN ){
116598bfa16dSdrh     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
116698bfa16dSdrh     if( pExpr->iColumn>=0 ){
116798bfa16dSdrh       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
116898bfa16dSdrh         pWalker->eCode |= CKCNSTRNT_COLUMN;
116998bfa16dSdrh       }
117098bfa16dSdrh     }else{
117198bfa16dSdrh       pWalker->eCode |= CKCNSTRNT_ROWID;
117298bfa16dSdrh     }
11732a0b527bSdrh   }
11742a0b527bSdrh   return WRC_Continue;
11752a0b527bSdrh }
11762a0b527bSdrh 
11772a0b527bSdrh /*
11782a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
11792a0b527bSdrh ** only columns that are modified by the UPDATE are those for which
118098bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
118198bfa16dSdrh **
1182e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the
118398bfa16dSdrh ** changing columns (or the rowid if it is changing).  In other words,
1184e9816d82Sdrh ** return true if this CHECK constraint must be validated for
118598bfa16dSdrh ** the new row in the UPDATE statement.
1186e9816d82Sdrh **
1187e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1188e9816d82Sdrh ** The operation of this routine is the same - return true if an only if
1189e9816d82Sdrh ** the expression uses one or more of columns identified by the second and
1190e9816d82Sdrh ** third arguments.
11912a0b527bSdrh */
1192e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn(
1193e9816d82Sdrh   Expr *pExpr,    /* The expression to be checked */
1194e9816d82Sdrh   int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
1195e9816d82Sdrh   int chngRowid   /* True if UPDATE changes the rowid */
1196e9816d82Sdrh ){
11972a0b527bSdrh   Walker w;
11982a0b527bSdrh   memset(&w, 0, sizeof(w));
119998bfa16dSdrh   w.eCode = 0;
12002a0b527bSdrh   w.xExprCallback = checkConstraintExprNode;
12012a0b527bSdrh   w.u.aiCol = aiChng;
12022a0b527bSdrh   sqlite3WalkExpr(&w, pExpr);
120305723a9eSdrh   if( !chngRowid ){
120405723a9eSdrh     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
120505723a9eSdrh     w.eCode &= ~CKCNSTRNT_ROWID;
120605723a9eSdrh   }
120705723a9eSdrh   testcase( w.eCode==0 );
120805723a9eSdrh   testcase( w.eCode==CKCNSTRNT_COLUMN );
120905723a9eSdrh   testcase( w.eCode==CKCNSTRNT_ROWID );
121005723a9eSdrh   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1211e9816d82Sdrh   return w.eCode!=0;
12122a0b527bSdrh }
12132a0b527bSdrh 
121411e85273Sdrh /*
12156934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
12166934fc7bSdrh ** on table pTab.
12179cfcf5d4Sdrh **
12186934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
12196934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
12206934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
12216934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
12226934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
12236934fc7bSdrh ** contain the content of the first table column.  The third register will
12246934fc7bSdrh ** contain the content of the second table column.  And so forth.
12250ca3e24bSdrh **
1226f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1227f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1228f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1229f8ffb278Sdrh ** checking regOldData for zero.
12300ca3e24bSdrh **
1231f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1232f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1233f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1234f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
12350ca3e24bSdrh **
1236f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1237f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1238f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1239f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1240f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1241f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
12420ca3e24bSdrh **
12436934fc7bSdrh ** The code generated by this routine will store new index entries into
1244aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1245aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1246aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
12476934fc7bSdrh ** at pTab->pIndex.
12486934fc7bSdrh **
1249a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the
1250a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the
1251a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first
1252a7c3b93fSdrh ** entry of aRegIdx[] past the last index.  It is important that the
1253a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes
1254a7c3b93fSdrh ** to the register content that occur after constraint checks but before
1255a7c3b93fSdrh ** the new record is inserted.
1256a7c3b93fSdrh **
12576934fc7bSdrh ** The caller must have already opened writeable cursors on the main
12586934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
12596934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
12606934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
12616934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
12626934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
12636934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
12649cfcf5d4Sdrh **
12659cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
12669cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
12671c92853dSdrh ** then the appropriate action is performed.  There are five possible
12681c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
12699cfcf5d4Sdrh **
12709cfcf5d4Sdrh **  Constraint type  Action       What Happens
12719cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
12721c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
12736934fc7bSdrh **                                sqlite3_step() returns immediately with a
12749cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
12759cfcf5d4Sdrh **
12761c92853dSdrh **  any              ABORT        Back out changes from the current command
12771c92853dSdrh **                                only (do not do a complete rollback) then
12786934fc7bSdrh **                                cause sqlite3_step() to return immediately
12791c92853dSdrh **                                with SQLITE_CONSTRAINT.
12801c92853dSdrh **
12816934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
12821c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
12831c92853dSdrh **                                transaction is not rolled back and any
12846934fc7bSdrh **                                changes to prior rows are retained.
12851c92853dSdrh **
12866934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
12876934fc7bSdrh **                                row is skipped, without throwing an error.
12886934fc7bSdrh **                                Processing continues with the next row.
12896934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
12909cfcf5d4Sdrh **
12919cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
12929cfcf5d4Sdrh **                                value for that column.  If the default value
12939cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
12949cfcf5d4Sdrh **
12959cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
12969cfcf5d4Sdrh **                                being inserted is removed.
12979cfcf5d4Sdrh **
12989cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12999cfcf5d4Sdrh **
13001c92853dSdrh ** Which action to take is determined by the overrideError parameter.
13011c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
13021c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
13031c92853dSdrh ** for the constraint is used.
13049cfcf5d4Sdrh */
13054adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
13069cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
13076934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1308f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
13096934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
131026198bb4Sdrh   int iIdxCur,         /* First index cursor */
13116934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1312f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1313f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1314f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1315de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1316bdb00225Sdrh   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1317788d55aaSdrh   int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
1318788d55aaSdrh   Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
13199cfcf5d4Sdrh ){
13201b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
13211b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
132211e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
13232938f924Sdrh   sqlite3 *db;         /* Database connection */
1324f8ffb278Sdrh   int i;               /* loop counter */
1325f8ffb278Sdrh   int ix;              /* Index loop counter */
13269cfcf5d4Sdrh   int nCol;            /* Number of columns */
13279cfcf5d4Sdrh   int onError;         /* Conflict resolution strategy */
1328728e0f91Sdrh   int addr1;           /* Address of jump instruction */
13291b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
13306fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1331096fd476Sdrh   Index *pUpIdx = 0;   /* Index to which to apply the upsert */
13328d1b82e4Sdrh   u8 isUpdate;         /* True if this is an UPDATE operation */
133357bf4a8eSdrh   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
1334096fd476Sdrh   int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */
133584304506Sdrh   int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */
133684304506Sdrh   int ipkTop = 0;        /* Top of the IPK uniqueness check */
133784304506Sdrh   int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
13389cfcf5d4Sdrh 
1339f8ffb278Sdrh   isUpdate = regOldData!=0;
13402938f924Sdrh   db = pParse->db;
13414adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
13429cfcf5d4Sdrh   assert( v!=0 );
1343417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
13449cfcf5d4Sdrh   nCol = pTab->nCol;
1345aa9b8963Sdrh 
13466934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
13476934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
13486934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
13496934fc7bSdrh   ** number of fields in the true primary key of the table. */
135026198bb4Sdrh   if( HasRowid(pTab) ){
135126198bb4Sdrh     pPk = 0;
135226198bb4Sdrh     nPkField = 1;
135326198bb4Sdrh   }else{
135426198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
135526198bb4Sdrh     nPkField = pPk->nKeyCol;
135626198bb4Sdrh   }
13576fbe41acSdrh 
13586fbe41acSdrh   /* Record that this module has started */
13596fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
13606934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
13619cfcf5d4Sdrh 
13629cfcf5d4Sdrh   /* Test all NOT NULL constraints.
13639cfcf5d4Sdrh   */
13649cfcf5d4Sdrh   for(i=0; i<nCol; i++){
13650ca3e24bSdrh     if( i==pTab->iPKey ){
1366bdb00225Sdrh       continue;        /* ROWID is never NULL */
1367bdb00225Sdrh     }
1368bdb00225Sdrh     if( aiChng && aiChng[i]<0 ){
1369bdb00225Sdrh       /* Don't bother checking for NOT NULL on columns that do not change */
13700ca3e24bSdrh       continue;
13710ca3e24bSdrh     }
13729cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
1373bdb00225Sdrh     if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
13749cfcf5d4Sdrh     if( overrideError!=OE_Default ){
13759cfcf5d4Sdrh       onError = overrideError;
1376a996e477Sdrh     }else if( onError==OE_Default ){
1377a996e477Sdrh       onError = OE_Abort;
13789cfcf5d4Sdrh     }
13797977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
13809cfcf5d4Sdrh       onError = OE_Abort;
13819cfcf5d4Sdrh     }
1382b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1383b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
13849bfb0794Sdrh     addr1 = 0;
13859cfcf5d4Sdrh     switch( onError ){
13869bfb0794Sdrh       case OE_Replace: {
13879bfb0794Sdrh         assert( onError==OE_Replace );
1388ec4ccdbcSdrh         addr1 = sqlite3VdbeMakeLabel(pParse);
13899bfb0794Sdrh         sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
13909bfb0794Sdrh           VdbeCoverage(v);
13919bfb0794Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
13929bfb0794Sdrh         sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
13939bfb0794Sdrh           VdbeCoverage(v);
13949bfb0794Sdrh         onError = OE_Abort;
13959bfb0794Sdrh         /* Fall through into the OE_Abort case to generate code that runs
13969bfb0794Sdrh         ** if both the input and the default value are NULL */
13979bfb0794Sdrh       }
13981c92853dSdrh       case OE_Abort:
1399e0af83acSdan         sqlite3MayAbort(pParse);
14000978d4ffSdrh         /* Fall through */
1401e0af83acSdan       case OE_Rollback:
14021c92853dSdrh       case OE_Fail: {
1403f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1404f9c8ce3cSdrh                                     pTab->aCol[i].zName);
14052700acaaSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
14062700acaaSdrh                           regNewData+1+i);
14072700acaaSdrh         sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1408f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1409688852abSdrh         VdbeCoverage(v);
14109bfb0794Sdrh         if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
14119cfcf5d4Sdrh         break;
14129cfcf5d4Sdrh       }
1413098d1684Sdrh       default: {
14149bfb0794Sdrh         assert( onError==OE_Ignore );
14159bfb0794Sdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
1416728e0f91Sdrh         VdbeCoverage(v);
14179cfcf5d4Sdrh         break;
14189cfcf5d4Sdrh       }
14199cfcf5d4Sdrh     }
14209cfcf5d4Sdrh   }
14219cfcf5d4Sdrh 
14229cfcf5d4Sdrh   /* Test all CHECK constraints
14239cfcf5d4Sdrh   */
1424ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
14252938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
14262938f924Sdrh     ExprList *pCheck = pTab->pCheck;
14276e97f8ecSdrh     pParse->iSelfTab = -(regNewData+1);
1428aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
14292938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
143005723a9eSdrh       int allOk;
14312a0b527bSdrh       Expr *pExpr = pCheck->a[i].pExpr;
1432e9816d82Sdrh       if( aiChng
1433e9816d82Sdrh        && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
1434e9816d82Sdrh       ){
1435e9816d82Sdrh         /* The check constraints do not reference any of the columns being
1436e9816d82Sdrh         ** updated so there is no point it verifying the check constraint */
1437e9816d82Sdrh         continue;
1438e9816d82Sdrh       }
1439ec4ccdbcSdrh       allOk = sqlite3VdbeMakeLabel(pParse);
14404031bafaSdrh       sqlite3VdbeVerifyAbortable(v, onError);
14412a0b527bSdrh       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
14422e06c67cSdrh       if( onError==OE_Ignore ){
1443076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
1444aa01c7e2Sdrh       }else{
1445f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1446f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
14470ce974d1Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
1448d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1449f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1450f9c8ce3cSdrh                               P5_ConstraintCheck);
1451aa01c7e2Sdrh       }
1452ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1453ffe07b2dSdrh     }
14546e97f8ecSdrh     pParse->iSelfTab = 0;
14552938f924Sdrh   }
1456ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
14579cfcf5d4Sdrh 
1458096fd476Sdrh   /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1459096fd476Sdrh   ** order:
1460096fd476Sdrh   **
146184304506Sdrh   **   (1)  OE_Update
146284304506Sdrh   **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1463096fd476Sdrh   **   (3)  OE_Replace
1464096fd476Sdrh   **
1465096fd476Sdrh   ** OE_Fail and OE_Ignore must happen before any changes are made.
1466096fd476Sdrh   ** OE_Update guarantees that only a single row will change, so it
1467096fd476Sdrh   ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
1468096fd476Sdrh   ** could happen in any order, but they are grouped up front for
1469096fd476Sdrh   ** convenience.
1470096fd476Sdrh   **
147184304506Sdrh   ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
147284304506Sdrh   ** The order of constraints used to have OE_Update as (2) and OE_Abort
147384304506Sdrh   ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
147484304506Sdrh   ** constraint before any others, so it had to be moved.
147584304506Sdrh   **
1476096fd476Sdrh   ** Constraint checking code is generated in this order:
1477096fd476Sdrh   **   (A)  The rowid constraint
1478096fd476Sdrh   **   (B)  Unique index constraints that do not have OE_Replace as their
1479096fd476Sdrh   **        default conflict resolution strategy
1480096fd476Sdrh   **   (C)  Unique index that do use OE_Replace by default.
1481096fd476Sdrh   **
1482096fd476Sdrh   ** The ordering of (2) and (3) is accomplished by making sure the linked
1483096fd476Sdrh   ** list of indexes attached to a table puts all OE_Replace indexes last
1484096fd476Sdrh   ** in the list.  See sqlite3CreateIndex() for where that happens.
1485096fd476Sdrh   */
1486096fd476Sdrh 
1487096fd476Sdrh   if( pUpsert ){
1488096fd476Sdrh     if( pUpsert->pUpsertTarget==0 ){
1489096fd476Sdrh       /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
1490096fd476Sdrh       ** Make all unique constraint resolution be OE_Ignore */
1491dedbc508Sdrh       assert( pUpsert->pUpsertSet==0 );
1492096fd476Sdrh       overrideError = OE_Ignore;
1493096fd476Sdrh       pUpsert = 0;
1494096fd476Sdrh     }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
149584304506Sdrh       /* If the constraint-target uniqueness check must be run first.
149684304506Sdrh       ** Jump to that uniqueness check now */
149784304506Sdrh       upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
149884304506Sdrh       VdbeComment((v, "UPSERT constraint goes first"));
1499096fd476Sdrh     }
1500096fd476Sdrh   }
1501096fd476Sdrh 
1502f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1503f8ffb278Sdrh   ** exist in the table.
15049cfcf5d4Sdrh   */
15056fbe41acSdrh   if( pkChng && pPk==0 ){
1506ec4ccdbcSdrh     int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
150711e85273Sdrh 
1508f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
15090ca3e24bSdrh     onError = pTab->keyConf;
15100ca3e24bSdrh     if( overrideError!=OE_Default ){
15110ca3e24bSdrh       onError = overrideError;
1512a996e477Sdrh     }else if( onError==OE_Default ){
1513a996e477Sdrh       onError = OE_Abort;
15140ca3e24bSdrh     }
1515a0217ba7Sdrh 
1516c8a0c90bSdrh     /* figure out whether or not upsert applies in this case */
1517096fd476Sdrh     if( pUpsert && pUpsert->pUpsertIdx==0 ){
1518c8a0c90bSdrh       if( pUpsert->pUpsertSet==0 ){
1519c8a0c90bSdrh         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1520c8a0c90bSdrh       }else{
1521c8a0c90bSdrh         onError = OE_Update;  /* DO UPDATE */
1522c8a0c90bSdrh       }
1523c8a0c90bSdrh     }
1524c8a0c90bSdrh 
15258d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
15268d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
15278d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
15288d1b82e4Sdrh     ** the UNIQUE constraints have run.
15298d1b82e4Sdrh     */
153084304506Sdrh     if( onError==OE_Replace      /* IPK rule is REPLACE */
153184304506Sdrh      && onError!=overrideError   /* Rules for other contraints are different */
153284304506Sdrh      && pTab->pIndex             /* There exist other constraints */
1533096fd476Sdrh     ){
153484304506Sdrh       ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
153584304506Sdrh       VdbeComment((v, "defer IPK REPLACE until last"));
15368d1b82e4Sdrh     }
15378d1b82e4Sdrh 
1538bb6b1ca7Sdrh     if( isUpdate ){
1539bb6b1ca7Sdrh       /* pkChng!=0 does not mean that the rowid has changed, only that
1540bb6b1ca7Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1541bb6b1ca7Sdrh       ** is unchanged. */
1542bb6b1ca7Sdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
1543bb6b1ca7Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1544bb6b1ca7Sdrh       VdbeCoverage(v);
1545bb6b1ca7Sdrh     }
1546bb6b1ca7Sdrh 
1547f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1548f8ffb278Sdrh     ** the following conflict logic if it does not. */
15497f5f306bSdrh     VdbeNoopComment((v, "uniqueness check for ROWID"));
15504031bafaSdrh     sqlite3VdbeVerifyAbortable(v, onError);
15516934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1552688852abSdrh     VdbeCoverage(v);
1553f8ffb278Sdrh 
15540ca3e24bSdrh     switch( onError ){
1555a0217ba7Sdrh       default: {
1556a0217ba7Sdrh         onError = OE_Abort;
1557a0217ba7Sdrh         /* Fall thru into the next case */
1558a0217ba7Sdrh       }
15591c92853dSdrh       case OE_Rollback:
15601c92853dSdrh       case OE_Abort:
15611c92853dSdrh       case OE_Fail: {
15629916048bSdrh         testcase( onError==OE_Rollback );
15639916048bSdrh         testcase( onError==OE_Abort );
15649916048bSdrh         testcase( onError==OE_Fail );
1565f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
15660ca3e24bSdrh         break;
15670ca3e24bSdrh       }
15685383ae5cSdrh       case OE_Replace: {
15692283d46cSdan         /* If there are DELETE triggers on this table and the
15702283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1571d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
15722283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
15732283d46cSdan         **
15742283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1575da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1576da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1577da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1578da730f6eSdan         ** when it is inserted.
1579da730f6eSdan         **
1580da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1581da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1582da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1583da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1584da730f6eSdan         ** but being more selective here allows statements like:
1585da730f6eSdan         **
1586da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1587da730f6eSdan         **
1588da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1589da730f6eSdan         ** table.
1590da730f6eSdan         */
15912283d46cSdan         Trigger *pTrigger = 0;
15922938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15932283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15942283d46cSdan         }
1595e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1596da730f6eSdan           sqlite3MultiWrite(pParse);
159726198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1598438b8815Sdan                                    regNewData, 1, 0, OE_Replace, 1, -1);
159946c47d46Sdan         }else{
16009b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
160154f2cd90Sdrh           assert( HasRowid(pTab) );
160246c47d46Sdan           /* This OP_Delete opcode fires the pre-update-hook only. It does
160346c47d46Sdan           ** not modify the b-tree. It is more efficient to let the coming
160446c47d46Sdan           ** OP_Insert replace the existing entry than it is to delete the
160546c47d46Sdan           ** existing entry and then insert a new one. */
1606cbf1b8efSdrh           sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
1607f14b7fb7Sdrh           sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
16089b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
160946c47d46Sdan           if( pTab->pIndex ){
1610da730f6eSdan             sqlite3MultiWrite(pParse);
1611f0ee1d3cSdan             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
16122283d46cSdan           }
161346c47d46Sdan         }
16145383ae5cSdrh         seenReplace = 1;
16155383ae5cSdrh         break;
16165383ae5cSdrh       }
16179eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
16189eddacadSdrh       case OE_Update: {
16192cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
16209eddacadSdrh         /* Fall through */
16219eddacadSdrh       }
16229eddacadSdrh #endif
16230ca3e24bSdrh       case OE_Ignore: {
16249916048bSdrh         testcase( onError==OE_Ignore );
1625076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
16260ca3e24bSdrh         break;
16270ca3e24bSdrh       }
16280ca3e24bSdrh     }
162911e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
163084304506Sdrh     if( ipkTop ){
163184304506Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
163284304506Sdrh       sqlite3VdbeJumpHere(v, ipkTop-1);
1633a05a722fSdrh     }
16340ca3e24bSdrh   }
16350bd1f4eaSdrh 
16360bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
16370bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
163811e85273Sdrh   ** Compute the revised record entries for indices as we go.
1639f8ffb278Sdrh   **
1640f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1641f8ffb278Sdrh   ** WITHOUT ROWID table.
16420bd1f4eaSdrh   */
164326198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
16446934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
16456934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
16466934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
16476934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
16482184fc75Sdrh 
164926198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
16507f5f306bSdrh     if( pUpIdx==pIdx ){
165184304506Sdrh       addrUniqueOk = upsertJump+1;
16527f5f306bSdrh       upsertBypass = sqlite3VdbeGoto(v, 0);
16537f5f306bSdrh       VdbeComment((v, "Skip upsert subroutine"));
165484304506Sdrh       sqlite3VdbeJumpHere(v, upsertJump);
16557f5f306bSdrh     }else{
1656ec4ccdbcSdrh       addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
16577f5f306bSdrh     }
165884304506Sdrh     if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
165984304506Sdrh       sqlite3TableAffinity(v, pTab, regNewData+1);
166084304506Sdrh       bAffinityDone = 1;
166184304506Sdrh     }
16627f5f306bSdrh     VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
16636934fc7bSdrh     iThisCur = iIdxCur+ix;
16647f5f306bSdrh 
1665b2fe7d8cSdrh 
1666f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1667b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
166826198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
16696e97f8ecSdrh       pParse->iSelfTab = -(regNewData+1);
167072bc8208Sdrh       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1671b2b9d3d7Sdrh                             SQLITE_JUMPIFNULL);
16726e97f8ecSdrh       pParse->iSelfTab = 0;
1673b2b9d3d7Sdrh     }
1674b2b9d3d7Sdrh 
16756934fc7bSdrh     /* Create a record for this index entry as it should appear after
1676f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1677f8ffb278Sdrh     */
1678bf2f5739Sdrh     regIdx = aRegIdx[ix]+1;
16799cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
16806934fc7bSdrh       int iField = pIdx->aiColumn[i];
1681f82b9afcSdrh       int x;
16824b92f98cSdrh       if( iField==XN_EXPR ){
16836e97f8ecSdrh         pParse->iSelfTab = -(regNewData+1);
16841c75c9d7Sdrh         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
16856e97f8ecSdrh         pParse->iSelfTab = 0;
16861f9ca2c8Sdrh         VdbeComment((v, "%s column %d", pIdx->zName, i));
16871f9ca2c8Sdrh       }else{
16884b92f98cSdrh         if( iField==XN_ROWID || iField==pTab->iPKey ){
1689f82b9afcSdrh           x = regNewData;
16909cfcf5d4Sdrh         }else{
1691f82b9afcSdrh           x = iField + regNewData + 1;
16929cfcf5d4Sdrh         }
1693fed7ac6fSdrh         sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
1694f82b9afcSdrh         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
16959cfcf5d4Sdrh       }
16961f9ca2c8Sdrh     }
169726198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
169826198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
16997e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
17009df385ecSdrh     if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
17019df385ecSdrh       sqlite3SetMakeRecordP5(v, pIdx->pTable);
17029df385ecSdrh     }
17037e4acf7bSdrh #endif
1704b2fe7d8cSdrh 
1705f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1706f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1707f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1708f8ffb278Sdrh     ** logic below can all be skipped. */
170900012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1710da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1711da475b8dSdrh       continue;
1712da475b8dSdrh     }
1713f8ffb278Sdrh 
17146934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
17159cfcf5d4Sdrh     onError = pIdx->onError;
1716de630353Sdanielk1977     if( onError==OE_None ){
171711e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1718de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1719de630353Sdanielk1977     }
17209cfcf5d4Sdrh     if( overrideError!=OE_Default ){
17219cfcf5d4Sdrh       onError = overrideError;
1722a996e477Sdrh     }else if( onError==OE_Default ){
1723a996e477Sdrh       onError = OE_Abort;
17249cfcf5d4Sdrh     }
17255383ae5cSdrh 
1726c8a0c90bSdrh     /* Figure out if the upsert clause applies to this index */
1727096fd476Sdrh     if( pUpIdx==pIdx ){
1728c8a0c90bSdrh       if( pUpsert->pUpsertSet==0 ){
1729c8a0c90bSdrh         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1730c8a0c90bSdrh       }else{
1731c8a0c90bSdrh         onError = OE_Update;  /* DO UPDATE */
1732c8a0c90bSdrh       }
1733c8a0c90bSdrh     }
1734c8a0c90bSdrh 
1735801f55d8Sdrh     /* Collision detection may be omitted if all of the following are true:
1736801f55d8Sdrh     **   (1) The conflict resolution algorithm is REPLACE
1737801f55d8Sdrh     **   (2) The table is a WITHOUT ROWID table
1738801f55d8Sdrh     **   (3) There are no secondary indexes on the table
1739801f55d8Sdrh     **   (4) No delete triggers need to be fired if there is a conflict
1740f9a12a10Sdan     **   (5) No FK constraint counters need to be updated if a conflict occurs.
1741418454c6Sdan     **
1742418454c6Sdan     ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
1743418454c6Sdan     ** must be explicitly deleted in order to ensure any pre-update hook
1744418454c6Sdan     ** is invoked.  */
1745418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
1746801f55d8Sdrh     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
1747801f55d8Sdrh      && pPk==pIdx                                   /* Condition 2 */
1748801f55d8Sdrh      && onError==OE_Replace                         /* Condition 1 */
1749801f55d8Sdrh      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
1750801f55d8Sdrh           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
1751f9a12a10Sdan      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
1752f9a12a10Sdan          (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
17534e1f0efbSdan     ){
1754c6c9e158Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1755c6c9e158Sdrh       continue;
1756c6c9e158Sdrh     }
1757418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
1758c6c9e158Sdrh 
1759b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
17604031bafaSdrh     sqlite3VdbeVerifyAbortable(v, onError);
176126198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
1762688852abSdrh                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
1763f8ffb278Sdrh 
1764f8ffb278Sdrh     /* Generate code to handle collisions */
1765392ee21dSdrh     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
176646d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
176711e85273Sdrh       if( HasRowid(pTab) ){
17686934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
17690978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
17700978d4ffSdrh         ** is different from old-rowid */
1771f8ffb278Sdrh         if( isUpdate ){
17726934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
17733d77dee9Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1774688852abSdrh           VdbeCoverage(v);
1775f8ffb278Sdrh         }
177626198bb4Sdrh       }else{
1777ccc79f02Sdrh         int x;
177826198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
1779da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
1780a021f121Sdrh         if( pIdx!=pPk ){
178126198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
17824b92f98cSdrh             assert( pPk->aiColumn[i]>=0 );
1783ccc79f02Sdrh             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
178426198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
178526198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
178626198bb4Sdrh                          pTab->aCol[pPk->aiColumn[i]].zName));
178726198bb4Sdrh           }
1788da475b8dSdrh         }
1789da475b8dSdrh         if( isUpdate ){
1790e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1791e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
1792e83267daSdan           ** different from the old.
1793e83267daSdan           **
1794e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1795e83267daSdan           ** of the matched index row are different from the original PRIMARY
1796e83267daSdan           ** KEY values of this row before the update.  */
1797e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1798e83267daSdan           int op = OP_Ne;
179948dd1d8eSdrh           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
1800e83267daSdan 
1801e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
1802e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1803ccc79f02Sdrh             x = pPk->aiColumn[i];
18044b92f98cSdrh             assert( x>=0 );
1805e83267daSdan             if( i==(pPk->nKeyCol-1) ){
1806e83267daSdan               addrJump = addrUniqueOk;
1807e83267daSdan               op = OP_Eq;
180811e85273Sdrh             }
1809e83267daSdan             sqlite3VdbeAddOp4(v, op,
1810e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1811e83267daSdan             );
18123d77dee9Sdrh             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
18133d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Eq);
18143d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Ne);
1815da475b8dSdrh           }
181611e85273Sdrh         }
181726198bb4Sdrh       }
181846d03fcbSdrh     }
1819b2fe7d8cSdrh 
1820b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1821b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
18229eddacadSdrh         || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
18239cfcf5d4Sdrh     switch( onError ){
18241c92853dSdrh       case OE_Rollback:
18251c92853dSdrh       case OE_Abort:
18261c92853dSdrh       case OE_Fail: {
18279916048bSdrh         testcase( onError==OE_Rollback );
18289916048bSdrh         testcase( onError==OE_Abort );
18299916048bSdrh         testcase( onError==OE_Fail );
1830f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
18319cfcf5d4Sdrh         break;
18329cfcf5d4Sdrh       }
18339eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
18349eddacadSdrh       case OE_Update: {
18352cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
18369eddacadSdrh         /* Fall through */
18379eddacadSdrh       }
18389eddacadSdrh #endif
18399cfcf5d4Sdrh       case OE_Ignore: {
18409916048bSdrh         testcase( onError==OE_Ignore );
1841076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
18429cfcf5d4Sdrh         break;
18439cfcf5d4Sdrh       }
1844098d1684Sdrh       default: {
18452283d46cSdan         Trigger *pTrigger = 0;
1846098d1684Sdrh         assert( onError==OE_Replace );
18472938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
18482283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
18492283d46cSdan         }
1850fecfb318Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1851fecfb318Sdan           sqlite3MultiWrite(pParse);
1852fecfb318Sdan         }
185326198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1854b0264eecSdrh             regR, nPkField, 0, OE_Replace,
185568116939Sdrh             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
18560ca3e24bSdrh         seenReplace = 1;
18579cfcf5d4Sdrh         break;
18589cfcf5d4Sdrh       }
18599cfcf5d4Sdrh     }
18607f5f306bSdrh     if( pUpIdx==pIdx ){
186184304506Sdrh       sqlite3VdbeGoto(v, upsertJump+1);
18627f5f306bSdrh       sqlite3VdbeJumpHere(v, upsertBypass);
18637f5f306bSdrh     }else{
186411e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
18657f5f306bSdrh     }
1866392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
18679cfcf5d4Sdrh   }
186884304506Sdrh 
186984304506Sdrh   /* If the IPK constraint is a REPLACE, run it last */
187084304506Sdrh   if( ipkTop ){
18716214d939Sdrh     sqlite3VdbeGoto(v, ipkTop);
187284304506Sdrh     VdbeComment((v, "Do IPK REPLACE"));
187384304506Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
187484304506Sdrh   }
1875de630353Sdanielk1977 
1876a7c3b93fSdrh   /* Generate the table record */
1877a7c3b93fSdrh   if( HasRowid(pTab) ){
1878a7c3b93fSdrh     int regRec = aRegIdx[ix];
18797e508f1eSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1,
18807e508f1eSdrh                       pTab->nCol-pTab->nVCol, regRec);
1881a7c3b93fSdrh     sqlite3SetMakeRecordP5(v, pTab);
1882a7c3b93fSdrh     if( !bAffinityDone ){
1883a7c3b93fSdrh       sqlite3TableAffinity(v, pTab, 0);
1884a7c3b93fSdrh     }
1885a7c3b93fSdrh   }
1886a7c3b93fSdrh 
1887de630353Sdanielk1977   *pbMayReplace = seenReplace;
1888ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
18899cfcf5d4Sdrh }
18900ca3e24bSdrh 
1891d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
18920ca3e24bSdrh /*
1893585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
1894585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed.
1895585ce192Sdrh **
1896585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
1897585ce192Sdrh */
1898585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
1899585ce192Sdrh   u16 i;
1900585ce192Sdrh 
1901585ce192Sdrh   /* Records with omitted columns are only allowed for schema format
1902585ce192Sdrh   ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
1903585ce192Sdrh   if( pTab->pSchema->file_format<2 ) return;
1904585ce192Sdrh 
19057e4acf7bSdrh   for(i=pTab->nCol-1; i>0; i--){
19067e4acf7bSdrh     if( pTab->aCol[i].pDflt!=0 ) break;
19077e4acf7bSdrh     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
19087e4acf7bSdrh   }
19097e4acf7bSdrh   sqlite3VdbeChangeP5(v, i+1);
1910585ce192Sdrh }
1911d447dcedSdrh #endif
1912585ce192Sdrh 
19130ca3e24bSdrh /*
19140ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
19154adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
19166934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
191704adf416Sdrh ** rowid and the content to be inserted.
19180ca3e24bSdrh **
1919b419a926Sdrh ** The arguments to this routine should be the same as the first six
19204adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
19210ca3e24bSdrh */
19224adee20fSdanielk1977 void sqlite3CompleteInsertion(
19230ca3e24bSdrh   Parse *pParse,      /* The parser context */
19240ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
192526198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
192626198bb4Sdrh   int iIdxCur,        /* First index cursor */
19276934fc7bSdrh   int regNewData,     /* Range of content */
1928aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1929f91c1318Sdan   int update_flags,   /* True for UPDATE, False for INSERT */
1930de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1931de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
19320ca3e24bSdrh ){
19336934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
19346934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
19356934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
19366934fc7bSdrh   int i;              /* Loop counter */
19370ca3e24bSdrh 
1938f91c1318Sdan   assert( update_flags==0
1939f91c1318Sdan        || update_flags==OPFLAG_ISUPDATE
1940f91c1318Sdan        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
1941f91c1318Sdan   );
1942f91c1318Sdan 
19434adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
19440ca3e24bSdrh   assert( v!=0 );
1945417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1946b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1947aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1948b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1949b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1950688852abSdrh       VdbeCoverage(v);
1951b2b9d3d7Sdrh     }
1952cb9a3643Sdan     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
195348dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
19544308e348Sdrh       assert( pParse->nested==0 );
19556546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1956f91c1318Sdan       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
1957cb9a3643Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1958cb9a3643Sdan       if( update_flags==0 ){
195950ef6716Sdrh         int r = sqlite3GetTempReg(pParse);
196050ef6716Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
196150ef6716Sdrh         sqlite3VdbeAddOp4(v, OP_Insert,
196250ef6716Sdrh             iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
1963cb9a3643Sdan         );
1964cb9a3643Sdan         sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
196550ef6716Sdrh         sqlite3ReleaseTempReg(pParse, r);
1966de630353Sdanielk1977       }
1967cb9a3643Sdan #endif
1968cb9a3643Sdan     }
1969cb9a3643Sdan     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
1970cb9a3643Sdan                          aRegIdx[i]+1,
1971cb9a3643Sdan                          pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
19729b34abeeSdrh     sqlite3VdbeChangeP5(v, pik_flags);
19730ca3e24bSdrh   }
1974ec95c441Sdrh   if( !HasRowid(pTab) ) return;
19754794f735Sdrh   if( pParse->nested ){
19764794f735Sdrh     pik_flags = 0;
19774794f735Sdrh   }else{
197894eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
1979f91c1318Sdan     pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
19804794f735Sdrh   }
1981e4d90813Sdrh   if( appendBias ){
1982e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1983e4d90813Sdrh   }
1984de630353Sdanielk1977   if( useSeekResult ){
1985de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1986de630353Sdanielk1977   }
1987a7c3b93fSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
198894eb6a14Sdanielk1977   if( !pParse->nested ){
1989f14b7fb7Sdrh     sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
199094eb6a14Sdanielk1977   }
1991b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
19920ca3e24bSdrh }
1993cd44690aSdrh 
1994cd44690aSdrh /*
199526198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
199626198bb4Sdrh ** code to open and initialized those cursors.
1997aa9b8963Sdrh **
199826198bb4Sdrh ** The cursor for the object that contains the complete data (normally
199926198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
200026198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
200126198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
200226198bb4Sdrh **
200326198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
200426198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
200526198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
200626198bb4Sdrh **
200726198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
200826198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
200926198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
201026198bb4Sdrh ** pTab->pIndex list.
2011b6b4b79fSdrh **
2012b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the
2013b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized.
2014cd44690aSdrh */
2015aa9b8963Sdrh int sqlite3OpenTableAndIndices(
2016290c1948Sdrh   Parse *pParse,   /* Parsing context */
2017290c1948Sdrh   Table *pTab,     /* Table to be opened */
201826198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
2019b89aeb6aSdrh   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
202026198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
20216a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
202226198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
202326198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
2024290c1948Sdrh ){
2025cd44690aSdrh   int i;
20264cbdda9eSdrh   int iDb;
20276a53499aSdrh   int iDataCur;
2028cd44690aSdrh   Index *pIdx;
20294cbdda9eSdrh   Vdbe *v;
20304cbdda9eSdrh 
203126198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
2032fd261ec6Sdan   assert( op==OP_OpenWrite || p5==0 );
203326198bb4Sdrh   if( IsVirtual(pTab) ){
2034b6b4b79fSdrh     /* This routine is a no-op for virtual tables. Leave the output
2035b6b4b79fSdrh     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
2036b6b4b79fSdrh     ** can detect if they are used by mistake in the caller. */
203726198bb4Sdrh     return 0;
203826198bb4Sdrh   }
20394cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
20404cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
2041cd44690aSdrh   assert( v!=0 );
204226198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
20436a53499aSdrh   iDataCur = iBase++;
20446a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
20456a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
20466a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
20476fbe41acSdrh   }else{
204826198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
20496fbe41acSdrh   }
20506a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
205126198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
205226198bb4Sdrh     int iIdxCur = iBase++;
2053da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
205461441c34Sdan     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
205561441c34Sdan       if( piDataCur ) *piDataCur = iIdxCur;
205661441c34Sdan       p5 = 0;
205761441c34Sdan     }
20586a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
20592ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
20602ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2061b89aeb6aSdrh       sqlite3VdbeChangeP5(v, p5);
206261441c34Sdan       VdbeComment((v, "%s", pIdx->zName));
2063b89aeb6aSdrh     }
20646a53499aSdrh   }
206526198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
206626198bb4Sdrh   return i;
2067cd44690aSdrh }
20689d9cf229Sdrh 
206991c58e23Sdrh 
207091c58e23Sdrh #ifdef SQLITE_TEST
207191c58e23Sdrh /*
207291c58e23Sdrh ** The following global variable is incremented whenever the
207391c58e23Sdrh ** transfer optimization is used.  This is used for testing
207491c58e23Sdrh ** purposes only - to make sure the transfer optimization really
207560ec914cSpeter.d.reid ** is happening when it is supposed to.
207691c58e23Sdrh */
207791c58e23Sdrh int sqlite3_xferopt_count;
207891c58e23Sdrh #endif /* SQLITE_TEST */
207991c58e23Sdrh 
208091c58e23Sdrh 
20819d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
20829d9cf229Sdrh /*
20839d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
20849d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
20859d9cf229Sdrh ** for a compatible index:
20869d9cf229Sdrh **
20879d9cf229Sdrh **    *   The index is over the same set of columns
20889d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
20899d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
20909d9cf229Sdrh **    *   The same collating sequence on each column
2091b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
20929d9cf229Sdrh */
20939d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
20949d9cf229Sdrh   int i;
20959d9cf229Sdrh   assert( pDest && pSrc );
20969d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
2097bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
20989d9cf229Sdrh     return 0;   /* Different number of columns */
20999d9cf229Sdrh   }
21009d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
21019d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
21029d9cf229Sdrh   }
2103bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
21049d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
21059d9cf229Sdrh       return 0;   /* Different columns indexed */
21069d9cf229Sdrh     }
21074b92f98cSdrh     if( pSrc->aiColumn[i]==XN_EXPR ){
21081f9ca2c8Sdrh       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
21095aa550cfSdan       if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
21101f9ca2c8Sdrh                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
21111f9ca2c8Sdrh         return 0;   /* Different expressions in the index */
21121f9ca2c8Sdrh       }
21131f9ca2c8Sdrh     }
21149d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
21159d9cf229Sdrh       return 0;   /* Different sort orders */
21169d9cf229Sdrh     }
21170472af91Sdrh     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
211860a713c6Sdrh       return 0;   /* Different collating sequences */
21199d9cf229Sdrh     }
21209d9cf229Sdrh   }
21215aa550cfSdan   if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2122b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
2123b2b9d3d7Sdrh   }
21249d9cf229Sdrh 
21259d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
21269d9cf229Sdrh   return 1;
21279d9cf229Sdrh }
21289d9cf229Sdrh 
21299d9cf229Sdrh /*
21309d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
21319d9cf229Sdrh **
21329d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
21339d9cf229Sdrh **
2134ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
213560ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves
2136ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
21379d9cf229Sdrh **
2138ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2139ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
2140ccdf1baeSdrh ** embedded in the code for details.
21419d9cf229Sdrh **
2142ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
2143ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
2144ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
2145ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
2146ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
2147ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
2148ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
2149ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
2150ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
21519d9cf229Sdrh **
2152ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
21539d9cf229Sdrh */
21549d9cf229Sdrh static int xferOptimization(
21559d9cf229Sdrh   Parse *pParse,        /* Parser context */
21569d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
21579d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
21589d9cf229Sdrh   int onError,          /* How to handle constraint errors */
21599d9cf229Sdrh   int iDbDest           /* The database of pDest */
21609d9cf229Sdrh ){
2161e34162b1Sdan   sqlite3 *db = pParse->db;
21629d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
21639d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
21649d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
21659d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
21669d9cf229Sdrh   int i;                           /* Loop counter */
21679d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
21689d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
21699d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
2170da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
2171da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
21729d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
21736a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
2174f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
2175b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
21769d9cf229Sdrh 
21779d9cf229Sdrh   if( pSelect==0 ){
21789d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
21799d9cf229Sdrh   }
2180ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
2181ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
2182ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
2183ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
2184ebbf08a0Sdan     return 0;
2185ebbf08a0Sdan   }
21862f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
21879d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
21889d9cf229Sdrh   }
21899d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
219044266ec6Sdrh   if( IsVirtual(pDest) ){
21919d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
21929d9cf229Sdrh   }
21939d9cf229Sdrh #endif
21949d9cf229Sdrh   if( onError==OE_Default ){
2195e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2196e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
21979d9cf229Sdrh   }
21985ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
21999d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
22009d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
22019d9cf229Sdrh   }
22029d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
22039d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
22049d9cf229Sdrh   }
22059d9cf229Sdrh   if( pSelect->pWhere ){
22069d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
22079d9cf229Sdrh   }
22089d9cf229Sdrh   if( pSelect->pOrderBy ){
22099d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
22109d9cf229Sdrh   }
22118103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
22128103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
22139d9cf229Sdrh   if( pSelect->pGroupBy ){
22149d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
22159d9cf229Sdrh   }
22169d9cf229Sdrh   if( pSelect->pLimit ){
22179d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
22189d9cf229Sdrh   }
22199d9cf229Sdrh   if( pSelect->pPrior ){
22209d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
22219d9cf229Sdrh   }
22227d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
22239d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
22249d9cf229Sdrh   }
22259d9cf229Sdrh   pEList = pSelect->pEList;
22269d9cf229Sdrh   assert( pEList!=0 );
22279d9cf229Sdrh   if( pEList->nExpr!=1 ){
22289d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
22299d9cf229Sdrh   }
22309d9cf229Sdrh   assert( pEList->a[0].pExpr );
22311a1d3cd2Sdrh   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
22329d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
22339d9cf229Sdrh   }
22349d9cf229Sdrh 
22359d9cf229Sdrh   /* At this point we have established that the statement is of the
22369d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
22379d9cf229Sdrh   ** we have to check the semantics.
22389d9cf229Sdrh   */
22399d9cf229Sdrh   pItem = pSelect->pSrc->a;
224041fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
22419d9cf229Sdrh   if( pSrc==0 ){
22429d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
22439d9cf229Sdrh   }
224421908b21Sdrh   if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
224521908b21Sdrh     testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
22469d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
22479d9cf229Sdrh   }
224855548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
224955548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
225055548273Sdrh   }
22519d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
225244266ec6Sdrh   if( IsVirtual(pSrc) ){
22539d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
22549d9cf229Sdrh   }
22559d9cf229Sdrh #endif
22569d9cf229Sdrh   if( pSrc->pSelect ){
22579d9cf229Sdrh     return 0;   /* tab2 may not be a view */
22589d9cf229Sdrh   }
22599d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
22609d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
22619d9cf229Sdrh   }
22629d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
22639d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
22649d9cf229Sdrh   }
22659d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
22669940e2aaSdan     Column *pDestCol = &pDest->aCol[i];
22679940e2aaSdan     Column *pSrcCol = &pSrc->aCol[i];
2268ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
22698257aa8dSdrh     if( (db->mDbFlags & DBFLAG_Vacuum)==0
2270aaea3143Sdan      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2271aaea3143Sdan     ){
2272ba68f8f3Sdan       return 0;    /* Neither table may have __hidden__ columns */
2273ba68f8f3Sdan     }
2274ba68f8f3Sdan #endif
22759940e2aaSdan     if( pDestCol->affinity!=pSrcCol->affinity ){
22769d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
22779d9cf229Sdrh     }
22780472af91Sdrh     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
22799d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
22809d9cf229Sdrh     }
22819940e2aaSdan     if( pDestCol->notNull && !pSrcCol->notNull ){
22829d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
22839d9cf229Sdrh     }
2284453e0261Sdrh     /* Default values for second and subsequent columns need to match. */
228594fa9c41Sdrh     if( i>0 ){
228694fa9c41Sdrh       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
228794fa9c41Sdrh       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
228894fa9c41Sdrh       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
228994fa9c41Sdrh        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
229094fa9c41Sdrh                                        pSrcCol->pDflt->u.zToken)!=0)
22919940e2aaSdan       ){
22929940e2aaSdan         return 0;    /* Default values must be the same for all columns */
22939940e2aaSdan       }
22949d9cf229Sdrh     }
229594fa9c41Sdrh   }
22969d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
22975f1d1d9cSdrh     if( IsUniqueIndex(pDestIdx) ){
2298f33c9fadSdrh       destHasUniqueIdx = 1;
2299f33c9fadSdrh     }
23009d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
23019d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
23029d9cf229Sdrh     }
23039d9cf229Sdrh     if( pSrcIdx==0 ){
23049d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
23059d9cf229Sdrh     }
2306e3bd232eSdrh     if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
2307e3bd232eSdrh          && sqlite3FaultSim(411)==SQLITE_OK ){
2308e3bd232eSdrh       /* The sqlite3FaultSim() call allows this corruption test to be
2309e3bd232eSdrh       ** bypassed during testing, in order to exercise other corruption tests
2310e3bd232eSdrh       ** further downstream. */
231186223e8dSdrh       return 0;   /* Corrupt schema - two indexes on the same btree */
231286223e8dSdrh     }
23139d9cf229Sdrh   }
23147fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
2315619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
23168103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
23178103b7d2Sdrh   }
23187fc2f41bSdrh #endif
2319713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
2320713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
2321713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
2322713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
2323713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
2324713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
2325713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2326713de341Sdrh   */
2327e34162b1Sdan   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
2328713de341Sdrh     return 0;
2329713de341Sdrh   }
2330713de341Sdrh #endif
2331e34162b1Sdan   if( (db->flags & SQLITE_CountRows)!=0 ){
2332ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
23331696124dSdan   }
23349d9cf229Sdrh 
2335ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
2336ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
2337ccdf1baeSdrh   ** table (tab1) is initially empty.
23389d9cf229Sdrh   */
2339dd73521bSdrh #ifdef SQLITE_TEST
2340dd73521bSdrh   sqlite3_xferopt_count++;
2341dd73521bSdrh #endif
2342e34162b1Sdan   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
23439d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
2344f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
23459d9cf229Sdrh   iSrc = pParse->nTab++;
23469d9cf229Sdrh   iDest = pParse->nTab++;
23476a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
234855548273Sdrh   regData = sqlite3GetTempReg(pParse);
234955548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
23509d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2351427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
23528257aa8dSdrh   if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
2353e34162b1Sdan       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2354ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
2355ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2356e34162b1Sdan   )){
2357ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
2358e34162b1Sdan     ** only if the destination table is initially empty. Unless the
23598257aa8dSdrh     ** DBFLAG_Vacuum flag is set, this block generates code to make
23608257aa8dSdrh     ** that determination. If DBFLAG_Vacuum is set, then the destination
2361e34162b1Sdan     ** table is always empty.
2362e34162b1Sdan     **
2363e34162b1Sdan     ** Conditions under which the destination must be empty:
2364f33c9fadSdrh     **
2365ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2366ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
2367ccdf1baeSdrh     **     of index entries might need to change.)
2368ccdf1baeSdrh     **
2369ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
2370ccdf1baeSdrh     **     is unable to test uniqueness.)
2371ccdf1baeSdrh     **
2372ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
23739d9cf229Sdrh     */
2374688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
23752991ba05Sdrh     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
23769d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
23779d9cf229Sdrh   }
2378427ebba1Sdan   if( HasRowid(pSrc) ){
2379c9b9deaeSdrh     u8 insFlags;
23809d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
2381688852abSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
238242242dedSdrh     if( pDest->iPKey>=0 ){
2383b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
23844031bafaSdrh       sqlite3VdbeVerifyAbortable(v, onError);
2385b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2386688852abSdrh       VdbeCoverage(v);
2387f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
23889d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
2389b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
23904e61e883Sdrh     }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
2391b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
239295bad4c7Sdrh     }else{
2393b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
23947d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
239595bad4c7Sdrh     }
2396e7b554d6Sdrh     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
23978257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
239886b40dfdSdrh       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2399c9b9deaeSdrh       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
2400c9b9deaeSdrh                            OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
2401c9b9deaeSdrh     }else{
2402c9b9deaeSdrh       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
2403c9b9deaeSdrh     }
24049b34abeeSdrh     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
240520f272c9Sdrh                       (char*)pDest, P4_TABLE);
2406c9b9deaeSdrh     sqlite3VdbeChangeP5(v, insFlags);
2407688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
240855548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
240955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2410da475b8dSdrh   }else{
2411da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2412da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
241355548273Sdrh   }
24149d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
241541b9ca25Sdrh     u8 idxInsFlags = 0;
24161b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
24179d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
24189d9cf229Sdrh     }
24199d9cf229Sdrh     assert( pSrcIdx );
24202ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
24212ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2422d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
24232ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
24242ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
242559885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2426207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
2427688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2428e7b554d6Sdrh     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
24298257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
2430e34162b1Sdan       /* This INSERT command is part of a VACUUM operation, which guarantees
2431e34162b1Sdan       ** that the destination table is empty. If all indexed columns use
2432e34162b1Sdan       ** collation sequence BINARY, then it can also be assumed that the
2433e34162b1Sdan       ** index will be populated by inserting keys in strictly sorted
2434e34162b1Sdan       ** order. In this case, instead of seeking within the b-tree as part
243586b40dfdSdrh       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
2436e34162b1Sdan       ** OP_IdxInsert to seek to the point within the b-tree where each key
2437e34162b1Sdan       ** should be inserted. This is faster.
2438e34162b1Sdan       **
2439e34162b1Sdan       ** If any of the indexed columns use a collation sequence other than
2440e34162b1Sdan       ** BINARY, this optimization is disabled. This is because the user
2441e34162b1Sdan       ** might change the definition of a collation sequence and then run
2442e34162b1Sdan       ** a VACUUM command. In that case keys may not be written in strictly
2443e34162b1Sdan       ** sorted order.  */
2444e34162b1Sdan       for(i=0; i<pSrcIdx->nColumn; i++){
2445f19aa5faSdrh         const char *zColl = pSrcIdx->azColl[i];
2446f19aa5faSdrh         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
2447e34162b1Sdan       }
2448e34162b1Sdan       if( i==pSrcIdx->nColumn ){
244941b9ca25Sdrh         idxInsFlags = OPFLAG_USESEEKRESULT;
245086b40dfdSdrh         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2451e34162b1Sdan       }
2452e34162b1Sdan     }
24539df385ecSdrh     if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
245441b9ca25Sdrh       idxInsFlags |= OPFLAG_NCHANGE;
245541b9ca25Sdrh     }
24569b4eaebcSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
24579b4eaebcSdrh     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
2458688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
24599d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
246055548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
246155548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
24629d9cf229Sdrh   }
2463aceb31b1Sdrh   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2464b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2465b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
24669d9cf229Sdrh   if( emptyDestTest ){
24671dd518cfSdrh     sqlite3AutoincrementEnd(pParse);
246866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
24699d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
247066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
24719d9cf229Sdrh     return 0;
24729d9cf229Sdrh   }else{
24739d9cf229Sdrh     return 1;
24749d9cf229Sdrh   }
24759d9cf229Sdrh }
24769d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2477