xref: /sqlite-3.40.0/src/insert.c (revision ef07f96f)
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) );
35289a0c84Sdrh   assert( pParse->pVdbe!=0 );
36289a0c84Sdrh   v = pParse->pVdbe;
37bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
382ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
392ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
40ec95c441Sdrh   if( HasRowid(pTab) ){
410b0b3a95Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
42bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
4326198bb4Sdrh   }else{
44dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
45dd9930efSdrh     assert( pPk!=0 );
4639075608Sdrh     assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
472ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
482ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
49bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
50bbb5e4e0Sdrh   }
51bbb5e4e0Sdrh }
52bbb5e4e0Sdrh 
53bbb5e4e0Sdrh /*
5469f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5569f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5669f8bb9cSdan ** the table, according to the affinity of the column:
573d1bfeaaSdanielk1977 **
583d1bfeaaSdanielk1977 **  Character      Column affinity
593d1bfeaaSdanielk1977 **  ------------------------------
6005883a34Sdrh **  'A'            BLOB
614583c37cSdrh **  'B'            TEXT
624583c37cSdrh **  'C'            NUMERIC
634583c37cSdrh **  'D'            INTEGER
644583c37cSdrh **  'F'            REAL
652d401ab8Sdrh **
664583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the
672d401ab8Sdrh ** rowid that appears as the last column in every index.
6869f8bb9cSdan **
6969f8bb9cSdan ** Memory for the buffer containing the column index affinity string
7069f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7169f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
723d1bfeaaSdanielk1977 */
73e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
74a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
75e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
76a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
77e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
78a37cdde0Sdanielk1977     **
79a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
80e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
81a37cdde0Sdanielk1977     ** up.
82a37cdde0Sdanielk1977     */
83a37cdde0Sdanielk1977     int n;
84a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
85ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
86a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
874a642b60Sdrh       sqlite3OomFault(db);
8869f8bb9cSdan       return 0;
89a37cdde0Sdanielk1977     }
90a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
91ad124329Sdrh       i16 x = pIdx->aiColumn[n];
926860e6faSdrh       char aff;
9381506b88Sdrh       if( x>=0 ){
9481506b88Sdrh         aff = pTab->aCol[x].affinity;
9581506b88Sdrh       }else if( x==XN_ROWID ){
9681506b88Sdrh         aff = SQLITE_AFF_INTEGER;
9781506b88Sdrh       }else{
984b92f98cSdrh         assert( x==XN_EXPR );
991f9ca2c8Sdrh         assert( pIdx->aColExpr!=0 );
1006860e6faSdrh         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
10181506b88Sdrh       }
10296fb16eeSdrh       if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
1037314495fSdrh       if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
1046860e6faSdrh       pIdx->zColAff[n] = aff;
1051f9ca2c8Sdrh     }
1062d401ab8Sdrh     pIdx->zColAff[n] = 0;
107a37cdde0Sdanielk1977   }
1083d1bfeaaSdanielk1977 
10969f8bb9cSdan   return pIdx->zColAff;
110a37cdde0Sdanielk1977 }
111a37cdde0Sdanielk1977 
112a37cdde0Sdanielk1977 /*
11371c770fbSdrh ** Make changes to the evolving bytecode to do affinity transformations
11471c770fbSdrh ** of values that are about to be gathered into a row for table pTab.
11571c770fbSdrh **
11671c770fbSdrh ** For ordinary (legacy, non-strict) tables:
11771c770fbSdrh ** -----------------------------------------
11871c770fbSdrh **
11957bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been
12005883a34Sdrh ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
12157bf4a8eSdrh **
12271c770fbSdrh ** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
12371c770fbSdrh ** which were then optimized out) then this routine becomes a no-op.
12471c770fbSdrh **
12571c770fbSdrh ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
12671c770fbSdrh ** affinities for register iReg and following.  Or if iReg==0,
12757bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should  be
12857bf4a8eSdrh ** an OP_MakeRecord) to the affinity string.
12957bf4a8eSdrh **
130b6e8fd10Sdrh ** A column affinity string has one character per column:
131a37cdde0Sdanielk1977 **
132a37cdde0Sdanielk1977 **    Character      Column affinity
13371c770fbSdrh **    ---------      ---------------
13405883a34Sdrh **    'A'            BLOB
1354583c37cSdrh **    'B'            TEXT
1364583c37cSdrh **    'C'            NUMERIC
1374583c37cSdrh **    'D'            INTEGER
1384583c37cSdrh **    'E'            REAL
13971c770fbSdrh **
14071c770fbSdrh ** For STRICT tables:
14171c770fbSdrh ** ------------------
14271c770fbSdrh **
14371c770fbSdrh ** Generate an appropropriate OP_TypeCheck opcode that will verify the
14471c770fbSdrh ** datatypes against the column definitions in pTab.  If iReg==0, that
14571c770fbSdrh ** means an OP_MakeRecord opcode has already been generated and should be
14671c770fbSdrh ** the last opcode generated.  The new OP_TypeCheck needs to be inserted
14771c770fbSdrh ** before the OP_MakeRecord.  The new OP_TypeCheck should use the same
14871c770fbSdrh ** register set as the OP_MakeRecord.  If iReg>0 then register iReg is
14971c770fbSdrh ** the first of a series of registers that will form the new record.
15071c770fbSdrh ** Apply the type checking to that array of registers.
151a37cdde0Sdanielk1977 */
15257bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
153ab45fc04Sdrh   int i, j;
15472532f52Sdrh   char *zColAff;
15572532f52Sdrh   if( pTab->tabFlags & TF_Strict ){
15672532f52Sdrh     if( iReg==0 ){
15772532f52Sdrh       /* Move the previous opcode (which should be OP_MakeRecord) forward
15872532f52Sdrh       ** by one slot and insert a new OP_TypeCheck where the current
15972532f52Sdrh       ** OP_MakeRecord is found */
16072532f52Sdrh       VdbeOp *pPrev;
16172532f52Sdrh       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
16272532f52Sdrh       pPrev = sqlite3VdbeGetOp(v, -1);
16371c770fbSdrh       assert( pPrev!=0 );
16471c770fbSdrh       assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
16572532f52Sdrh       pPrev->opcode = OP_TypeCheck;
16672532f52Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
16772532f52Sdrh     }else{
16872532f52Sdrh       /* Insert an isolated OP_Typecheck */
16972532f52Sdrh       sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
17072532f52Sdrh       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
17172532f52Sdrh     }
17272532f52Sdrh     return;
17372532f52Sdrh   }
17472532f52Sdrh   zColAff = pTab->zColAff;
17557bf4a8eSdrh   if( zColAff==0 ){
176abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
177b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1783d1bfeaaSdanielk1977     if( !zColAff ){
1794a642b60Sdrh       sqlite3OomFault(db);
180a37cdde0Sdanielk1977       return;
1813d1bfeaaSdanielk1977     }
1823d1bfeaaSdanielk1977 
183ab45fc04Sdrh     for(i=j=0; i<pTab->nCol; i++){
184*ef07f96fSdrh       assert( pTab->aCol[i].affinity!=0 || sqlite3VdbeParser(v)->nErr>0 );
185ab45fc04Sdrh       if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
186ab45fc04Sdrh         zColAff[j++] = pTab->aCol[i].affinity;
187ab45fc04Sdrh       }
1883d1bfeaaSdanielk1977     }
18957bf4a8eSdrh     do{
190ab45fc04Sdrh       zColAff[j--] = 0;
191ab45fc04Sdrh     }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
1923d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1933d1bfeaaSdanielk1977   }
1947301e774Sdrh   assert( zColAff!=0 );
1957301e774Sdrh   i = sqlite3Strlen30NN(zColAff);
19657bf4a8eSdrh   if( i ){
19757bf4a8eSdrh     if( iReg ){
19857bf4a8eSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
19957bf4a8eSdrh     }else{
20071c770fbSdrh       assert( sqlite3VdbeGetOp(v, -1)->opcode==OP_MakeRecord
20171c770fbSdrh               || sqlite3VdbeDb(v)->mallocFailed );
20257bf4a8eSdrh       sqlite3VdbeChangeP4(v, -1, zColAff, i);
20357bf4a8eSdrh     }
20457bf4a8eSdrh   }
2053d1bfeaaSdanielk1977 }
2063d1bfeaaSdanielk1977 
2074d88778bSdanielk1977 /*
20848d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
209b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if
21048d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
211b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT.
2124d88778bSdanielk1977 */
21305a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){
214595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
2154d88778bSdanielk1977   int i;
21648d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
217595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
218595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
219595a523aSdanielk1977 #endif
220595a523aSdanielk1977 
22105a86c5cSdrh   for(i=1; i<iEnd; i++){
22248d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
223ef0bea92Sdrh     assert( pOp!=0 );
224207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
22548d1178aSdrh       Index *pIndex;
2268deae5adSdrh       Pgno tnum = pOp->p2;
22748d1178aSdrh       if( tnum==pTab->tnum ){
22848d1178aSdrh         return 1;
22948d1178aSdrh       }
23048d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
23148d1178aSdrh         if( tnum==pIndex->tnum ){
23248d1178aSdrh           return 1;
23348d1178aSdrh         }
23448d1178aSdrh       }
23548d1178aSdrh     }
236543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
237595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
2382dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
23966a5167bSdrh       assert( pOp->p4type==P4_VTAB );
24048d1178aSdrh       return 1;
2414d88778bSdanielk1977     }
242543165efSdrh #endif
2434d88778bSdanielk1977   }
2444d88778bSdanielk1977   return 0;
2454d88778bSdanielk1977 }
2463d1bfeaaSdanielk1977 
247dfa15270Sdrh /* This walker callback will compute the union of colFlags flags for all
2487dc76d8bSdrh ** referenced columns in a CHECK constraint or generated column expression.
249dfa15270Sdrh */
250dfa15270Sdrh static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
2517dc76d8bSdrh   if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
2527dc76d8bSdrh     assert( pExpr->iColumn < pWalker->u.pTab->nCol );
253dfa15270Sdrh     pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
254dfa15270Sdrh   }
255dfa15270Sdrh   return WRC_Continue;
256dfa15270Sdrh }
257dfa15270Sdrh 
258c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
259c1431144Sdrh /*
260c1431144Sdrh ** All regular columns for table pTab have been puts into registers
261c1431144Sdrh ** starting with iRegStore.  The registers that correspond to STORED
262dd6cc9b5Sdrh ** or VIRTUAL columns have not yet been initialized.  This routine goes
263dd6cc9b5Sdrh ** back and computes the values for those columns based on the previously
264dd6cc9b5Sdrh ** computed normal columns.
265c1431144Sdrh */
266dd6cc9b5Sdrh void sqlite3ComputeGeneratedColumns(
267c1431144Sdrh   Parse *pParse,    /* Parsing context */
268c1431144Sdrh   int iRegStore,    /* Register holding the first column */
269c1431144Sdrh   Table *pTab       /* The table */
270c1431144Sdrh ){
271c1431144Sdrh   int i;
272dfa15270Sdrh   Walker w;
273dfa15270Sdrh   Column *pRedo;
274dfa15270Sdrh   int eProgress;
275b5f6243fSdrh   VdbeOp *pOp;
276b5f6243fSdrh 
277b5f6243fSdrh   assert( pTab->tabFlags & TF_HasGenerated );
278b5f6243fSdrh   testcase( pTab->tabFlags & TF_HasVirtual );
279b5f6243fSdrh   testcase( pTab->tabFlags & TF_HasStored );
280b5f6243fSdrh 
281b5f6243fSdrh   /* Before computing generated columns, first go through and make sure
282b5f6243fSdrh   ** that appropriate affinity has been applied to the regular columns
283b5f6243fSdrh   */
284b5f6243fSdrh   sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
285926aac51Sdrh   if( (pTab->tabFlags & TF_HasStored)!=0 ){
286926aac51Sdrh     pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
287926aac51Sdrh     if( pOp->opcode==OP_Affinity ){
288b5f6243fSdrh       /* Change the OP_Affinity argument to '@' (NONE) for all stored
289b5f6243fSdrh       ** columns.  '@' is the no-op affinity and those columns have not
290b5f6243fSdrh       ** yet been computed. */
291b5f6243fSdrh       int ii, jj;
292b5f6243fSdrh       char *zP4 = pOp->p4.z;
293b5f6243fSdrh       assert( zP4!=0 );
294b5f6243fSdrh       assert( pOp->p4type==P4_DYNAMIC );
295b5f6243fSdrh       for(ii=jj=0; zP4[jj]; ii++){
296b5f6243fSdrh         if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
297b5f6243fSdrh           continue;
298b5f6243fSdrh         }
299b5f6243fSdrh         if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
300b5f6243fSdrh           zP4[jj] = SQLITE_AFF_NONE;
301b5f6243fSdrh         }
302b5f6243fSdrh         jj++;
303b5f6243fSdrh       }
304926aac51Sdrh     }else if( pOp->opcode==OP_TypeCheck ){
305926aac51Sdrh       /* If an OP_TypeCheck was generated because the table is STRICT,
306926aac51Sdrh       ** then set the P3 operand to indicate that generated columns should
307926aac51Sdrh       ** not be checked */
308926aac51Sdrh       pOp->p3 = 1;
309926aac51Sdrh     }
310b5f6243fSdrh   }
311dfa15270Sdrh 
312dd6cc9b5Sdrh   /* Because there can be multiple generated columns that refer to one another,
313dd6cc9b5Sdrh   ** this is a two-pass algorithm.  On the first pass, mark all generated
314dd6cc9b5Sdrh   ** columns as "not available".
3159942ef0dSdrh   */
3169942ef0dSdrh   for(i=0; i<pTab->nCol; i++){
317dd6cc9b5Sdrh     if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
318ab0992f0Sdrh       testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
319ab0992f0Sdrh       testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
3209942ef0dSdrh       pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
3219942ef0dSdrh     }
3229942ef0dSdrh   }
323dfa15270Sdrh 
324dfa15270Sdrh   w.u.pTab = pTab;
325dfa15270Sdrh   w.xExprCallback = exprColumnFlagUnion;
326dfa15270Sdrh   w.xSelectCallback = 0;
327dfa15270Sdrh   w.xSelectCallback2 = 0;
328dfa15270Sdrh 
3299942ef0dSdrh   /* On the second pass, compute the value of each NOT-AVAILABLE column.
3309942ef0dSdrh   ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
3319942ef0dSdrh   ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
3329942ef0dSdrh   ** they are needed.
3339942ef0dSdrh   */
334c1431144Sdrh   pParse->iSelfTab = -iRegStore;
335dfa15270Sdrh   do{
336dfa15270Sdrh     eProgress = 0;
337dfa15270Sdrh     pRedo = 0;
338dfa15270Sdrh     for(i=0; i<pTab->nCol; i++){
339dfa15270Sdrh       Column *pCol = pTab->aCol + i;
340dfa15270Sdrh       if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
341dfa15270Sdrh         int x;
342dfa15270Sdrh         pCol->colFlags |= COLFLAG_BUSY;
343dfa15270Sdrh         w.eCode = 0;
34479cf2b71Sdrh         sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
345dfa15270Sdrh         pCol->colFlags &= ~COLFLAG_BUSY;
346dfa15270Sdrh         if( w.eCode & COLFLAG_NOTAVAIL ){
347dfa15270Sdrh           pRedo = pCol;
348dfa15270Sdrh           continue;
349dd6cc9b5Sdrh         }
350dfa15270Sdrh         eProgress = 1;
351dfa15270Sdrh         assert( pCol->colFlags & COLFLAG_GENERATED );
352dfa15270Sdrh         x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
35379cf2b71Sdrh         sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
354dfa15270Sdrh         pCol->colFlags &= ~COLFLAG_NOTAVAIL;
355c1431144Sdrh       }
356dfa15270Sdrh     }
357dfa15270Sdrh   }while( pRedo && eProgress );
358dfa15270Sdrh   if( pRedo ){
359cf9d36d1Sdrh     sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
360c1431144Sdrh   }
361c1431144Sdrh   pParse->iSelfTab = 0;
362c1431144Sdrh }
363c1431144Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
364c1431144Sdrh 
365c1431144Sdrh 
3669d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
3679d9cf229Sdrh /*
3680b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
3690b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
3709ef5e770Sdrh ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
3719ef5e770Sdrh ** table.  (Also return zero when doing a VACUUM since we do not want to
3729ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.)
3739d9cf229Sdrh **
3740b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
3750b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
3760b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
3770b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
3780b9f50d8Sdrh ** AutoincInfo structure is used.
3799d9cf229Sdrh **
380c8abbc11Sdrh ** Four consecutive registers are allocated:
3810b9f50d8Sdrh **
382c8abbc11Sdrh **   (1)  The name of the pTab table.
383c8abbc11Sdrh **   (2)  The maximum ROWID of pTab.
384c8abbc11Sdrh **   (3)  The rowid in sqlite_sequence of pTab
385c8abbc11Sdrh **   (4)  The original value of the max ROWID in pTab, or NULL if none
3860b9f50d8Sdrh **
3870b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
3880b9f50d8Sdrh ** insert routine needs to know about.
3899d9cf229Sdrh */
3909d9cf229Sdrh static int autoIncBegin(
3919d9cf229Sdrh   Parse *pParse,      /* Parsing context */
3929d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
3939d9cf229Sdrh   Table *pTab         /* The table we are writing to */
3949d9cf229Sdrh ){
3956a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
396186ebd41Sdrh   assert( pParse->db->aDb[iDb].pSchema!=0 );
3979ef5e770Sdrh   if( (pTab->tabFlags & TF_Autoincrement)!=0
3988257aa8dSdrh    && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
3999ef5e770Sdrh   ){
40065a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
4010b9f50d8Sdrh     AutoincInfo *pInfo;
402186ebd41Sdrh     Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
403186ebd41Sdrh 
404186ebd41Sdrh     /* Verify that the sqlite_sequence table exists and is an ordinary
405186ebd41Sdrh     ** rowid table with exactly two columns.
406186ebd41Sdrh     ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
407186ebd41Sdrh     if( pSeqTab==0
408186ebd41Sdrh      || !HasRowid(pSeqTab)
4090003d878Sdrh      || NEVER(IsVirtual(pSeqTab))
410186ebd41Sdrh      || pSeqTab->nCol!=2
411186ebd41Sdrh     ){
412186ebd41Sdrh       pParse->nErr++;
413186ebd41Sdrh       pParse->rc = SQLITE_CORRUPT_SEQUENCE;
414186ebd41Sdrh       return 0;
415186ebd41Sdrh     }
4160b9f50d8Sdrh 
41765a7cd16Sdan     pInfo = pToplevel->pAinc;
4180b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
4190b9f50d8Sdrh     if( pInfo==0 ){
420575fad65Sdrh       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
42121d4f5b5Sdrh       sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
42221d4f5b5Sdrh       testcase( pParse->earlyCleanup );
42321d4f5b5Sdrh       if( pParse->db->mallocFailed ) return 0;
42465a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
42565a7cd16Sdan       pToplevel->pAinc = pInfo;
4260b9f50d8Sdrh       pInfo->pTab = pTab;
4270b9f50d8Sdrh       pInfo->iDb = iDb;
42865a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
42965a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
430c8abbc11Sdrh       pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
4310b9f50d8Sdrh     }
4320b9f50d8Sdrh     memId = pInfo->regCtr;
4339d9cf229Sdrh   }
4349d9cf229Sdrh   return memId;
4359d9cf229Sdrh }
4369d9cf229Sdrh 
4379d9cf229Sdrh /*
4380b9f50d8Sdrh ** This routine generates code that will initialize all of the
4390b9f50d8Sdrh ** register used by the autoincrement tracker.
4400b9f50d8Sdrh */
4410b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
4420b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
4430b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
4440b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
4450b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
4460b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
4470b9f50d8Sdrh 
448345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
449345ba7dbSdrh   ** only called from the top-level */
450345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
451c149f18fSdrh   assert( sqlite3IsToplevel(pParse) );
45276d462eeSdan 
4530b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
4540b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
4551b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
4561b32554bSdrh     static const VdbeOpList autoInc[] = {
4571b32554bSdrh       /* 0  */ {OP_Null,    0,  0, 0},
458c8abbc11Sdrh       /* 1  */ {OP_Rewind,  0, 10, 0},
4591b32554bSdrh       /* 2  */ {OP_Column,  0,  0, 0},
460c8abbc11Sdrh       /* 3  */ {OP_Ne,      0,  9, 0},
4611b32554bSdrh       /* 4  */ {OP_Rowid,   0,  0, 0},
4621b32554bSdrh       /* 5  */ {OP_Column,  0,  1, 0},
463c8abbc11Sdrh       /* 6  */ {OP_AddImm,  0,  0, 0},
464c8abbc11Sdrh       /* 7  */ {OP_Copy,    0,  0, 0},
465c8abbc11Sdrh       /* 8  */ {OP_Goto,    0, 11, 0},
466c8abbc11Sdrh       /* 9  */ {OP_Next,    0,  2, 0},
467c8abbc11Sdrh       /* 10 */ {OP_Integer, 0,  0, 0},
468c8abbc11Sdrh       /* 11 */ {OP_Close,   0,  0, 0}
4691b32554bSdrh     };
4701b32554bSdrh     VdbeOp *aOp;
4710b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
4720b9f50d8Sdrh     memId = p->regCtr;
4732120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
4740b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
475076e85f5Sdrh     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
4761b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
4771b32554bSdrh     if( aOp==0 ) break;
4781b32554bSdrh     aOp[0].p2 = memId;
479c8abbc11Sdrh     aOp[0].p3 = memId+2;
4801b32554bSdrh     aOp[2].p3 = memId;
4811b32554bSdrh     aOp[3].p1 = memId-1;
4821b32554bSdrh     aOp[3].p3 = memId;
4831b32554bSdrh     aOp[3].p5 = SQLITE_JUMPIFNULL;
4841b32554bSdrh     aOp[4].p2 = memId+1;
4851b32554bSdrh     aOp[5].p3 = memId;
486c8abbc11Sdrh     aOp[6].p1 = memId;
487c8abbc11Sdrh     aOp[7].p2 = memId+2;
488c8abbc11Sdrh     aOp[7].p1 = memId;
489c8abbc11Sdrh     aOp[10].p2 = memId;
49004ab586bSdrh     if( pParse->nTab==0 ) pParse->nTab = 1;
4910b9f50d8Sdrh   }
4920b9f50d8Sdrh }
4930b9f50d8Sdrh 
4940b9f50d8Sdrh /*
4959d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
4969d9cf229Sdrh **
4971b32554bSdrh ** This routine should be called when the regRowid register holds a
4989d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
4999d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
5001b32554bSdrh ** memory cell is updated.
5019d9cf229Sdrh */
5026a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
5039d9cf229Sdrh   if( memId>0 ){
5046a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
5059d9cf229Sdrh   }
5069d9cf229Sdrh }
5079d9cf229Sdrh 
5089d9cf229Sdrh /*
5090b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
5100b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
5110b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
5120b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
5130b9f50d8Sdrh ** routine just before the "exit" code.
5149d9cf229Sdrh */
5151b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
5160b9f50d8Sdrh   AutoincInfo *p;
5179d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
5180b9f50d8Sdrh   sqlite3 *db = pParse->db;
5196a288a33Sdrh 
5209d9cf229Sdrh   assert( v );
5210b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
5221b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
5231b32554bSdrh     static const VdbeOpList autoIncEnd[] = {
5241b32554bSdrh       /* 0 */ {OP_NotNull,     0, 2, 0},
5251b32554bSdrh       /* 1 */ {OP_NewRowid,    0, 0, 0},
5261b32554bSdrh       /* 2 */ {OP_MakeRecord,  0, 2, 0},
5271b32554bSdrh       /* 3 */ {OP_Insert,      0, 0, 0},
5281b32554bSdrh       /* 4 */ {OP_Close,       0, 0, 0}
5291b32554bSdrh     };
5301b32554bSdrh     VdbeOp *aOp;
5310b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
5320b9f50d8Sdrh     int iRec;
5330b9f50d8Sdrh     int memId = p->regCtr;
5340b9f50d8Sdrh 
5350b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
5362120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
537c8abbc11Sdrh     sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
538c8abbc11Sdrh     VdbeCoverage(v);
5390b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
5401b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
5411b32554bSdrh     if( aOp==0 ) break;
5421b32554bSdrh     aOp[0].p1 = memId+1;
5431b32554bSdrh     aOp[1].p2 = memId+1;
5441b32554bSdrh     aOp[2].p1 = memId-1;
5451b32554bSdrh     aOp[2].p3 = iRec;
5461b32554bSdrh     aOp[3].p2 = iRec;
5471b32554bSdrh     aOp[3].p3 = memId+1;
5481b32554bSdrh     aOp[3].p5 = OPFLAG_APPEND;
5490b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
5509d9cf229Sdrh   }
5519d9cf229Sdrh }
5521b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){
5531b32554bSdrh   if( pParse->pAinc ) autoIncrementEnd(pParse);
5541b32554bSdrh }
5559d9cf229Sdrh #else
5569d9cf229Sdrh /*
5579d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
5589d9cf229Sdrh ** above are all no-ops
5599d9cf229Sdrh */
5609d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
561287fb61cSdanielk1977 # define autoIncStep(A,B,C)
5629d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
5639d9cf229Sdrh 
5649d9cf229Sdrh 
5659d9cf229Sdrh /* Forward declaration */
5669d9cf229Sdrh static int xferOptimization(
5679d9cf229Sdrh   Parse *pParse,        /* Parser context */
5689d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
5699d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5709d9cf229Sdrh   int onError,          /* How to handle constraint errors */
5719d9cf229Sdrh   int iDbDest           /* The database of pDest */
5729d9cf229Sdrh );
5739d9cf229Sdrh 
5743d1bfeaaSdanielk1977 /*
575d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
576cce7d176Sdrh **
577a21f78b9Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
5781ccde15dSdrh **    insert into TABLE (IDLIST) select
579a21f78b9Sdrh **    insert into TABLE (IDLIST) default values
580cce7d176Sdrh **
5811ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
582a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted.
583a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
584a21f78b9Sdrh ** is omitted.
5851ccde15dSdrh **
586a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the
587a21f78b9Sdrh ** first two forms shown above.  A VALUES clause is really just short-hand
588a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else
589a21f78b9Sdrh ** that follows.  If the pSelect parameter is NULL, that means that the
590a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended.
591142e30dfSdrh **
5929d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
593a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes
594e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
595e00ee6ebSdrh ** the "1st template"):
596142e30dfSdrh **
597142e30dfSdrh **         open write cursor to <table> and its indices
598ec95c441Sdrh **         put VALUES clause expressions into registers
599142e30dfSdrh **         write the resulting record into <table>
600142e30dfSdrh **         cleanup
601142e30dfSdrh **
6029d9cf229Sdrh ** The three remaining templates assume the statement is of the form
603142e30dfSdrh **
604142e30dfSdrh **   INSERT INTO <table> SELECT ...
605142e30dfSdrh **
6069d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
6079d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
6089d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
6099d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
6109d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
6119d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
6129d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
613e00ee6ebSdrh ** template.  This is the 2nd template.
6149d9cf229Sdrh **
6159d9cf229Sdrh **         open a write cursor to <table>
6169d9cf229Sdrh **         open read cursor on <table2>
6179d9cf229Sdrh **         transfer all records in <table2> over to <table>
6189d9cf229Sdrh **         close cursors
6199d9cf229Sdrh **         foreach index on <table>
6209d9cf229Sdrh **           open a write cursor on the <table> index
6219d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
6229d9cf229Sdrh **           transfer all records from the read to the write cursors
6239d9cf229Sdrh **           close cursors
6249d9cf229Sdrh **         end foreach
6259d9cf229Sdrh **
626e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
6279d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
6289d9cf229Sdrh ** The generated code follows this template:
629142e30dfSdrh **
630e00ee6ebSdrh **         X <- A
631142e30dfSdrh **         goto B
632142e30dfSdrh **      A: setup for the SELECT
6339d9cf229Sdrh **         loop over the rows in the SELECT
634e00ee6ebSdrh **           load values into registers R..R+n
635e00ee6ebSdrh **           yield X
636142e30dfSdrh **         end loop
637142e30dfSdrh **         cleanup after the SELECT
63881cf13ecSdrh **         end-coroutine X
639e00ee6ebSdrh **      B: open write cursor to <table> and its indices
64081cf13ecSdrh **      C: yield X, at EOF goto D
641e00ee6ebSdrh **         insert the select result into <table> from R..R+n
642e00ee6ebSdrh **         goto C
643142e30dfSdrh **      D: cleanup
644142e30dfSdrh **
645e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
646142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
647142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
64860ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of
649142e30dfSdrh ** the select.  The template is like this:
650142e30dfSdrh **
651e00ee6ebSdrh **         X <- A
652142e30dfSdrh **         goto B
653142e30dfSdrh **      A: setup for the SELECT
654142e30dfSdrh **         loop over the tables in the SELECT
655e00ee6ebSdrh **           load value into register R..R+n
656e00ee6ebSdrh **           yield X
657142e30dfSdrh **         end loop
658142e30dfSdrh **         cleanup after the SELECT
65981cf13ecSdrh **         end co-routine R
660e00ee6ebSdrh **      B: open temp table
66181cf13ecSdrh **      L: yield X, at EOF goto M
662e00ee6ebSdrh **         insert row from R..R+n into temp table
663e00ee6ebSdrh **         goto L
664e00ee6ebSdrh **      M: open write cursor to <table> and its indices
665e00ee6ebSdrh **         rewind temp table
666e00ee6ebSdrh **      C: loop over rows of intermediate table
667142e30dfSdrh **           transfer values form intermediate table into <table>
668e00ee6ebSdrh **         end loop
669e00ee6ebSdrh **      D: cleanup
670cce7d176Sdrh */
6714adee20fSdanielk1977 void sqlite3Insert(
672cce7d176Sdrh   Parse *pParse,        /* Parser context */
673113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
6745974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
675f5f1915dSdrh   IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */
6762c2e844aSdrh   int onError,          /* How to handle constraint errors */
67746d2e5c3Sdrh   Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
678cce7d176Sdrh ){
6796a288a33Sdrh   sqlite3 *db;          /* The main database structure */
6806a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
68160ffc807Sdrh   int i, j;             /* Loop counters */
6825974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
6835974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
684967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
6856a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
68626198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
68726198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
688d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
6890ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
690cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
691e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
692e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
6932eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
6946a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
69505a86c5cSdrh   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
69605a86c5cSdrh   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
69705a86c5cSdrh   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
698a21f78b9Sdrh   u8 bIdListInOrder;    /* True if IDLIST is in table order */
69975593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
700c27ea2aeSdrh   int iRegStore;        /* Register in which to store next column */
701cce7d176Sdrh 
7026a288a33Sdrh   /* Register allocations */
7031bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
7046a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
7056a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
7066a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
7076a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
7086a288a33Sdrh   int regData;          /* register holding first column to insert */
709aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
7106a288a33Sdrh 
711798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
712798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
7132f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
7142f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
715798da52cSdrh #endif
716c3f9bad2Sdanielk1977 
71717435752Sdrh   db = pParse->db;
7180c7d3d39Sdrh   assert( db->pParse==pParse );
7190c7d3d39Sdrh   if( pParse->nErr ){
7206f7adc8aSdrh     goto insert_cleanup;
7216f7adc8aSdrh   }
7220c7d3d39Sdrh   assert( db->mallocFailed==0 );
7234c883487Sdrh   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
724daffd0e5Sdrh 
72575593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
726a21f78b9Sdrh   ** single row (the common case) then keep that one row of values
727a21f78b9Sdrh   ** and discard the other (unused) parts of the pSelect object
72875593d96Sdrh   */
72975593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
73075593d96Sdrh     pList = pSelect->pEList;
73175593d96Sdrh     pSelect->pEList = 0;
73275593d96Sdrh     sqlite3SelectDelete(db, pSelect);
73375593d96Sdrh     pSelect = 0;
73475593d96Sdrh   }
73575593d96Sdrh 
7361ccde15dSdrh   /* Locate the table into which we will be inserting new information.
7371ccde15dSdrh   */
738113088ecSdrh   assert( pTabList->nSrc==1 );
7394adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
740c3f9bad2Sdanielk1977   if( pTab==0 ){
741c3f9bad2Sdanielk1977     goto insert_cleanup;
742c3f9bad2Sdanielk1977   }
743da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
744da184236Sdanielk1977   assert( iDb<db->nDb );
745a0daa751Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
746a0daa751Sdrh                        db->aDb[iDb].zDbSName) ){
7471962bda7Sdrh     goto insert_cleanup;
7481962bda7Sdrh   }
749ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
750c3f9bad2Sdanielk1977 
751b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
752b7f9164eSdrh   ** inserted into is a view
753b7f9164eSdrh   */
754b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
7552f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
756f38524d2Sdrh   isView = IsView(pTab);
757b7f9164eSdrh #else
7582f886d1dSdanielk1977 # define pTrigger 0
7592f886d1dSdanielk1977 # define tmask 0
760b7f9164eSdrh # define isView 0
761b7f9164eSdrh #endif
762b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
763b7f9164eSdrh # undef isView
764b7f9164eSdrh # define isView 0
765b7f9164eSdrh #endif
7662f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
767b7f9164eSdrh 
768f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
769d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
770f573c99bSdrh   */
771b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
772f573c99bSdrh     goto insert_cleanup;
773f573c99bSdrh   }
774f573c99bSdrh 
775d82b5021Sdrh   /* Cannot insert into a read-only table.
776595a523aSdanielk1977   */
777595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
778595a523aSdanielk1977     goto insert_cleanup;
779595a523aSdanielk1977   }
780595a523aSdanielk1977 
7811ccde15dSdrh   /* Allocate a VDBE
7821ccde15dSdrh   */
7834adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
7845974a30fSdrh   if( v==0 ) goto insert_cleanup;
7854794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
7862f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
7871ccde15dSdrh 
7889d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
7899d9cf229Sdrh   /* If the statement is of the form
7909d9cf229Sdrh   **
7919d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
7929d9cf229Sdrh   **
7939d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
7949d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
795e00ee6ebSdrh   **
796e00ee6ebSdrh   ** This is the 2nd template.
7979d9cf229Sdrh   */
798935c3722Sdrh   if( pColumn==0
799935c3722Sdrh    && pSelect!=0
800935c3722Sdrh    && pTrigger==0
801935c3722Sdrh    && xferOptimization(pParse, pTab, pSelect, onError, iDb)
802935c3722Sdrh   ){
8032f886d1dSdanielk1977     assert( !pTrigger );
8049d9cf229Sdrh     assert( pList==0 );
8050b9f50d8Sdrh     goto insert_end;
8069d9cf229Sdrh   }
8079d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
8089d9cf229Sdrh 
8092958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
8106a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
8112958a4e6Sdrh   */
8126a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
8132958a4e6Sdrh 
814f5f1915dSdrh   /* Allocate a block registers to hold the rowid and the values
815f5f1915dSdrh   ** for all columns of the new row.
8161ccde15dSdrh   */
81705a86c5cSdrh   regRowid = regIns = pParse->nMem+1;
81805a86c5cSdrh   pParse->nMem += pTab->nCol + 1;
819034ca14fSdanielk1977   if( IsVirtual(pTab) ){
82005a86c5cSdrh     regRowid++;
82105a86c5cSdrh     pParse->nMem++;
822034ca14fSdanielk1977   }
82305a86c5cSdrh   regData = regRowid+1;
8241ccde15dSdrh 
8251ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
8261ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
8271ccde15dSdrh   ** remember the column indices.
828c8392586Sdrh   **
829c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
830d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
831d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
832c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
833d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
834f5f1915dSdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)  After this
835f5f1915dSdrh   ** loop, if ipkColumn==(-1), that means that integer primary key
836f5f1915dSdrh   ** is unspecified, and hence the table is either WITHOUT ROWID or
837f5f1915dSdrh   ** it will automatically generated an integer primary key.
838f5f1915dSdrh   **
839f5f1915dSdrh   ** bIdListInOrder is true if the columns in IDLIST are in storage
840f5f1915dSdrh   ** order.  This enables an optimization that avoids shuffling the
841f5f1915dSdrh   ** columns into storage order.  False negatives are harmless,
842f5f1915dSdrh   ** but false positives will cause database corruption.
8431ccde15dSdrh   */
844d4cd292cSdrh   bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
845967e8b73Sdrh   if( pColumn ){
846967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
847967e8b73Sdrh       pColumn->a[i].idx = -1;
848cce7d176Sdrh     }
849967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
850cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
851cf9d36d1Sdrh         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
852967e8b73Sdrh           pColumn->a[i].idx = j;
85305a86c5cSdrh           if( i!=j ) bIdListInOrder = 0;
8544a32431cSdrh           if( j==pTab->iPKey ){
855d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
8564a32431cSdrh           }
8577e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
8587e508f1eSdrh           if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
8597e508f1eSdrh             sqlite3ErrorMsg(pParse,
8607e508f1eSdrh                "cannot INSERT into generated column \"%s\"",
861cf9d36d1Sdrh                pTab->aCol[j].zCnName);
8627e508f1eSdrh             goto insert_cleanup;
8637e508f1eSdrh           }
8647e508f1eSdrh #endif
865cce7d176Sdrh           break;
866cce7d176Sdrh         }
867cce7d176Sdrh       }
868cce7d176Sdrh       if( j>=pTab->nCol ){
869ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
870d82b5021Sdrh           ipkColumn = i;
871e48ae715Sdrh           bIdListInOrder = 0;
872a0217ba7Sdrh         }else{
8734adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
874a979993bSdrh               pTabList->a, pColumn->a[i].zName);
8751db95106Sdan           pParse->checkSchema = 1;
876cce7d176Sdrh           goto insert_cleanup;
877cce7d176Sdrh         }
878cce7d176Sdrh       }
879cce7d176Sdrh     }
880a0217ba7Sdrh   }
8811ccde15dSdrh 
882cce7d176Sdrh   /* Figure out how many columns of data are supplied.  If the data
883cce7d176Sdrh   ** is coming from a SELECT statement, then generate a co-routine that
884cce7d176Sdrh   ** produces a single row of the SELECT on each invocation.  The
885cce7d176Sdrh   ** co-routine is the common header to the 3rd and 4th templates.
886cce7d176Sdrh   */
8875f085269Sdrh   if( pSelect ){
888a21f78b9Sdrh     /* Data is coming from a SELECT or from a multi-row VALUES clause.
889a21f78b9Sdrh     ** Generate a co-routine to run the SELECT. */
89005a86c5cSdrh     int regYield;       /* Register holding co-routine entry-point */
89105a86c5cSdrh     int addrTop;        /* Top of the co-routine */
89205a86c5cSdrh     int rc;             /* Result code */
893cce7d176Sdrh 
89405a86c5cSdrh     regYield = ++pParse->nMem;
89505a86c5cSdrh     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
89605a86c5cSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
89705a86c5cSdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
89805a86c5cSdrh     dest.iSdst = bIdListInOrder ? regData : 0;
89905a86c5cSdrh     dest.nSdst = pTab->nCol;
90005a86c5cSdrh     rc = sqlite3Select(pParse, pSelect, &dest);
9012b596da8Sdrh     regFromSelect = dest.iSdst;
9020c7d3d39Sdrh     assert( db->pParse==pParse );
9030c7d3d39Sdrh     if( rc || pParse->nErr ) goto insert_cleanup;
9040c7d3d39Sdrh     assert( db->mallocFailed==0 );
9052fade2f7Sdrh     sqlite3VdbeEndCoroutine(v, regYield);
90605a86c5cSdrh     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
907cce7d176Sdrh     assert( pSelect->pEList );
908cce7d176Sdrh     nColumn = pSelect->pEList->nExpr;
909cce7d176Sdrh 
910cce7d176Sdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
911cce7d176Sdrh     ** should be written into a temporary table (template 4).  Set to
912cce7d176Sdrh     ** FALSE if each output row of the SELECT can be written directly into
913cce7d176Sdrh     ** the destination table (template 3).
914cce7d176Sdrh     **
915cce7d176Sdrh     ** A temp table must be used if the table being updated is also one
916cce7d176Sdrh     ** of the tables being read by the SELECT statement.  Also use a
917cce7d176Sdrh     ** temp table in the case of row triggers.
918cce7d176Sdrh     */
91905a86c5cSdrh     if( pTrigger || readsTable(pParse, iDb, pTab) ){
920cce7d176Sdrh       useTempTable = 1;
921cce7d176Sdrh     }
922cce7d176Sdrh 
923cce7d176Sdrh     if( useTempTable ){
924cce7d176Sdrh       /* Invoke the coroutine to extract information from the SELECT
925cce7d176Sdrh       ** and add it to a transient table srcTab.  The code generated
926cce7d176Sdrh       ** here is from the 4th template:
927cce7d176Sdrh       **
928cce7d176Sdrh       **      B: open temp table
92981cf13ecSdrh       **      L: yield X, goto M at EOF
930cce7d176Sdrh       **         insert row from R..R+n into temp table
931cce7d176Sdrh       **         goto L
932cce7d176Sdrh       **      M: ...
933cce7d176Sdrh       */
934cce7d176Sdrh       int regRec;          /* Register to hold packed record */
935cce7d176Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
93606280ee5Sdrh       int addrL;           /* Label "L" */
937cce7d176Sdrh 
938cce7d176Sdrh       srcTab = pParse->nTab++;
939cce7d176Sdrh       regRec = sqlite3GetTempReg(pParse);
940cce7d176Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
941cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
94206280ee5Sdrh       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
943cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
944cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
945cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
946076e85f5Sdrh       sqlite3VdbeGoto(v, addrL);
94706280ee5Sdrh       sqlite3VdbeJumpHere(v, addrL);
948cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
949cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
950cce7d176Sdrh     }
951cce7d176Sdrh   }else{
952a21f78b9Sdrh     /* This is the case if the data for the INSERT is coming from a
953a21f78b9Sdrh     ** single-row VALUES clause
954cce7d176Sdrh     */
955cce7d176Sdrh     NameContext sNC;
956cce7d176Sdrh     memset(&sNC, 0, sizeof(sNC));
957cce7d176Sdrh     sNC.pParse = pParse;
958cce7d176Sdrh     srcTab = -1;
959cce7d176Sdrh     assert( useTempTable==0 );
960fea870beSdrh     if( pList ){
961fea870beSdrh       nColumn = pList->nExpr;
962fea870beSdrh       if( sqlite3ResolveExprListNames(&sNC, pList) ){
963cce7d176Sdrh         goto insert_cleanup;
964cce7d176Sdrh       }
965fea870beSdrh     }else{
966fea870beSdrh       nColumn = 0;
967cce7d176Sdrh     }
968cce7d176Sdrh   }
969cce7d176Sdrh 
970aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
971d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
972d82b5021Sdrh   ** column index in the original table definition.
9734a32431cSdrh   */
974147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
975d82b5021Sdrh     ipkColumn = pTab->iPKey;
976427b96aeSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
9776ab61d70Sdrh     if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
978427b96aeSdrh       testcase( pTab->tabFlags & TF_HasVirtual );
9796ab61d70Sdrh       testcase( pTab->tabFlags & TF_HasStored );
980427b96aeSdrh       for(i=ipkColumn-1; i>=0; i--){
981427b96aeSdrh         if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
982427b96aeSdrh           testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
9836ab61d70Sdrh           testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
984427b96aeSdrh           ipkColumn--;
985427b96aeSdrh         }
986427b96aeSdrh       }
987427b96aeSdrh     }
988427b96aeSdrh #endif
9894a32431cSdrh 
990cce7d176Sdrh     /* Make sure the number of columns in the source data matches the number
991cce7d176Sdrh     ** of columns to be inserted into the table.
992cce7d176Sdrh     */
9936f6e60ddSdrh     assert( TF_HasHidden==COLFLAG_HIDDEN );
9946f6e60ddSdrh     assert( TF_HasGenerated==COLFLAG_GENERATED );
9956f6e60ddSdrh     assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
9966f6e60ddSdrh     if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
997cce7d176Sdrh       for(i=0; i<pTab->nCol; i++){
9987e508f1eSdrh         if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
999cce7d176Sdrh       }
1000c7e93f58Sdrh     }
1001c7e93f58Sdrh     if( nColumn!=(pTab->nCol-nHidden) ){
1002cce7d176Sdrh       sqlite3ErrorMsg(pParse,
1003cce7d176Sdrh          "table %S has %d columns but %d values were supplied",
1004a979993bSdrh          pTabList->a, pTab->nCol-nHidden, nColumn);
1005cce7d176Sdrh      goto insert_cleanup;
1006cce7d176Sdrh     }
1007c7e93f58Sdrh   }
1008cce7d176Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
1009cce7d176Sdrh     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1010cce7d176Sdrh     goto insert_cleanup;
1011cce7d176Sdrh   }
1012cce7d176Sdrh 
1013c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
10141ccde15dSdrh   */
101579636913Sdrh   if( (db->flags & SQLITE_CountRows)!=0
101679636913Sdrh    && !pParse->nested
101779636913Sdrh    && !pParse->pTriggerTab
1018d086aa0aSdrh    && !pParse->bReturning
101979636913Sdrh   ){
10206a288a33Sdrh     regRowCount = ++pParse->nMem;
10216a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1022c3f9bad2Sdanielk1977   }
1023c3f9bad2Sdanielk1977 
1024e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
1025e448dc4aSdanielk1977   if( !isView ){
1026aa9b8963Sdrh     int nIdx;
1027fd261ec6Sdan     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
102826198bb4Sdrh                                       &iDataCur, &iIdxCur);
1029a7c3b93fSdrh     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1030aa9b8963Sdrh     if( aRegIdx==0 ){
1031aa9b8963Sdrh       goto insert_cleanup;
1032aa9b8963Sdrh     }
10332c4dfc30Sdrh     for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
10342c4dfc30Sdrh       assert( pIdx );
1035aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
10362c4dfc30Sdrh       pParse->nMem += pIdx->nColumn;
1037aa9b8963Sdrh     }
1038a7c3b93fSdrh     aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */
1039feeb1394Sdrh   }
1040788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT
10410b30a116Sdrh   if( pUpsert ){
104220b86324Sdrh     Upsert *pNx;
1043b042d921Sdrh     if( IsVirtual(pTab) ){
1044b042d921Sdrh       sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1045b042d921Sdrh               pTab->zName);
1046b042d921Sdrh       goto insert_cleanup;
1047b042d921Sdrh     }
1048f38524d2Sdrh     if( IsView(pTab) ){
1049c6b24ab1Sdrh       sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1050c6b24ab1Sdrh       goto insert_cleanup;
1051c6b24ab1Sdrh     }
10529105fd51Sdan     if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
10539105fd51Sdan       goto insert_cleanup;
10549105fd51Sdan     }
1055788d55aaSdrh     pTabList->a[0].iCursor = iDataCur;
105620b86324Sdrh     pNx = pUpsert;
105720b86324Sdrh     do{
105820b86324Sdrh       pNx->pUpsertSrc = pTabList;
105920b86324Sdrh       pNx->regData = regData;
106020b86324Sdrh       pNx->iDataCur = iDataCur;
106120b86324Sdrh       pNx->iIdxCur = iIdxCur;
106220b86324Sdrh       if( pNx->pUpsertTarget ){
106393eb9064Sdan         if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx) ){
106493eb9064Sdan           goto insert_cleanup;
106593eb9064Sdan         }
1066788d55aaSdrh       }
106720b86324Sdrh       pNx = pNx->pNextUpsert;
106820b86324Sdrh     }while( pNx!=0 );
10690b30a116Sdrh   }
1070788d55aaSdrh #endif
1071788d55aaSdrh 
1072feeb1394Sdrh 
1073e00ee6ebSdrh   /* This is the top of the main insertion loop */
1074142e30dfSdrh   if( useTempTable ){
1075e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
1076e00ee6ebSdrh     ** following pseudocode (template 4):
1077e00ee6ebSdrh     **
107881cf13ecSdrh     **         rewind temp table, if empty goto D
1079e00ee6ebSdrh     **      C: loop over rows of intermediate table
1080e00ee6ebSdrh     **           transfer values form intermediate table into <table>
1081e00ee6ebSdrh     **         end loop
1082e00ee6ebSdrh     **      D: ...
1083e00ee6ebSdrh     */
1084688852abSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1085e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
1086142e30dfSdrh   }else if( pSelect ){
1087e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
1088e00ee6ebSdrh     ** following pseudocode (template 3):
1089e00ee6ebSdrh     **
109081cf13ecSdrh     **      C: yield X, at EOF goto D
1091e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
1092e00ee6ebSdrh     **         goto C
1093e00ee6ebSdrh     **      D: ...
1094e00ee6ebSdrh     */
10953aef2fb1Sdrh     sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
109681cf13ecSdrh     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1097688852abSdrh     VdbeCoverage(v);
1098f5f1915dSdrh     if( ipkColumn>=0 ){
1099f5f1915dSdrh       /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1100f5f1915dSdrh       ** SELECT, go ahead and copy the value into the rowid slot now, so that
1101f5f1915dSdrh       ** the value does not get overwritten by a NULL at tag-20191021-002. */
1102f5f1915dSdrh       sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1103bed8690fSdrh     }
1104f5f1915dSdrh   }
1105f5f1915dSdrh 
1106f5f1915dSdrh   /* Compute data for ordinary columns of the new entry.  Values
1107f5f1915dSdrh   ** are written in storage order into registers starting with regData.
1108f5f1915dSdrh   ** Only ordinary columns are computed in this loop. The rowid
1109f5f1915dSdrh   ** (if there is one) is computed later and generated columns are
1110f5f1915dSdrh   ** computed after the rowid since they might depend on the value
1111f5f1915dSdrh   ** of the rowid.
1112f5f1915dSdrh   */
1113f5f1915dSdrh   nHidden = 0;
1114f5f1915dSdrh   iRegStore = regData;  assert( regData==regRowid+1 );
1115f5f1915dSdrh   for(i=0; i<pTab->nCol; i++, iRegStore++){
1116f5f1915dSdrh     int k;
1117f5f1915dSdrh     u32 colFlags;
1118f5f1915dSdrh     assert( i>=nHidden );
1119f5f1915dSdrh     if( i==pTab->iPKey ){
1120f5f1915dSdrh       /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1121f5f1915dSdrh       ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1122f5f1915dSdrh       ** using excess space.  The file format definition requires this extra
1123f5f1915dSdrh       ** NULL - we cannot optimize further by skipping the column completely */
1124f5f1915dSdrh       sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1125f5f1915dSdrh       continue;
1126f5f1915dSdrh     }
1127f5f1915dSdrh     if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1128f5f1915dSdrh       nHidden++;
1129f5f1915dSdrh       if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1130f5f1915dSdrh         /* Virtual columns do not participate in OP_MakeRecord.  So back up
1131f5f1915dSdrh         ** iRegStore by one slot to compensate for the iRegStore++ in the
1132f5f1915dSdrh         ** outer for() loop */
1133f5f1915dSdrh         iRegStore--;
1134f5f1915dSdrh         continue;
1135f5f1915dSdrh       }else if( (colFlags & COLFLAG_STORED)!=0 ){
1136f5f1915dSdrh         /* Stored columns are computed later.  But if there are BEFORE
1137f5f1915dSdrh         ** triggers, the slots used for stored columns will be OP_Copy-ed
1138f5f1915dSdrh         ** to a second block of registers, so the register needs to be
1139f5f1915dSdrh         ** initialized to NULL to avoid an uninitialized register read */
1140f5f1915dSdrh         if( tmask & TRIGGER_BEFORE ){
1141f5f1915dSdrh           sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1142f5f1915dSdrh         }
1143f5f1915dSdrh         continue;
1144f5f1915dSdrh       }else if( pColumn==0 ){
1145f5f1915dSdrh         /* Hidden columns that are not explicitly named in the INSERT
1146f5f1915dSdrh         ** get there default value */
114779cf2b71Sdrh         sqlite3ExprCodeFactorable(pParse,
114879cf2b71Sdrh             sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
114979cf2b71Sdrh             iRegStore);
1150f5f1915dSdrh         continue;
1151f5f1915dSdrh       }
1152f5f1915dSdrh     }
1153f5f1915dSdrh     if( pColumn ){
1154f5f1915dSdrh       for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){}
1155f5f1915dSdrh       if( j>=pColumn->nId ){
1156f5f1915dSdrh         /* A column not named in the insert column list gets its
1157f5f1915dSdrh         ** default value */
115879cf2b71Sdrh         sqlite3ExprCodeFactorable(pParse,
115979cf2b71Sdrh             sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
116079cf2b71Sdrh             iRegStore);
1161f5f1915dSdrh         continue;
1162f5f1915dSdrh       }
1163f5f1915dSdrh       k = j;
1164f5f1915dSdrh     }else if( nColumn==0 ){
1165f5f1915dSdrh       /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
116679cf2b71Sdrh       sqlite3ExprCodeFactorable(pParse,
116779cf2b71Sdrh           sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
116879cf2b71Sdrh           iRegStore);
1169f5f1915dSdrh       continue;
1170f5f1915dSdrh     }else{
1171f5f1915dSdrh       k = i - nHidden;
1172f5f1915dSdrh     }
1173f5f1915dSdrh 
1174f5f1915dSdrh     if( useTempTable ){
1175f5f1915dSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1176f5f1915dSdrh     }else if( pSelect ){
1177f5f1915dSdrh       if( regFromSelect!=regData ){
1178f5f1915dSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1179f5f1915dSdrh       }
1180f5f1915dSdrh     }else{
1181f5f1915dSdrh       sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore);
1182f5f1915dSdrh     }
1183f5f1915dSdrh   }
1184f5f1915dSdrh 
11851ccde15dSdrh 
11865cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
118770ce3f0cSdrh   */
1188ec4ccdbcSdrh   endOfLoop = sqlite3VdbeMakeLabel(pParse);
11892f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
119076d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1191c3f9bad2Sdanielk1977 
119270ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
119370ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
119470ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
119570ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
119670ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
119770ce3f0cSdrh     */
1198d82b5021Sdrh     if( ipkColumn<0 ){
119976d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
120070ce3f0cSdrh     }else{
1201728e0f91Sdrh       int addr1;
1202ec95c441Sdrh       assert( !withoutRowid );
12037fe45908Sdrh       if( useTempTable ){
1204d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
12057fe45908Sdrh       }else{
1206d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
1207d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
12087fe45908Sdrh       }
1209728e0f91Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
121076d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1211728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
1212688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
121370ce3f0cSdrh     }
121470ce3f0cSdrh 
1215f5f1915dSdrh     /* Copy the new data already generated. */
1216f5f1915dSdrh     assert( pTab->nNVCol>0 );
1217f5f1915dSdrh     sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1218f5f1915dSdrh 
1219f5f1915dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1220f5f1915dSdrh     /* Compute the new value for generated columns after all other
1221f5f1915dSdrh     ** columns have already been computed.  This must be done after
1222f5f1915dSdrh     ** computing the ROWID in case one of the generated columns
1223f5f1915dSdrh     ** refers to the ROWID. */
1224427b96aeSdrh     if( pTab->tabFlags & TF_HasGenerated ){
1225427b96aeSdrh       testcase( pTab->tabFlags & TF_HasVirtual );
1226427b96aeSdrh       testcase( pTab->tabFlags & TF_HasStored );
1227f5f1915dSdrh       sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1228c3f9bad2Sdanielk1977     }
1229f5f1915dSdrh #endif
1230a37cdde0Sdanielk1977 
1231a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1232a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
1233a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
1234a37cdde0Sdanielk1977     ** table column affinities.
1235a37cdde0Sdanielk1977     */
1236a37cdde0Sdanielk1977     if( !isView ){
123757bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regCols+1);
1238a37cdde0Sdanielk1977     }
1239c3f9bad2Sdanielk1977 
12405cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
1241165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
124294d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1243165921a7Sdan 
124476d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
124570ce3f0cSdrh   }
1246c3f9bad2Sdanielk1977 
12475cf590c1Sdrh   if( !isView ){
12484cbdda9eSdrh     if( IsVirtual(pTab) ){
12494cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
12506a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
12514cbdda9eSdrh     }
1252d82b5021Sdrh     if( ipkColumn>=0 ){
1253f5f1915dSdrh       /* Compute the new rowid */
1254142e30dfSdrh       if( useTempTable ){
1255d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1256142e30dfSdrh       }else if( pSelect ){
1257f5f1915dSdrh         /* Rowid already initialized at tag-20191021-001 */
12584a32431cSdrh       }else{
125904fcef00Sdrh         Expr *pIpk = pList->a[ipkColumn].pExpr;
126004fcef00Sdrh         if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
126104fcef00Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1262e4d90813Sdrh           appendFlag = 1;
126304fcef00Sdrh         }else{
126404fcef00Sdrh           sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1265e4d90813Sdrh         }
126627a32783Sdrh       }
1267f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1268e1e68f49Sdrh       ** to generate a unique primary key value.
1269e1e68f49Sdrh       */
1270e4d90813Sdrh       if( !appendFlag ){
1271728e0f91Sdrh         int addr1;
1272bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
1273728e0f91Sdrh           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
127426198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1275728e0f91Sdrh           sqlite3VdbeJumpHere(v, addr1);
1276bb50e7adSdanielk1977         }else{
1277728e0f91Sdrh           addr1 = sqlite3VdbeCurrentAddr(v);
1278728e0f91Sdrh           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1279bb50e7adSdanielk1977         }
1280688852abSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1281e4d90813Sdrh       }
1282ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
12836a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
12844a32431cSdrh     }else{
128526198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1286e4d90813Sdrh       appendFlag = 1;
12874a32431cSdrh     }
12886a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
12894a32431cSdrh 
1290c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1291dd6cc9b5Sdrh     /* Compute the new value for generated columns after all other
1292f5f1915dSdrh     ** columns have already been computed.  This must be done after
1293f5f1915dSdrh     ** computing the ROWID in case one of the generated columns
1294b5f6243fSdrh     ** is derived from the INTEGER PRIMARY KEY. */
1295427b96aeSdrh     if( pTab->tabFlags & TF_HasGenerated ){
1296dd6cc9b5Sdrh       sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
12974a32431cSdrh     }
1298c1431144Sdrh #endif
12991ccde15dSdrh 
13000ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
13010ca3e24bSdrh     ** do the insertion.
13024a32431cSdrh     */
13034cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
13044cbdda9eSdrh     if( IsVirtual(pTab) ){
1305595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
13064f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1307595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1308b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1309e0af83acSdan       sqlite3MayAbort(pParse);
13104cbdda9eSdrh     }else
13114cbdda9eSdrh #endif
13124cbdda9eSdrh     {
131311fbee24Sdan       int isReplace = 0;/* Set to true if constraints may cause a replace */
13143b908d41Sdan       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
1315f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1316788d55aaSdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
131704adf416Sdrh       );
13188ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
13193b908d41Sdan 
13203b908d41Sdan       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
13213b908d41Sdan       ** constraints or (b) there are no triggers and this table is not a
13223b908d41Sdan       ** parent table in a foreign key constraint. It is safe to set the
13233b908d41Sdan       ** flag in the second case as if any REPLACE constraint is hit, an
13243b908d41Sdan       ** OP_Delete or OP_IdxDelete instruction will be executed on each
13253b908d41Sdan       ** cursor that is disturbed. And these instructions both clear the
13263b908d41Sdan       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
13273b908d41Sdan       ** functionality.  */
132806baba54Sdrh       bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
132926198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
13303b908d41Sdan           regIns, aRegIdx, 0, appendFlag, bUseSeek
13313b908d41Sdan       );
13325cf590c1Sdrh     }
13336e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
13342a1aeaa3Sdan   }else if( pParse->bReturning ){
13352a1aeaa3Sdan     /* If there is a RETURNING clause, populate the rowid register with
13362a1aeaa3Sdan     ** constant value -1, in case one or more of the returned expressions
13372a1aeaa3Sdan     ** refer to the "rowid" of the view.  */
13382a1aeaa3Sdan     sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
13396e5020e8Sdrh #endif
13404cbdda9eSdrh   }
13411bee3d7bSdrh 
1342feeb1394Sdrh   /* Update the count of rows that are inserted
13431bee3d7bSdrh   */
134479636913Sdrh   if( regRowCount ){
13456a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
13461bee3d7bSdrh   }
1347c3f9bad2Sdanielk1977 
13482f886d1dSdanielk1977   if( pTrigger ){
1349c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1350165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
135194d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1352c3f9bad2Sdanielk1977   }
13531bee3d7bSdrh 
1354e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1355e00ee6ebSdrh   ** is a SELECT statement.
13561ccde15dSdrh   */
13574adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1358142e30dfSdrh   if( useTempTable ){
1359688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1360e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
13612eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1362142e30dfSdrh   }else if( pSelect ){
1363076e85f5Sdrh     sqlite3VdbeGoto(v, addrCont);
1364d9670abbSdrh #ifdef SQLITE_DEBUG
1365d9670abbSdrh     /* If we are jumping back to an OP_Yield that is preceded by an
1366d9670abbSdrh     ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1367d9670abbSdrh     ** OP_ReleaseReg will be included in the loop. */
1368d9670abbSdrh     if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1369d9670abbSdrh       assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1370d9670abbSdrh       sqlite3VdbeChangeP5(v, 1);
1371d9670abbSdrh     }
1372d9670abbSdrh #endif
1373e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
13746b56344dSdrh   }
1375c3f9bad2Sdanielk1977 
1376d6665c51Smistachkin #ifndef SQLITE_OMIT_XFER_OPT
13770b9f50d8Sdrh insert_end:
1378d6665c51Smistachkin #endif /* SQLITE_OMIT_XFER_OPT */
1379f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
13800b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
13810b9f50d8Sdrh   ** autoincrement tables.
13822958a4e6Sdrh   */
1383165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
13840b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
13850b9f50d8Sdrh   }
13862958a4e6Sdrh 
13871bee3d7bSdrh   /*
1388e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1389e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1390e7de6f25Sdanielk1977   ** invoke the callback function.
13911bee3d7bSdrh   */
139279636913Sdrh   if( regRowCount ){
13933b26b2b5Sdrh     sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
13941bee3d7bSdrh   }
1395cce7d176Sdrh 
1396cce7d176Sdrh insert_cleanup:
1397633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1398633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
139946d2e5c3Sdrh   sqlite3UpsertDelete(db, pUpsert);
1400633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1401633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1402633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1403cce7d176Sdrh }
14049cfcf5d4Sdrh 
140575cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
140660ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
140775cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
140875cbd984Sdan #ifdef isView
140975cbd984Sdan  #undef isView
141075cbd984Sdan #endif
141175cbd984Sdan #ifdef pTrigger
141275cbd984Sdan  #undef pTrigger
141375cbd984Sdan #endif
141475cbd984Sdan #ifdef tmask
141575cbd984Sdan  #undef tmask
141675cbd984Sdan #endif
141775cbd984Sdan 
14189cfcf5d4Sdrh /*
1419e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for
1420e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn()
142198bfa16dSdrh */
142298bfa16dSdrh #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
142398bfa16dSdrh #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
142498bfa16dSdrh 
1425e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1426e9816d82Sdrh *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1427e9816d82Sdrh ** expression node references any of the
14282a0b527bSdrh ** columns that are being modifed by an UPDATE statement.
14292a0b527bSdrh */
14302a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
143198bfa16dSdrh   if( pExpr->op==TK_COLUMN ){
143298bfa16dSdrh     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
143398bfa16dSdrh     if( pExpr->iColumn>=0 ){
143498bfa16dSdrh       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
143598bfa16dSdrh         pWalker->eCode |= CKCNSTRNT_COLUMN;
143698bfa16dSdrh       }
143798bfa16dSdrh     }else{
143898bfa16dSdrh       pWalker->eCode |= CKCNSTRNT_ROWID;
143998bfa16dSdrh     }
14402a0b527bSdrh   }
14412a0b527bSdrh   return WRC_Continue;
14422a0b527bSdrh }
14432a0b527bSdrh 
14442a0b527bSdrh /*
14452a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
14462a0b527bSdrh ** only columns that are modified by the UPDATE are those for which
144798bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
144898bfa16dSdrh **
1449e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the
145098bfa16dSdrh ** changing columns (or the rowid if it is changing).  In other words,
1451e9816d82Sdrh ** return true if this CHECK constraint must be validated for
145298bfa16dSdrh ** the new row in the UPDATE statement.
1453e9816d82Sdrh **
1454e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1455e9816d82Sdrh ** The operation of this routine is the same - return true if an only if
1456e9816d82Sdrh ** the expression uses one or more of columns identified by the second and
1457e9816d82Sdrh ** third arguments.
14582a0b527bSdrh */
1459e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn(
1460e9816d82Sdrh   Expr *pExpr,    /* The expression to be checked */
1461e9816d82Sdrh   int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
1462e9816d82Sdrh   int chngRowid   /* True if UPDATE changes the rowid */
1463e9816d82Sdrh ){
14642a0b527bSdrh   Walker w;
14652a0b527bSdrh   memset(&w, 0, sizeof(w));
146698bfa16dSdrh   w.eCode = 0;
14672a0b527bSdrh   w.xExprCallback = checkConstraintExprNode;
14682a0b527bSdrh   w.u.aiCol = aiChng;
14692a0b527bSdrh   sqlite3WalkExpr(&w, pExpr);
147005723a9eSdrh   if( !chngRowid ){
147105723a9eSdrh     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
147205723a9eSdrh     w.eCode &= ~CKCNSTRNT_ROWID;
147305723a9eSdrh   }
147405723a9eSdrh   testcase( w.eCode==0 );
147505723a9eSdrh   testcase( w.eCode==CKCNSTRNT_COLUMN );
147605723a9eSdrh   testcase( w.eCode==CKCNSTRNT_ROWID );
147705723a9eSdrh   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1478e9816d82Sdrh   return w.eCode!=0;
14792a0b527bSdrh }
14802a0b527bSdrh 
148111e85273Sdrh /*
1482daf2761cSdrh ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1483daf2761cSdrh ** the indexes of a table in the order provided in the Table->pIndex list.
1484daf2761cSdrh ** However, sometimes (rarely - when there is an upsert) it wants to visit
1485daf2761cSdrh ** the indexes in a different order.  The following data structures accomplish
1486daf2761cSdrh ** this.
1487daf2761cSdrh **
1488daf2761cSdrh ** The IndexIterator object is used to walk through all of the indexes
1489daf2761cSdrh ** of a table in either Index.pNext order, or in some other order established
1490daf2761cSdrh ** by an array of IndexListTerm objects.
1491daf2761cSdrh */
1492daf2761cSdrh typedef struct IndexListTerm IndexListTerm;
1493daf2761cSdrh typedef struct IndexIterator IndexIterator;
1494daf2761cSdrh struct IndexIterator {
1495daf2761cSdrh   int eType;    /* 0 for Index.pNext list.  1 for an array of IndexListTerm */
1496daf2761cSdrh   int i;        /* Index of the current item from the list */
1497daf2761cSdrh   union {
1498daf2761cSdrh     struct {    /* Use this object for eType==0: A Index.pNext list */
1499daf2761cSdrh       Index *pIdx;   /* The current Index */
1500daf2761cSdrh     } lx;
1501daf2761cSdrh     struct {    /* Use this object for eType==1; Array of IndexListTerm */
1502daf2761cSdrh       int nIdx;               /* Size of the array */
1503daf2761cSdrh       IndexListTerm *aIdx;    /* Array of IndexListTerms */
1504daf2761cSdrh     } ax;
1505daf2761cSdrh   } u;
1506daf2761cSdrh };
1507daf2761cSdrh 
1508daf2761cSdrh /* When IndexIterator.eType==1, then each index is an array of instances
1509daf2761cSdrh ** of the following object
1510daf2761cSdrh */
1511daf2761cSdrh struct IndexListTerm {
1512daf2761cSdrh   Index *p;  /* The index */
1513daf2761cSdrh   int ix;    /* Which entry in the original Table.pIndex list is this index*/
1514daf2761cSdrh };
1515daf2761cSdrh 
1516daf2761cSdrh /* Return the first index on the list */
1517daf2761cSdrh static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1518ed4c5469Sdrh   assert( pIter->i==0 );
1519ed4c5469Sdrh   if( pIter->eType ){
1520ed4c5469Sdrh     *pIx = pIter->u.ax.aIdx[0].ix;
1521ed4c5469Sdrh     return pIter->u.ax.aIdx[0].p;
1522ed4c5469Sdrh   }else{
1523ed4c5469Sdrh     *pIx = 0;
1524ed4c5469Sdrh     return pIter->u.lx.pIdx;
1525ed4c5469Sdrh   }
1526daf2761cSdrh }
1527daf2761cSdrh 
1528daf2761cSdrh /* Return the next index from the list.  Return NULL when out of indexes */
1529daf2761cSdrh static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1530daf2761cSdrh   if( pIter->eType ){
1531d3e21a10Sdrh     int i = ++pIter->i;
153261e280adSdrh     if( i>=pIter->u.ax.nIdx ){
153361e280adSdrh       *pIx = i;
153461e280adSdrh       return 0;
153561e280adSdrh     }
1536daf2761cSdrh     *pIx = pIter->u.ax.aIdx[i].ix;
1537daf2761cSdrh     return pIter->u.ax.aIdx[i].p;
1538daf2761cSdrh   }else{
1539d3e21a10Sdrh     ++(*pIx);
1540daf2761cSdrh     pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1541daf2761cSdrh     return pIter->u.lx.pIdx;
1542daf2761cSdrh   }
1543daf2761cSdrh }
1544daf2761cSdrh 
1545daf2761cSdrh /*
15466934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
15476934fc7bSdrh ** on table pTab.
15489cfcf5d4Sdrh **
15496934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
15506934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
15516934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
15526934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
15536934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
15546934fc7bSdrh ** contain the content of the first table column.  The third register will
15556934fc7bSdrh ** contain the content of the second table column.  And so forth.
15560ca3e24bSdrh **
1557f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1558f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1559f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1560f8ffb278Sdrh ** checking regOldData for zero.
15610ca3e24bSdrh **
1562f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1563f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1564f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1565f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
15660ca3e24bSdrh **
1567f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1568f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1569f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1570f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1571f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1572f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
15730ca3e24bSdrh **
15746934fc7bSdrh ** The code generated by this routine will store new index entries into
1575aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1576aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1577aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
15786934fc7bSdrh ** at pTab->pIndex.
15796934fc7bSdrh **
1580a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the
1581a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the
1582a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first
1583a7c3b93fSdrh ** entry of aRegIdx[] past the last index.  It is important that the
1584a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes
1585a7c3b93fSdrh ** to the register content that occur after constraint checks but before
1586a7c3b93fSdrh ** the new record is inserted.
1587a7c3b93fSdrh **
15886934fc7bSdrh ** The caller must have already opened writeable cursors on the main
15896934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
15906934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
15916934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
15926934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
15936934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
15946934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
15959cfcf5d4Sdrh **
15969cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
15979cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
15981c92853dSdrh ** then the appropriate action is performed.  There are five possible
15991c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
16009cfcf5d4Sdrh **
16019cfcf5d4Sdrh **  Constraint type  Action       What Happens
16029cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
16031c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
16046934fc7bSdrh **                                sqlite3_step() returns immediately with a
16059cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
16069cfcf5d4Sdrh **
16071c92853dSdrh **  any              ABORT        Back out changes from the current command
16081c92853dSdrh **                                only (do not do a complete rollback) then
16096934fc7bSdrh **                                cause sqlite3_step() to return immediately
16101c92853dSdrh **                                with SQLITE_CONSTRAINT.
16111c92853dSdrh **
16126934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
16131c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
16141c92853dSdrh **                                transaction is not rolled back and any
16156934fc7bSdrh **                                changes to prior rows are retained.
16161c92853dSdrh **
16176934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
16186934fc7bSdrh **                                row is skipped, without throwing an error.
16196934fc7bSdrh **                                Processing continues with the next row.
16206934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
16219cfcf5d4Sdrh **
16229cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
16239cfcf5d4Sdrh **                                value for that column.  If the default value
16249cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
16259cfcf5d4Sdrh **
16269cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
16279cfcf5d4Sdrh **                                being inserted is removed.
16289cfcf5d4Sdrh **
16299cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
16309cfcf5d4Sdrh **
16311c92853dSdrh ** Which action to take is determined by the overrideError parameter.
16321c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
16331c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
16341c92853dSdrh ** for the constraint is used.
16359cfcf5d4Sdrh */
16364adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
16379cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
16386934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1639f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
16406934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
164126198bb4Sdrh   int iIdxCur,         /* First index cursor */
16426934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1643f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1644f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1645f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1646de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1647bdb00225Sdrh   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1648788d55aaSdrh   int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
1649788d55aaSdrh   Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
16509cfcf5d4Sdrh ){
16511b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
16521b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
1653e84ad92fSdrh   Index *pPk = 0;      /* The PRIMARY KEY index for WITHOUT ROWID tables */
16542938f924Sdrh   sqlite3 *db;         /* Database connection */
1655f8ffb278Sdrh   int i;               /* loop counter */
1656f8ffb278Sdrh   int ix;              /* Index loop counter */
16579cfcf5d4Sdrh   int nCol;            /* Number of columns */
16589cfcf5d4Sdrh   int onError;         /* Conflict resolution strategy */
16591b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
16606fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
166161e280adSdrh   Upsert *pUpsertClause = 0;  /* The specific ON CONFLICT clause for pIdx */
16628d1b82e4Sdrh   u8 isUpdate;           /* True if this is an UPDATE operation */
166357bf4a8eSdrh   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
166461e280adSdrh   int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
166561e280adSdrh   int upsertIpkDelay = 0;  /* Address of Goto to bypass initial IPK check */
166684304506Sdrh   int ipkTop = 0;        /* Top of the IPK uniqueness check */
166784304506Sdrh   int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
1668a407eccbSdrh   /* Variables associated with retesting uniqueness constraints after
1669a407eccbSdrh   ** replace triggers fire have run */
1670a407eccbSdrh   int regTrigCnt;       /* Register used to count replace trigger invocations */
1671a407eccbSdrh   int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */
1672a407eccbSdrh   int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1673a407eccbSdrh   Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
1674a407eccbSdrh   int nReplaceTrig = 0; /* Number of replace triggers coded */
167561e280adSdrh   IndexIterator sIdxIter;  /* Index iterator */
16769cfcf5d4Sdrh 
1677f8ffb278Sdrh   isUpdate = regOldData!=0;
16782938f924Sdrh   db = pParse->db;
1679f0b41745Sdrh   v = pParse->pVdbe;
16809cfcf5d4Sdrh   assert( v!=0 );
1681f38524d2Sdrh   assert( !IsView(pTab) );  /* This table is not a VIEW */
16829cfcf5d4Sdrh   nCol = pTab->nCol;
1683aa9b8963Sdrh 
16846934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
16856934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
16866934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
16876934fc7bSdrh   ** number of fields in the true primary key of the table. */
168826198bb4Sdrh   if( HasRowid(pTab) ){
168926198bb4Sdrh     pPk = 0;
169026198bb4Sdrh     nPkField = 1;
169126198bb4Sdrh   }else{
169226198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
169326198bb4Sdrh     nPkField = pPk->nKeyCol;
169426198bb4Sdrh   }
16956fbe41acSdrh 
16966fbe41acSdrh   /* Record that this module has started */
16976fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
16986934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
16999cfcf5d4Sdrh 
17009cfcf5d4Sdrh   /* Test all NOT NULL constraints.
17019cfcf5d4Sdrh   */
1702cbda9c7aSdrh   if( pTab->tabFlags & TF_HasNotNull ){
1703ad5f1577Sdrh     int b2ndPass = 0;         /* True if currently running 2nd pass */
1704ad5f1577Sdrh     int nSeenReplace = 0;     /* Number of ON CONFLICT REPLACE operations */
1705ad5f1577Sdrh     int nGenerated = 0;       /* Number of generated columns with NOT NULL */
1706ad5f1577Sdrh     while(1){  /* Make 2 passes over columns. Exit loop via "break" */
17079cfcf5d4Sdrh       for(i=0; i<nCol; i++){
1708ad5f1577Sdrh         int iReg;                        /* Register holding column value */
1709ad5f1577Sdrh         Column *pCol = &pTab->aCol[i];   /* The column to check for NOT NULL */
1710ad5f1577Sdrh         int isGenerated;                 /* non-zero if column is generated */
1711ad5f1577Sdrh         onError = pCol->notNull;
1712cbda9c7aSdrh         if( onError==OE_None ) continue; /* No NOT NULL on this column */
17130ca3e24bSdrh         if( i==pTab->iPKey ){
1714bdb00225Sdrh           continue;        /* ROWID is never NULL */
1715bdb00225Sdrh         }
1716ad5f1577Sdrh         isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1717ad5f1577Sdrh         if( isGenerated && !b2ndPass ){
1718ad5f1577Sdrh           nGenerated++;
1719ad5f1577Sdrh           continue;        /* Generated columns processed on 2nd pass */
1720ad5f1577Sdrh         }
1721ad5f1577Sdrh         if( aiChng && aiChng[i]<0 && !isGenerated ){
1722ad5f1577Sdrh           /* Do not check NOT NULL on columns that do not change */
17230ca3e24bSdrh           continue;
17240ca3e24bSdrh         }
17259cfcf5d4Sdrh         if( overrideError!=OE_Default ){
17269cfcf5d4Sdrh           onError = overrideError;
1727a996e477Sdrh         }else if( onError==OE_Default ){
1728a996e477Sdrh           onError = OE_Abort;
17299cfcf5d4Sdrh         }
1730ad5f1577Sdrh         if( onError==OE_Replace ){
1731ad5f1577Sdrh           if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */
173279cf2b71Sdrh            || pCol->iDflt==0  /* REPLACE is ABORT if no DEFAULT value */
1733ad5f1577Sdrh           ){
1734ad5f1577Sdrh             testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1735ad5f1577Sdrh             testcase( pCol->colFlags & COLFLAG_STORED );
1736ad5f1577Sdrh             testcase( pCol->colFlags & COLFLAG_GENERATED );
17379cfcf5d4Sdrh             onError = OE_Abort;
1738ad5f1577Sdrh           }else{
1739ad5f1577Sdrh             assert( !isGenerated );
1740ad5f1577Sdrh           }
1741ad5f1577Sdrh         }else if( b2ndPass && !isGenerated ){
1742ad5f1577Sdrh           continue;
17439cfcf5d4Sdrh         }
1744b84f96f8Sdanielk1977         assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1745b84f96f8Sdanielk1977             || onError==OE_Ignore || onError==OE_Replace );
1746c5f808d8Sdrh         testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1747b9bcf7caSdrh         iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
17489cfcf5d4Sdrh         switch( onError ){
17499bfb0794Sdrh           case OE_Replace: {
1750ad5f1577Sdrh             int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
17519bfb0794Sdrh             VdbeCoverage(v);
1752ad5f1577Sdrh             assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
1753ad5f1577Sdrh             nSeenReplace++;
175479cf2b71Sdrh             sqlite3ExprCodeCopy(pParse,
175579cf2b71Sdrh                sqlite3ColumnExpr(pTab, pCol), iReg);
1756ad5f1577Sdrh             sqlite3VdbeJumpHere(v, addr1);
1757ad5f1577Sdrh             break;
17589bfb0794Sdrh           }
17591c92853dSdrh           case OE_Abort:
1760e0af83acSdan             sqlite3MayAbort(pParse);
176108b92086Sdrh             /* no break */ deliberate_fall_through
1762e0af83acSdan           case OE_Rollback:
17631c92853dSdrh           case OE_Fail: {
1764f9c8ce3cSdrh             char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1765cf9d36d1Sdrh                                         pCol->zCnName);
1766cbda9c7aSdrh             sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
1767a88c8c1aSdrh                               onError, iReg);
17682700acaaSdrh             sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1769f9c8ce3cSdrh             sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1770688852abSdrh             VdbeCoverage(v);
17719cfcf5d4Sdrh             break;
17729cfcf5d4Sdrh           }
1773098d1684Sdrh           default: {
17749bfb0794Sdrh             assert( onError==OE_Ignore );
17758e10d74bSdrh             sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
1776728e0f91Sdrh             VdbeCoverage(v);
17779cfcf5d4Sdrh             break;
17789cfcf5d4Sdrh           }
1779ad5f1577Sdrh         } /* end switch(onError) */
1780ad5f1577Sdrh       } /* end loop i over columns */
1781ad5f1577Sdrh       if( nGenerated==0 && nSeenReplace==0 ){
1782ad5f1577Sdrh         /* If there are no generated columns with NOT NULL constraints
1783ad5f1577Sdrh         ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
1784ad5f1577Sdrh         ** pass is sufficient */
1785ad5f1577Sdrh         break;
17869cfcf5d4Sdrh       }
1787ad5f1577Sdrh       if( b2ndPass ) break;  /* Never need more than 2 passes */
1788ad5f1577Sdrh       b2ndPass = 1;
1789ef9f719dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1790ad5f1577Sdrh       if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1791ad5f1577Sdrh         /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
1792ad5f1577Sdrh         ** first pass, recomputed values for all generated columns, as
1793ad5f1577Sdrh         ** those values might depend on columns affected by the REPLACE.
1794ad5f1577Sdrh         */
1795ad5f1577Sdrh         sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
17969cfcf5d4Sdrh       }
1797ef9f719dSdrh #endif
1798ad5f1577Sdrh     } /* end of 2-pass loop */
1799ad5f1577Sdrh   } /* end if( has-not-null-constraints ) */
18009cfcf5d4Sdrh 
18019cfcf5d4Sdrh   /* Test all CHECK constraints
18029cfcf5d4Sdrh   */
1803ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
18042938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
18052938f924Sdrh     ExprList *pCheck = pTab->pCheck;
18066e97f8ecSdrh     pParse->iSelfTab = -(regNewData+1);
1807aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
18082938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
180905723a9eSdrh       int allOk;
18105cf1b611Sdrh       Expr *pCopy;
18112a0b527bSdrh       Expr *pExpr = pCheck->a[i].pExpr;
1812e9816d82Sdrh       if( aiChng
1813e9816d82Sdrh        && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
1814e9816d82Sdrh       ){
1815e9816d82Sdrh         /* The check constraints do not reference any of the columns being
1816e9816d82Sdrh         ** updated so there is no point it verifying the check constraint */
1817e9816d82Sdrh         continue;
1818e9816d82Sdrh       }
18199dce0ef4Sdrh       if( bAffinityDone==0 ){
18209dce0ef4Sdrh         sqlite3TableAffinity(v, pTab, regNewData+1);
18219dce0ef4Sdrh         bAffinityDone = 1;
18229dce0ef4Sdrh       }
1823ec4ccdbcSdrh       allOk = sqlite3VdbeMakeLabel(pParse);
18244031bafaSdrh       sqlite3VdbeVerifyAbortable(v, onError);
18255cf1b611Sdrh       pCopy = sqlite3ExprDup(db, pExpr, 0);
18265cf1b611Sdrh       if( !db->mallocFailed ){
18275cf1b611Sdrh         sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
18285cf1b611Sdrh       }
18295cf1b611Sdrh       sqlite3ExprDelete(db, pCopy);
18302e06c67cSdrh       if( onError==OE_Ignore ){
1831076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
1832aa01c7e2Sdrh       }else{
183341cee668Sdrh         char *zName = pCheck->a[i].zEName;
1834e2678b93Sdrh         assert( zName!=0 || pParse->db->mallocFailed );
18350ce974d1Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
1836d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1837f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1838f9c8ce3cSdrh                               P5_ConstraintCheck);
1839aa01c7e2Sdrh       }
1840ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1841ffe07b2dSdrh     }
18426e97f8ecSdrh     pParse->iSelfTab = 0;
18432938f924Sdrh   }
1844ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
18459cfcf5d4Sdrh 
1846096fd476Sdrh   /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1847096fd476Sdrh   ** order:
1848096fd476Sdrh   **
184984304506Sdrh   **   (1)  OE_Update
185084304506Sdrh   **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1851096fd476Sdrh   **   (3)  OE_Replace
1852096fd476Sdrh   **
1853096fd476Sdrh   ** OE_Fail and OE_Ignore must happen before any changes are made.
1854096fd476Sdrh   ** OE_Update guarantees that only a single row will change, so it
1855096fd476Sdrh   ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
1856096fd476Sdrh   ** could happen in any order, but they are grouped up front for
1857096fd476Sdrh   ** convenience.
1858096fd476Sdrh   **
185984304506Sdrh   ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
186084304506Sdrh   ** The order of constraints used to have OE_Update as (2) and OE_Abort
186184304506Sdrh   ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
186284304506Sdrh   ** constraint before any others, so it had to be moved.
186384304506Sdrh   **
1864096fd476Sdrh   ** Constraint checking code is generated in this order:
1865096fd476Sdrh   **   (A)  The rowid constraint
1866096fd476Sdrh   **   (B)  Unique index constraints that do not have OE_Replace as their
1867096fd476Sdrh   **        default conflict resolution strategy
1868096fd476Sdrh   **   (C)  Unique index that do use OE_Replace by default.
1869096fd476Sdrh   **
1870096fd476Sdrh   ** The ordering of (2) and (3) is accomplished by making sure the linked
1871096fd476Sdrh   ** list of indexes attached to a table puts all OE_Replace indexes last
1872096fd476Sdrh   ** in the list.  See sqlite3CreateIndex() for where that happens.
1873096fd476Sdrh   */
187461e280adSdrh   sIdxIter.eType = 0;
187561e280adSdrh   sIdxIter.i = 0;
1876d3e21a10Sdrh   sIdxIter.u.ax.aIdx = 0;  /* Silence harmless compiler warning */
187761e280adSdrh   sIdxIter.u.lx.pIdx = pTab->pIndex;
1878096fd476Sdrh   if( pUpsert ){
1879096fd476Sdrh     if( pUpsert->pUpsertTarget==0 ){
188061e280adSdrh       /* There is just on ON CONFLICT clause and it has no constraint-target */
188161e280adSdrh       assert( pUpsert->pNextUpsert==0 );
1882255c1c15Sdrh       if( pUpsert->isDoUpdate==0 ){
188361e280adSdrh         /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
1884096fd476Sdrh         ** Make all unique constraint resolution be OE_Ignore */
1885096fd476Sdrh         overrideError = OE_Ignore;
1886096fd476Sdrh         pUpsert = 0;
188761e280adSdrh       }else{
188861e280adSdrh         /* A single ON CONFLICT DO UPDATE.  Make all resolutions OE_Update */
188961e280adSdrh         overrideError = OE_Update;
189061e280adSdrh       }
189161e280adSdrh     }else if( pTab->pIndex!=0 ){
189261e280adSdrh       /* Otherwise, we'll need to run the IndexListTerm array version of the
189361e280adSdrh       ** iterator to ensure that all of the ON CONFLICT conditions are
189461e280adSdrh       ** checked first and in order. */
189561e280adSdrh       int nIdx, jj;
189661e280adSdrh       u64 nByte;
189761e280adSdrh       Upsert *pTerm;
189861e280adSdrh       u8 *bUsed;
189961e280adSdrh       for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
190061e280adSdrh          assert( aRegIdx[nIdx]>0 );
190161e280adSdrh       }
190261e280adSdrh       sIdxIter.eType = 1;
190361e280adSdrh       sIdxIter.u.ax.nIdx = nIdx;
190461e280adSdrh       nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
190561e280adSdrh       sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
190661e280adSdrh       if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
190761e280adSdrh       bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
190861e280adSdrh       pUpsert->pToFree = sIdxIter.u.ax.aIdx;
190961e280adSdrh       for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
191061e280adSdrh         if( pTerm->pUpsertTarget==0 ) break;
191161e280adSdrh         if( pTerm->pUpsertIdx==0 ) continue;  /* Skip ON CONFLICT for the IPK */
191261e280adSdrh         jj = 0;
191361e280adSdrh         pIdx = pTab->pIndex;
191461e280adSdrh         while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
191561e280adSdrh            pIdx = pIdx->pNext;
191661e280adSdrh            jj++;
191761e280adSdrh         }
191861e280adSdrh         if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
191961e280adSdrh         bUsed[jj] = 1;
192061e280adSdrh         sIdxIter.u.ax.aIdx[i].p = pIdx;
192161e280adSdrh         sIdxIter.u.ax.aIdx[i].ix = jj;
192261e280adSdrh         i++;
192361e280adSdrh       }
192461e280adSdrh       for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
192561e280adSdrh         if( bUsed[jj] ) continue;
192661e280adSdrh         sIdxIter.u.ax.aIdx[i].p = pIdx;
192761e280adSdrh         sIdxIter.u.ax.aIdx[i].ix = jj;
192861e280adSdrh         i++;
192961e280adSdrh       }
193061e280adSdrh       assert( i==nIdx );
1931096fd476Sdrh     }
1932096fd476Sdrh   }
1933096fd476Sdrh 
1934a407eccbSdrh   /* Determine if it is possible that triggers (either explicitly coded
1935a407eccbSdrh   ** triggers or FK resolution actions) might run as a result of deletes
1936a407eccbSdrh   ** that happen when OE_Replace conflict resolution occurs. (Call these
1937a407eccbSdrh   ** "replace triggers".)  If any replace triggers run, we will need to
1938a407eccbSdrh   ** recheck all of the uniqueness constraints after they have all run.
1939a407eccbSdrh   ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
1940a407eccbSdrh   **
1941a407eccbSdrh   ** If replace triggers are a possibility, then
1942a407eccbSdrh   **
1943a407eccbSdrh   **   (1) Allocate register regTrigCnt and initialize it to zero.
1944a407eccbSdrh   **       That register will count the number of replace triggers that
1945d3c468b7Sdrh   **       fire.  Constraint recheck only occurs if the number is positive.
1946d3c468b7Sdrh   **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
1947a407eccbSdrh   **   (3) Initialize addrRecheck and lblRecheckOk
1948a407eccbSdrh   **
1949a407eccbSdrh   ** The uniqueness rechecking code will create a series of tests to run
1950a407eccbSdrh   ** in a second pass.  The addrRecheck and lblRecheckOk variables are
1951a407eccbSdrh   ** used to link together these tests which are separated from each other
1952a407eccbSdrh   ** in the generate bytecode.
1953a407eccbSdrh   */
1954a407eccbSdrh   if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
1955a407eccbSdrh     /* There are not DELETE triggers nor FK constraints.  No constraint
1956a407eccbSdrh     ** rechecks are needed. */
1957a407eccbSdrh     pTrigger = 0;
1958a407eccbSdrh     regTrigCnt = 0;
1959a407eccbSdrh   }else{
1960a407eccbSdrh     if( db->flags&SQLITE_RecTriggers ){
1961a407eccbSdrh       pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1962a407eccbSdrh       regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
1963a407eccbSdrh     }else{
1964a407eccbSdrh       pTrigger = 0;
1965a407eccbSdrh       regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
1966a407eccbSdrh     }
1967a407eccbSdrh     if( regTrigCnt ){
1968a407eccbSdrh       /* Replace triggers might exist.  Allocate the counter and
1969a407eccbSdrh       ** initialize it to zero. */
1970a407eccbSdrh       regTrigCnt = ++pParse->nMem;
1971a407eccbSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
1972a407eccbSdrh       VdbeComment((v, "trigger count"));
1973a407eccbSdrh       lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
1974a407eccbSdrh       addrRecheck = lblRecheckOk;
1975a407eccbSdrh     }
1976a407eccbSdrh   }
1977a407eccbSdrh 
1978f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1979f8ffb278Sdrh   ** exist in the table.
19809cfcf5d4Sdrh   */
19816fbe41acSdrh   if( pkChng && pPk==0 ){
1982ec4ccdbcSdrh     int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
198311e85273Sdrh 
1984f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
19850ca3e24bSdrh     onError = pTab->keyConf;
19860ca3e24bSdrh     if( overrideError!=OE_Default ){
19870ca3e24bSdrh       onError = overrideError;
1988a996e477Sdrh     }else if( onError==OE_Default ){
1989a996e477Sdrh       onError = OE_Abort;
19900ca3e24bSdrh     }
1991a0217ba7Sdrh 
1992c8a0c90bSdrh     /* figure out whether or not upsert applies in this case */
199361e280adSdrh     if( pUpsert ){
199461e280adSdrh       pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
199561e280adSdrh       if( pUpsertClause!=0 ){
1996255c1c15Sdrh         if( pUpsertClause->isDoUpdate==0 ){
1997c8a0c90bSdrh           onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
1998c8a0c90bSdrh         }else{
1999c8a0c90bSdrh           onError = OE_Update;  /* DO UPDATE */
2000c8a0c90bSdrh         }
2001c8a0c90bSdrh       }
200261e280adSdrh       if( pUpsertClause!=pUpsert ){
200361e280adSdrh         /* The first ON CONFLICT clause has a conflict target other than
200461e280adSdrh         ** the IPK.  We have to jump ahead to that first ON CONFLICT clause
200561e280adSdrh         ** and then come back here and deal with the IPK afterwards */
200661e280adSdrh         upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
200761e280adSdrh       }
200861e280adSdrh     }
2009c8a0c90bSdrh 
20108d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
20118d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
20128d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
20138d1b82e4Sdrh     ** the UNIQUE constraints have run.
20148d1b82e4Sdrh     */
201584304506Sdrh     if( onError==OE_Replace      /* IPK rule is REPLACE */
20169a60e716Smistachkin      && onError!=overrideError   /* Rules for other constraints are different */
201784304506Sdrh      && pTab->pIndex             /* There exist other constraints */
201866306d86Sdrh      && !upsertIpkDelay          /* IPK check already deferred by UPSERT */
2019096fd476Sdrh     ){
202084304506Sdrh       ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
202184304506Sdrh       VdbeComment((v, "defer IPK REPLACE until last"));
20228d1b82e4Sdrh     }
20238d1b82e4Sdrh 
2024bb6b1ca7Sdrh     if( isUpdate ){
2025bb6b1ca7Sdrh       /* pkChng!=0 does not mean that the rowid has changed, only that
2026bb6b1ca7Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
2027bb6b1ca7Sdrh       ** is unchanged. */
2028bb6b1ca7Sdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2029bb6b1ca7Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2030bb6b1ca7Sdrh       VdbeCoverage(v);
2031bb6b1ca7Sdrh     }
2032bb6b1ca7Sdrh 
2033f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
2034f8ffb278Sdrh     ** the following conflict logic if it does not. */
20357f5f306bSdrh     VdbeNoopComment((v, "uniqueness check for ROWID"));
20364031bafaSdrh     sqlite3VdbeVerifyAbortable(v, onError);
20376934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2038688852abSdrh     VdbeCoverage(v);
2039f8ffb278Sdrh 
20400ca3e24bSdrh     switch( onError ){
2041a0217ba7Sdrh       default: {
2042a0217ba7Sdrh         onError = OE_Abort;
204308b92086Sdrh         /* no break */ deliberate_fall_through
2044a0217ba7Sdrh       }
20451c92853dSdrh       case OE_Rollback:
20461c92853dSdrh       case OE_Abort:
20471c92853dSdrh       case OE_Fail: {
20489916048bSdrh         testcase( onError==OE_Rollback );
20499916048bSdrh         testcase( onError==OE_Abort );
20509916048bSdrh         testcase( onError==OE_Fail );
2051f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
20520ca3e24bSdrh         break;
20530ca3e24bSdrh       }
20545383ae5cSdrh       case OE_Replace: {
20552283d46cSdan         /* If there are DELETE triggers on this table and the
20562283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
2057d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
20582283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
20592283d46cSdan         **
20602283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
2061da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
2062da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
2063da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
2064da730f6eSdan         ** when it is inserted.
2065da730f6eSdan         **
2066da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2067da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
2068da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
2069da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2070da730f6eSdan         ** but being more selective here allows statements like:
2071da730f6eSdan         **
2072da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
2073da730f6eSdan         **
2074da730f6eSdan         ** to run without a statement journal if there are no indexes on the
2075da730f6eSdan         ** table.
2076da730f6eSdan         */
2077a407eccbSdrh         if( regTrigCnt ){
2078da730f6eSdan           sqlite3MultiWrite(pParse);
207926198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2080438b8815Sdan                                    regNewData, 1, 0, OE_Replace, 1, -1);
2081a407eccbSdrh           sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2082a407eccbSdrh           nReplaceTrig++;
208346c47d46Sdan         }else{
20849b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
208554f2cd90Sdrh           assert( HasRowid(pTab) );
208646c47d46Sdan           /* This OP_Delete opcode fires the pre-update-hook only. It does
208746c47d46Sdan           ** not modify the b-tree. It is more efficient to let the coming
208846c47d46Sdan           ** OP_Insert replace the existing entry than it is to delete the
208946c47d46Sdan           ** existing entry and then insert a new one. */
2090cbf1b8efSdrh           sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2091f14b7fb7Sdrh           sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
20929b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
209346c47d46Sdan           if( pTab->pIndex ){
2094da730f6eSdan             sqlite3MultiWrite(pParse);
2095f0ee1d3cSdan             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
20962283d46cSdan           }
209746c47d46Sdan         }
20985383ae5cSdrh         seenReplace = 1;
20995383ae5cSdrh         break;
21005383ae5cSdrh       }
21019eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
21029eddacadSdrh       case OE_Update: {
21032cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
210408b92086Sdrh         /* no break */ deliberate_fall_through
21059eddacadSdrh       }
21069eddacadSdrh #endif
21070ca3e24bSdrh       case OE_Ignore: {
21089916048bSdrh         testcase( onError==OE_Ignore );
2109076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
21100ca3e24bSdrh         break;
21110ca3e24bSdrh       }
21120ca3e24bSdrh     }
211311e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
211461e280adSdrh     if( pUpsert && pUpsertClause!=pUpsert ){
211561e280adSdrh       upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
211661e280adSdrh     }else if( ipkTop ){
211784304506Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
211884304506Sdrh       sqlite3VdbeJumpHere(v, ipkTop-1);
2119a05a722fSdrh     }
21200ca3e24bSdrh   }
21210bd1f4eaSdrh 
21220bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
21230bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
212411e85273Sdrh   ** Compute the revised record entries for indices as we go.
2125f8ffb278Sdrh   **
2126f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
2127f8ffb278Sdrh   ** WITHOUT ROWID table.
21280bd1f4eaSdrh   */
212961e280adSdrh   for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2130daf2761cSdrh       pIdx;
213161e280adSdrh       pIdx = indexIteratorNext(&sIdxIter, &ix)
2132daf2761cSdrh   ){
21336934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
21346934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
21356934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
21366934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
2137a407eccbSdrh     int addrConflictCk;  /* First opcode in the conflict check logic */
21382184fc75Sdrh 
213926198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
214061e280adSdrh     if( pUpsert ){
214161e280adSdrh       pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
214261e280adSdrh       if( upsertIpkDelay && pUpsertClause==pUpsert ){
214361e280adSdrh         sqlite3VdbeJumpHere(v, upsertIpkDelay);
21447f5f306bSdrh       }
214561e280adSdrh     }
214661e280adSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
214761e280adSdrh     if( bAffinityDone==0 ){
214884304506Sdrh       sqlite3TableAffinity(v, pTab, regNewData+1);
214984304506Sdrh       bAffinityDone = 1;
215084304506Sdrh     }
21518e50d65aSdrh     VdbeNoopComment((v, "prep index %s", pIdx->zName));
21526934fc7bSdrh     iThisCur = iIdxCur+ix;
21537f5f306bSdrh 
2154b2fe7d8cSdrh 
2155f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
2156b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
215726198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
21586e97f8ecSdrh       pParse->iSelfTab = -(regNewData+1);
215972bc8208Sdrh       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2160b2b9d3d7Sdrh                             SQLITE_JUMPIFNULL);
21616e97f8ecSdrh       pParse->iSelfTab = 0;
2162b2b9d3d7Sdrh     }
2163b2b9d3d7Sdrh 
21646934fc7bSdrh     /* Create a record for this index entry as it should appear after
2165f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
2166f8ffb278Sdrh     */
2167bf2f5739Sdrh     regIdx = aRegIdx[ix]+1;
21689cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
21696934fc7bSdrh       int iField = pIdx->aiColumn[i];
2170f82b9afcSdrh       int x;
21714b92f98cSdrh       if( iField==XN_EXPR ){
21726e97f8ecSdrh         pParse->iSelfTab = -(regNewData+1);
21731c75c9d7Sdrh         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
21746e97f8ecSdrh         pParse->iSelfTab = 0;
21751f9ca2c8Sdrh         VdbeComment((v, "%s column %d", pIdx->zName, i));
2176463e76ffSdrh       }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2177f82b9afcSdrh         x = regNewData;
2178463e76ffSdrh         sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2179463e76ffSdrh         VdbeComment((v, "rowid"));
21809cfcf5d4Sdrh       }else{
2181c5f808d8Sdrh         testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2182b9bcf7caSdrh         x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2183463e76ffSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2184cf9d36d1Sdrh         VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
21859cfcf5d4Sdrh       }
21861f9ca2c8Sdrh     }
218726198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
218826198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
21897e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
21909df385ecSdrh     if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
21919df385ecSdrh       sqlite3SetMakeRecordP5(v, pIdx->pTable);
21929df385ecSdrh     }
21937e4acf7bSdrh #endif
21943aef2fb1Sdrh     sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2195b2fe7d8cSdrh 
2196f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
2197f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
2198f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
2199f8ffb278Sdrh     ** logic below can all be skipped. */
220000012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
2201da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2202da475b8dSdrh       continue;
2203da475b8dSdrh     }
2204f8ffb278Sdrh 
22056934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
22069cfcf5d4Sdrh     onError = pIdx->onError;
2207de630353Sdanielk1977     if( onError==OE_None ){
220811e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2209de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
2210de630353Sdanielk1977     }
22119cfcf5d4Sdrh     if( overrideError!=OE_Default ){
22129cfcf5d4Sdrh       onError = overrideError;
2213a996e477Sdrh     }else if( onError==OE_Default ){
2214a996e477Sdrh       onError = OE_Abort;
22159cfcf5d4Sdrh     }
22165383ae5cSdrh 
2217c8a0c90bSdrh     /* Figure out if the upsert clause applies to this index */
221861e280adSdrh     if( pUpsertClause ){
2219255c1c15Sdrh       if( pUpsertClause->isDoUpdate==0 ){
2220c8a0c90bSdrh         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
2221c8a0c90bSdrh       }else{
2222c8a0c90bSdrh         onError = OE_Update;  /* DO UPDATE */
2223c8a0c90bSdrh       }
2224c8a0c90bSdrh     }
2225c8a0c90bSdrh 
2226801f55d8Sdrh     /* Collision detection may be omitted if all of the following are true:
2227801f55d8Sdrh     **   (1) The conflict resolution algorithm is REPLACE
2228801f55d8Sdrh     **   (2) The table is a WITHOUT ROWID table
2229801f55d8Sdrh     **   (3) There are no secondary indexes on the table
2230801f55d8Sdrh     **   (4) No delete triggers need to be fired if there is a conflict
2231f9a12a10Sdan     **   (5) No FK constraint counters need to be updated if a conflict occurs.
2232418454c6Sdan     **
2233418454c6Sdan     ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2234418454c6Sdan     ** must be explicitly deleted in order to ensure any pre-update hook
2235418454c6Sdan     ** is invoked.  */
223678b2fa86Sdrh     assert( IsOrdinaryTable(pTab) );
2237418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2238801f55d8Sdrh     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
2239801f55d8Sdrh      && pPk==pIdx                                   /* Condition 2 */
2240801f55d8Sdrh      && onError==OE_Replace                         /* Condition 1 */
2241801f55d8Sdrh      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
2242801f55d8Sdrh           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2243f9a12a10Sdan      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
2244f38524d2Sdrh          (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
22454e1f0efbSdan     ){
2246c6c9e158Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
2247c6c9e158Sdrh       continue;
2248c6c9e158Sdrh     }
2249418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2250c6c9e158Sdrh 
2251b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
22524031bafaSdrh     sqlite3VdbeVerifyAbortable(v, onError);
2253a407eccbSdrh     addrConflictCk =
225426198bb4Sdrh       sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2255688852abSdrh                            regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2256f8ffb278Sdrh 
2257f8ffb278Sdrh     /* Generate code to handle collisions */
2258d3e21a10Sdrh     regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
225946d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
226011e85273Sdrh       if( HasRowid(pTab) ){
22616934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
22620978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
22630978d4ffSdrh         ** is different from old-rowid */
2264f8ffb278Sdrh         if( isUpdate ){
22656934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
22663d77dee9Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2267688852abSdrh           VdbeCoverage(v);
2268f8ffb278Sdrh         }
226926198bb4Sdrh       }else{
2270ccc79f02Sdrh         int x;
227126198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
2272da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
2273a021f121Sdrh         if( pIdx!=pPk ){
227426198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
22754b92f98cSdrh             assert( pPk->aiColumn[i]>=0 );
2276b9bcf7caSdrh             x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
227726198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
227826198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
2279cf9d36d1Sdrh                          pTab->aCol[pPk->aiColumn[i]].zCnName));
228026198bb4Sdrh           }
2281da475b8dSdrh         }
2282da475b8dSdrh         if( isUpdate ){
2283e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2284e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
22855a1f7612Sdrh           ** different from the old.  See TH3 withoutrowid04.test.
2286e83267daSdan           **
2287e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2288e83267daSdan           ** of the matched index row are different from the original PRIMARY
2289e83267daSdan           ** KEY values of this row before the update.  */
2290e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2291e83267daSdan           int op = OP_Ne;
229248dd1d8eSdrh           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2293e83267daSdan 
2294e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
2295e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2296ccc79f02Sdrh             x = pPk->aiColumn[i];
22974b92f98cSdrh             assert( x>=0 );
2298e83267daSdan             if( i==(pPk->nKeyCol-1) ){
2299e83267daSdan               addrJump = addrUniqueOk;
2300e83267daSdan               op = OP_Eq;
230111e85273Sdrh             }
2302b6d861e5Sdrh             x = sqlite3TableColumnToStorage(pTab, x);
2303e83267daSdan             sqlite3VdbeAddOp4(v, op,
2304e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2305e83267daSdan             );
23063d77dee9Sdrh             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
23073d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Eq);
23083d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Ne);
2309da475b8dSdrh           }
231011e85273Sdrh         }
231126198bb4Sdrh       }
231246d03fcbSdrh     }
2313b2fe7d8cSdrh 
2314b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
2315b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
23169eddacadSdrh         || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
23179cfcf5d4Sdrh     switch( onError ){
23181c92853dSdrh       case OE_Rollback:
23191c92853dSdrh       case OE_Abort:
23201c92853dSdrh       case OE_Fail: {
23219916048bSdrh         testcase( onError==OE_Rollback );
23229916048bSdrh         testcase( onError==OE_Abort );
23239916048bSdrh         testcase( onError==OE_Fail );
2324f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
23259cfcf5d4Sdrh         break;
23269cfcf5d4Sdrh       }
23279eddacadSdrh #ifndef SQLITE_OMIT_UPSERT
23289eddacadSdrh       case OE_Update: {
23292cc00423Sdan         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
233008b92086Sdrh         /* no break */ deliberate_fall_through
23319eddacadSdrh       }
23329eddacadSdrh #endif
23339cfcf5d4Sdrh       case OE_Ignore: {
23349916048bSdrh         testcase( onError==OE_Ignore );
2335076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
23369cfcf5d4Sdrh         break;
23379cfcf5d4Sdrh       }
2338098d1684Sdrh       default: {
2339a407eccbSdrh         int nConflictCk;   /* Number of opcodes in conflict check logic */
2340a407eccbSdrh 
2341098d1684Sdrh         assert( onError==OE_Replace );
2342a407eccbSdrh         nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2343362c1819Sdrh         assert( nConflictCk>0 || db->mallocFailed );
2344362c1819Sdrh         testcase( nConflictCk<=0 );
2345d3c468b7Sdrh         testcase( nConflictCk>1 );
2346a407eccbSdrh         if( regTrigCnt ){
2347fecfb318Sdan           sqlite3MultiWrite(pParse);
2348a407eccbSdrh           nReplaceTrig++;
2349fecfb318Sdan         }
23507b14b65dSdrh         if( pTrigger && isUpdate ){
23517b14b65dSdrh           sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
23527b14b65dSdrh         }
235326198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2354b0264eecSdrh             regR, nPkField, 0, OE_Replace,
235568116939Sdrh             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
23567b14b65dSdrh         if( pTrigger && isUpdate ){
23577b14b65dSdrh           sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
23587b14b65dSdrh         }
2359a407eccbSdrh         if( regTrigCnt ){
2360a407eccbSdrh           int addrBypass;  /* Jump destination to bypass recheck logic */
2361a407eccbSdrh 
2362a407eccbSdrh           sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2363a407eccbSdrh           addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */
2364a407eccbSdrh           VdbeComment((v, "bypass recheck"));
2365a407eccbSdrh 
2366a407eccbSdrh           /* Here we insert code that will be invoked after all constraint
2367a407eccbSdrh           ** checks have run, if and only if one or more replace triggers
2368a407eccbSdrh           ** fired. */
2369a407eccbSdrh           sqlite3VdbeResolveLabel(v, lblRecheckOk);
2370a407eccbSdrh           lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2371a407eccbSdrh           if( pIdx->pPartIdxWhere ){
2372a407eccbSdrh             /* Bypass the recheck if this partial index is not defined
2373a407eccbSdrh             ** for the current row */
23740660884eSdrh             sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2375a407eccbSdrh             VdbeCoverage(v);
2376a407eccbSdrh           }
2377a407eccbSdrh           /* Copy the constraint check code from above, except change
2378a407eccbSdrh           ** the constraint-ok jump destination to be the address of
2379a407eccbSdrh           ** the next retest block */
2380d3c468b7Sdrh           while( nConflictCk>0 ){
2381d901b168Sdrh             VdbeOp x;    /* Conflict check opcode to copy */
2382d901b168Sdrh             /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2383d901b168Sdrh             ** Hence, make a complete copy of the opcode, rather than using
2384d901b168Sdrh             ** a pointer to the opcode. */
2385d901b168Sdrh             x = *sqlite3VdbeGetOp(v, addrConflictCk);
2386d901b168Sdrh             if( x.opcode!=OP_IdxRowid ){
2387d901b168Sdrh               int p2;      /* New P2 value for copied conflict check opcode */
2388b9f2e5f7Sdrh               const char *zP4;
2389d901b168Sdrh               if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2390a407eccbSdrh                 p2 = lblRecheckOk;
2391a407eccbSdrh               }else{
2392d901b168Sdrh                 p2 = x.p2;
2393a407eccbSdrh               }
2394b9f2e5f7Sdrh               zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2395b9f2e5f7Sdrh               sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2396d901b168Sdrh               sqlite3VdbeChangeP5(v, x.p5);
2397d901b168Sdrh               VdbeCoverageIf(v, p2!=x.p2);
2398a407eccbSdrh             }
2399a407eccbSdrh             nConflictCk--;
2400d901b168Sdrh             addrConflictCk++;
2401a407eccbSdrh           }
2402a407eccbSdrh           /* If the retest fails, issue an abort */
24032da8d6feSdrh           sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2404a407eccbSdrh 
2405a407eccbSdrh           sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
24062da8d6feSdrh         }
24070ca3e24bSdrh         seenReplace = 1;
24089cfcf5d4Sdrh         break;
24099cfcf5d4Sdrh       }
24109cfcf5d4Sdrh     }
241111e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
2412392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2413ed4c5469Sdrh     if( pUpsertClause
2414ed4c5469Sdrh      && upsertIpkReturn
2415ed4c5469Sdrh      && sqlite3UpsertNextIsIPK(pUpsertClause)
2416ed4c5469Sdrh     ){
241761e280adSdrh       sqlite3VdbeGoto(v, upsertIpkDelay+1);
241861e280adSdrh       sqlite3VdbeJumpHere(v, upsertIpkReturn);
241958b18a47Sdrh       upsertIpkReturn = 0;
242061e280adSdrh     }
24219cfcf5d4Sdrh   }
242284304506Sdrh 
242384304506Sdrh   /* If the IPK constraint is a REPLACE, run it last */
242484304506Sdrh   if( ipkTop ){
24256214d939Sdrh     sqlite3VdbeGoto(v, ipkTop);
242684304506Sdrh     VdbeComment((v, "Do IPK REPLACE"));
242766306d86Sdrh     assert( ipkBottom>0 );
242884304506Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
242984304506Sdrh   }
2430de630353Sdanielk1977 
2431a407eccbSdrh   /* Recheck all uniqueness constraints after replace triggers have run */
2432a407eccbSdrh   testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2433d3c468b7Sdrh   assert( regTrigCnt!=0 || nReplaceTrig==0 );
2434a407eccbSdrh   if( nReplaceTrig ){
2435a407eccbSdrh     sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2436a407eccbSdrh     if( !pPk ){
2437a407eccbSdrh       if( isUpdate ){
2438a407eccbSdrh         sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2439a407eccbSdrh         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2440a407eccbSdrh         VdbeCoverage(v);
2441a407eccbSdrh       }
2442a407eccbSdrh       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2443a407eccbSdrh       VdbeCoverage(v);
2444a407eccbSdrh       sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2445a407eccbSdrh     }else{
2446a407eccbSdrh       sqlite3VdbeGoto(v, addrRecheck);
2447a407eccbSdrh     }
2448a407eccbSdrh     sqlite3VdbeResolveLabel(v, lblRecheckOk);
2449a407eccbSdrh   }
2450a407eccbSdrh 
2451a7c3b93fSdrh   /* Generate the table record */
2452a7c3b93fSdrh   if( HasRowid(pTab) ){
2453a7c3b93fSdrh     int regRec = aRegIdx[ix];
24540b0b3a95Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2455a7c3b93fSdrh     sqlite3SetMakeRecordP5(v, pTab);
2456a7c3b93fSdrh     if( !bAffinityDone ){
2457a7c3b93fSdrh       sqlite3TableAffinity(v, pTab, 0);
2458a7c3b93fSdrh     }
2459a7c3b93fSdrh   }
2460a7c3b93fSdrh 
2461de630353Sdanielk1977   *pbMayReplace = seenReplace;
2462ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
24639cfcf5d4Sdrh }
24640ca3e24bSdrh 
2465d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM
24660ca3e24bSdrh /*
2467585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2468585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed.
2469585ce192Sdrh **
2470585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2471585ce192Sdrh */
2472585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2473585ce192Sdrh   u16 i;
2474585ce192Sdrh 
2475585ce192Sdrh   /* Records with omitted columns are only allowed for schema format
2476585ce192Sdrh   ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2477585ce192Sdrh   if( pTab->pSchema->file_format<2 ) return;
2478585ce192Sdrh 
24797e4acf7bSdrh   for(i=pTab->nCol-1; i>0; i--){
248079cf2b71Sdrh     if( pTab->aCol[i].iDflt!=0 ) break;
24817e4acf7bSdrh     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
24827e4acf7bSdrh   }
24837e4acf7bSdrh   sqlite3VdbeChangeP5(v, i+1);
2484585ce192Sdrh }
2485d447dcedSdrh #endif
2486585ce192Sdrh 
24870ca3e24bSdrh /*
2488fadc0e34Sdan ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2489fadc0e34Sdan ** number is iCur, and register regData contains the new record for the
2490fadc0e34Sdan ** PK index. This function adds code to invoke the pre-update hook,
2491fadc0e34Sdan ** if one is registered.
2492fadc0e34Sdan */
2493fadc0e34Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2494fadc0e34Sdan static void codeWithoutRowidPreupdate(
2495fadc0e34Sdan   Parse *pParse,                  /* Parse context */
2496fadc0e34Sdan   Table *pTab,                    /* Table being updated */
2497fadc0e34Sdan   int iCur,                       /* Cursor number for table */
2498fadc0e34Sdan   int regData                     /* Data containing new record */
2499fadc0e34Sdan ){
2500fadc0e34Sdan   Vdbe *v = pParse->pVdbe;
2501fadc0e34Sdan   int r = sqlite3GetTempReg(pParse);
2502fadc0e34Sdan   assert( !HasRowid(pTab) );
2503d01206ffSdrh   assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2504fadc0e34Sdan   sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2505fadc0e34Sdan   sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2506fadc0e34Sdan   sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2507fadc0e34Sdan   sqlite3ReleaseTempReg(pParse, r);
2508fadc0e34Sdan }
2509fadc0e34Sdan #else
2510fadc0e34Sdan # define codeWithoutRowidPreupdate(a,b,c,d)
2511fadc0e34Sdan #endif
2512fadc0e34Sdan 
2513fadc0e34Sdan /*
25140ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
25154adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
25166934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
251704adf416Sdrh ** rowid and the content to be inserted.
25180ca3e24bSdrh **
2519b419a926Sdrh ** The arguments to this routine should be the same as the first six
25204adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
25210ca3e24bSdrh */
25224adee20fSdanielk1977 void sqlite3CompleteInsertion(
25230ca3e24bSdrh   Parse *pParse,      /* The parser context */
25240ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
252526198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
252626198bb4Sdrh   int iIdxCur,        /* First index cursor */
25276934fc7bSdrh   int regNewData,     /* Range of content */
2528aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
2529f91c1318Sdan   int update_flags,   /* True for UPDATE, False for INSERT */
2530de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
2531de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
25320ca3e24bSdrh ){
25336934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
25346934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
25356934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
25366934fc7bSdrh   int i;              /* Loop counter */
25370ca3e24bSdrh 
2538f91c1318Sdan   assert( update_flags==0
2539f91c1318Sdan        || update_flags==OPFLAG_ISUPDATE
2540f91c1318Sdan        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2541f91c1318Sdan   );
2542f91c1318Sdan 
2543f0b41745Sdrh   v = pParse->pVdbe;
25440ca3e24bSdrh   assert( v!=0 );
2545f38524d2Sdrh   assert( !IsView(pTab) );  /* This table is not a VIEW */
2546b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2547d35bdd6cSdrh     /* All REPLACE indexes are at the end of the list */
2548d35bdd6cSdrh     assert( pIdx->onError!=OE_Replace
2549d35bdd6cSdrh          || pIdx->pNext==0
2550d35bdd6cSdrh          || pIdx->pNext->onError==OE_Replace );
2551aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
2552b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
2553b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2554688852abSdrh       VdbeCoverage(v);
2555b2b9d3d7Sdrh     }
2556cb9a3643Sdan     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
255748dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
25586546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
2559f91c1318Sdan       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2560cb9a3643Sdan       if( update_flags==0 ){
2561fadc0e34Sdan         codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2562de630353Sdanielk1977       }
2563cb9a3643Sdan     }
2564cb9a3643Sdan     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2565cb9a3643Sdan                          aRegIdx[i]+1,
2566cb9a3643Sdan                          pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
25679b34abeeSdrh     sqlite3VdbeChangeP5(v, pik_flags);
25680ca3e24bSdrh   }
2569ec95c441Sdrh   if( !HasRowid(pTab) ) return;
25704794f735Sdrh   if( pParse->nested ){
25714794f735Sdrh     pik_flags = 0;
25724794f735Sdrh   }else{
257394eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
2574f91c1318Sdan     pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
25754794f735Sdrh   }
2576e4d90813Sdrh   if( appendBias ){
2577e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
2578e4d90813Sdrh   }
2579de630353Sdanielk1977   if( useSeekResult ){
2580de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
2581de630353Sdanielk1977   }
2582a7c3b93fSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
258394eb6a14Sdanielk1977   if( !pParse->nested ){
2584f14b7fb7Sdrh     sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
258594eb6a14Sdanielk1977   }
2586b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
25870ca3e24bSdrh }
2588cd44690aSdrh 
2589cd44690aSdrh /*
259026198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
259126198bb4Sdrh ** code to open and initialized those cursors.
2592aa9b8963Sdrh **
259326198bb4Sdrh ** The cursor for the object that contains the complete data (normally
259426198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
259526198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
259626198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
259726198bb4Sdrh **
259826198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
259926198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
260026198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
260126198bb4Sdrh **
260226198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
260326198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
260426198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
260526198bb4Sdrh ** pTab->pIndex list.
2606b6b4b79fSdrh **
2607b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the
2608b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized.
2609cd44690aSdrh */
2610aa9b8963Sdrh int sqlite3OpenTableAndIndices(
2611290c1948Sdrh   Parse *pParse,   /* Parsing context */
2612290c1948Sdrh   Table *pTab,     /* Table to be opened */
261326198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
2614b89aeb6aSdrh   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
261526198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
26166a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
261726198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
261826198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
2619290c1948Sdrh ){
2620cd44690aSdrh   int i;
26214cbdda9eSdrh   int iDb;
26226a53499aSdrh   int iDataCur;
2623cd44690aSdrh   Index *pIdx;
26244cbdda9eSdrh   Vdbe *v;
26254cbdda9eSdrh 
262626198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
2627fd261ec6Sdan   assert( op==OP_OpenWrite || p5==0 );
262826198bb4Sdrh   if( IsVirtual(pTab) ){
2629b6b4b79fSdrh     /* This routine is a no-op for virtual tables. Leave the output
263033d28ab4Sdrh     ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
263133d28ab4Sdrh     ** for improved error detection. */
263233d28ab4Sdrh     *piDataCur = *piIdxCur = -999;
263326198bb4Sdrh     return 0;
263426198bb4Sdrh   }
26354cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2636f0b41745Sdrh   v = pParse->pVdbe;
2637cd44690aSdrh   assert( v!=0 );
263826198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
26396a53499aSdrh   iDataCur = iBase++;
26406a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
26416a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
26426a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
26436fbe41acSdrh   }else{
264426198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
26456fbe41acSdrh   }
26466a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
264726198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
264826198bb4Sdrh     int iIdxCur = iBase++;
2649da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
265061441c34Sdan     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
265161441c34Sdan       if( piDataCur ) *piDataCur = iIdxCur;
265261441c34Sdan       p5 = 0;
265361441c34Sdan     }
26546a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
26552ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
26562ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2657b89aeb6aSdrh       sqlite3VdbeChangeP5(v, p5);
265861441c34Sdan       VdbeComment((v, "%s", pIdx->zName));
2659b89aeb6aSdrh     }
26606a53499aSdrh   }
266126198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
266226198bb4Sdrh   return i;
2663cd44690aSdrh }
26649d9cf229Sdrh 
266591c58e23Sdrh 
266691c58e23Sdrh #ifdef SQLITE_TEST
266791c58e23Sdrh /*
266891c58e23Sdrh ** The following global variable is incremented whenever the
266991c58e23Sdrh ** transfer optimization is used.  This is used for testing
267091c58e23Sdrh ** purposes only - to make sure the transfer optimization really
267160ec914cSpeter.d.reid ** is happening when it is supposed to.
267291c58e23Sdrh */
267391c58e23Sdrh int sqlite3_xferopt_count;
267491c58e23Sdrh #endif /* SQLITE_TEST */
267591c58e23Sdrh 
267691c58e23Sdrh 
26779d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
26789d9cf229Sdrh /*
26799d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
26809d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
26819d9cf229Sdrh ** for a compatible index:
26829d9cf229Sdrh **
26839d9cf229Sdrh **    *   The index is over the same set of columns
26849d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
26859d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
26869d9cf229Sdrh **    *   The same collating sequence on each column
2687b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
26889d9cf229Sdrh */
26899d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
26909d9cf229Sdrh   int i;
26919d9cf229Sdrh   assert( pDest && pSrc );
26929d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
26931e7c00e6Sdrh   if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
26949d9cf229Sdrh     return 0;   /* Different number of columns */
26959d9cf229Sdrh   }
26969d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
26979d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
26989d9cf229Sdrh   }
2699bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
27009d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
27019d9cf229Sdrh       return 0;   /* Different columns indexed */
27029d9cf229Sdrh     }
27034b92f98cSdrh     if( pSrc->aiColumn[i]==XN_EXPR ){
27041f9ca2c8Sdrh       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
27055aa550cfSdan       if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
27061f9ca2c8Sdrh                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
27071f9ca2c8Sdrh         return 0;   /* Different expressions in the index */
27081f9ca2c8Sdrh       }
27091f9ca2c8Sdrh     }
27109d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
27119d9cf229Sdrh       return 0;   /* Different sort orders */
27129d9cf229Sdrh     }
27130472af91Sdrh     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
271460a713c6Sdrh       return 0;   /* Different collating sequences */
27159d9cf229Sdrh     }
27169d9cf229Sdrh   }
27175aa550cfSdan   if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2718b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
2719b2b9d3d7Sdrh   }
27209d9cf229Sdrh 
27219d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
27229d9cf229Sdrh   return 1;
27239d9cf229Sdrh }
27249d9cf229Sdrh 
27259d9cf229Sdrh /*
27269d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
27279d9cf229Sdrh **
27289d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
27299d9cf229Sdrh **
2730ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
273160ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves
2732ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
27339d9cf229Sdrh **
2734ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2735ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
2736ccdf1baeSdrh ** embedded in the code for details.
27379d9cf229Sdrh **
2738ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
2739ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
2740ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
2741ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
2742ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
2743ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
2744ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
2745ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
2746ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
27479d9cf229Sdrh **
2748ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
27499d9cf229Sdrh */
27509d9cf229Sdrh static int xferOptimization(
27519d9cf229Sdrh   Parse *pParse,        /* Parser context */
27529d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
27539d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
27549d9cf229Sdrh   int onError,          /* How to handle constraint errors */
27559d9cf229Sdrh   int iDbDest           /* The database of pDest */
27569d9cf229Sdrh ){
2757e34162b1Sdan   sqlite3 *db = pParse->db;
27589d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
27599d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
27609d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
27617601294aSdrh   SrcItem *pItem;                  /* An element of pSelect->pSrc */
27629d9cf229Sdrh   int i;                           /* Loop counter */
27639d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
27649d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
27659d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
2766da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
2767da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
27689d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
27696a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
2770f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
2771b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
27729d9cf229Sdrh 
2773935c3722Sdrh   assert( pSelect!=0 );
2774ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
2775ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
2776ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
2777ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
2778ebbf08a0Sdan     return 0;
2779ebbf08a0Sdan   }
27809d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
278144266ec6Sdrh   if( IsVirtual(pDest) ){
27829d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
27839d9cf229Sdrh   }
27849d9cf229Sdrh #endif
27859d9cf229Sdrh   if( onError==OE_Default ){
2786e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2787e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
27889d9cf229Sdrh   }
27895ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
27909d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
27919d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
27929d9cf229Sdrh   }
27939d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
27949d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
27959d9cf229Sdrh   }
27969d9cf229Sdrh   if( pSelect->pWhere ){
27979d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
27989d9cf229Sdrh   }
27999d9cf229Sdrh   if( pSelect->pOrderBy ){
28009d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
28019d9cf229Sdrh   }
28028103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
28038103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
28049d9cf229Sdrh   if( pSelect->pGroupBy ){
28059d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
28069d9cf229Sdrh   }
28079d9cf229Sdrh   if( pSelect->pLimit ){
28089d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
28099d9cf229Sdrh   }
28109d9cf229Sdrh   if( pSelect->pPrior ){
28119d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
28129d9cf229Sdrh   }
28137d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
28149d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
28159d9cf229Sdrh   }
28169d9cf229Sdrh   pEList = pSelect->pEList;
28179d9cf229Sdrh   assert( pEList!=0 );
28189d9cf229Sdrh   if( pEList->nExpr!=1 ){
28199d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
28209d9cf229Sdrh   }
28219d9cf229Sdrh   assert( pEList->a[0].pExpr );
28221a1d3cd2Sdrh   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
28239d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
28249d9cf229Sdrh   }
28259d9cf229Sdrh 
28269d9cf229Sdrh   /* At this point we have established that the statement is of the
28279d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
28289d9cf229Sdrh   ** we have to check the semantics.
28299d9cf229Sdrh   */
28309d9cf229Sdrh   pItem = pSelect->pSrc->a;
283141fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
28329d9cf229Sdrh   if( pSrc==0 ){
28339d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
28349d9cf229Sdrh   }
283521908b21Sdrh   if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
28361e32bed3Sdrh     testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
28379d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
28389d9cf229Sdrh   }
283955548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
284055548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
284155548273Sdrh   }
2842f38524d2Sdrh   if( !IsOrdinaryTable(pSrc) ){
2843f38524d2Sdrh     return 0;   /* tab2 may not be a view or virtual table */
28449d9cf229Sdrh   }
28459d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
28469d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
28479d9cf229Sdrh   }
28489d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
28499d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
28509d9cf229Sdrh   }
28517b4b74acSdrh   if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
28527b4b74acSdrh     return 0;   /* Cannot feed from a non-strict into a strict table */
28537b4b74acSdrh   }
28549d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
28559940e2aaSdan     Column *pDestCol = &pDest->aCol[i];
28569940e2aaSdan     Column *pSrcCol = &pSrc->aCol[i];
2857ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
28588257aa8dSdrh     if( (db->mDbFlags & DBFLAG_Vacuum)==0
2859aaea3143Sdan      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2860aaea3143Sdan     ){
2861ba68f8f3Sdan       return 0;    /* Neither table may have __hidden__ columns */
2862ba68f8f3Sdan     }
2863ba68f8f3Sdan #endif
28646ab61d70Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS
28656ab61d70Sdrh     /* Even if tables t1 and t2 have identical schemas, if they contain
28666ab61d70Sdrh     ** generated columns, then this statement is semantically incorrect:
28676ab61d70Sdrh     **
28686ab61d70Sdrh     **     INSERT INTO t2 SELECT * FROM t1;
28696ab61d70Sdrh     **
28706ab61d70Sdrh     ** The reason is that generated column values are returned by the
28716ab61d70Sdrh     ** the SELECT statement on the right but the INSERT statement on the
28726ab61d70Sdrh     ** left wants them to be omitted.
28736ab61d70Sdrh     **
28746ab61d70Sdrh     ** Nevertheless, this is a useful notational shorthand to tell SQLite
28756ab61d70Sdrh     ** to do a bulk transfer all of the content from t1 over to t2.
28766ab61d70Sdrh     **
28776ab61d70Sdrh     ** We could, in theory, disable this (except for internal use by the
28786ab61d70Sdrh     ** VACUUM command where it is actually needed).  But why do that?  It
28796ab61d70Sdrh     ** seems harmless enough, and provides a useful service.
28806ab61d70Sdrh     */
2881ae3977a8Sdrh     if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
2882ae3977a8Sdrh         (pSrcCol->colFlags & COLFLAG_GENERATED) ){
28836ab61d70Sdrh       return 0;    /* Both columns have the same generated-column type */
2884ae3977a8Sdrh     }
28856ab61d70Sdrh     /* But the transfer is only allowed if both the source and destination
28866ab61d70Sdrh     ** tables have the exact same expressions for generated columns.
28876ab61d70Sdrh     ** This requirement could be relaxed for VIRTUAL columns, I suppose.
28886ab61d70Sdrh     */
28896ab61d70Sdrh     if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
289079cf2b71Sdrh       if( sqlite3ExprCompare(0,
289179cf2b71Sdrh              sqlite3ColumnExpr(pSrc, pSrcCol),
289279cf2b71Sdrh              sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
28936ab61d70Sdrh         testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
28946ab61d70Sdrh         testcase( pDestCol->colFlags & COLFLAG_STORED );
28956ab61d70Sdrh         return 0;  /* Different generator expressions */
28966ab61d70Sdrh       }
28976ab61d70Sdrh     }
28986ab61d70Sdrh #endif
28999940e2aaSdan     if( pDestCol->affinity!=pSrcCol->affinity ){
29009d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
29019d9cf229Sdrh     }
290265b40093Sdrh     if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
290365b40093Sdrh                         sqlite3ColumnColl(pSrcCol))!=0 ){
29049d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
29059d9cf229Sdrh     }
29069940e2aaSdan     if( pDestCol->notNull && !pSrcCol->notNull ){
29079d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
29089d9cf229Sdrh     }
2909453e0261Sdrh     /* Default values for second and subsequent columns need to match. */
2910ae3977a8Sdrh     if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
291179cf2b71Sdrh       Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
291279cf2b71Sdrh       Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
291379cf2b71Sdrh       assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
2914f9751074Sdrh       assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
291579cf2b71Sdrh       assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
2916f9751074Sdrh       assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
291779cf2b71Sdrh       if( (pDestExpr==0)!=(pSrcExpr==0)
291879cf2b71Sdrh        || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
291979cf2b71Sdrh                                        pSrcExpr->u.zToken)!=0)
29209940e2aaSdan       ){
29219940e2aaSdan         return 0;    /* Default values must be the same for all columns */
29229940e2aaSdan       }
29239d9cf229Sdrh     }
292494fa9c41Sdrh   }
29259d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
29265f1d1d9cSdrh     if( IsUniqueIndex(pDestIdx) ){
2927f33c9fadSdrh       destHasUniqueIdx = 1;
2928f33c9fadSdrh     }
29299d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
29309d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
29319d9cf229Sdrh     }
29329d9cf229Sdrh     if( pSrcIdx==0 ){
29339d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
29349d9cf229Sdrh     }
2935e3bd232eSdrh     if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
2936e3bd232eSdrh          && sqlite3FaultSim(411)==SQLITE_OK ){
2937e3bd232eSdrh       /* The sqlite3FaultSim() call allows this corruption test to be
2938e3bd232eSdrh       ** bypassed during testing, in order to exercise other corruption tests
2939e3bd232eSdrh       ** further downstream. */
294086223e8dSdrh       return 0;   /* Corrupt schema - two indexes on the same btree */
294186223e8dSdrh     }
29429d9cf229Sdrh   }
29437fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
2944619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
29458103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
29468103b7d2Sdrh   }
29477fc2f41bSdrh #endif
2948713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
2949713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
2950713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
2951713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
2952713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
2953713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
2954713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2955713de341Sdrh   */
295678b2fa86Sdrh   assert( IsOrdinaryTable(pDest) );
2957f38524d2Sdrh   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
2958713de341Sdrh     return 0;
2959713de341Sdrh   }
2960713de341Sdrh #endif
2961e34162b1Sdan   if( (db->flags & SQLITE_CountRows)!=0 ){
2962ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
29631696124dSdan   }
29649d9cf229Sdrh 
2965ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
2966ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
2967ccdf1baeSdrh   ** table (tab1) is initially empty.
29689d9cf229Sdrh   */
2969dd73521bSdrh #ifdef SQLITE_TEST
2970dd73521bSdrh   sqlite3_xferopt_count++;
2971dd73521bSdrh #endif
2972e34162b1Sdan   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
29739d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
2974f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
29759d9cf229Sdrh   iSrc = pParse->nTab++;
29769d9cf229Sdrh   iDest = pParse->nTab++;
29776a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
297855548273Sdrh   regData = sqlite3GetTempReg(pParse);
29797aae7358Sdan   sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
298055548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
29819d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2982427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
29838257aa8dSdrh   if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
2984e34162b1Sdan       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2985ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
2986ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2987e34162b1Sdan   )){
2988ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
2989e34162b1Sdan     ** only if the destination table is initially empty. Unless the
29908257aa8dSdrh     ** DBFLAG_Vacuum flag is set, this block generates code to make
29918257aa8dSdrh     ** that determination. If DBFLAG_Vacuum is set, then the destination
2992e34162b1Sdan     ** table is always empty.
2993e34162b1Sdan     **
2994e34162b1Sdan     ** Conditions under which the destination must be empty:
2995f33c9fadSdrh     **
2996ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2997ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
2998ccdf1baeSdrh     **     of index entries might need to change.)
2999ccdf1baeSdrh     **
3000ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
3001ccdf1baeSdrh     **     is unable to test uniqueness.)
3002ccdf1baeSdrh     **
3003ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
30049d9cf229Sdrh     */
3005688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
30062991ba05Sdrh     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
30079d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
30089d9cf229Sdrh   }
3009427ebba1Sdan   if( HasRowid(pSrc) ){
3010c9b9deaeSdrh     u8 insFlags;
30119d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3012688852abSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
301342242dedSdrh     if( pDest->iPKey>=0 ){
3014b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3015036e0675Sdan       if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
30164031bafaSdrh         sqlite3VdbeVerifyAbortable(v, onError);
3017b7654111Sdrh         addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3018688852abSdrh         VdbeCoverage(v);
3019f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pDest);
30209d9cf229Sdrh         sqlite3VdbeJumpHere(v, addr2);
3021036e0675Sdan       }
3022b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
30234e61e883Sdrh     }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3024b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
302595bad4c7Sdrh     }else{
3026b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
30277d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
302895bad4c7Sdrh     }
30297aae7358Sdan 
30308257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
303186b40dfdSdrh       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
30327aae7358Sdan       insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3033c9b9deaeSdrh     }else{
30347aae7358Sdan       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
30357aae7358Sdan     }
30367aae7358Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3037a55a839aSdan     if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
303851f37b2bSdrh       sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
30397aae7358Sdan       insFlags &= ~OPFLAG_PREFORMAT;
3040a55a839aSdan     }else
3041fadc0e34Sdan #endif
3042a55a839aSdan     {
3043a55a839aSdan       sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3044a55a839aSdan     }
3045a55a839aSdan     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3046a55a839aSdan     if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3047a55a839aSdan       sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3048a55a839aSdan     }
3049c9b9deaeSdrh     sqlite3VdbeChangeP5(v, insFlags);
30507aae7358Sdan 
3051688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
305255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
305355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3054da475b8dSdrh   }else{
3055da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3056da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
305755548273Sdrh   }
30589d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
305941b9ca25Sdrh     u8 idxInsFlags = 0;
30601b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
30619d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
30629d9cf229Sdrh     }
30639d9cf229Sdrh     assert( pSrcIdx );
30642ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
30652ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3066d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
30672ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
30682ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
306959885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3070207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
3071688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
30728257aa8dSdrh     if( db->mDbFlags & DBFLAG_Vacuum ){
3073e34162b1Sdan       /* This INSERT command is part of a VACUUM operation, which guarantees
3074e34162b1Sdan       ** that the destination table is empty. If all indexed columns use
3075e34162b1Sdan       ** collation sequence BINARY, then it can also be assumed that the
3076e34162b1Sdan       ** index will be populated by inserting keys in strictly sorted
3077e34162b1Sdan       ** order. In this case, instead of seeking within the b-tree as part
307886b40dfdSdrh       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3079e34162b1Sdan       ** OP_IdxInsert to seek to the point within the b-tree where each key
3080e34162b1Sdan       ** should be inserted. This is faster.
3081e34162b1Sdan       **
3082e34162b1Sdan       ** If any of the indexed columns use a collation sequence other than
3083e34162b1Sdan       ** BINARY, this optimization is disabled. This is because the user
3084e34162b1Sdan       ** might change the definition of a collation sequence and then run
3085e34162b1Sdan       ** a VACUUM command. In that case keys may not be written in strictly
3086e34162b1Sdan       ** sorted order.  */
3087e34162b1Sdan       for(i=0; i<pSrcIdx->nColumn; i++){
3088f19aa5faSdrh         const char *zColl = pSrcIdx->azColl[i];
3089f19aa5faSdrh         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3090e34162b1Sdan       }
3091e34162b1Sdan       if( i==pSrcIdx->nColumn ){
30927aae7358Sdan         idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
309386b40dfdSdrh         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3094a06eafc8Sdrh         sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3095e34162b1Sdan       }
3096c84ad318Sdrh     }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
309741b9ca25Sdrh       idxInsFlags |= OPFLAG_NCHANGE;
309841b9ca25Sdrh     }
30997aae7358Sdan     if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
310051f37b2bSdrh       sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3101a55a839aSdan       if( (db->mDbFlags & DBFLAG_Vacuum)==0
3102a55a839aSdan        && !HasRowid(pDest)
3103a55a839aSdan        && IsPrimaryKeyIndex(pDestIdx)
3104a55a839aSdan       ){
3105fadc0e34Sdan         codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3106fadc0e34Sdan       }
31077aae7358Sdan     }
31089b4eaebcSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
31099b4eaebcSdrh     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3110688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
31119d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
311255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
311355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
31149d9cf229Sdrh   }
3115aceb31b1Sdrh   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3116b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
3117b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
31189d9cf229Sdrh   if( emptyDestTest ){
31191dd518cfSdrh     sqlite3AutoincrementEnd(pParse);
312066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
31219d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
312266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
31239d9cf229Sdrh     return 0;
31249d9cf229Sdrh   }else{
31259d9cf229Sdrh     return 1;
31269d9cf229Sdrh   }
31279d9cf229Sdrh }
31289d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
3129