xref: /sqlite-3.40.0/src/insert.c (revision 186ebd41)
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) ){
40261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
41bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
4226198bb4Sdrh   }else{
43dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44dd9930efSdrh     assert( pPk!=0 );
45afe028a8Sdrh     assert( pPk->tnum==pTab->tnum );
462ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
472ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
48bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
49bbb5e4e0Sdrh   }
50bbb5e4e0Sdrh }
51bbb5e4e0Sdrh 
52bbb5e4e0Sdrh /*
5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5569f8bb9cSdan ** the table, according to the affinity of the column:
563d1bfeaaSdanielk1977 **
573d1bfeaaSdanielk1977 **  Character      Column affinity
583d1bfeaaSdanielk1977 **  ------------------------------
5905883a34Sdrh **  'A'            BLOB
604583c37cSdrh **  'B'            TEXT
614583c37cSdrh **  'C'            NUMERIC
624583c37cSdrh **  'D'            INTEGER
634583c37cSdrh **  'F'            REAL
642d401ab8Sdrh **
654583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the
662d401ab8Sdrh ** rowid that appears as the last column in every index.
6769f8bb9cSdan **
6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
713d1bfeaaSdanielk1977 */
72e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
73a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
74e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
75a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
76e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
77a37cdde0Sdanielk1977     **
78a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
79e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80a37cdde0Sdanielk1977     ** up.
81a37cdde0Sdanielk1977     */
82a37cdde0Sdanielk1977     int n;
83a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
84ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
864a642b60Sdrh       sqlite3OomFault(db);
8769f8bb9cSdan       return 0;
88a37cdde0Sdanielk1977     }
89a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
90ad124329Sdrh       i16 x = pIdx->aiColumn[n];
911f9ca2c8Sdrh       if( x>=0 ){
921f9ca2c8Sdrh         pIdx->zColAff[n] = pTab->aCol[x].affinity;
934b92f98cSdrh       }else if( x==XN_ROWID ){
941f9ca2c8Sdrh         pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
951f9ca2c8Sdrh       }else{
966860e6faSdrh         char aff;
974b92f98cSdrh         assert( x==XN_EXPR );
981f9ca2c8Sdrh         assert( pIdx->aColExpr!=0 );
996860e6faSdrh         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
1006860e6faSdrh         if( aff==0 ) aff = SQLITE_AFF_BLOB;
1016860e6faSdrh         pIdx->zColAff[n] = aff;
1021f9ca2c8Sdrh       }
103a37cdde0Sdanielk1977     }
1042d401ab8Sdrh     pIdx->zColAff[n] = 0;
105a37cdde0Sdanielk1977   }
1063d1bfeaaSdanielk1977 
10769f8bb9cSdan   return pIdx->zColAff;
108a37cdde0Sdanielk1977 }
109a37cdde0Sdanielk1977 
110a37cdde0Sdanielk1977 /*
11157bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been
11205883a34Sdrh ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
11357bf4a8eSdrh **
11405883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
11557bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
11657bf4a8eSdrh ** for register iReg and following.  Or if affinities exists and iReg==0,
11757bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should  be
11857bf4a8eSdrh ** an OP_MakeRecord) to the affinity string.
11957bf4a8eSdrh **
120b6e8fd10Sdrh ** A column affinity string has one character per column:
121a37cdde0Sdanielk1977 **
122a37cdde0Sdanielk1977 **  Character      Column affinity
123a37cdde0Sdanielk1977 **  ------------------------------
12405883a34Sdrh **  'A'            BLOB
1254583c37cSdrh **  'B'            TEXT
1264583c37cSdrh **  'C'            NUMERIC
1274583c37cSdrh **  'D'            INTEGER
1284583c37cSdrh **  'E'            REAL
129a37cdde0Sdanielk1977 */
13057bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
1313d1bfeaaSdanielk1977   int i;
13257bf4a8eSdrh   char *zColAff = pTab->zColAff;
13357bf4a8eSdrh   if( zColAff==0 ){
134abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
135b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1363d1bfeaaSdanielk1977     if( !zColAff ){
1374a642b60Sdrh       sqlite3OomFault(db);
138a37cdde0Sdanielk1977       return;
1393d1bfeaaSdanielk1977     }
1403d1bfeaaSdanielk1977 
1413d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
142a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1433d1bfeaaSdanielk1977     }
14457bf4a8eSdrh     do{
14557bf4a8eSdrh       zColAff[i--] = 0;
14605883a34Sdrh     }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
1473d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1483d1bfeaaSdanielk1977   }
14957bf4a8eSdrh   i = sqlite3Strlen30(zColAff);
15057bf4a8eSdrh   if( i ){
15157bf4a8eSdrh     if( iReg ){
15257bf4a8eSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
15357bf4a8eSdrh     }else{
15457bf4a8eSdrh       sqlite3VdbeChangeP4(v, -1, zColAff, i);
15557bf4a8eSdrh     }
15657bf4a8eSdrh   }
1573d1bfeaaSdanielk1977 }
1583d1bfeaaSdanielk1977 
1594d88778bSdanielk1977 /*
16048d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
161b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if
16248d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
163b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT.
1644d88778bSdanielk1977 */
16505a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){
166595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1674d88778bSdanielk1977   int i;
16848d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
169595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
170595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
171595a523aSdanielk1977 #endif
172595a523aSdanielk1977 
17305a86c5cSdrh   for(i=1; i<iEnd; i++){
17448d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
175ef0bea92Sdrh     assert( pOp!=0 );
176207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
17748d1178aSdrh       Index *pIndex;
178207872a4Sdanielk1977       int tnum = pOp->p2;
17948d1178aSdrh       if( tnum==pTab->tnum ){
18048d1178aSdrh         return 1;
18148d1178aSdrh       }
18248d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
18348d1178aSdrh         if( tnum==pIndex->tnum ){
18448d1178aSdrh           return 1;
18548d1178aSdrh         }
18648d1178aSdrh       }
18748d1178aSdrh     }
188543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
189595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1902dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
19166a5167bSdrh       assert( pOp->p4type==P4_VTAB );
19248d1178aSdrh       return 1;
1934d88778bSdanielk1977     }
194543165efSdrh #endif
1954d88778bSdanielk1977   }
1964d88778bSdanielk1977   return 0;
1974d88778bSdanielk1977 }
1983d1bfeaaSdanielk1977 
1999d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
2009d9cf229Sdrh /*
2010b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
2020b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
2039ef5e770Sdrh ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
2049ef5e770Sdrh ** table.  (Also return zero when doing a VACUUM since we do not want to
2059ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.)
2069d9cf229Sdrh **
2070b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
2080b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
2090b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
2100b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
2110b9f50d8Sdrh ** AutoincInfo structure is used.
2129d9cf229Sdrh **
213c8abbc11Sdrh ** Four consecutive registers are allocated:
2140b9f50d8Sdrh **
215c8abbc11Sdrh **   (1)  The name of the pTab table.
216c8abbc11Sdrh **   (2)  The maximum ROWID of pTab.
217c8abbc11Sdrh **   (3)  The rowid in sqlite_sequence of pTab
218c8abbc11Sdrh **   (4)  The original value of the max ROWID in pTab, or NULL if none
2190b9f50d8Sdrh **
2200b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2210b9f50d8Sdrh ** insert routine needs to know about.
2229d9cf229Sdrh */
2239d9cf229Sdrh static int autoIncBegin(
2249d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2259d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2269d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2279d9cf229Sdrh ){
2286a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
229*186ebd41Sdrh   assert( pParse->db->aDb[iDb].pSchema!=0 );
2309ef5e770Sdrh   if( (pTab->tabFlags & TF_Autoincrement)!=0
2318257aa8dSdrh    && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
2329ef5e770Sdrh   ){
23365a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2340b9f50d8Sdrh     AutoincInfo *pInfo;
235*186ebd41Sdrh     Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
236*186ebd41Sdrh 
237*186ebd41Sdrh     /* Verify that the sqlite_sequence table exists and is an ordinary
238*186ebd41Sdrh     ** rowid table with exactly two columns.
239*186ebd41Sdrh     ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
240*186ebd41Sdrh     if( pSeqTab==0
241*186ebd41Sdrh      || !HasRowid(pSeqTab)
242*186ebd41Sdrh      || IsVirtual(pSeqTab)
243*186ebd41Sdrh      || pSeqTab->nCol!=2
244*186ebd41Sdrh     ){
245*186ebd41Sdrh       pParse->nErr++;
246*186ebd41Sdrh       pParse->rc = SQLITE_CORRUPT_SEQUENCE;
247*186ebd41Sdrh       return 0;
248*186ebd41Sdrh     }
2490b9f50d8Sdrh 
25065a7cd16Sdan     pInfo = pToplevel->pAinc;
2510b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2520b9f50d8Sdrh     if( pInfo==0 ){
253575fad65Sdrh       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
2540b9f50d8Sdrh       if( pInfo==0 ) return 0;
25565a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
25665a7cd16Sdan       pToplevel->pAinc = pInfo;
2570b9f50d8Sdrh       pInfo->pTab = pTab;
2580b9f50d8Sdrh       pInfo->iDb = iDb;
25965a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
26065a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
261c8abbc11Sdrh       pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
2620b9f50d8Sdrh     }
2630b9f50d8Sdrh     memId = pInfo->regCtr;
2649d9cf229Sdrh   }
2659d9cf229Sdrh   return memId;
2669d9cf229Sdrh }
2679d9cf229Sdrh 
2689d9cf229Sdrh /*
2690b9f50d8Sdrh ** This routine generates code that will initialize all of the
2700b9f50d8Sdrh ** register used by the autoincrement tracker.
2710b9f50d8Sdrh */
2720b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2730b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2740b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2750b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2760b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2770b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2780b9f50d8Sdrh 
279345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
280345ba7dbSdrh   ** only called from the top-level */
281345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
282c149f18fSdrh   assert( sqlite3IsToplevel(pParse) );
28376d462eeSdan 
2840b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2850b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2861b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
2871b32554bSdrh     static const VdbeOpList autoInc[] = {
2881b32554bSdrh       /* 0  */ {OP_Null,    0,  0, 0},
289c8abbc11Sdrh       /* 1  */ {OP_Rewind,  0, 10, 0},
2901b32554bSdrh       /* 2  */ {OP_Column,  0,  0, 0},
291c8abbc11Sdrh       /* 3  */ {OP_Ne,      0,  9, 0},
2921b32554bSdrh       /* 4  */ {OP_Rowid,   0,  0, 0},
2931b32554bSdrh       /* 5  */ {OP_Column,  0,  1, 0},
294c8abbc11Sdrh       /* 6  */ {OP_AddImm,  0,  0, 0},
295c8abbc11Sdrh       /* 7  */ {OP_Copy,    0,  0, 0},
296c8abbc11Sdrh       /* 8  */ {OP_Goto,    0, 11, 0},
297c8abbc11Sdrh       /* 9  */ {OP_Next,    0,  2, 0},
298c8abbc11Sdrh       /* 10 */ {OP_Integer, 0,  0, 0},
299c8abbc11Sdrh       /* 11 */ {OP_Close,   0,  0, 0}
3001b32554bSdrh     };
3011b32554bSdrh     VdbeOp *aOp;
3020b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
3030b9f50d8Sdrh     memId = p->regCtr;
3042120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3050b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
306076e85f5Sdrh     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
3071b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
3081b32554bSdrh     if( aOp==0 ) break;
3091b32554bSdrh     aOp[0].p2 = memId;
310c8abbc11Sdrh     aOp[0].p3 = memId+2;
3111b32554bSdrh     aOp[2].p3 = memId;
3121b32554bSdrh     aOp[3].p1 = memId-1;
3131b32554bSdrh     aOp[3].p3 = memId;
3141b32554bSdrh     aOp[3].p5 = SQLITE_JUMPIFNULL;
3151b32554bSdrh     aOp[4].p2 = memId+1;
3161b32554bSdrh     aOp[5].p3 = memId;
317c8abbc11Sdrh     aOp[6].p1 = memId;
318c8abbc11Sdrh     aOp[7].p2 = memId+2;
319c8abbc11Sdrh     aOp[7].p1 = memId;
320c8abbc11Sdrh     aOp[10].p2 = memId;
3210b9f50d8Sdrh   }
3220b9f50d8Sdrh }
3230b9f50d8Sdrh 
3240b9f50d8Sdrh /*
3259d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
3269d9cf229Sdrh **
3271b32554bSdrh ** This routine should be called when the regRowid register holds a
3289d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
3299d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
3301b32554bSdrh ** memory cell is updated.
3319d9cf229Sdrh */
3326a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
3339d9cf229Sdrh   if( memId>0 ){
3346a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
3359d9cf229Sdrh   }
3369d9cf229Sdrh }
3379d9cf229Sdrh 
3389d9cf229Sdrh /*
3390b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
3400b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
3410b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
3420b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
3430b9f50d8Sdrh ** routine just before the "exit" code.
3449d9cf229Sdrh */
3451b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
3460b9f50d8Sdrh   AutoincInfo *p;
3479d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
3480b9f50d8Sdrh   sqlite3 *db = pParse->db;
3496a288a33Sdrh 
3509d9cf229Sdrh   assert( v );
3510b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3521b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
3531b32554bSdrh     static const VdbeOpList autoIncEnd[] = {
3541b32554bSdrh       /* 0 */ {OP_NotNull,     0, 2, 0},
3551b32554bSdrh       /* 1 */ {OP_NewRowid,    0, 0, 0},
3561b32554bSdrh       /* 2 */ {OP_MakeRecord,  0, 2, 0},
3571b32554bSdrh       /* 3 */ {OP_Insert,      0, 0, 0},
3581b32554bSdrh       /* 4 */ {OP_Close,       0, 0, 0}
3591b32554bSdrh     };
3601b32554bSdrh     VdbeOp *aOp;
3610b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3620b9f50d8Sdrh     int iRec;
3630b9f50d8Sdrh     int memId = p->regCtr;
3640b9f50d8Sdrh 
3650b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3662120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
367c8abbc11Sdrh     sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
368c8abbc11Sdrh     VdbeCoverage(v);
3690b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3701b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
3711b32554bSdrh     if( aOp==0 ) break;
3721b32554bSdrh     aOp[0].p1 = memId+1;
3731b32554bSdrh     aOp[1].p2 = memId+1;
3741b32554bSdrh     aOp[2].p1 = memId-1;
3751b32554bSdrh     aOp[2].p3 = iRec;
3761b32554bSdrh     aOp[3].p2 = iRec;
3771b32554bSdrh     aOp[3].p3 = memId+1;
3781b32554bSdrh     aOp[3].p5 = OPFLAG_APPEND;
3790b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3809d9cf229Sdrh   }
3819d9cf229Sdrh }
3821b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){
3831b32554bSdrh   if( pParse->pAinc ) autoIncrementEnd(pParse);
3841b32554bSdrh }
3859d9cf229Sdrh #else
3869d9cf229Sdrh /*
3879d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3889d9cf229Sdrh ** above are all no-ops
3899d9cf229Sdrh */
3909d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
391287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3929d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3939d9cf229Sdrh 
3949d9cf229Sdrh 
3959d9cf229Sdrh /* Forward declaration */
3969d9cf229Sdrh static int xferOptimization(
3979d9cf229Sdrh   Parse *pParse,        /* Parser context */
3989d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
3999d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4009d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4019d9cf229Sdrh   int iDbDest           /* The database of pDest */
4029d9cf229Sdrh );
4039d9cf229Sdrh 
4043d1bfeaaSdanielk1977 /*
405d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
406cce7d176Sdrh **
407a21f78b9Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
4081ccde15dSdrh **    insert into TABLE (IDLIST) select
409a21f78b9Sdrh **    insert into TABLE (IDLIST) default values
410cce7d176Sdrh **
4111ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
412a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted.
413a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
414a21f78b9Sdrh ** is omitted.
4151ccde15dSdrh **
416a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the
417a21f78b9Sdrh ** first two forms shown above.  A VALUES clause is really just short-hand
418a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else
419a21f78b9Sdrh ** that follows.  If the pSelect parameter is NULL, that means that the
420a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended.
421142e30dfSdrh **
4229d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
423a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes
424e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
425e00ee6ebSdrh ** the "1st template"):
426142e30dfSdrh **
427142e30dfSdrh **         open write cursor to <table> and its indices
428ec95c441Sdrh **         put VALUES clause expressions into registers
429142e30dfSdrh **         write the resulting record into <table>
430142e30dfSdrh **         cleanup
431142e30dfSdrh **
4329d9cf229Sdrh ** The three remaining templates assume the statement is of the form
433142e30dfSdrh **
434142e30dfSdrh **   INSERT INTO <table> SELECT ...
435142e30dfSdrh **
4369d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4379d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4389d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4399d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4409d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4419d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4429d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
443e00ee6ebSdrh ** template.  This is the 2nd template.
4449d9cf229Sdrh **
4459d9cf229Sdrh **         open a write cursor to <table>
4469d9cf229Sdrh **         open read cursor on <table2>
4479d9cf229Sdrh **         transfer all records in <table2> over to <table>
4489d9cf229Sdrh **         close cursors
4499d9cf229Sdrh **         foreach index on <table>
4509d9cf229Sdrh **           open a write cursor on the <table> index
4519d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4529d9cf229Sdrh **           transfer all records from the read to the write cursors
4539d9cf229Sdrh **           close cursors
4549d9cf229Sdrh **         end foreach
4559d9cf229Sdrh **
456e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4579d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4589d9cf229Sdrh ** The generated code follows this template:
459142e30dfSdrh **
460e00ee6ebSdrh **         X <- A
461142e30dfSdrh **         goto B
462142e30dfSdrh **      A: setup for the SELECT
4639d9cf229Sdrh **         loop over the rows in the SELECT
464e00ee6ebSdrh **           load values into registers R..R+n
465e00ee6ebSdrh **           yield X
466142e30dfSdrh **         end loop
467142e30dfSdrh **         cleanup after the SELECT
46881cf13ecSdrh **         end-coroutine X
469e00ee6ebSdrh **      B: open write cursor to <table> and its indices
47081cf13ecSdrh **      C: yield X, at EOF goto D
471e00ee6ebSdrh **         insert the select result into <table> from R..R+n
472e00ee6ebSdrh **         goto C
473142e30dfSdrh **      D: cleanup
474142e30dfSdrh **
475e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
476142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
477142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
47860ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of
479142e30dfSdrh ** the select.  The template is like this:
480142e30dfSdrh **
481e00ee6ebSdrh **         X <- A
482142e30dfSdrh **         goto B
483142e30dfSdrh **      A: setup for the SELECT
484142e30dfSdrh **         loop over the tables in the SELECT
485e00ee6ebSdrh **           load value into register R..R+n
486e00ee6ebSdrh **           yield X
487142e30dfSdrh **         end loop
488142e30dfSdrh **         cleanup after the SELECT
48981cf13ecSdrh **         end co-routine R
490e00ee6ebSdrh **      B: open temp table
49181cf13ecSdrh **      L: yield X, at EOF goto M
492e00ee6ebSdrh **         insert row from R..R+n into temp table
493e00ee6ebSdrh **         goto L
494e00ee6ebSdrh **      M: open write cursor to <table> and its indices
495e00ee6ebSdrh **         rewind temp table
496e00ee6ebSdrh **      C: loop over rows of intermediate table
497142e30dfSdrh **           transfer values form intermediate table into <table>
498e00ee6ebSdrh **         end loop
499e00ee6ebSdrh **      D: cleanup
500cce7d176Sdrh */
5014adee20fSdanielk1977 void sqlite3Insert(
502cce7d176Sdrh   Parse *pParse,        /* Parser context */
503113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
5045974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5059cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5062c2e844aSdrh   int onError,          /* How to handle constraint errors */
50746d2e5c3Sdrh   Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
508cce7d176Sdrh ){
5096a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5106a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
51160ffc807Sdrh   int i, j;             /* Loop counters */
5125974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5135974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
514967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5156a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
51626198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
51726198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
518d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5190ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
520cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
521e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
522e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
5232eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5246a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
52505a86c5cSdrh   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
52605a86c5cSdrh   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
52705a86c5cSdrh   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
528a21f78b9Sdrh   u8 bIdListInOrder;    /* True if IDLIST is in table order */
52975593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
530cce7d176Sdrh 
5316a288a33Sdrh   /* Register allocations */
5321bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5336a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5346a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5356a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5366a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5376a288a33Sdrh   int regData;          /* register holding first column to insert */
538aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5396a288a33Sdrh 
540798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
541798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5422f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5432f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
544798da52cSdrh #endif
545c3f9bad2Sdanielk1977 
54617435752Sdrh   db = pParse->db;
54717435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5486f7adc8aSdrh     goto insert_cleanup;
5496f7adc8aSdrh   }
5504c883487Sdrh   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
551daffd0e5Sdrh 
55275593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
553a21f78b9Sdrh   ** single row (the common case) then keep that one row of values
554a21f78b9Sdrh   ** and discard the other (unused) parts of the pSelect object
55575593d96Sdrh   */
55675593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
55775593d96Sdrh     pList = pSelect->pEList;
55875593d96Sdrh     pSelect->pEList = 0;
55975593d96Sdrh     sqlite3SelectDelete(db, pSelect);
56075593d96Sdrh     pSelect = 0;
56175593d96Sdrh   }
56275593d96Sdrh 
5631ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5641ccde15dSdrh   */
565113088ecSdrh   assert( pTabList->nSrc==1 );
5664adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
567c3f9bad2Sdanielk1977   if( pTab==0 ){
568c3f9bad2Sdanielk1977     goto insert_cleanup;
569c3f9bad2Sdanielk1977   }
570da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
571da184236Sdanielk1977   assert( iDb<db->nDb );
572a0daa751Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
573a0daa751Sdrh                        db->aDb[iDb].zDbSName) ){
5741962bda7Sdrh     goto insert_cleanup;
5751962bda7Sdrh   }
576ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
577c3f9bad2Sdanielk1977 
578b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
579b7f9164eSdrh   ** inserted into is a view
580b7f9164eSdrh   */
581b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
5822f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
583b7f9164eSdrh   isView = pTab->pSelect!=0;
584b7f9164eSdrh #else
5852f886d1dSdanielk1977 # define pTrigger 0
5862f886d1dSdanielk1977 # define tmask 0
587b7f9164eSdrh # define isView 0
588b7f9164eSdrh #endif
589b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
590b7f9164eSdrh # undef isView
591b7f9164eSdrh # define isView 0
592b7f9164eSdrh #endif
5932f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
594b7f9164eSdrh 
595f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
596d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
597f573c99bSdrh   */
598b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
599f573c99bSdrh     goto insert_cleanup;
600f573c99bSdrh   }
601f573c99bSdrh 
602d82b5021Sdrh   /* Cannot insert into a read-only table.
603595a523aSdanielk1977   */
604595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
605595a523aSdanielk1977     goto insert_cleanup;
606595a523aSdanielk1977   }
607595a523aSdanielk1977 
6081ccde15dSdrh   /* Allocate a VDBE
6091ccde15dSdrh   */
6104adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6115974a30fSdrh   if( v==0 ) goto insert_cleanup;
6124794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6132f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6141ccde15dSdrh 
6159d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6169d9cf229Sdrh   /* If the statement is of the form
6179d9cf229Sdrh   **
6189d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6199d9cf229Sdrh   **
6209d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6219d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
622e00ee6ebSdrh   **
623e00ee6ebSdrh   ** This is the 2nd template.
6249d9cf229Sdrh   */
6259d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6262f886d1dSdanielk1977     assert( !pTrigger );
6279d9cf229Sdrh     assert( pList==0 );
6280b9f50d8Sdrh     goto insert_end;
6299d9cf229Sdrh   }
6309d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6319d9cf229Sdrh 
6322958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6336a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6342958a4e6Sdrh   */
6356a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6362958a4e6Sdrh 
63705a86c5cSdrh   /* Allocate registers for holding the rowid of the new row,
63860ec914cSpeter.d.reid   ** the content of the new row, and the assembled row record.
6391ccde15dSdrh   */
64005a86c5cSdrh   regRowid = regIns = pParse->nMem+1;
64105a86c5cSdrh   pParse->nMem += pTab->nCol + 1;
642034ca14fSdanielk1977   if( IsVirtual(pTab) ){
64305a86c5cSdrh     regRowid++;
64405a86c5cSdrh     pParse->nMem++;
645034ca14fSdanielk1977   }
64605a86c5cSdrh   regData = regRowid+1;
6471ccde15dSdrh 
6481ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6491ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6501ccde15dSdrh   ** remember the column indices.
651c8392586Sdrh   **
652c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
653d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
654d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
655c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
656d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
657d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
6581ccde15dSdrh   */
659a21f78b9Sdrh   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
660967e8b73Sdrh   if( pColumn ){
661967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
662967e8b73Sdrh       pColumn->a[i].idx = -1;
663cce7d176Sdrh     }
664967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
665cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6664adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
667967e8b73Sdrh           pColumn->a[i].idx = j;
66805a86c5cSdrh           if( i!=j ) bIdListInOrder = 0;
6694a32431cSdrh           if( j==pTab->iPKey ){
670d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
6714a32431cSdrh           }
672cce7d176Sdrh           break;
673cce7d176Sdrh         }
674cce7d176Sdrh       }
675cce7d176Sdrh       if( j>=pTab->nCol ){
676ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
677d82b5021Sdrh           ipkColumn = i;
678e48ae715Sdrh           bIdListInOrder = 0;
679a0217ba7Sdrh         }else{
6804adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
681da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
6821db95106Sdan           pParse->checkSchema = 1;
683cce7d176Sdrh           goto insert_cleanup;
684cce7d176Sdrh         }
685cce7d176Sdrh       }
686cce7d176Sdrh     }
687a0217ba7Sdrh   }
6881ccde15dSdrh 
689cce7d176Sdrh   /* Figure out how many columns of data are supplied.  If the data
690cce7d176Sdrh   ** is coming from a SELECT statement, then generate a co-routine that
691cce7d176Sdrh   ** produces a single row of the SELECT on each invocation.  The
692cce7d176Sdrh   ** co-routine is the common header to the 3rd and 4th templates.
693cce7d176Sdrh   */
6945f085269Sdrh   if( pSelect ){
695a21f78b9Sdrh     /* Data is coming from a SELECT or from a multi-row VALUES clause.
696a21f78b9Sdrh     ** Generate a co-routine to run the SELECT. */
69705a86c5cSdrh     int regYield;       /* Register holding co-routine entry-point */
69805a86c5cSdrh     int addrTop;        /* Top of the co-routine */
69905a86c5cSdrh     int rc;             /* Result code */
700cce7d176Sdrh 
70105a86c5cSdrh     regYield = ++pParse->nMem;
70205a86c5cSdrh     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
70305a86c5cSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
70405a86c5cSdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
70505a86c5cSdrh     dest.iSdst = bIdListInOrder ? regData : 0;
70605a86c5cSdrh     dest.nSdst = pTab->nCol;
70705a86c5cSdrh     rc = sqlite3Select(pParse, pSelect, &dest);
7082b596da8Sdrh     regFromSelect = dest.iSdst;
709992590beSdrh     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
7102fade2f7Sdrh     sqlite3VdbeEndCoroutine(v, regYield);
71105a86c5cSdrh     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
712cce7d176Sdrh     assert( pSelect->pEList );
713cce7d176Sdrh     nColumn = pSelect->pEList->nExpr;
714cce7d176Sdrh 
715cce7d176Sdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
716cce7d176Sdrh     ** should be written into a temporary table (template 4).  Set to
717cce7d176Sdrh     ** FALSE if each output row of the SELECT can be written directly into
718cce7d176Sdrh     ** the destination table (template 3).
719cce7d176Sdrh     **
720cce7d176Sdrh     ** A temp table must be used if the table being updated is also one
721cce7d176Sdrh     ** of the tables being read by the SELECT statement.  Also use a
722cce7d176Sdrh     ** temp table in the case of row triggers.
723cce7d176Sdrh     */
72405a86c5cSdrh     if( pTrigger || readsTable(pParse, iDb, pTab) ){
725cce7d176Sdrh       useTempTable = 1;
726cce7d176Sdrh     }
727cce7d176Sdrh 
728cce7d176Sdrh     if( useTempTable ){
729cce7d176Sdrh       /* Invoke the coroutine to extract information from the SELECT
730cce7d176Sdrh       ** and add it to a transient table srcTab.  The code generated
731cce7d176Sdrh       ** here is from the 4th template:
732cce7d176Sdrh       **
733cce7d176Sdrh       **      B: open temp table
73481cf13ecSdrh       **      L: yield X, goto M at EOF
735cce7d176Sdrh       **         insert row from R..R+n into temp table
736cce7d176Sdrh       **         goto L
737cce7d176Sdrh       **      M: ...
738cce7d176Sdrh       */
739cce7d176Sdrh       int regRec;          /* Register to hold packed record */
740cce7d176Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
74106280ee5Sdrh       int addrL;           /* Label "L" */
742cce7d176Sdrh 
743cce7d176Sdrh       srcTab = pParse->nTab++;
744cce7d176Sdrh       regRec = sqlite3GetTempReg(pParse);
745cce7d176Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
746cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
74706280ee5Sdrh       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
748cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
749cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
750cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
751076e85f5Sdrh       sqlite3VdbeGoto(v, addrL);
75206280ee5Sdrh       sqlite3VdbeJumpHere(v, addrL);
753cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
754cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
755cce7d176Sdrh     }
756cce7d176Sdrh   }else{
757a21f78b9Sdrh     /* This is the case if the data for the INSERT is coming from a
758a21f78b9Sdrh     ** single-row VALUES clause
759cce7d176Sdrh     */
760cce7d176Sdrh     NameContext sNC;
761cce7d176Sdrh     memset(&sNC, 0, sizeof(sNC));
762cce7d176Sdrh     sNC.pParse = pParse;
763cce7d176Sdrh     srcTab = -1;
764cce7d176Sdrh     assert( useTempTable==0 );
765fea870beSdrh     if( pList ){
766fea870beSdrh       nColumn = pList->nExpr;
767fea870beSdrh       if( sqlite3ResolveExprListNames(&sNC, pList) ){
768cce7d176Sdrh         goto insert_cleanup;
769cce7d176Sdrh       }
770fea870beSdrh     }else{
771fea870beSdrh       nColumn = 0;
772cce7d176Sdrh     }
773cce7d176Sdrh   }
774cce7d176Sdrh 
775aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
776d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
777d82b5021Sdrh   ** column index in the original table definition.
7784a32431cSdrh   */
779147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
780d82b5021Sdrh     ipkColumn = pTab->iPKey;
7814a32431cSdrh   }
7824a32431cSdrh 
783cce7d176Sdrh   /* Make sure the number of columns in the source data matches the number
784cce7d176Sdrh   ** of columns to be inserted into the table.
785cce7d176Sdrh   */
786cce7d176Sdrh   for(i=0; i<pTab->nCol; i++){
787cce7d176Sdrh     nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
788cce7d176Sdrh   }
789cce7d176Sdrh   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
790cce7d176Sdrh     sqlite3ErrorMsg(pParse,
791cce7d176Sdrh        "table %S has %d columns but %d values were supplied",
792cce7d176Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
793cce7d176Sdrh     goto insert_cleanup;
794cce7d176Sdrh   }
795cce7d176Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
796cce7d176Sdrh     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
797cce7d176Sdrh     goto insert_cleanup;
798cce7d176Sdrh   }
799cce7d176Sdrh 
800c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8011ccde15dSdrh   */
80279636913Sdrh   if( (db->flags & SQLITE_CountRows)!=0
80379636913Sdrh    && !pParse->nested
80479636913Sdrh    && !pParse->pTriggerTab
80579636913Sdrh   ){
8066a288a33Sdrh     regRowCount = ++pParse->nMem;
8076a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
808c3f9bad2Sdanielk1977   }
809c3f9bad2Sdanielk1977 
810e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
811e448dc4aSdanielk1977   if( !isView ){
812aa9b8963Sdrh     int nIdx;
813fd261ec6Sdan     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
81426198bb4Sdrh                                       &iDataCur, &iIdxCur);
815575fad65Sdrh     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
816aa9b8963Sdrh     if( aRegIdx==0 ){
817aa9b8963Sdrh       goto insert_cleanup;
818aa9b8963Sdrh     }
8192c4dfc30Sdrh     for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
8202c4dfc30Sdrh       assert( pIdx );
821aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
8222c4dfc30Sdrh       pParse->nMem += pIdx->nColumn;
823aa9b8963Sdrh     }
824feeb1394Sdrh   }
825788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT
8260b30a116Sdrh   if( pUpsert ){
827788d55aaSdrh     pTabList->a[0].iCursor = iDataCur;
8280b30a116Sdrh     pUpsert->pUpsertSrc = pTabList;
829eac9fabbSdrh     pUpsert->regData = regData;
8307fc3aba8Sdrh     pUpsert->iDataCur = iDataCur;
8317fc3aba8Sdrh     pUpsert->iIdxCur = iIdxCur;
8320b30a116Sdrh     if( pUpsert->pUpsertTarget ){
833e9c2e772Sdrh       sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
834788d55aaSdrh     }
8350b30a116Sdrh   }
836788d55aaSdrh #endif
837788d55aaSdrh 
838feeb1394Sdrh 
839e00ee6ebSdrh   /* This is the top of the main insertion loop */
840142e30dfSdrh   if( useTempTable ){
841e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
842e00ee6ebSdrh     ** following pseudocode (template 4):
843e00ee6ebSdrh     **
84481cf13ecSdrh     **         rewind temp table, if empty goto D
845e00ee6ebSdrh     **      C: loop over rows of intermediate table
846e00ee6ebSdrh     **           transfer values form intermediate table into <table>
847e00ee6ebSdrh     **         end loop
848e00ee6ebSdrh     **      D: ...
849e00ee6ebSdrh     */
850688852abSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
851e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
852142e30dfSdrh   }else if( pSelect ){
853e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
854e00ee6ebSdrh     ** following pseudocode (template 3):
855e00ee6ebSdrh     **
85681cf13ecSdrh     **      C: yield X, at EOF goto D
857e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
858e00ee6ebSdrh     **         goto C
859e00ee6ebSdrh     **      D: ...
860e00ee6ebSdrh     */
86181cf13ecSdrh     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
862688852abSdrh     VdbeCoverage(v);
863bed8690fSdrh   }
8641ccde15dSdrh 
8655cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
86670ce3f0cSdrh   */
8674adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8682f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
86976d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
870c3f9bad2Sdanielk1977 
87170ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
87270ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
87370ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
87470ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
87570ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
87670ce3f0cSdrh     */
877d82b5021Sdrh     if( ipkColumn<0 ){
87876d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
87970ce3f0cSdrh     }else{
880728e0f91Sdrh       int addr1;
881ec95c441Sdrh       assert( !withoutRowid );
8827fe45908Sdrh       if( useTempTable ){
883d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
8847fe45908Sdrh       }else{
885d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
886d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
8877fe45908Sdrh       }
888728e0f91Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
88976d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
890728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
891688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
89270ce3f0cSdrh     }
89370ce3f0cSdrh 
894034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
895034ca14fSdanielk1977     ** this block would have to account for hidden column.
896034ca14fSdanielk1977     */
897034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
898034ca14fSdanielk1977 
89970ce3f0cSdrh     /* Create the new column data
90070ce3f0cSdrh     */
901b1daa3f4Sdrh     for(i=j=0; i<pTab->nCol; i++){
902b1daa3f4Sdrh       if( pColumn ){
903c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
904c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
905c3f9bad2Sdanielk1977         }
906c3f9bad2Sdanielk1977       }
907b1daa3f4Sdrh       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
90803d69a68Sdrh             || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
90976d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
910142e30dfSdrh       }else if( useTempTable ){
91176d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
912c3f9bad2Sdanielk1977       }else{
913d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
91476d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
915c3f9bad2Sdanielk1977       }
91603d69a68Sdrh       if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
917c3f9bad2Sdanielk1977     }
918a37cdde0Sdanielk1977 
919a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
920a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
921a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
922a37cdde0Sdanielk1977     ** table column affinities.
923a37cdde0Sdanielk1977     */
924a37cdde0Sdanielk1977     if( !isView ){
92557bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regCols+1);
926a37cdde0Sdanielk1977     }
927c3f9bad2Sdanielk1977 
9285cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
929165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
93094d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
931165921a7Sdan 
93276d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
93370ce3f0cSdrh   }
934c3f9bad2Sdanielk1977 
935d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
936d82b5021Sdrh   ** registers beginning at regIns.
9371ccde15dSdrh   */
9385cf590c1Sdrh   if( !isView ){
9394cbdda9eSdrh     if( IsVirtual(pTab) ){
9404cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9416a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9424cbdda9eSdrh     }
943d82b5021Sdrh     if( ipkColumn>=0 ){
944142e30dfSdrh       if( useTempTable ){
945d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
946142e30dfSdrh       }else if( pSelect ){
94705a86c5cSdrh         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
9484a32431cSdrh       }else{
949e4d90813Sdrh         VdbeOp *pOp;
950d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
95120411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9529d9c41e2Sdrh         assert( pOp!=0 );
9539d9c41e2Sdrh         if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){
954e4d90813Sdrh           appendFlag = 1;
955e4d90813Sdrh           pOp->opcode = OP_NewRowid;
95626198bb4Sdrh           pOp->p1 = iDataCur;
9576a288a33Sdrh           pOp->p2 = regRowid;
9586a288a33Sdrh           pOp->p3 = regAutoinc;
959e4d90813Sdrh         }
96027a32783Sdrh       }
961f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
962e1e68f49Sdrh       ** to generate a unique primary key value.
963e1e68f49Sdrh       */
964e4d90813Sdrh       if( !appendFlag ){
965728e0f91Sdrh         int addr1;
966bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
967728e0f91Sdrh           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
96826198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
969728e0f91Sdrh           sqlite3VdbeJumpHere(v, addr1);
970bb50e7adSdanielk1977         }else{
971728e0f91Sdrh           addr1 = sqlite3VdbeCurrentAddr(v);
972728e0f91Sdrh           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
973bb50e7adSdanielk1977         }
974688852abSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
975e4d90813Sdrh       }
976ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9776a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9784a32431cSdrh     }else{
97926198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
980e4d90813Sdrh       appendFlag = 1;
9814a32431cSdrh     }
9826a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9834a32431cSdrh 
984d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
9854a32431cSdrh     ** with the first column.
9864a32431cSdrh     */
987034ca14fSdanielk1977     nHidden = 0;
988cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9896a288a33Sdrh       int iRegStore = regRowid+1+i;
9904a32431cSdrh       if( i==pTab->iPKey ){
9914a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
992d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
993d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
99405a86c5cSdrh         ** taking up data space with information that will never be used.
99505a86c5cSdrh         ** As there may be shallow copies of this value, make it a soft-NULL */
99605a86c5cSdrh         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
9974a32431cSdrh         continue;
9984a32431cSdrh       }
999967e8b73Sdrh       if( pColumn==0 ){
1000034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1001034ca14fSdanielk1977           j = -1;
1002034ca14fSdanielk1977           nHidden++;
1003034ca14fSdanielk1977         }else{
1004034ca14fSdanielk1977           j = i - nHidden;
1005034ca14fSdanielk1977         }
1006cce7d176Sdrh       }else{
1007967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1008967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1009cce7d176Sdrh         }
1010cce7d176Sdrh       }
1011034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
101205a86c5cSdrh         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
1013142e30dfSdrh       }else if( useTempTable ){
1014287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1015142e30dfSdrh       }else if( pSelect ){
101605a86c5cSdrh         if( regFromSelect!=regData ){
1017b7654111Sdrh           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
101805a86c5cSdrh         }
1019cce7d176Sdrh       }else{
1020287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1021cce7d176Sdrh       }
1022cce7d176Sdrh     }
10231ccde15dSdrh 
10240ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10250ca3e24bSdrh     ** do the insertion.
10264a32431cSdrh     */
10274cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10284cbdda9eSdrh     if( IsVirtual(pTab) ){
1029595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10304f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1031595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1032b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1033e0af83acSdan       sqlite3MayAbort(pParse);
10344cbdda9eSdrh     }else
10354cbdda9eSdrh #endif
10364cbdda9eSdrh     {
1037de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
10383b908d41Sdan       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
1039f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1040788d55aaSdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
104104adf416Sdrh       );
10428ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
10433b908d41Sdan 
10443b908d41Sdan       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
10453b908d41Sdan       ** constraints or (b) there are no triggers and this table is not a
10463b908d41Sdan       ** parent table in a foreign key constraint. It is safe to set the
10473b908d41Sdan       ** flag in the second case as if any REPLACE constraint is hit, an
10483b908d41Sdan       ** OP_Delete or OP_IdxDelete instruction will be executed on each
10493b908d41Sdan       ** cursor that is disturbed. And these instructions both clear the
10503b908d41Sdan       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
10513b908d41Sdan       ** functionality.  */
10523b908d41Sdan       bUseSeek = (isReplace==0 || (pTrigger==0 &&
10533b908d41Sdan           ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
10543b908d41Sdan       ));
105526198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
10563b908d41Sdan           regIns, aRegIdx, 0, appendFlag, bUseSeek
10573b908d41Sdan       );
10585cf590c1Sdrh     }
10594cbdda9eSdrh   }
10601bee3d7bSdrh 
1061feeb1394Sdrh   /* Update the count of rows that are inserted
10621bee3d7bSdrh   */
106379636913Sdrh   if( regRowCount ){
10646a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10651bee3d7bSdrh   }
1066c3f9bad2Sdanielk1977 
10672f886d1dSdanielk1977   if( pTrigger ){
1068c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1069165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
107094d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1071c3f9bad2Sdanielk1977   }
10721bee3d7bSdrh 
1073e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1074e00ee6ebSdrh   ** is a SELECT statement.
10751ccde15dSdrh   */
10764adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1077142e30dfSdrh   if( useTempTable ){
1078688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1079e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10802eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1081142e30dfSdrh   }else if( pSelect ){
1082076e85f5Sdrh     sqlite3VdbeGoto(v, addrCont);
1083e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10846b56344dSdrh   }
1085c3f9bad2Sdanielk1977 
10860b9f50d8Sdrh insert_end:
1087f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10880b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10890b9f50d8Sdrh   ** autoincrement tables.
10902958a4e6Sdrh   */
1091165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10920b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10930b9f50d8Sdrh   }
10942958a4e6Sdrh 
10951bee3d7bSdrh   /*
1096e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1097e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1098e7de6f25Sdanielk1977   ** invoke the callback function.
10991bee3d7bSdrh   */
110079636913Sdrh   if( regRowCount ){
11016a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110222322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
110310fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11041bee3d7bSdrh   }
1105cce7d176Sdrh 
1106cce7d176Sdrh insert_cleanup:
1107633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1108633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
110946d2e5c3Sdrh   sqlite3UpsertDelete(db, pUpsert);
1110633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1111633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1112633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1113cce7d176Sdrh }
11149cfcf5d4Sdrh 
111575cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
111660ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
111775cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
111875cbd984Sdan #ifdef isView
111975cbd984Sdan  #undef isView
112075cbd984Sdan #endif
112175cbd984Sdan #ifdef pTrigger
112275cbd984Sdan  #undef pTrigger
112375cbd984Sdan #endif
112475cbd984Sdan #ifdef tmask
112575cbd984Sdan  #undef tmask
112675cbd984Sdan #endif
112775cbd984Sdan 
11289cfcf5d4Sdrh /*
112998bfa16dSdrh ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
113098bfa16dSdrh */
113198bfa16dSdrh #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
113298bfa16dSdrh #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
113398bfa16dSdrh 
11342a0b527bSdrh /* This is the Walker callback from checkConstraintUnchanged().  Set
113598bfa16dSdrh ** bit 0x01 of pWalker->eCode if
11362a0b527bSdrh ** pWalker->eCode to 0 if this expression node references any of the
11372a0b527bSdrh ** columns that are being modifed by an UPDATE statement.
11382a0b527bSdrh */
11392a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
114098bfa16dSdrh   if( pExpr->op==TK_COLUMN ){
114198bfa16dSdrh     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
114298bfa16dSdrh     if( pExpr->iColumn>=0 ){
114398bfa16dSdrh       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
114498bfa16dSdrh         pWalker->eCode |= CKCNSTRNT_COLUMN;
114598bfa16dSdrh       }
114698bfa16dSdrh     }else{
114798bfa16dSdrh       pWalker->eCode |= CKCNSTRNT_ROWID;
114898bfa16dSdrh     }
11492a0b527bSdrh   }
11502a0b527bSdrh   return WRC_Continue;
11512a0b527bSdrh }
11522a0b527bSdrh 
11532a0b527bSdrh /*
11542a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
11552a0b527bSdrh ** only columns that are modified by the UPDATE are those for which
115698bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
115798bfa16dSdrh **
115898bfa16dSdrh ** Return true if CHECK constraint pExpr does not use any of the
115998bfa16dSdrh ** changing columns (or the rowid if it is changing).  In other words,
116098bfa16dSdrh ** return true if this CHECK constraint can be skipped when validating
116198bfa16dSdrh ** the new row in the UPDATE statement.
11622a0b527bSdrh */
116398bfa16dSdrh static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
11642a0b527bSdrh   Walker w;
11652a0b527bSdrh   memset(&w, 0, sizeof(w));
116698bfa16dSdrh   w.eCode = 0;
11672a0b527bSdrh   w.xExprCallback = checkConstraintExprNode;
11682a0b527bSdrh   w.u.aiCol = aiChng;
11692a0b527bSdrh   sqlite3WalkExpr(&w, pExpr);
117005723a9eSdrh   if( !chngRowid ){
117105723a9eSdrh     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
117205723a9eSdrh     w.eCode &= ~CKCNSTRNT_ROWID;
117305723a9eSdrh   }
117405723a9eSdrh   testcase( w.eCode==0 );
117505723a9eSdrh   testcase( w.eCode==CKCNSTRNT_COLUMN );
117605723a9eSdrh   testcase( w.eCode==CKCNSTRNT_ROWID );
117705723a9eSdrh   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
117898bfa16dSdrh   return !w.eCode;
11792a0b527bSdrh }
11802a0b527bSdrh 
118111e85273Sdrh /*
1182096fd476Sdrh ** An instance of the ConstraintAddr object remembers the byte-code addresses
1183096fd476Sdrh ** for sections of the constraint checks that deal with uniqueness constraints
1184096fd476Sdrh ** on the rowid and on the upsert constraint.
1185096fd476Sdrh **
1186096fd476Sdrh ** This information is passed into checkReorderConstraintChecks() to insert
1187096fd476Sdrh ** some OP_Goto operations so that the rowid and upsert constraints occur
1188096fd476Sdrh ** in the correct order relative to other constraints.
1189096fd476Sdrh */
1190096fd476Sdrh typedef struct ConstraintAddr ConstraintAddr;
1191096fd476Sdrh struct ConstraintAddr {
1192096fd476Sdrh   int ipkTop;          /* Subroutine for rowid constraint check */
1193096fd476Sdrh   int upsertTop;       /* Label for upsert constraint check subroutine */
11949916048bSdrh   int upsertTop2;      /* Copy of upsertTop not cleared by the call */
1195096fd476Sdrh   int upsertBtm;       /* upsert constraint returns to this label */
11969916048bSdrh   int ipkBtm;          /* Return opcode rowid constraint check */
1197096fd476Sdrh };
1198096fd476Sdrh 
1199096fd476Sdrh /*
1200096fd476Sdrh ** Generate any OP_Goto operations needed to cause constraints to be
1201096fd476Sdrh ** run that haven't already been run.
1202096fd476Sdrh */
1203096fd476Sdrh static void reorderConstraintChecks(Vdbe *v, ConstraintAddr *p){
1204096fd476Sdrh   if( p->upsertTop ){
12059916048bSdrh     testcase( sqlite3VdbeLabelHasBeenResolved(v, p->upsertTop) );
1206096fd476Sdrh     sqlite3VdbeGoto(v, p->upsertTop);
1207096fd476Sdrh     VdbeComment((v, "call upsert subroutine"));
1208096fd476Sdrh     sqlite3VdbeResolveLabel(v, p->upsertBtm);
1209096fd476Sdrh     p->upsertTop = 0;
1210096fd476Sdrh   }
1211096fd476Sdrh   if( p->ipkTop ){
1212096fd476Sdrh     sqlite3VdbeGoto(v, p->ipkTop);
12139916048bSdrh     VdbeComment((v, "call rowid unique-check subroutine"));
1214096fd476Sdrh     sqlite3VdbeJumpHere(v, p->ipkBtm);
1215096fd476Sdrh     p->ipkTop = 0;
1216096fd476Sdrh   }
1217096fd476Sdrh }
1218096fd476Sdrh 
1219096fd476Sdrh /*
12206934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
12216934fc7bSdrh ** on table pTab.
12229cfcf5d4Sdrh **
12236934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
12246934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
12256934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
12266934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
12276934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
12286934fc7bSdrh ** contain the content of the first table column.  The third register will
12296934fc7bSdrh ** contain the content of the second table column.  And so forth.
12300ca3e24bSdrh **
1231f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1232f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1233f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1234f8ffb278Sdrh ** checking regOldData for zero.
12350ca3e24bSdrh **
1236f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1237f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1238f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1239f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
12400ca3e24bSdrh **
1241f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1242f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1243f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1244f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1245f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1246f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
12470ca3e24bSdrh **
12486934fc7bSdrh ** The code generated by this routine will store new index entries into
1249aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1250aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1251aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
12526934fc7bSdrh ** at pTab->pIndex.
12536934fc7bSdrh **
12546934fc7bSdrh ** The caller must have already opened writeable cursors on the main
12556934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
12566934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
12576934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
12586934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
12596934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
12606934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
12619cfcf5d4Sdrh **
12629cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
12639cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
12641c92853dSdrh ** then the appropriate action is performed.  There are five possible
12651c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
12669cfcf5d4Sdrh **
12679cfcf5d4Sdrh **  Constraint type  Action       What Happens
12689cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
12691c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
12706934fc7bSdrh **                                sqlite3_step() returns immediately with a
12719cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
12729cfcf5d4Sdrh **
12731c92853dSdrh **  any              ABORT        Back out changes from the current command
12741c92853dSdrh **                                only (do not do a complete rollback) then
12756934fc7bSdrh **                                cause sqlite3_step() to return immediately
12761c92853dSdrh **                                with SQLITE_CONSTRAINT.
12771c92853dSdrh **
12786934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
12791c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
12801c92853dSdrh **                                transaction is not rolled back and any
12816934fc7bSdrh **                                changes to prior rows are retained.
12821c92853dSdrh **
12836934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
12846934fc7bSdrh **                                row is skipped, without throwing an error.
12856934fc7bSdrh **                                Processing continues with the next row.
12866934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
12879cfcf5d4Sdrh **
12889cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
12899cfcf5d4Sdrh **                                value for that column.  If the default value
12909cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
12919cfcf5d4Sdrh **
12929cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
12939cfcf5d4Sdrh **                                being inserted is removed.
12949cfcf5d4Sdrh **
12959cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12969cfcf5d4Sdrh **
12971c92853dSdrh ** Which action to take is determined by the overrideError parameter.
12981c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12991c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
13001c92853dSdrh ** for the constraint is used.
13019cfcf5d4Sdrh */
13024adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
13039cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
13046934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1305f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
13066934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
130726198bb4Sdrh   int iIdxCur,         /* First index cursor */
13086934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1309f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1310f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1311f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1312de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1313bdb00225Sdrh   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1314788d55aaSdrh   int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
1315788d55aaSdrh   Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
13169cfcf5d4Sdrh ){
13171b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
13181b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
131911e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
13202938f924Sdrh   sqlite3 *db;         /* Database connection */
1321f8ffb278Sdrh   int i;               /* loop counter */
1322f8ffb278Sdrh   int ix;              /* Index loop counter */
13239cfcf5d4Sdrh   int nCol;            /* Number of columns */
13249cfcf5d4Sdrh   int onError;         /* Conflict resolution strategy */
1325728e0f91Sdrh   int addr1;           /* Address of jump instruction */
13261b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
13276fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1328096fd476Sdrh   ConstraintAddr sAddr;/* Address information for constraint reordering */
1329096fd476Sdrh   Index *pUpIdx = 0;   /* Index to which to apply the upsert */
13308d1b82e4Sdrh   u8 isUpdate;         /* True if this is an UPDATE operation */
133157bf4a8eSdrh   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
1332096fd476Sdrh   int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */
13339cfcf5d4Sdrh 
1334f8ffb278Sdrh   isUpdate = regOldData!=0;
13352938f924Sdrh   db = pParse->db;
13364adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
13379cfcf5d4Sdrh   assert( v!=0 );
1338417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
13399cfcf5d4Sdrh   nCol = pTab->nCol;
13409916048bSdrh   memset(&sAddr, 0, sizeof(sAddr));
1341aa9b8963Sdrh 
13426934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
13436934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
13446934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
13456934fc7bSdrh   ** number of fields in the true primary key of the table. */
134626198bb4Sdrh   if( HasRowid(pTab) ){
134726198bb4Sdrh     pPk = 0;
134826198bb4Sdrh     nPkField = 1;
134926198bb4Sdrh   }else{
135026198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
135126198bb4Sdrh     nPkField = pPk->nKeyCol;
135226198bb4Sdrh   }
13536fbe41acSdrh 
13546fbe41acSdrh   /* Record that this module has started */
13556fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
13566934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
13579cfcf5d4Sdrh 
13589cfcf5d4Sdrh   /* Test all NOT NULL constraints.
13599cfcf5d4Sdrh   */
13609cfcf5d4Sdrh   for(i=0; i<nCol; i++){
13610ca3e24bSdrh     if( i==pTab->iPKey ){
1362bdb00225Sdrh       continue;        /* ROWID is never NULL */
1363bdb00225Sdrh     }
1364bdb00225Sdrh     if( aiChng && aiChng[i]<0 ){
1365bdb00225Sdrh       /* Don't bother checking for NOT NULL on columns that do not change */
13660ca3e24bSdrh       continue;
13670ca3e24bSdrh     }
13689cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
1369bdb00225Sdrh     if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
13709cfcf5d4Sdrh     if( overrideError!=OE_Default ){
13719cfcf5d4Sdrh       onError = overrideError;
1372a996e477Sdrh     }else if( onError==OE_Default ){
1373a996e477Sdrh       onError = OE_Abort;
13749cfcf5d4Sdrh     }
13757977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
13769cfcf5d4Sdrh       onError = OE_Abort;
13779cfcf5d4Sdrh     }
1378b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1379b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
13809cfcf5d4Sdrh     switch( onError ){
13811c92853dSdrh       case OE_Abort:
1382e0af83acSdan         sqlite3MayAbort(pParse);
13830978d4ffSdrh         /* Fall through */
1384e0af83acSdan       case OE_Rollback:
13851c92853dSdrh       case OE_Fail: {
1386f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1387f9c8ce3cSdrh                                     pTab->aCol[i].zName);
13882700acaaSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
13892700acaaSdrh                           regNewData+1+i);
13902700acaaSdrh         sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1391f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1392688852abSdrh         VdbeCoverage(v);
13939cfcf5d4Sdrh         break;
13949cfcf5d4Sdrh       }
13959cfcf5d4Sdrh       case OE_Ignore: {
13966934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
1397688852abSdrh         VdbeCoverage(v);
13989cfcf5d4Sdrh         break;
13999cfcf5d4Sdrh       }
1400098d1684Sdrh       default: {
1401098d1684Sdrh         assert( onError==OE_Replace );
1402728e0f91Sdrh         addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
1403728e0f91Sdrh            VdbeCoverage(v);
14046934fc7bSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
1405728e0f91Sdrh         sqlite3VdbeJumpHere(v, addr1);
14069cfcf5d4Sdrh         break;
14079cfcf5d4Sdrh       }
14089cfcf5d4Sdrh     }
14099cfcf5d4Sdrh   }
14109cfcf5d4Sdrh 
14119cfcf5d4Sdrh   /* Test all CHECK constraints
14129cfcf5d4Sdrh   */
1413ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
14142938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
14152938f924Sdrh     ExprList *pCheck = pTab->pCheck;
14166e97f8ecSdrh     pParse->iSelfTab = -(regNewData+1);
1417aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
14182938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
141905723a9eSdrh       int allOk;
14202a0b527bSdrh       Expr *pExpr = pCheck->a[i].pExpr;
142198bfa16dSdrh       if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
142205723a9eSdrh       allOk = sqlite3VdbeMakeLabel(v);
14232a0b527bSdrh       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
14242e06c67cSdrh       if( onError==OE_Ignore ){
1425076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
1426aa01c7e2Sdrh       }else{
1427f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1428f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
14296dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1430d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1431f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1432f9c8ce3cSdrh                               P5_ConstraintCheck);
1433aa01c7e2Sdrh       }
1434ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1435ffe07b2dSdrh     }
14366e97f8ecSdrh     pParse->iSelfTab = 0;
14372938f924Sdrh   }
1438ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
14399cfcf5d4Sdrh 
1440096fd476Sdrh   /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1441096fd476Sdrh   ** order:
1442096fd476Sdrh   **
1443096fd476Sdrh   **   (1)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1444096fd476Sdrh   **   (2)  OE_Update
1445096fd476Sdrh   **   (3)  OE_Replace
1446096fd476Sdrh   **
1447096fd476Sdrh   ** OE_Fail and OE_Ignore must happen before any changes are made.
1448096fd476Sdrh   ** OE_Update guarantees that only a single row will change, so it
1449096fd476Sdrh   ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
1450096fd476Sdrh   ** could happen in any order, but they are grouped up front for
1451096fd476Sdrh   ** convenience.
1452096fd476Sdrh   **
1453096fd476Sdrh   ** Constraint checking code is generated in this order:
1454096fd476Sdrh   **   (A)  The rowid constraint
1455096fd476Sdrh   **   (B)  Unique index constraints that do not have OE_Replace as their
1456096fd476Sdrh   **        default conflict resolution strategy
1457096fd476Sdrh   **   (C)  Unique index that do use OE_Replace by default.
1458096fd476Sdrh   **
1459096fd476Sdrh   ** The ordering of (2) and (3) is accomplished by making sure the linked
1460096fd476Sdrh   ** list of indexes attached to a table puts all OE_Replace indexes last
1461096fd476Sdrh   ** in the list.  See sqlite3CreateIndex() for where that happens.
1462096fd476Sdrh   */
1463096fd476Sdrh 
1464096fd476Sdrh   if( pUpsert ){
1465096fd476Sdrh     if( pUpsert->pUpsertTarget==0 ){
1466096fd476Sdrh       /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
1467096fd476Sdrh       ** Make all unique constraint resolution be OE_Ignore */
1468dedbc508Sdrh       assert( pUpsert->pUpsertSet==0 );
1469096fd476Sdrh       overrideError = OE_Ignore;
1470096fd476Sdrh       pUpsert = 0;
1471096fd476Sdrh     }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
1472dedbc508Sdrh       /* If the constraint-target is on some column other than
1473dedbc508Sdrh       ** then ROWID, then we might need to move the UPSERT around
1474dedbc508Sdrh       ** so that it occurs in the correct order. */
14759916048bSdrh       sAddr.upsertTop = sAddr.upsertTop2 = sqlite3VdbeMakeLabel(v);
1476096fd476Sdrh       sAddr.upsertBtm = sqlite3VdbeMakeLabel(v);
1477096fd476Sdrh     }
1478096fd476Sdrh   }
1479096fd476Sdrh 
1480f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1481f8ffb278Sdrh   ** exist in the table.
14829cfcf5d4Sdrh   */
14836fbe41acSdrh   if( pkChng && pPk==0 ){
148411e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
148511e85273Sdrh 
1486f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
14870ca3e24bSdrh     onError = pTab->keyConf;
14880ca3e24bSdrh     if( overrideError!=OE_Default ){
14890ca3e24bSdrh       onError = overrideError;
1490a996e477Sdrh     }else if( onError==OE_Default ){
1491a996e477Sdrh       onError = OE_Abort;
14920ca3e24bSdrh     }
1493a0217ba7Sdrh 
1494c8a0c90bSdrh     /* figure out whether or not upsert applies in this case */
1495096fd476Sdrh     if( pUpsert && pUpsert->pUpsertIdx==0 ){
1496c8a0c90bSdrh       if( pUpsert->pUpsertSet==0 ){
1497c8a0c90bSdrh         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1498c8a0c90bSdrh       }else{
1499c8a0c90bSdrh         onError = OE_Update;  /* DO UPDATE */
1500c8a0c90bSdrh       }
1501c8a0c90bSdrh     }
1502c8a0c90bSdrh 
15038d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
15048d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
15058d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
15068d1b82e4Sdrh     ** the UNIQUE constraints have run.
15078d1b82e4Sdrh     */
1508096fd476Sdrh     assert( OE_Update>OE_Replace );
1509096fd476Sdrh     assert( OE_Ignore<OE_Replace );
1510096fd476Sdrh     assert( OE_Fail<OE_Replace );
1511096fd476Sdrh     assert( OE_Abort<OE_Replace );
1512096fd476Sdrh     assert( OE_Rollback<OE_Replace );
1513096fd476Sdrh     if( onError>=OE_Replace
1514a46838cbSdan      && (pUpsert || onError!=overrideError)
1515096fd476Sdrh      && pTab->pIndex
1516096fd476Sdrh     ){
1517096fd476Sdrh       sAddr.ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
15188d1b82e4Sdrh     }
15198d1b82e4Sdrh 
1520bb6b1ca7Sdrh     if( isUpdate ){
1521bb6b1ca7Sdrh       /* pkChng!=0 does not mean that the rowid has changed, only that
1522bb6b1ca7Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1523bb6b1ca7Sdrh       ** is unchanged. */
1524bb6b1ca7Sdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
1525bb6b1ca7Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1526bb6b1ca7Sdrh       VdbeCoverage(v);
1527bb6b1ca7Sdrh     }
1528bb6b1ca7Sdrh 
1529f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1530f8ffb278Sdrh     ** the following conflict logic if it does not. */
15317f5f306bSdrh     VdbeNoopComment((v, "uniqueness check for ROWID"));
15326934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1533688852abSdrh     VdbeCoverage(v);
1534f8ffb278Sdrh 
15350ca3e24bSdrh     switch( onError ){
1536a0217ba7Sdrh       default: {
1537a0217ba7Sdrh         onError = OE_Abort;
1538a0217ba7Sdrh         /* Fall thru into the next case */
1539a0217ba7Sdrh       }
15401c92853dSdrh       case OE_Rollback:
15411c92853dSdrh       case OE_Abort:
15421c92853dSdrh       case OE_Fail: {
15439916048bSdrh         testcase( onError==OE_Rollback );
15449916048bSdrh         testcase( onError==OE_Abort );
15459916048bSdrh         testcase( onError==OE_Fail );
1546f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
15470ca3e24bSdrh         break;
15480ca3e24bSdrh       }
15495383ae5cSdrh       case OE_Replace: {
15502283d46cSdan         /* If there are DELETE triggers on this table and the
15512283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1552d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
15532283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
15542283d46cSdan         **
15552283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1556da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1557da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1558da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1559da730f6eSdan         ** when it is inserted.
1560da730f6eSdan         **
1561da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1562da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1563da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1564da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1565da730f6eSdan         ** but being more selective here allows statements like:
1566da730f6eSdan         **
1567da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1568da730f6eSdan         **
1569da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1570da730f6eSdan         ** table.
1571da730f6eSdan         */
15722283d46cSdan         Trigger *pTrigger = 0;
15732938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15742283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15752283d46cSdan         }
1576e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1577da730f6eSdan           sqlite3MultiWrite(pParse);
157826198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1579438b8815Sdan                                    regNewData, 1, 0, OE_Replace, 1, -1);
158046c47d46Sdan         }else{
15819b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
158254f2cd90Sdrh           assert( HasRowid(pTab) );
158346c47d46Sdan           /* This OP_Delete opcode fires the pre-update-hook only. It does
158446c47d46Sdan           ** not modify the b-tree. It is more efficient to let the coming
158546c47d46Sdan           ** OP_Insert replace the existing entry than it is to delete the
158646c47d46Sdan           ** existing entry and then insert a new one. */
1587cbf1b8efSdrh           sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
1588f14b7fb7Sdrh           sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
15899b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
159046c47d46Sdan           if( pTab->pIndex ){
1591da730f6eSdan             sqlite3MultiWrite(pParse);
1592f0ee1d3cSdan             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
15932283d46cSdan           }
159446c47d46Sdan         }
15955383ae5cSdrh         seenReplace = 1;
15965383ae5cSdrh         break;
15975383ae5cSdrh       }
15989eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
15999eddacadSdrh       case OE_Update: {
16002cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
16019eddacadSdrh         /* Fall through */
16029eddacadSdrh       }
16039eddacadSdrh #endif
16040ca3e24bSdrh       case OE_Ignore: {
16059916048bSdrh         testcase( onError==OE_Ignore );
1606076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
16070ca3e24bSdrh         break;
16080ca3e24bSdrh       }
16090ca3e24bSdrh     }
161011e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
1611096fd476Sdrh     if( sAddr.ipkTop ){
1612096fd476Sdrh       sAddr.ipkBtm = sqlite3VdbeAddOp0(v, OP_Goto);
1613096fd476Sdrh       sqlite3VdbeJumpHere(v, sAddr.ipkTop-1);
1614a05a722fSdrh     }
16150ca3e24bSdrh   }
16160bd1f4eaSdrh 
16170bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
16180bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
161911e85273Sdrh   ** Compute the revised record entries for indices as we go.
1620f8ffb278Sdrh   **
1621f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1622f8ffb278Sdrh   ** WITHOUT ROWID table.
16230bd1f4eaSdrh   */
162426198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
16256934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
16266934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
16276934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
16286934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
16292184fc75Sdrh 
163026198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
16317f5f306bSdrh     if( pUpIdx==pIdx ){
16327f5f306bSdrh       addrUniqueOk = sAddr.upsertBtm;
16337f5f306bSdrh       upsertBypass = sqlite3VdbeGoto(v, 0);
16347f5f306bSdrh       VdbeComment((v, "Skip upsert subroutine"));
16359916048bSdrh       sqlite3VdbeResolveLabel(v, sAddr.upsertTop2);
16367f5f306bSdrh     }else{
16377f5f306bSdrh       addrUniqueOk = sqlite3VdbeMakeLabel(v);
16387f5f306bSdrh     }
16397f5f306bSdrh     VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
164057bf4a8eSdrh     if( bAffinityDone==0 ){
164157bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regNewData+1);
164257bf4a8eSdrh       bAffinityDone = 1;
164357bf4a8eSdrh     }
16446934fc7bSdrh     iThisCur = iIdxCur+ix;
16457f5f306bSdrh 
1646b2fe7d8cSdrh 
1647f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1648b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
164926198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
16506e97f8ecSdrh       pParse->iSelfTab = -(regNewData+1);
165172bc8208Sdrh       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1652b2b9d3d7Sdrh                             SQLITE_JUMPIFNULL);
16536e97f8ecSdrh       pParse->iSelfTab = 0;
1654b2b9d3d7Sdrh     }
1655b2b9d3d7Sdrh 
16566934fc7bSdrh     /* Create a record for this index entry as it should appear after
1657f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1658f8ffb278Sdrh     */
1659bf2f5739Sdrh     regIdx = aRegIdx[ix]+1;
16609cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
16616934fc7bSdrh       int iField = pIdx->aiColumn[i];
1662f82b9afcSdrh       int x;
16634b92f98cSdrh       if( iField==XN_EXPR ){
16646e97f8ecSdrh         pParse->iSelfTab = -(regNewData+1);
16651c75c9d7Sdrh         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
16666e97f8ecSdrh         pParse->iSelfTab = 0;
16671f9ca2c8Sdrh         VdbeComment((v, "%s column %d", pIdx->zName, i));
16681f9ca2c8Sdrh       }else{
16694b92f98cSdrh         if( iField==XN_ROWID || iField==pTab->iPKey ){
1670f82b9afcSdrh           x = regNewData;
16719cfcf5d4Sdrh         }else{
1672f82b9afcSdrh           x = iField + regNewData + 1;
16739cfcf5d4Sdrh         }
1674fed7ac6fSdrh         sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
1675f82b9afcSdrh         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
16769cfcf5d4Sdrh       }
16771f9ca2c8Sdrh     }
167826198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
167926198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
16807e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
16817e4acf7bSdrh     if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
16827e4acf7bSdrh #endif
1683b2fe7d8cSdrh 
1684f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1685f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1686f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1687f8ffb278Sdrh     ** logic below can all be skipped. */
168800012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1689da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1690da475b8dSdrh       continue;
1691da475b8dSdrh     }
1692f8ffb278Sdrh 
16936934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
16949cfcf5d4Sdrh     onError = pIdx->onError;
1695de630353Sdanielk1977     if( onError==OE_None ){
169611e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1697de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1698de630353Sdanielk1977     }
16999cfcf5d4Sdrh     if( overrideError!=OE_Default ){
17009cfcf5d4Sdrh       onError = overrideError;
1701a996e477Sdrh     }else if( onError==OE_Default ){
1702a996e477Sdrh       onError = OE_Abort;
17039cfcf5d4Sdrh     }
17045383ae5cSdrh 
1705c8a0c90bSdrh     /* Figure out if the upsert clause applies to this index */
1706096fd476Sdrh     if( pUpIdx==pIdx ){
1707c8a0c90bSdrh       if( pUpsert->pUpsertSet==0 ){
1708c8a0c90bSdrh         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1709c8a0c90bSdrh       }else{
1710c8a0c90bSdrh         onError = OE_Update;  /* DO UPDATE */
1711c8a0c90bSdrh       }
1712c8a0c90bSdrh     }
1713c8a0c90bSdrh 
17149916048bSdrh     /* Invoke subroutines to handle IPK replace and upsert prior to running
17159916048bSdrh     ** the first REPLACE constraint check. */
17169916048bSdrh     if( onError==OE_Replace ){
17179916048bSdrh       testcase( sAddr.ipkTop );
17189916048bSdrh       testcase( sAddr.upsertTop
17199916048bSdrh              && sqlite3VdbeLabelHasBeenResolved(v,sAddr.upsertTop) );
17209916048bSdrh       reorderConstraintChecks(v, &sAddr);
17219916048bSdrh     }
17229916048bSdrh 
1723801f55d8Sdrh     /* Collision detection may be omitted if all of the following are true:
1724801f55d8Sdrh     **   (1) The conflict resolution algorithm is REPLACE
1725801f55d8Sdrh     **   (2) The table is a WITHOUT ROWID table
1726801f55d8Sdrh     **   (3) There are no secondary indexes on the table
1727801f55d8Sdrh     **   (4) No delete triggers need to be fired if there is a conflict
1728f9a12a10Sdan     **   (5) No FK constraint counters need to be updated if a conflict occurs.
1729801f55d8Sdrh     */
1730801f55d8Sdrh     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
1731801f55d8Sdrh      && pPk==pIdx                                   /* Condition 2 */
1732801f55d8Sdrh      && onError==OE_Replace                         /* Condition 1 */
1733801f55d8Sdrh      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
1734801f55d8Sdrh           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
1735f9a12a10Sdan      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
1736f9a12a10Sdan          (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
17374e1f0efbSdan     ){
1738c6c9e158Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1739c6c9e158Sdrh       continue;
1740c6c9e158Sdrh     }
1741c6c9e158Sdrh 
1742b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
17434d795ef7Sdrh     sqlite3ExprCachePush(pParse);
174426198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
1745688852abSdrh                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
1746f8ffb278Sdrh 
1747f8ffb278Sdrh     /* Generate code to handle collisions */
1748392ee21dSdrh     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
174946d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
175011e85273Sdrh       if( HasRowid(pTab) ){
17516934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
17520978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
17530978d4ffSdrh         ** is different from old-rowid */
1754f8ffb278Sdrh         if( isUpdate ){
17556934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
17563d77dee9Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1757688852abSdrh           VdbeCoverage(v);
1758f8ffb278Sdrh         }
175926198bb4Sdrh       }else{
1760ccc79f02Sdrh         int x;
176126198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
1762da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
1763a021f121Sdrh         if( pIdx!=pPk ){
176426198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
17654b92f98cSdrh             assert( pPk->aiColumn[i]>=0 );
1766ccc79f02Sdrh             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
176726198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
176826198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
176926198bb4Sdrh                          pTab->aCol[pPk->aiColumn[i]].zName));
177026198bb4Sdrh           }
1771da475b8dSdrh         }
1772da475b8dSdrh         if( isUpdate ){
1773e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1774e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
1775e83267daSdan           ** different from the old.
1776e83267daSdan           **
1777e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1778e83267daSdan           ** of the matched index row are different from the original PRIMARY
1779e83267daSdan           ** KEY values of this row before the update.  */
1780e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1781e83267daSdan           int op = OP_Ne;
178248dd1d8eSdrh           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
1783e83267daSdan 
1784e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
1785e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1786ccc79f02Sdrh             x = pPk->aiColumn[i];
17874b92f98cSdrh             assert( x>=0 );
1788e83267daSdan             if( i==(pPk->nKeyCol-1) ){
1789e83267daSdan               addrJump = addrUniqueOk;
1790e83267daSdan               op = OP_Eq;
179111e85273Sdrh             }
1792e83267daSdan             sqlite3VdbeAddOp4(v, op,
1793e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1794e83267daSdan             );
17953d77dee9Sdrh             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
17963d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Eq);
17973d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Ne);
1798da475b8dSdrh           }
179911e85273Sdrh         }
180026198bb4Sdrh       }
180146d03fcbSdrh     }
1802b2fe7d8cSdrh 
1803b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1804b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
18059eddacadSdrh         || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
18069cfcf5d4Sdrh     switch( onError ){
18071c92853dSdrh       case OE_Rollback:
18081c92853dSdrh       case OE_Abort:
18091c92853dSdrh       case OE_Fail: {
18109916048bSdrh         testcase( onError==OE_Rollback );
18119916048bSdrh         testcase( onError==OE_Abort );
18129916048bSdrh         testcase( onError==OE_Fail );
1813f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
18149cfcf5d4Sdrh         break;
18159cfcf5d4Sdrh       }
18169eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
18179eddacadSdrh       case OE_Update: {
18182cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
18199eddacadSdrh         /* Fall through */
18209eddacadSdrh       }
18219eddacadSdrh #endif
18229cfcf5d4Sdrh       case OE_Ignore: {
18239916048bSdrh         testcase( onError==OE_Ignore );
1824076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
18259cfcf5d4Sdrh         break;
18269cfcf5d4Sdrh       }
1827098d1684Sdrh       default: {
18282283d46cSdan         Trigger *pTrigger = 0;
1829098d1684Sdrh         assert( onError==OE_Replace );
18301bea559aSdan         sqlite3MultiWrite(pParse);
18312938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
18322283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
18332283d46cSdan         }
183426198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1835b0264eecSdrh             regR, nPkField, 0, OE_Replace,
183668116939Sdrh             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
18370ca3e24bSdrh         seenReplace = 1;
18389cfcf5d4Sdrh         break;
18399cfcf5d4Sdrh       }
18409cfcf5d4Sdrh     }
18417f5f306bSdrh     if( pUpIdx==pIdx ){
18427f5f306bSdrh       sqlite3VdbeJumpHere(v, upsertBypass);
18437f5f306bSdrh     }else{
184411e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
18457f5f306bSdrh     }
18464d795ef7Sdrh     sqlite3ExprCachePop(pParse);
1847392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
1848096fd476Sdrh 
18499cfcf5d4Sdrh   }
18509916048bSdrh   testcase( sAddr.ipkTop!=0 );
18519916048bSdrh   testcase( sAddr.upsertTop
18529916048bSdrh          && sqlite3VdbeLabelHasBeenResolved(v,sAddr.upsertTop) );
1853096fd476Sdrh   reorderConstraintChecks(v, &sAddr);
1854de630353Sdanielk1977 
1855de630353Sdanielk1977   *pbMayReplace = seenReplace;
1856ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
18579cfcf5d4Sdrh }
18580ca3e24bSdrh 
1859d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
18600ca3e24bSdrh /*
1861585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
1862585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed.
1863585ce192Sdrh **
1864585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
1865585ce192Sdrh */
1866585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
1867585ce192Sdrh   u16 i;
1868585ce192Sdrh 
1869585ce192Sdrh   /* Records with omitted columns are only allowed for schema format
1870585ce192Sdrh   ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
1871585ce192Sdrh   if( pTab->pSchema->file_format<2 ) return;
1872585ce192Sdrh 
18737e4acf7bSdrh   for(i=pTab->nCol-1; i>0; i--){
18747e4acf7bSdrh     if( pTab->aCol[i].pDflt!=0 ) break;
18757e4acf7bSdrh     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
18767e4acf7bSdrh   }
18777e4acf7bSdrh   sqlite3VdbeChangeP5(v, i+1);
1878585ce192Sdrh }
1879d447dcedSdrh #endif
1880585ce192Sdrh 
18810ca3e24bSdrh /*
18820ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
18834adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
18846934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
188504adf416Sdrh ** rowid and the content to be inserted.
18860ca3e24bSdrh **
1887b419a926Sdrh ** The arguments to this routine should be the same as the first six
18884adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
18890ca3e24bSdrh */
18904adee20fSdanielk1977 void sqlite3CompleteInsertion(
18910ca3e24bSdrh   Parse *pParse,      /* The parser context */
18920ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
189326198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
189426198bb4Sdrh   int iIdxCur,        /* First index cursor */
18956934fc7bSdrh   int regNewData,     /* Range of content */
1896aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1897f91c1318Sdan   int update_flags,   /* True for UPDATE, False for INSERT */
1898de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1899de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
19000ca3e24bSdrh ){
19016934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
19026934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
19036934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
19046934fc7bSdrh   int regData;        /* Content registers (after the rowid) */
190560ec914cSpeter.d.reid   int regRec;         /* Register holding assembled record for the table */
19066934fc7bSdrh   int i;              /* Loop counter */
190757bf4a8eSdrh   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
19080ca3e24bSdrh 
1909f91c1318Sdan   assert( update_flags==0
1910f91c1318Sdan        || update_flags==OPFLAG_ISUPDATE
1911f91c1318Sdan        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
1912f91c1318Sdan   );
1913f91c1318Sdan 
19144adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
19150ca3e24bSdrh   assert( v!=0 );
1916417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1917b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1918aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
191957bf4a8eSdrh     bAffinityDone = 1;
1920b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1921b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1922688852abSdrh       VdbeCoverage(v);
1923b2b9d3d7Sdrh     }
1924cb9a3643Sdan     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
192548dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
19264308e348Sdrh       assert( pParse->nested==0 );
19276546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1928f91c1318Sdan       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
1929cb9a3643Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1930cb9a3643Sdan       if( update_flags==0 ){
1931cb9a3643Sdan         sqlite3VdbeAddOp4(v, OP_InsertInt,
1932cb9a3643Sdan             iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
1933cb9a3643Sdan         );
1934cb9a3643Sdan         sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
1935de630353Sdanielk1977       }
1936cb9a3643Sdan #endif
1937cb9a3643Sdan     }
1938cb9a3643Sdan     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
1939cb9a3643Sdan                          aRegIdx[i]+1,
1940cb9a3643Sdan                          pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
19419b34abeeSdrh     sqlite3VdbeChangeP5(v, pik_flags);
19420ca3e24bSdrh   }
1943ec95c441Sdrh   if( !HasRowid(pTab) ) return;
19446934fc7bSdrh   regData = regNewData + 1;
1945b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
19461db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1947585ce192Sdrh   sqlite3SetMakeRecordP5(v, pTab);
19482adb878bSdrh   if( !bAffinityDone ){
19492adb878bSdrh     sqlite3TableAffinity(v, pTab, 0);
1950da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
19512adb878bSdrh   }
19524794f735Sdrh   if( pParse->nested ){
19534794f735Sdrh     pik_flags = 0;
19544794f735Sdrh   }else{
195594eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
1956f91c1318Sdan     pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
19574794f735Sdrh   }
1958e4d90813Sdrh   if( appendBias ){
1959e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1960e4d90813Sdrh   }
1961de630353Sdanielk1977   if( useSeekResult ){
1962de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1963de630353Sdanielk1977   }
19646934fc7bSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
196594eb6a14Sdanielk1977   if( !pParse->nested ){
1966f14b7fb7Sdrh     sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
196794eb6a14Sdanielk1977   }
1968b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
19690ca3e24bSdrh }
1970cd44690aSdrh 
1971cd44690aSdrh /*
197226198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
197326198bb4Sdrh ** code to open and initialized those cursors.
1974aa9b8963Sdrh **
197526198bb4Sdrh ** The cursor for the object that contains the complete data (normally
197626198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
197726198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
197826198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
197926198bb4Sdrh **
198026198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
198126198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
198226198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
198326198bb4Sdrh **
198426198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
198526198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
198626198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
198726198bb4Sdrh ** pTab->pIndex list.
1988b6b4b79fSdrh **
1989b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the
1990b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized.
1991cd44690aSdrh */
1992aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1993290c1948Sdrh   Parse *pParse,   /* Parsing context */
1994290c1948Sdrh   Table *pTab,     /* Table to be opened */
199526198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
1996b89aeb6aSdrh   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
199726198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
19986a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
199926198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
200026198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
2001290c1948Sdrh ){
2002cd44690aSdrh   int i;
20034cbdda9eSdrh   int iDb;
20046a53499aSdrh   int iDataCur;
2005cd44690aSdrh   Index *pIdx;
20064cbdda9eSdrh   Vdbe *v;
20074cbdda9eSdrh 
200826198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
2009fd261ec6Sdan   assert( op==OP_OpenWrite || p5==0 );
201026198bb4Sdrh   if( IsVirtual(pTab) ){
2011b6b4b79fSdrh     /* This routine is a no-op for virtual tables. Leave the output
2012b6b4b79fSdrh     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
2013b6b4b79fSdrh     ** can detect if they are used by mistake in the caller. */
201426198bb4Sdrh     return 0;
201526198bb4Sdrh   }
20164cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
20174cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
2018cd44690aSdrh   assert( v!=0 );
201926198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
20206a53499aSdrh   iDataCur = iBase++;
20216a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
20226a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
20236a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
20246fbe41acSdrh   }else{
202526198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
20266fbe41acSdrh   }
20276a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
202826198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
202926198bb4Sdrh     int iIdxCur = iBase++;
2030da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
203161441c34Sdan     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
203261441c34Sdan       if( piDataCur ) *piDataCur = iIdxCur;
203361441c34Sdan       p5 = 0;
203461441c34Sdan     }
20356a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
20362ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
20372ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2038b89aeb6aSdrh       sqlite3VdbeChangeP5(v, p5);
203961441c34Sdan       VdbeComment((v, "%s", pIdx->zName));
2040b89aeb6aSdrh     }
20416a53499aSdrh   }
204226198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
204326198bb4Sdrh   return i;
2044cd44690aSdrh }
20459d9cf229Sdrh 
204691c58e23Sdrh 
204791c58e23Sdrh #ifdef SQLITE_TEST
204891c58e23Sdrh /*
204991c58e23Sdrh ** The following global variable is incremented whenever the
205091c58e23Sdrh ** transfer optimization is used.  This is used for testing
205191c58e23Sdrh ** purposes only - to make sure the transfer optimization really
205260ec914cSpeter.d.reid ** is happening when it is supposed to.
205391c58e23Sdrh */
205491c58e23Sdrh int sqlite3_xferopt_count;
205591c58e23Sdrh #endif /* SQLITE_TEST */
205691c58e23Sdrh 
205791c58e23Sdrh 
20589d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
20599d9cf229Sdrh /*
20609d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
20619d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
20629d9cf229Sdrh ** for a compatible index:
20639d9cf229Sdrh **
20649d9cf229Sdrh **    *   The index is over the same set of columns
20659d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
20669d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
20679d9cf229Sdrh **    *   The same collating sequence on each column
2068b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
20699d9cf229Sdrh */
20709d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
20719d9cf229Sdrh   int i;
20729d9cf229Sdrh   assert( pDest && pSrc );
20739d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
2074bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
20759d9cf229Sdrh     return 0;   /* Different number of columns */
20769d9cf229Sdrh   }
20779d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
20789d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
20799d9cf229Sdrh   }
2080bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
20819d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
20829d9cf229Sdrh       return 0;   /* Different columns indexed */
20839d9cf229Sdrh     }
20844b92f98cSdrh     if( pSrc->aiColumn[i]==XN_EXPR ){
20851f9ca2c8Sdrh       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
20865aa550cfSdan       if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
20871f9ca2c8Sdrh                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
20881f9ca2c8Sdrh         return 0;   /* Different expressions in the index */
20891f9ca2c8Sdrh       }
20901f9ca2c8Sdrh     }
20919d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
20929d9cf229Sdrh       return 0;   /* Different sort orders */
20939d9cf229Sdrh     }
20940472af91Sdrh     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
209560a713c6Sdrh       return 0;   /* Different collating sequences */
20969d9cf229Sdrh     }
20979d9cf229Sdrh   }
20985aa550cfSdan   if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2099b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
2100b2b9d3d7Sdrh   }
21019d9cf229Sdrh 
21029d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
21039d9cf229Sdrh   return 1;
21049d9cf229Sdrh }
21059d9cf229Sdrh 
21069d9cf229Sdrh /*
21079d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
21089d9cf229Sdrh **
21099d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
21109d9cf229Sdrh **
2111ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
211260ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves
2113ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
21149d9cf229Sdrh **
2115ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2116ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
2117ccdf1baeSdrh ** embedded in the code for details.
21189d9cf229Sdrh **
2119ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
2120ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
2121ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
2122ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
2123ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
2124ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
2125ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
2126ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
2127ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
21289d9cf229Sdrh **
2129ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
21309d9cf229Sdrh */
21319d9cf229Sdrh static int xferOptimization(
21329d9cf229Sdrh   Parse *pParse,        /* Parser context */
21339d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
21349d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
21359d9cf229Sdrh   int onError,          /* How to handle constraint errors */
21369d9cf229Sdrh   int iDbDest           /* The database of pDest */
21379d9cf229Sdrh ){
2138e34162b1Sdan   sqlite3 *db = pParse->db;
21399d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
21409d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
21419d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
21429d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
21439d9cf229Sdrh   int i;                           /* Loop counter */
21449d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
21459d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
21469d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
2147da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
2148da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
21499d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
21506a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
2151f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
2152b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
21539d9cf229Sdrh 
21549d9cf229Sdrh   if( pSelect==0 ){
21559d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
21569d9cf229Sdrh   }
2157ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
2158ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
2159ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
2160ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
2161ebbf08a0Sdan     return 0;
2162ebbf08a0Sdan   }
21632f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
21649d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
21659d9cf229Sdrh   }
21669d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
216744266ec6Sdrh   if( IsVirtual(pDest) ){
21689d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
21699d9cf229Sdrh   }
21709d9cf229Sdrh #endif
21719d9cf229Sdrh   if( onError==OE_Default ){
2172e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2173e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
21749d9cf229Sdrh   }
21755ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
21769d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
21779d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
21789d9cf229Sdrh   }
21799d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
21809d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
21819d9cf229Sdrh   }
21829d9cf229Sdrh   if( pSelect->pWhere ){
21839d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
21849d9cf229Sdrh   }
21859d9cf229Sdrh   if( pSelect->pOrderBy ){
21869d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
21879d9cf229Sdrh   }
21888103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
21898103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
21909d9cf229Sdrh   if( pSelect->pGroupBy ){
21919d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
21929d9cf229Sdrh   }
21939d9cf229Sdrh   if( pSelect->pLimit ){
21949d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
21959d9cf229Sdrh   }
21969d9cf229Sdrh   if( pSelect->pPrior ){
21979d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
21989d9cf229Sdrh   }
21997d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
22009d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
22019d9cf229Sdrh   }
22029d9cf229Sdrh   pEList = pSelect->pEList;
22039d9cf229Sdrh   assert( pEList!=0 );
22049d9cf229Sdrh   if( pEList->nExpr!=1 ){
22059d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
22069d9cf229Sdrh   }
22079d9cf229Sdrh   assert( pEList->a[0].pExpr );
22081a1d3cd2Sdrh   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
22099d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
22109d9cf229Sdrh   }
22119d9cf229Sdrh 
22129d9cf229Sdrh   /* At this point we have established that the statement is of the
22139d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
22149d9cf229Sdrh   ** we have to check the semantics.
22159d9cf229Sdrh   */
22169d9cf229Sdrh   pItem = pSelect->pSrc->a;
221741fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
22189d9cf229Sdrh   if( pSrc==0 ){
22199d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
22209d9cf229Sdrh   }
22219d9cf229Sdrh   if( pSrc==pDest ){
22229d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
22239d9cf229Sdrh   }
222455548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
222555548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
222655548273Sdrh   }
22279d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
222844266ec6Sdrh   if( IsVirtual(pSrc) ){
22299d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
22309d9cf229Sdrh   }
22319d9cf229Sdrh #endif
22329d9cf229Sdrh   if( pSrc->pSelect ){
22339d9cf229Sdrh     return 0;   /* tab2 may not be a view */
22349d9cf229Sdrh   }
22359d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
22369d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
22379d9cf229Sdrh   }
22389d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
22399d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
22409d9cf229Sdrh   }
22419d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
22429940e2aaSdan     Column *pDestCol = &pDest->aCol[i];
22439940e2aaSdan     Column *pSrcCol = &pSrc->aCol[i];
2244ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
22458257aa8dSdrh     if( (db->mDbFlags & DBFLAG_Vacuum)==0
2246aaea3143Sdan      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2247aaea3143Sdan     ){
2248ba68f8f3Sdan       return 0;    /* Neither table may have __hidden__ columns */
2249ba68f8f3Sdan     }
2250ba68f8f3Sdan #endif
22519940e2aaSdan     if( pDestCol->affinity!=pSrcCol->affinity ){
22529d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
22539d9cf229Sdrh     }
22540472af91Sdrh     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
22559d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
22569d9cf229Sdrh     }
22579940e2aaSdan     if( pDestCol->notNull && !pSrcCol->notNull ){
22589d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
22599d9cf229Sdrh     }
2260453e0261Sdrh     /* Default values for second and subsequent columns need to match. */
226194fa9c41Sdrh     if( i>0 ){
226294fa9c41Sdrh       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
226394fa9c41Sdrh       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
226494fa9c41Sdrh       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
226594fa9c41Sdrh        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
226694fa9c41Sdrh                                        pSrcCol->pDflt->u.zToken)!=0)
22679940e2aaSdan       ){
22689940e2aaSdan         return 0;    /* Default values must be the same for all columns */
22699940e2aaSdan       }
22709d9cf229Sdrh     }
227194fa9c41Sdrh   }
22729d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
22735f1d1d9cSdrh     if( IsUniqueIndex(pDestIdx) ){
2274f33c9fadSdrh       destHasUniqueIdx = 1;
2275f33c9fadSdrh     }
22769d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
22779d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
22789d9cf229Sdrh     }
22799d9cf229Sdrh     if( pSrcIdx==0 ){
22809d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
22819d9cf229Sdrh     }
22829d9cf229Sdrh   }
22837fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
2284619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
22858103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
22868103b7d2Sdrh   }
22877fc2f41bSdrh #endif
2288713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
2289713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
2290713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
2291713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
2292713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
2293713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
2294713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2295713de341Sdrh   */
2296e34162b1Sdan   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
2297713de341Sdrh     return 0;
2298713de341Sdrh   }
2299713de341Sdrh #endif
2300e34162b1Sdan   if( (db->flags & SQLITE_CountRows)!=0 ){
2301ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
23021696124dSdan   }
23039d9cf229Sdrh 
2304ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
2305ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
2306ccdf1baeSdrh   ** table (tab1) is initially empty.
23079d9cf229Sdrh   */
2308dd73521bSdrh #ifdef SQLITE_TEST
2309dd73521bSdrh   sqlite3_xferopt_count++;
2310dd73521bSdrh #endif
2311e34162b1Sdan   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
23129d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
2313f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
23149d9cf229Sdrh   iSrc = pParse->nTab++;
23159d9cf229Sdrh   iDest = pParse->nTab++;
23166a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
231755548273Sdrh   regData = sqlite3GetTempReg(pParse);
231855548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
23199d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2320427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
23218257aa8dSdrh   if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
2322e34162b1Sdan       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2323ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
2324ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2325e34162b1Sdan   )){
2326ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
2327e34162b1Sdan     ** only if the destination table is initially empty. Unless the
23288257aa8dSdrh     ** DBFLAG_Vacuum flag is set, this block generates code to make
23298257aa8dSdrh     ** that determination. If DBFLAG_Vacuum is set, then the destination
2330e34162b1Sdan     ** table is always empty.
2331e34162b1Sdan     **
2332e34162b1Sdan     ** Conditions under which the destination must be empty:
2333f33c9fadSdrh     **
2334ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2335ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
2336ccdf1baeSdrh     **     of index entries might need to change.)
2337ccdf1baeSdrh     **
2338ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
2339ccdf1baeSdrh     **     is unable to test uniqueness.)
2340ccdf1baeSdrh     **
2341ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
23429d9cf229Sdrh     */
2343688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
23442991ba05Sdrh     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
23459d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
23469d9cf229Sdrh   }
2347427ebba1Sdan   if( HasRowid(pSrc) ){
2348c9b9deaeSdrh     u8 insFlags;
23499d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
2350688852abSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
235142242dedSdrh     if( pDest->iPKey>=0 ){
2352b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2353b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2354688852abSdrh       VdbeCoverage(v);
2355f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
23569d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
2357b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
2358bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
2359b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
236095bad4c7Sdrh     }else{
2361b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
23627d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
236395bad4c7Sdrh     }
2364e7b554d6Sdrh     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
23658257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
236686b40dfdSdrh       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2367c9b9deaeSdrh       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
2368c9b9deaeSdrh                            OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
2369c9b9deaeSdrh     }else{
2370c9b9deaeSdrh       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
2371c9b9deaeSdrh     }
23729b34abeeSdrh     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
237320f272c9Sdrh                       (char*)pDest, P4_TABLE);
2374c9b9deaeSdrh     sqlite3VdbeChangeP5(v, insFlags);
2375688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
237655548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
237755548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2378da475b8dSdrh   }else{
2379da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2380da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
238155548273Sdrh   }
23829d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
238341b9ca25Sdrh     u8 idxInsFlags = 0;
23841b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
23859d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
23869d9cf229Sdrh     }
23879d9cf229Sdrh     assert( pSrcIdx );
23882ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
23892ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2390d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
23912ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
23922ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
239359885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2394207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
2395688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2396e7b554d6Sdrh     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
23978257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
2398e34162b1Sdan       /* This INSERT command is part of a VACUUM operation, which guarantees
2399e34162b1Sdan       ** that the destination table is empty. If all indexed columns use
2400e34162b1Sdan       ** collation sequence BINARY, then it can also be assumed that the
2401e34162b1Sdan       ** index will be populated by inserting keys in strictly sorted
2402e34162b1Sdan       ** order. In this case, instead of seeking within the b-tree as part
240386b40dfdSdrh       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
2404e34162b1Sdan       ** OP_IdxInsert to seek to the point within the b-tree where each key
2405e34162b1Sdan       ** should be inserted. This is faster.
2406e34162b1Sdan       **
2407e34162b1Sdan       ** If any of the indexed columns use a collation sequence other than
2408e34162b1Sdan       ** BINARY, this optimization is disabled. This is because the user
2409e34162b1Sdan       ** might change the definition of a collation sequence and then run
2410e34162b1Sdan       ** a VACUUM command. In that case keys may not be written in strictly
2411e34162b1Sdan       ** sorted order.  */
2412e34162b1Sdan       for(i=0; i<pSrcIdx->nColumn; i++){
2413f19aa5faSdrh         const char *zColl = pSrcIdx->azColl[i];
2414f19aa5faSdrh         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
2415e34162b1Sdan       }
2416e34162b1Sdan       if( i==pSrcIdx->nColumn ){
241741b9ca25Sdrh         idxInsFlags = OPFLAG_USESEEKRESULT;
241886b40dfdSdrh         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2419e34162b1Sdan       }
2420e34162b1Sdan     }
242141b9ca25Sdrh     if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
242241b9ca25Sdrh       idxInsFlags |= OPFLAG_NCHANGE;
242341b9ca25Sdrh     }
24249b4eaebcSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
24259b4eaebcSdrh     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
2426688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
24279d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
242855548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
242955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
24309d9cf229Sdrh   }
2431aceb31b1Sdrh   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2432b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2433b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
24349d9cf229Sdrh   if( emptyDestTest ){
24351dd518cfSdrh     sqlite3AutoincrementEnd(pParse);
243666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
24379d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
243866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
24399d9cf229Sdrh     return 0;
24409d9cf229Sdrh   }else{
24419d9cf229Sdrh     return 1;
24429d9cf229Sdrh   }
24439d9cf229Sdrh }
24449d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2445