xref: /sqlite-3.40.0/src/insert.c (revision 9b4eaebc)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17cce7d176Sdrh /*
1826198bb4Sdrh ** Generate code that will
19dd9930efSdrh **
2026198bb4Sdrh **   (1) acquire a lock for table pTab then
2126198bb4Sdrh **   (2) open pTab as cursor iCur.
2226198bb4Sdrh **
2326198bb4Sdrh ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
2426198bb4Sdrh ** for that table that is actually opened.
25bbb5e4e0Sdrh */
26bbb5e4e0Sdrh void sqlite3OpenTable(
272ec2fb22Sdrh   Parse *pParse,  /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
352ec2fb22Sdrh   v = sqlite3GetVdbe(pParse);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
372ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
382ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
39ec95c441Sdrh   if( HasRowid(pTab) ){
40261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
41bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
4226198bb4Sdrh   }else{
43dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44dd9930efSdrh     assert( pPk!=0 );
45afe028a8Sdrh     assert( pPk->tnum==pTab->tnum );
462ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
472ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
48bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
49bbb5e4e0Sdrh   }
50bbb5e4e0Sdrh }
51bbb5e4e0Sdrh 
52bbb5e4e0Sdrh /*
5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5569f8bb9cSdan ** the table, according to the affinity of the column:
563d1bfeaaSdanielk1977 **
573d1bfeaaSdanielk1977 **  Character      Column affinity
583d1bfeaaSdanielk1977 **  ------------------------------
5905883a34Sdrh **  'A'            BLOB
604583c37cSdrh **  'B'            TEXT
614583c37cSdrh **  'C'            NUMERIC
624583c37cSdrh **  'D'            INTEGER
634583c37cSdrh **  'F'            REAL
642d401ab8Sdrh **
654583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the
662d401ab8Sdrh ** rowid that appears as the last column in every index.
6769f8bb9cSdan **
6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
713d1bfeaaSdanielk1977 */
72e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
73a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
74e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
75a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
76e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
77a37cdde0Sdanielk1977     **
78a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
79e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80a37cdde0Sdanielk1977     ** up.
81a37cdde0Sdanielk1977     */
82a37cdde0Sdanielk1977     int n;
83a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
84ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
864a642b60Sdrh       sqlite3OomFault(db);
8769f8bb9cSdan       return 0;
88a37cdde0Sdanielk1977     }
89a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
90ad124329Sdrh       i16 x = pIdx->aiColumn[n];
911f9ca2c8Sdrh       if( x>=0 ){
921f9ca2c8Sdrh         pIdx->zColAff[n] = pTab->aCol[x].affinity;
934b92f98cSdrh       }else if( x==XN_ROWID ){
941f9ca2c8Sdrh         pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
951f9ca2c8Sdrh       }else{
966860e6faSdrh         char aff;
974b92f98cSdrh         assert( x==XN_EXPR );
981f9ca2c8Sdrh         assert( pIdx->aColExpr!=0 );
996860e6faSdrh         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
1006860e6faSdrh         if( aff==0 ) aff = SQLITE_AFF_BLOB;
1016860e6faSdrh         pIdx->zColAff[n] = aff;
1021f9ca2c8Sdrh       }
103a37cdde0Sdanielk1977     }
1042d401ab8Sdrh     pIdx->zColAff[n] = 0;
105a37cdde0Sdanielk1977   }
1063d1bfeaaSdanielk1977 
10769f8bb9cSdan   return pIdx->zColAff;
108a37cdde0Sdanielk1977 }
109a37cdde0Sdanielk1977 
110a37cdde0Sdanielk1977 /*
11157bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been
11205883a34Sdrh ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
11357bf4a8eSdrh **
11405883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
11557bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
11657bf4a8eSdrh ** for register iReg and following.  Or if affinities exists and iReg==0,
11757bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should  be
11857bf4a8eSdrh ** an OP_MakeRecord) to the affinity string.
11957bf4a8eSdrh **
120b6e8fd10Sdrh ** A column affinity string has one character per column:
121a37cdde0Sdanielk1977 **
122a37cdde0Sdanielk1977 **  Character      Column affinity
123a37cdde0Sdanielk1977 **  ------------------------------
12405883a34Sdrh **  'A'            BLOB
1254583c37cSdrh **  'B'            TEXT
1264583c37cSdrh **  'C'            NUMERIC
1274583c37cSdrh **  'D'            INTEGER
1284583c37cSdrh **  'E'            REAL
129a37cdde0Sdanielk1977 */
13057bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
1313d1bfeaaSdanielk1977   int i;
13257bf4a8eSdrh   char *zColAff = pTab->zColAff;
13357bf4a8eSdrh   if( zColAff==0 ){
134abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
135b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1363d1bfeaaSdanielk1977     if( !zColAff ){
1374a642b60Sdrh       sqlite3OomFault(db);
138a37cdde0Sdanielk1977       return;
1393d1bfeaaSdanielk1977     }
1403d1bfeaaSdanielk1977 
1413d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
142a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1433d1bfeaaSdanielk1977     }
14457bf4a8eSdrh     do{
14557bf4a8eSdrh       zColAff[i--] = 0;
14605883a34Sdrh     }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
1473d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1483d1bfeaaSdanielk1977   }
14957bf4a8eSdrh   i = sqlite3Strlen30(zColAff);
15057bf4a8eSdrh   if( i ){
15157bf4a8eSdrh     if( iReg ){
15257bf4a8eSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
15357bf4a8eSdrh     }else{
15457bf4a8eSdrh       sqlite3VdbeChangeP4(v, -1, zColAff, i);
15557bf4a8eSdrh     }
15657bf4a8eSdrh   }
1573d1bfeaaSdanielk1977 }
1583d1bfeaaSdanielk1977 
1594d88778bSdanielk1977 /*
16048d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
161b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if
16248d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
163b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT.
1644d88778bSdanielk1977 */
16505a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){
166595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1674d88778bSdanielk1977   int i;
16848d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
169595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
170595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
171595a523aSdanielk1977 #endif
172595a523aSdanielk1977 
17305a86c5cSdrh   for(i=1; i<iEnd; i++){
17448d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
175ef0bea92Sdrh     assert( pOp!=0 );
176207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
17748d1178aSdrh       Index *pIndex;
178207872a4Sdanielk1977       int tnum = pOp->p2;
17948d1178aSdrh       if( tnum==pTab->tnum ){
18048d1178aSdrh         return 1;
18148d1178aSdrh       }
18248d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
18348d1178aSdrh         if( tnum==pIndex->tnum ){
18448d1178aSdrh           return 1;
18548d1178aSdrh         }
18648d1178aSdrh       }
18748d1178aSdrh     }
188543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
189595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1902dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
19166a5167bSdrh       assert( pOp->p4type==P4_VTAB );
19248d1178aSdrh       return 1;
1934d88778bSdanielk1977     }
194543165efSdrh #endif
1954d88778bSdanielk1977   }
1964d88778bSdanielk1977   return 0;
1974d88778bSdanielk1977 }
1983d1bfeaaSdanielk1977 
1999d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
2009d9cf229Sdrh /*
2010b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
2020b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
2039ef5e770Sdrh ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
2049ef5e770Sdrh ** table.  (Also return zero when doing a VACUUM since we do not want to
2059ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.)
2069d9cf229Sdrh **
2070b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
2080b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
2090b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
2100b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
2110b9f50d8Sdrh ** AutoincInfo structure is used.
2129d9cf229Sdrh **
2130b9f50d8Sdrh ** Three memory locations are allocated:
2140b9f50d8Sdrh **
2150b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
2160b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2170b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2180b9f50d8Sdrh **
2190b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2200b9f50d8Sdrh ** insert routine needs to know about.
2219d9cf229Sdrh */
2229d9cf229Sdrh static int autoIncBegin(
2239d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2249d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2259d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2269d9cf229Sdrh ){
2276a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2289ef5e770Sdrh   if( (pTab->tabFlags & TF_Autoincrement)!=0
2299ef5e770Sdrh    && (pParse->db->flags & SQLITE_Vacuum)==0
2309ef5e770Sdrh   ){
23165a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2320b9f50d8Sdrh     AutoincInfo *pInfo;
2330b9f50d8Sdrh 
23465a7cd16Sdan     pInfo = pToplevel->pAinc;
2350b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2360b9f50d8Sdrh     if( pInfo==0 ){
237575fad65Sdrh       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
2380b9f50d8Sdrh       if( pInfo==0 ) return 0;
23965a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
24065a7cd16Sdan       pToplevel->pAinc = pInfo;
2410b9f50d8Sdrh       pInfo->pTab = pTab;
2420b9f50d8Sdrh       pInfo->iDb = iDb;
24365a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
24465a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
24565a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2460b9f50d8Sdrh     }
2470b9f50d8Sdrh     memId = pInfo->regCtr;
2489d9cf229Sdrh   }
2499d9cf229Sdrh   return memId;
2509d9cf229Sdrh }
2519d9cf229Sdrh 
2529d9cf229Sdrh /*
2530b9f50d8Sdrh ** This routine generates code that will initialize all of the
2540b9f50d8Sdrh ** register used by the autoincrement tracker.
2550b9f50d8Sdrh */
2560b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2570b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2580b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2590b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2600b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2610b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2620b9f50d8Sdrh 
263345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
264345ba7dbSdrh   ** only called from the top-level */
265345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
266c149f18fSdrh   assert( sqlite3IsToplevel(pParse) );
26776d462eeSdan 
2680b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2690b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2701b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
2711b32554bSdrh     static const VdbeOpList autoInc[] = {
2721b32554bSdrh       /* 0  */ {OP_Null,    0,  0, 0},
2731b32554bSdrh       /* 1  */ {OP_Rewind,  0,  9, 0},
2741b32554bSdrh       /* 2  */ {OP_Column,  0,  0, 0},
2751b32554bSdrh       /* 3  */ {OP_Ne,      0,  7, 0},
2761b32554bSdrh       /* 4  */ {OP_Rowid,   0,  0, 0},
2771b32554bSdrh       /* 5  */ {OP_Column,  0,  1, 0},
2781b32554bSdrh       /* 6  */ {OP_Goto,    0,  9, 0},
2791b32554bSdrh       /* 7  */ {OP_Next,    0,  2, 0},
2801b32554bSdrh       /* 8  */ {OP_Integer, 0,  0, 0},
2811b32554bSdrh       /* 9  */ {OP_Close,   0,  0, 0}
2821b32554bSdrh     };
2831b32554bSdrh     VdbeOp *aOp;
2840b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2850b9f50d8Sdrh     memId = p->regCtr;
2862120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2870b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
288076e85f5Sdrh     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
2891b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
2901b32554bSdrh     if( aOp==0 ) break;
2911b32554bSdrh     aOp[0].p2 = memId;
2921b32554bSdrh     aOp[0].p3 = memId+1;
2931b32554bSdrh     aOp[2].p3 = memId;
2941b32554bSdrh     aOp[3].p1 = memId-1;
2951b32554bSdrh     aOp[3].p3 = memId;
2961b32554bSdrh     aOp[3].p5 = SQLITE_JUMPIFNULL;
2971b32554bSdrh     aOp[4].p2 = memId+1;
2981b32554bSdrh     aOp[5].p3 = memId;
2991b32554bSdrh     aOp[8].p2 = memId;
3000b9f50d8Sdrh   }
3010b9f50d8Sdrh }
3020b9f50d8Sdrh 
3030b9f50d8Sdrh /*
3049d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
3059d9cf229Sdrh **
3061b32554bSdrh ** This routine should be called when the regRowid register holds a
3079d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
3089d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
3091b32554bSdrh ** memory cell is updated.
3109d9cf229Sdrh */
3116a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
3129d9cf229Sdrh   if( memId>0 ){
3136a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
3149d9cf229Sdrh   }
3159d9cf229Sdrh }
3169d9cf229Sdrh 
3179d9cf229Sdrh /*
3180b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
3190b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
3200b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
3210b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
3220b9f50d8Sdrh ** routine just before the "exit" code.
3239d9cf229Sdrh */
3241b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
3250b9f50d8Sdrh   AutoincInfo *p;
3269d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
3270b9f50d8Sdrh   sqlite3 *db = pParse->db;
3286a288a33Sdrh 
3299d9cf229Sdrh   assert( v );
3300b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3311b32554bSdrh     static const int iLn = VDBE_OFFSET_LINENO(2);
3321b32554bSdrh     static const VdbeOpList autoIncEnd[] = {
3331b32554bSdrh       /* 0 */ {OP_NotNull,     0, 2, 0},
3341b32554bSdrh       /* 1 */ {OP_NewRowid,    0, 0, 0},
3351b32554bSdrh       /* 2 */ {OP_MakeRecord,  0, 2, 0},
3361b32554bSdrh       /* 3 */ {OP_Insert,      0, 0, 0},
3371b32554bSdrh       /* 4 */ {OP_Close,       0, 0, 0}
3381b32554bSdrh     };
3391b32554bSdrh     VdbeOp *aOp;
3400b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3410b9f50d8Sdrh     int iRec;
3420b9f50d8Sdrh     int memId = p->regCtr;
3430b9f50d8Sdrh 
3440b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3452120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3460b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3471b32554bSdrh     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
3481b32554bSdrh     if( aOp==0 ) break;
3491b32554bSdrh     aOp[0].p1 = memId+1;
3501b32554bSdrh     aOp[1].p2 = memId+1;
3511b32554bSdrh     aOp[2].p1 = memId-1;
3521b32554bSdrh     aOp[2].p3 = iRec;
3531b32554bSdrh     aOp[3].p2 = iRec;
3541b32554bSdrh     aOp[3].p3 = memId+1;
3551b32554bSdrh     aOp[3].p5 = OPFLAG_APPEND;
3560b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3579d9cf229Sdrh   }
3589d9cf229Sdrh }
3591b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){
3601b32554bSdrh   if( pParse->pAinc ) autoIncrementEnd(pParse);
3611b32554bSdrh }
3629d9cf229Sdrh #else
3639d9cf229Sdrh /*
3649d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3659d9cf229Sdrh ** above are all no-ops
3669d9cf229Sdrh */
3679d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
368287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3699d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3709d9cf229Sdrh 
3719d9cf229Sdrh 
3729d9cf229Sdrh /* Forward declaration */
3739d9cf229Sdrh static int xferOptimization(
3749d9cf229Sdrh   Parse *pParse,        /* Parser context */
3759d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
3769d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3779d9cf229Sdrh   int onError,          /* How to handle constraint errors */
3789d9cf229Sdrh   int iDbDest           /* The database of pDest */
3799d9cf229Sdrh );
3809d9cf229Sdrh 
3813d1bfeaaSdanielk1977 /*
382d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
383cce7d176Sdrh **
384a21f78b9Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
3851ccde15dSdrh **    insert into TABLE (IDLIST) select
386a21f78b9Sdrh **    insert into TABLE (IDLIST) default values
387cce7d176Sdrh **
3881ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
389a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted.
390a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
391a21f78b9Sdrh ** is omitted.
3921ccde15dSdrh **
393a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the
394a21f78b9Sdrh ** first two forms shown above.  A VALUES clause is really just short-hand
395a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else
396a21f78b9Sdrh ** that follows.  If the pSelect parameter is NULL, that means that the
397a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended.
398142e30dfSdrh **
3999d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
400a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes
401e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
402e00ee6ebSdrh ** the "1st template"):
403142e30dfSdrh **
404142e30dfSdrh **         open write cursor to <table> and its indices
405ec95c441Sdrh **         put VALUES clause expressions into registers
406142e30dfSdrh **         write the resulting record into <table>
407142e30dfSdrh **         cleanup
408142e30dfSdrh **
4099d9cf229Sdrh ** The three remaining templates assume the statement is of the form
410142e30dfSdrh **
411142e30dfSdrh **   INSERT INTO <table> SELECT ...
412142e30dfSdrh **
4139d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4149d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4159d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4169d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4179d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4189d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4199d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
420e00ee6ebSdrh ** template.  This is the 2nd template.
4219d9cf229Sdrh **
4229d9cf229Sdrh **         open a write cursor to <table>
4239d9cf229Sdrh **         open read cursor on <table2>
4249d9cf229Sdrh **         transfer all records in <table2> over to <table>
4259d9cf229Sdrh **         close cursors
4269d9cf229Sdrh **         foreach index on <table>
4279d9cf229Sdrh **           open a write cursor on the <table> index
4289d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4299d9cf229Sdrh **           transfer all records from the read to the write cursors
4309d9cf229Sdrh **           close cursors
4319d9cf229Sdrh **         end foreach
4329d9cf229Sdrh **
433e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4349d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4359d9cf229Sdrh ** The generated code follows this template:
436142e30dfSdrh **
437e00ee6ebSdrh **         X <- A
438142e30dfSdrh **         goto B
439142e30dfSdrh **      A: setup for the SELECT
4409d9cf229Sdrh **         loop over the rows in the SELECT
441e00ee6ebSdrh **           load values into registers R..R+n
442e00ee6ebSdrh **           yield X
443142e30dfSdrh **         end loop
444142e30dfSdrh **         cleanup after the SELECT
44581cf13ecSdrh **         end-coroutine X
446e00ee6ebSdrh **      B: open write cursor to <table> and its indices
44781cf13ecSdrh **      C: yield X, at EOF goto D
448e00ee6ebSdrh **         insert the select result into <table> from R..R+n
449e00ee6ebSdrh **         goto C
450142e30dfSdrh **      D: cleanup
451142e30dfSdrh **
452e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
453142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
454142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
45560ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of
456142e30dfSdrh ** the select.  The template is like this:
457142e30dfSdrh **
458e00ee6ebSdrh **         X <- A
459142e30dfSdrh **         goto B
460142e30dfSdrh **      A: setup for the SELECT
461142e30dfSdrh **         loop over the tables in the SELECT
462e00ee6ebSdrh **           load value into register R..R+n
463e00ee6ebSdrh **           yield X
464142e30dfSdrh **         end loop
465142e30dfSdrh **         cleanup after the SELECT
46681cf13ecSdrh **         end co-routine R
467e00ee6ebSdrh **      B: open temp table
46881cf13ecSdrh **      L: yield X, at EOF goto M
469e00ee6ebSdrh **         insert row from R..R+n into temp table
470e00ee6ebSdrh **         goto L
471e00ee6ebSdrh **      M: open write cursor to <table> and its indices
472e00ee6ebSdrh **         rewind temp table
473e00ee6ebSdrh **      C: loop over rows of intermediate table
474142e30dfSdrh **           transfer values form intermediate table into <table>
475e00ee6ebSdrh **         end loop
476e00ee6ebSdrh **      D: cleanup
477cce7d176Sdrh */
4784adee20fSdanielk1977 void sqlite3Insert(
479cce7d176Sdrh   Parse *pParse,        /* Parser context */
480113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
4815974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4829cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
4839cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
484cce7d176Sdrh ){
4856a288a33Sdrh   sqlite3 *db;          /* The main database structure */
4866a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
487113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
4885974a30fSdrh   int i, j, idx;        /* Loop counters */
4895974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
4905974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
491967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
4926a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
49326198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
49426198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
495d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
4960ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
497cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
498e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
499e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
5002eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5016a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
50205a86c5cSdrh   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
50305a86c5cSdrh   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
50405a86c5cSdrh   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
505a21f78b9Sdrh   u8 bIdListInOrder;    /* True if IDLIST is in table order */
50675593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
507cce7d176Sdrh 
5086a288a33Sdrh   /* Register allocations */
5091bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5106a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5116a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5126a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5136a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5146a288a33Sdrh   int regData;          /* register holding first column to insert */
515aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5166a288a33Sdrh 
517798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
518798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5192f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5202f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
521798da52cSdrh #endif
522c3f9bad2Sdanielk1977 
52317435752Sdrh   db = pParse->db;
5241bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
52517435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5266f7adc8aSdrh     goto insert_cleanup;
5276f7adc8aSdrh   }
528daffd0e5Sdrh 
52975593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
530a21f78b9Sdrh   ** single row (the common case) then keep that one row of values
531a21f78b9Sdrh   ** and discard the other (unused) parts of the pSelect object
53275593d96Sdrh   */
53375593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
53475593d96Sdrh     pList = pSelect->pEList;
53575593d96Sdrh     pSelect->pEList = 0;
53675593d96Sdrh     sqlite3SelectDelete(db, pSelect);
53775593d96Sdrh     pSelect = 0;
53875593d96Sdrh   }
53975593d96Sdrh 
5401ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5411ccde15dSdrh   */
542113088ecSdrh   assert( pTabList->nSrc==1 );
543113088ecSdrh   zTab = pTabList->a[0].zName;
544098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5454adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
546c3f9bad2Sdanielk1977   if( pTab==0 ){
547c3f9bad2Sdanielk1977     goto insert_cleanup;
548c3f9bad2Sdanielk1977   }
549da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
550da184236Sdanielk1977   assert( iDb<db->nDb );
551a0daa751Sdrh   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
552a0daa751Sdrh                        db->aDb[iDb].zDbSName) ){
5531962bda7Sdrh     goto insert_cleanup;
5541962bda7Sdrh   }
555ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
556c3f9bad2Sdanielk1977 
557b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
558b7f9164eSdrh   ** inserted into is a view
559b7f9164eSdrh   */
560b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
5612f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
562b7f9164eSdrh   isView = pTab->pSelect!=0;
563b7f9164eSdrh #else
5642f886d1dSdanielk1977 # define pTrigger 0
5652f886d1dSdanielk1977 # define tmask 0
566b7f9164eSdrh # define isView 0
567b7f9164eSdrh #endif
568b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
569b7f9164eSdrh # undef isView
570b7f9164eSdrh # define isView 0
571b7f9164eSdrh #endif
5722f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
573b7f9164eSdrh 
574f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
575d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
576f573c99bSdrh   */
577b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
578f573c99bSdrh     goto insert_cleanup;
579f573c99bSdrh   }
580f573c99bSdrh 
581d82b5021Sdrh   /* Cannot insert into a read-only table.
582595a523aSdanielk1977   */
583595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
584595a523aSdanielk1977     goto insert_cleanup;
585595a523aSdanielk1977   }
586595a523aSdanielk1977 
5871ccde15dSdrh   /* Allocate a VDBE
5881ccde15dSdrh   */
5894adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
5905974a30fSdrh   if( v==0 ) goto insert_cleanup;
5914794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
5922f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
5931ccde15dSdrh 
5949d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
5959d9cf229Sdrh   /* If the statement is of the form
5969d9cf229Sdrh   **
5979d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
5989d9cf229Sdrh   **
5999d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6009d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
601e00ee6ebSdrh   **
602e00ee6ebSdrh   ** This is the 2nd template.
6039d9cf229Sdrh   */
6049d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6052f886d1dSdanielk1977     assert( !pTrigger );
6069d9cf229Sdrh     assert( pList==0 );
6070b9f50d8Sdrh     goto insert_end;
6089d9cf229Sdrh   }
6099d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6109d9cf229Sdrh 
6112958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6126a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6132958a4e6Sdrh   */
6146a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6152958a4e6Sdrh 
61605a86c5cSdrh   /* Allocate registers for holding the rowid of the new row,
61760ec914cSpeter.d.reid   ** the content of the new row, and the assembled row record.
6181ccde15dSdrh   */
61905a86c5cSdrh   regRowid = regIns = pParse->nMem+1;
62005a86c5cSdrh   pParse->nMem += pTab->nCol + 1;
621034ca14fSdanielk1977   if( IsVirtual(pTab) ){
62205a86c5cSdrh     regRowid++;
62305a86c5cSdrh     pParse->nMem++;
624034ca14fSdanielk1977   }
62505a86c5cSdrh   regData = regRowid+1;
6261ccde15dSdrh 
6271ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6281ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6291ccde15dSdrh   ** remember the column indices.
630c8392586Sdrh   **
631c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
632d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
633d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
634c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
635d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
636d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
6371ccde15dSdrh   */
638a21f78b9Sdrh   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
639967e8b73Sdrh   if( pColumn ){
640967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
641967e8b73Sdrh       pColumn->a[i].idx = -1;
642cce7d176Sdrh     }
643967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
644cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6454adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
646967e8b73Sdrh           pColumn->a[i].idx = j;
64705a86c5cSdrh           if( i!=j ) bIdListInOrder = 0;
6484a32431cSdrh           if( j==pTab->iPKey ){
649d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
6504a32431cSdrh           }
651cce7d176Sdrh           break;
652cce7d176Sdrh         }
653cce7d176Sdrh       }
654cce7d176Sdrh       if( j>=pTab->nCol ){
655ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
656d82b5021Sdrh           ipkColumn = i;
657e48ae715Sdrh           bIdListInOrder = 0;
658a0217ba7Sdrh         }else{
6594adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
660da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
6611db95106Sdan           pParse->checkSchema = 1;
662cce7d176Sdrh           goto insert_cleanup;
663cce7d176Sdrh         }
664cce7d176Sdrh       }
665cce7d176Sdrh     }
666a0217ba7Sdrh   }
6671ccde15dSdrh 
668cce7d176Sdrh   /* Figure out how many columns of data are supplied.  If the data
669cce7d176Sdrh   ** is coming from a SELECT statement, then generate a co-routine that
670cce7d176Sdrh   ** produces a single row of the SELECT on each invocation.  The
671cce7d176Sdrh   ** co-routine is the common header to the 3rd and 4th templates.
672cce7d176Sdrh   */
6735f085269Sdrh   if( pSelect ){
674a21f78b9Sdrh     /* Data is coming from a SELECT or from a multi-row VALUES clause.
675a21f78b9Sdrh     ** Generate a co-routine to run the SELECT. */
67605a86c5cSdrh     int regYield;       /* Register holding co-routine entry-point */
67705a86c5cSdrh     int addrTop;        /* Top of the co-routine */
67805a86c5cSdrh     int rc;             /* Result code */
679cce7d176Sdrh 
68005a86c5cSdrh     regYield = ++pParse->nMem;
68105a86c5cSdrh     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
68205a86c5cSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
68305a86c5cSdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
68405a86c5cSdrh     dest.iSdst = bIdListInOrder ? regData : 0;
68505a86c5cSdrh     dest.nSdst = pTab->nCol;
68605a86c5cSdrh     rc = sqlite3Select(pParse, pSelect, &dest);
6872b596da8Sdrh     regFromSelect = dest.iSdst;
688992590beSdrh     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
6892fade2f7Sdrh     sqlite3VdbeEndCoroutine(v, regYield);
69005a86c5cSdrh     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
691cce7d176Sdrh     assert( pSelect->pEList );
692cce7d176Sdrh     nColumn = pSelect->pEList->nExpr;
693cce7d176Sdrh 
694cce7d176Sdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
695cce7d176Sdrh     ** should be written into a temporary table (template 4).  Set to
696cce7d176Sdrh     ** FALSE if each output row of the SELECT can be written directly into
697cce7d176Sdrh     ** the destination table (template 3).
698cce7d176Sdrh     **
699cce7d176Sdrh     ** A temp table must be used if the table being updated is also one
700cce7d176Sdrh     ** of the tables being read by the SELECT statement.  Also use a
701cce7d176Sdrh     ** temp table in the case of row triggers.
702cce7d176Sdrh     */
70305a86c5cSdrh     if( pTrigger || readsTable(pParse, iDb, pTab) ){
704cce7d176Sdrh       useTempTable = 1;
705cce7d176Sdrh     }
706cce7d176Sdrh 
707cce7d176Sdrh     if( useTempTable ){
708cce7d176Sdrh       /* Invoke the coroutine to extract information from the SELECT
709cce7d176Sdrh       ** and add it to a transient table srcTab.  The code generated
710cce7d176Sdrh       ** here is from the 4th template:
711cce7d176Sdrh       **
712cce7d176Sdrh       **      B: open temp table
71381cf13ecSdrh       **      L: yield X, goto M at EOF
714cce7d176Sdrh       **         insert row from R..R+n into temp table
715cce7d176Sdrh       **         goto L
716cce7d176Sdrh       **      M: ...
717cce7d176Sdrh       */
718cce7d176Sdrh       int regRec;          /* Register to hold packed record */
719cce7d176Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
72006280ee5Sdrh       int addrL;           /* Label "L" */
721cce7d176Sdrh 
722cce7d176Sdrh       srcTab = pParse->nTab++;
723cce7d176Sdrh       regRec = sqlite3GetTempReg(pParse);
724cce7d176Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
725cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
72606280ee5Sdrh       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
727cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
728cce7d176Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
729cce7d176Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
730076e85f5Sdrh       sqlite3VdbeGoto(v, addrL);
73106280ee5Sdrh       sqlite3VdbeJumpHere(v, addrL);
732cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
733cce7d176Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
734cce7d176Sdrh     }
735cce7d176Sdrh   }else{
736a21f78b9Sdrh     /* This is the case if the data for the INSERT is coming from a
737a21f78b9Sdrh     ** single-row VALUES clause
738cce7d176Sdrh     */
739cce7d176Sdrh     NameContext sNC;
740cce7d176Sdrh     memset(&sNC, 0, sizeof(sNC));
741cce7d176Sdrh     sNC.pParse = pParse;
742cce7d176Sdrh     srcTab = -1;
743cce7d176Sdrh     assert( useTempTable==0 );
744fea870beSdrh     if( pList ){
745fea870beSdrh       nColumn = pList->nExpr;
746fea870beSdrh       if( sqlite3ResolveExprListNames(&sNC, pList) ){
747cce7d176Sdrh         goto insert_cleanup;
748cce7d176Sdrh       }
749fea870beSdrh     }else{
750fea870beSdrh       nColumn = 0;
751cce7d176Sdrh     }
752cce7d176Sdrh   }
753cce7d176Sdrh 
754aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
755d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
756d82b5021Sdrh   ** column index in the original table definition.
7574a32431cSdrh   */
758147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
759d82b5021Sdrh     ipkColumn = pTab->iPKey;
7604a32431cSdrh   }
7614a32431cSdrh 
762cce7d176Sdrh   /* Make sure the number of columns in the source data matches the number
763cce7d176Sdrh   ** of columns to be inserted into the table.
764cce7d176Sdrh   */
765cce7d176Sdrh   for(i=0; i<pTab->nCol; i++){
766cce7d176Sdrh     nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
767cce7d176Sdrh   }
768cce7d176Sdrh   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
769cce7d176Sdrh     sqlite3ErrorMsg(pParse,
770cce7d176Sdrh        "table %S has %d columns but %d values were supplied",
771cce7d176Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
772cce7d176Sdrh     goto insert_cleanup;
773cce7d176Sdrh   }
774cce7d176Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
775cce7d176Sdrh     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
776cce7d176Sdrh     goto insert_cleanup;
777cce7d176Sdrh   }
778cce7d176Sdrh 
779c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
7801ccde15dSdrh   */
781142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
7826a288a33Sdrh     regRowCount = ++pParse->nMem;
7836a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
784c3f9bad2Sdanielk1977   }
785c3f9bad2Sdanielk1977 
786e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
787e448dc4aSdanielk1977   if( !isView ){
788aa9b8963Sdrh     int nIdx;
789fd261ec6Sdan     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
79026198bb4Sdrh                                       &iDataCur, &iIdxCur);
791575fad65Sdrh     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
792aa9b8963Sdrh     if( aRegIdx==0 ){
793aa9b8963Sdrh       goto insert_cleanup;
794aa9b8963Sdrh     }
795aa9b8963Sdrh     for(i=0; i<nIdx; i++){
796aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
797aa9b8963Sdrh     }
798feeb1394Sdrh   }
799feeb1394Sdrh 
800e00ee6ebSdrh   /* This is the top of the main insertion loop */
801142e30dfSdrh   if( useTempTable ){
802e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
803e00ee6ebSdrh     ** following pseudocode (template 4):
804e00ee6ebSdrh     **
80581cf13ecSdrh     **         rewind temp table, if empty goto D
806e00ee6ebSdrh     **      C: loop over rows of intermediate table
807e00ee6ebSdrh     **           transfer values form intermediate table into <table>
808e00ee6ebSdrh     **         end loop
809e00ee6ebSdrh     **      D: ...
810e00ee6ebSdrh     */
811688852abSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
812e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
813142e30dfSdrh   }else if( pSelect ){
814e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
815e00ee6ebSdrh     ** following pseudocode (template 3):
816e00ee6ebSdrh     **
81781cf13ecSdrh     **      C: yield X, at EOF goto D
818e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
819e00ee6ebSdrh     **         goto C
820e00ee6ebSdrh     **      D: ...
821e00ee6ebSdrh     */
82281cf13ecSdrh     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
823688852abSdrh     VdbeCoverage(v);
824bed8690fSdrh   }
8251ccde15dSdrh 
8265cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
82770ce3f0cSdrh   */
8284adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8292f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
83076d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
831c3f9bad2Sdanielk1977 
83270ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
83370ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
83470ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
83570ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
83670ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
83770ce3f0cSdrh     */
838d82b5021Sdrh     if( ipkColumn<0 ){
83976d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
84070ce3f0cSdrh     }else{
841728e0f91Sdrh       int addr1;
842ec95c441Sdrh       assert( !withoutRowid );
8437fe45908Sdrh       if( useTempTable ){
844d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
8457fe45908Sdrh       }else{
846d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
847d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
8487fe45908Sdrh       }
849728e0f91Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
85076d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
851728e0f91Sdrh       sqlite3VdbeJumpHere(v, addr1);
852688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
85370ce3f0cSdrh     }
85470ce3f0cSdrh 
855034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
856034ca14fSdanielk1977     ** this block would have to account for hidden column.
857034ca14fSdanielk1977     */
858034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
859034ca14fSdanielk1977 
86070ce3f0cSdrh     /* Create the new column data
86170ce3f0cSdrh     */
862b1daa3f4Sdrh     for(i=j=0; i<pTab->nCol; i++){
863b1daa3f4Sdrh       if( pColumn ){
864c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
865c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
866c3f9bad2Sdanielk1977         }
867c3f9bad2Sdanielk1977       }
868b1daa3f4Sdrh       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
86903d69a68Sdrh             || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
87076d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
871142e30dfSdrh       }else if( useTempTable ){
87276d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
873c3f9bad2Sdanielk1977       }else{
874d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
87576d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
876c3f9bad2Sdanielk1977       }
87703d69a68Sdrh       if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
878c3f9bad2Sdanielk1977     }
879a37cdde0Sdanielk1977 
880a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
881a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
882a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
883a37cdde0Sdanielk1977     ** table column affinities.
884a37cdde0Sdanielk1977     */
885a37cdde0Sdanielk1977     if( !isView ){
88657bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regCols+1);
887a37cdde0Sdanielk1977     }
888c3f9bad2Sdanielk1977 
8895cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
890165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
89194d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
892165921a7Sdan 
89376d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89470ce3f0cSdrh   }
895c3f9bad2Sdanielk1977 
896d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
897d82b5021Sdrh   ** registers beginning at regIns.
8981ccde15dSdrh   */
8995cf590c1Sdrh   if( !isView ){
9004cbdda9eSdrh     if( IsVirtual(pTab) ){
9014cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9026a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9034cbdda9eSdrh     }
904d82b5021Sdrh     if( ipkColumn>=0 ){
905142e30dfSdrh       if( useTempTable ){
906d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
907142e30dfSdrh       }else if( pSelect ){
90805a86c5cSdrh         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
9094a32431cSdrh       }else{
910e4d90813Sdrh         VdbeOp *pOp;
911d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
91220411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9131b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
914e4d90813Sdrh           appendFlag = 1;
915e4d90813Sdrh           pOp->opcode = OP_NewRowid;
91626198bb4Sdrh           pOp->p1 = iDataCur;
9176a288a33Sdrh           pOp->p2 = regRowid;
9186a288a33Sdrh           pOp->p3 = regAutoinc;
919e4d90813Sdrh         }
92027a32783Sdrh       }
921f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
922e1e68f49Sdrh       ** to generate a unique primary key value.
923e1e68f49Sdrh       */
924e4d90813Sdrh       if( !appendFlag ){
925728e0f91Sdrh         int addr1;
926bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
927728e0f91Sdrh           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
92826198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
929728e0f91Sdrh           sqlite3VdbeJumpHere(v, addr1);
930bb50e7adSdanielk1977         }else{
931728e0f91Sdrh           addr1 = sqlite3VdbeCurrentAddr(v);
932728e0f91Sdrh           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
933bb50e7adSdanielk1977         }
934688852abSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
935e4d90813Sdrh       }
936ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9376a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9384a32431cSdrh     }else{
93926198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
940e4d90813Sdrh       appendFlag = 1;
9414a32431cSdrh     }
9426a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9434a32431cSdrh 
944d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
9454a32431cSdrh     ** with the first column.
9464a32431cSdrh     */
947034ca14fSdanielk1977     nHidden = 0;
948cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9496a288a33Sdrh       int iRegStore = regRowid+1+i;
9504a32431cSdrh       if( i==pTab->iPKey ){
9514a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
952d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
953d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
95405a86c5cSdrh         ** taking up data space with information that will never be used.
95505a86c5cSdrh         ** As there may be shallow copies of this value, make it a soft-NULL */
95605a86c5cSdrh         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
9574a32431cSdrh         continue;
9584a32431cSdrh       }
959967e8b73Sdrh       if( pColumn==0 ){
960034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
961034ca14fSdanielk1977           j = -1;
962034ca14fSdanielk1977           nHidden++;
963034ca14fSdanielk1977         }else{
964034ca14fSdanielk1977           j = i - nHidden;
965034ca14fSdanielk1977         }
966cce7d176Sdrh       }else{
967967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
968967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
969cce7d176Sdrh         }
970cce7d176Sdrh       }
971034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
97205a86c5cSdrh         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
973142e30dfSdrh       }else if( useTempTable ){
974287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
975142e30dfSdrh       }else if( pSelect ){
97605a86c5cSdrh         if( regFromSelect!=regData ){
977b7654111Sdrh           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
97805a86c5cSdrh         }
979cce7d176Sdrh       }else{
980287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
981cce7d176Sdrh       }
982cce7d176Sdrh     }
9831ccde15dSdrh 
9840ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
9850ca3e24bSdrh     ** do the insertion.
9864a32431cSdrh     */
9874cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
9884cbdda9eSdrh     if( IsVirtual(pTab) ){
989595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
9904f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
991595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
992b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
993e0af83acSdan       sqlite3MayAbort(pParse);
9944cbdda9eSdrh     }else
9954cbdda9eSdrh #endif
9964cbdda9eSdrh     {
997de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
9983b908d41Sdan       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
999f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1000bdb00225Sdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
100104adf416Sdrh       );
10028ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
10033b908d41Sdan 
10043b908d41Sdan       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
10053b908d41Sdan       ** constraints or (b) there are no triggers and this table is not a
10063b908d41Sdan       ** parent table in a foreign key constraint. It is safe to set the
10073b908d41Sdan       ** flag in the second case as if any REPLACE constraint is hit, an
10083b908d41Sdan       ** OP_Delete or OP_IdxDelete instruction will be executed on each
10093b908d41Sdan       ** cursor that is disturbed. And these instructions both clear the
10103b908d41Sdan       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
10113b908d41Sdan       ** functionality.  */
10123b908d41Sdan       bUseSeek = (isReplace==0 || (pTrigger==0 &&
10133b908d41Sdan           ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
10143b908d41Sdan       ));
101526198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
10163b908d41Sdan           regIns, aRegIdx, 0, appendFlag, bUseSeek
10173b908d41Sdan       );
10185cf590c1Sdrh     }
10194cbdda9eSdrh   }
10201bee3d7bSdrh 
1021feeb1394Sdrh   /* Update the count of rows that are inserted
10221bee3d7bSdrh   */
1023142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10246a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10251bee3d7bSdrh   }
1026c3f9bad2Sdanielk1977 
10272f886d1dSdanielk1977   if( pTrigger ){
1028c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1029165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
103094d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1031c3f9bad2Sdanielk1977   }
10321bee3d7bSdrh 
1033e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1034e00ee6ebSdrh   ** is a SELECT statement.
10351ccde15dSdrh   */
10364adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1037142e30dfSdrh   if( useTempTable ){
1038688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1039e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10402eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1041142e30dfSdrh   }else if( pSelect ){
1042076e85f5Sdrh     sqlite3VdbeGoto(v, addrCont);
1043e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10446b56344dSdrh   }
1045c3f9bad2Sdanielk1977 
1046e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1047c3f9bad2Sdanielk1977     /* Close all tables opened */
104826198bb4Sdrh     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
104926198bb4Sdrh     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
105026198bb4Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
1051cce7d176Sdrh     }
1052c3f9bad2Sdanielk1977   }
1053c3f9bad2Sdanielk1977 
10540b9f50d8Sdrh insert_end:
1055f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10560b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10570b9f50d8Sdrh   ** autoincrement tables.
10582958a4e6Sdrh   */
1059165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10600b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10610b9f50d8Sdrh   }
10622958a4e6Sdrh 
10631bee3d7bSdrh   /*
1064e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1065e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1066e7de6f25Sdanielk1977   ** invoke the callback function.
10671bee3d7bSdrh   */
1068165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
10696a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
107022322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
107110fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
10721bee3d7bSdrh   }
1073cce7d176Sdrh 
1074cce7d176Sdrh insert_cleanup:
1075633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1076633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1077633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1078633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1079633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1080cce7d176Sdrh }
10819cfcf5d4Sdrh 
108275cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
108360ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
108475cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
108575cbd984Sdan #ifdef isView
108675cbd984Sdan  #undef isView
108775cbd984Sdan #endif
108875cbd984Sdan #ifdef pTrigger
108975cbd984Sdan  #undef pTrigger
109075cbd984Sdan #endif
109175cbd984Sdan #ifdef tmask
109275cbd984Sdan  #undef tmask
109375cbd984Sdan #endif
109475cbd984Sdan 
10959cfcf5d4Sdrh /*
109698bfa16dSdrh ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
109798bfa16dSdrh */
109898bfa16dSdrh #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
109998bfa16dSdrh #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
110098bfa16dSdrh 
11012a0b527bSdrh /* This is the Walker callback from checkConstraintUnchanged().  Set
110298bfa16dSdrh ** bit 0x01 of pWalker->eCode if
11032a0b527bSdrh ** pWalker->eCode to 0 if this expression node references any of the
11042a0b527bSdrh ** columns that are being modifed by an UPDATE statement.
11052a0b527bSdrh */
11062a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
110798bfa16dSdrh   if( pExpr->op==TK_COLUMN ){
110898bfa16dSdrh     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
110998bfa16dSdrh     if( pExpr->iColumn>=0 ){
111098bfa16dSdrh       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
111198bfa16dSdrh         pWalker->eCode |= CKCNSTRNT_COLUMN;
111298bfa16dSdrh       }
111398bfa16dSdrh     }else{
111498bfa16dSdrh       pWalker->eCode |= CKCNSTRNT_ROWID;
111598bfa16dSdrh     }
11162a0b527bSdrh   }
11172a0b527bSdrh   return WRC_Continue;
11182a0b527bSdrh }
11192a0b527bSdrh 
11202a0b527bSdrh /*
11212a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
11222a0b527bSdrh ** only columns that are modified by the UPDATE are those for which
112398bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
112498bfa16dSdrh **
112598bfa16dSdrh ** Return true if CHECK constraint pExpr does not use any of the
112698bfa16dSdrh ** changing columns (or the rowid if it is changing).  In other words,
112798bfa16dSdrh ** return true if this CHECK constraint can be skipped when validating
112898bfa16dSdrh ** the new row in the UPDATE statement.
11292a0b527bSdrh */
113098bfa16dSdrh static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
11312a0b527bSdrh   Walker w;
11322a0b527bSdrh   memset(&w, 0, sizeof(w));
113398bfa16dSdrh   w.eCode = 0;
11342a0b527bSdrh   w.xExprCallback = checkConstraintExprNode;
11352a0b527bSdrh   w.u.aiCol = aiChng;
11362a0b527bSdrh   sqlite3WalkExpr(&w, pExpr);
113705723a9eSdrh   if( !chngRowid ){
113805723a9eSdrh     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
113905723a9eSdrh     w.eCode &= ~CKCNSTRNT_ROWID;
114005723a9eSdrh   }
114105723a9eSdrh   testcase( w.eCode==0 );
114205723a9eSdrh   testcase( w.eCode==CKCNSTRNT_COLUMN );
114305723a9eSdrh   testcase( w.eCode==CKCNSTRNT_ROWID );
114405723a9eSdrh   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
114598bfa16dSdrh   return !w.eCode;
11462a0b527bSdrh }
11472a0b527bSdrh 
114811e85273Sdrh /*
11496934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
11506934fc7bSdrh ** on table pTab.
11519cfcf5d4Sdrh **
11526934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
11536934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
11546934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
11556934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
11566934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
11576934fc7bSdrh ** contain the content of the first table column.  The third register will
11586934fc7bSdrh ** contain the content of the second table column.  And so forth.
11590ca3e24bSdrh **
1160f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1161f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1162f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1163f8ffb278Sdrh ** checking regOldData for zero.
11640ca3e24bSdrh **
1165f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1166f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1167f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1168f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
11690ca3e24bSdrh **
1170f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1171f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1172f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1173f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1174f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1175f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
11760ca3e24bSdrh **
11776934fc7bSdrh ** The code generated by this routine will store new index entries into
1178aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1179aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1180aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
11816934fc7bSdrh ** at pTab->pIndex.
11826934fc7bSdrh **
11836934fc7bSdrh ** The caller must have already opened writeable cursors on the main
11846934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
11856934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
11866934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
11876934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
11886934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
11896934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
11909cfcf5d4Sdrh **
11919cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11929cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11931c92853dSdrh ** then the appropriate action is performed.  There are five possible
11941c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11959cfcf5d4Sdrh **
11969cfcf5d4Sdrh **  Constraint type  Action       What Happens
11979cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11981c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
11996934fc7bSdrh **                                sqlite3_step() returns immediately with a
12009cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
12019cfcf5d4Sdrh **
12021c92853dSdrh **  any              ABORT        Back out changes from the current command
12031c92853dSdrh **                                only (do not do a complete rollback) then
12046934fc7bSdrh **                                cause sqlite3_step() to return immediately
12051c92853dSdrh **                                with SQLITE_CONSTRAINT.
12061c92853dSdrh **
12076934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
12081c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
12091c92853dSdrh **                                transaction is not rolled back and any
12106934fc7bSdrh **                                changes to prior rows are retained.
12111c92853dSdrh **
12126934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
12136934fc7bSdrh **                                row is skipped, without throwing an error.
12146934fc7bSdrh **                                Processing continues with the next row.
12156934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
12169cfcf5d4Sdrh **
12179cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
12189cfcf5d4Sdrh **                                value for that column.  If the default value
12199cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
12209cfcf5d4Sdrh **
12219cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
12229cfcf5d4Sdrh **                                being inserted is removed.
12239cfcf5d4Sdrh **
12249cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12259cfcf5d4Sdrh **
12261c92853dSdrh ** Which action to take is determined by the overrideError parameter.
12271c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12281c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12291c92853dSdrh ** for the constraint is used.
12309cfcf5d4Sdrh */
12314adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12329cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
12336934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1234f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
12356934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
123626198bb4Sdrh   int iIdxCur,         /* First index cursor */
12376934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1238f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1239f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1240f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1241de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1242bdb00225Sdrh   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
1243bdb00225Sdrh   int *aiChng          /* column i is unchanged if aiChng[i]<0 */
12449cfcf5d4Sdrh ){
12451b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
12461b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
124711e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
12482938f924Sdrh   sqlite3 *db;         /* Database connection */
1249f8ffb278Sdrh   int i;               /* loop counter */
1250f8ffb278Sdrh   int ix;              /* Index loop counter */
12519cfcf5d4Sdrh   int nCol;            /* Number of columns */
12529cfcf5d4Sdrh   int onError;         /* Conflict resolution strategy */
1253728e0f91Sdrh   int addr1;           /* Address of jump instruction */
12541b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
12556fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
12568d1b82e4Sdrh   int ipkTop = 0;      /* Top of the rowid change constraint check */
12578d1b82e4Sdrh   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
12588d1b82e4Sdrh   u8 isUpdate;         /* True if this is an UPDATE operation */
125957bf4a8eSdrh   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
12605426d809Sdrh   int regRowid = -1;   /* Register holding ROWID value */
12619cfcf5d4Sdrh 
1262f8ffb278Sdrh   isUpdate = regOldData!=0;
12632938f924Sdrh   db = pParse->db;
12644adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12659cfcf5d4Sdrh   assert( v!=0 );
1266417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12679cfcf5d4Sdrh   nCol = pTab->nCol;
1268aa9b8963Sdrh 
12696934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
12706934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
12716934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
12726934fc7bSdrh   ** number of fields in the true primary key of the table. */
127326198bb4Sdrh   if( HasRowid(pTab) ){
127426198bb4Sdrh     pPk = 0;
127526198bb4Sdrh     nPkField = 1;
127626198bb4Sdrh   }else{
127726198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
127826198bb4Sdrh     nPkField = pPk->nKeyCol;
127926198bb4Sdrh   }
12806fbe41acSdrh 
12816fbe41acSdrh   /* Record that this module has started */
12826fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
12836934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
12849cfcf5d4Sdrh 
12859cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12869cfcf5d4Sdrh   */
12879cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12880ca3e24bSdrh     if( i==pTab->iPKey ){
1289bdb00225Sdrh       continue;        /* ROWID is never NULL */
1290bdb00225Sdrh     }
1291bdb00225Sdrh     if( aiChng && aiChng[i]<0 ){
1292bdb00225Sdrh       /* Don't bother checking for NOT NULL on columns that do not change */
12930ca3e24bSdrh       continue;
12940ca3e24bSdrh     }
12959cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
1296bdb00225Sdrh     if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
12979cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12989cfcf5d4Sdrh       onError = overrideError;
1299a996e477Sdrh     }else if( onError==OE_Default ){
1300a996e477Sdrh       onError = OE_Abort;
13019cfcf5d4Sdrh     }
13027977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
13039cfcf5d4Sdrh       onError = OE_Abort;
13049cfcf5d4Sdrh     }
1305b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1306b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
13079cfcf5d4Sdrh     switch( onError ){
13081c92853dSdrh       case OE_Abort:
1309e0af83acSdan         sqlite3MayAbort(pParse);
13100978d4ffSdrh         /* Fall through */
1311e0af83acSdan       case OE_Rollback:
13121c92853dSdrh       case OE_Fail: {
1313f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1314f9c8ce3cSdrh                                     pTab->aCol[i].zName);
1315f9c8ce3cSdrh         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1316f9c8ce3cSdrh                           regNewData+1+i, zMsg, P4_DYNAMIC);
1317f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1318688852abSdrh         VdbeCoverage(v);
13199cfcf5d4Sdrh         break;
13209cfcf5d4Sdrh       }
13219cfcf5d4Sdrh       case OE_Ignore: {
13226934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
1323688852abSdrh         VdbeCoverage(v);
13249cfcf5d4Sdrh         break;
13259cfcf5d4Sdrh       }
1326098d1684Sdrh       default: {
1327098d1684Sdrh         assert( onError==OE_Replace );
1328728e0f91Sdrh         addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
1329728e0f91Sdrh            VdbeCoverage(v);
13306934fc7bSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
1331728e0f91Sdrh         sqlite3VdbeJumpHere(v, addr1);
13329cfcf5d4Sdrh         break;
13339cfcf5d4Sdrh       }
13349cfcf5d4Sdrh     }
13359cfcf5d4Sdrh   }
13369cfcf5d4Sdrh 
13379cfcf5d4Sdrh   /* Test all CHECK constraints
13389cfcf5d4Sdrh   */
1339ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
13402938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
13412938f924Sdrh     ExprList *pCheck = pTab->pCheck;
13426934fc7bSdrh     pParse->ckBase = regNewData+1;
1343aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
13442938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
134505723a9eSdrh       int allOk;
13462a0b527bSdrh       Expr *pExpr = pCheck->a[i].pExpr;
134798bfa16dSdrh       if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
134805723a9eSdrh       allOk = sqlite3VdbeMakeLabel(v);
13492a0b527bSdrh       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
13502e06c67cSdrh       if( onError==OE_Ignore ){
1351076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
1352aa01c7e2Sdrh       }else{
1353f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1354f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
13556dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1356d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1357f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1358f9c8ce3cSdrh                               P5_ConstraintCheck);
1359aa01c7e2Sdrh       }
1360ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1361ffe07b2dSdrh     }
13622938f924Sdrh   }
1363ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13649cfcf5d4Sdrh 
1365f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1366f8ffb278Sdrh   ** exist in the table.
13679cfcf5d4Sdrh   */
13686fbe41acSdrh   if( pkChng && pPk==0 ){
136911e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
137011e85273Sdrh 
1371f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
13720ca3e24bSdrh     onError = pTab->keyConf;
13730ca3e24bSdrh     if( overrideError!=OE_Default ){
13740ca3e24bSdrh       onError = overrideError;
1375a996e477Sdrh     }else if( onError==OE_Default ){
1376a996e477Sdrh       onError = OE_Abort;
13770ca3e24bSdrh     }
1378a0217ba7Sdrh 
137979b0c956Sdrh     if( isUpdate ){
1380f8ffb278Sdrh       /* pkChng!=0 does not mean that the rowid has change, only that
1381f8ffb278Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1382f8ffb278Sdrh       ** is unchanged. */
13836934fc7bSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
13843d77dee9Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1385688852abSdrh       VdbeCoverage(v);
138679b0c956Sdrh     }
1387f8ffb278Sdrh 
13888d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
13898d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
13908d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
13918d1b82e4Sdrh     ** the UNIQUE constraints have run.
13928d1b82e4Sdrh     */
13938d1b82e4Sdrh     if( onError==OE_Replace && overrideError!=OE_Replace ){
13948d1b82e4Sdrh       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
13958d1b82e4Sdrh         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
13968d1b82e4Sdrh           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
13978d1b82e4Sdrh           break;
13988d1b82e4Sdrh         }
13998d1b82e4Sdrh       }
14008d1b82e4Sdrh     }
14018d1b82e4Sdrh 
1402f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1403f8ffb278Sdrh     ** the following conflict logic if it does not. */
14046934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1405688852abSdrh     VdbeCoverage(v);
1406f8ffb278Sdrh 
1407f8ffb278Sdrh     /* Generate code that deals with a rowid collision */
14080ca3e24bSdrh     switch( onError ){
1409a0217ba7Sdrh       default: {
1410a0217ba7Sdrh         onError = OE_Abort;
1411a0217ba7Sdrh         /* Fall thru into the next case */
1412a0217ba7Sdrh       }
14131c92853dSdrh       case OE_Rollback:
14141c92853dSdrh       case OE_Abort:
14151c92853dSdrh       case OE_Fail: {
1416f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
14170ca3e24bSdrh         break;
14180ca3e24bSdrh       }
14195383ae5cSdrh       case OE_Replace: {
14202283d46cSdan         /* If there are DELETE triggers on this table and the
14212283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1422d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
14232283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
14242283d46cSdan         **
14252283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1426da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1427da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1428da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1429da730f6eSdan         ** when it is inserted.
1430da730f6eSdan         **
1431da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1432da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1433da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1434da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1435da730f6eSdan         ** but being more selective here allows statements like:
1436da730f6eSdan         **
1437da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1438da730f6eSdan         **
1439da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1440da730f6eSdan         ** table.
1441da730f6eSdan         */
14422283d46cSdan         Trigger *pTrigger = 0;
14432938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14442283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14452283d46cSdan         }
1446e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1447da730f6eSdan           sqlite3MultiWrite(pParse);
144826198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1449438b8815Sdan                                    regNewData, 1, 0, OE_Replace, 1, -1);
145046c47d46Sdan         }else{
14519b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1452cbf1b8efSdrh           if( HasRowid(pTab) ){
145346c47d46Sdan             /* This OP_Delete opcode fires the pre-update-hook only. It does
145446c47d46Sdan             ** not modify the b-tree. It is more efficient to let the coming
145546c47d46Sdan             ** OP_Insert replace the existing entry than it is to delete the
145646c47d46Sdan             ** existing entry and then insert a new one. */
1457cbf1b8efSdrh             sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
1458319eeb7bSdan             sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
1459cbf1b8efSdrh           }
14609b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
146146c47d46Sdan           if( pTab->pIndex ){
1462da730f6eSdan             sqlite3MultiWrite(pParse);
1463f0ee1d3cSdan             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
14642283d46cSdan           }
146546c47d46Sdan         }
14665383ae5cSdrh         seenReplace = 1;
14675383ae5cSdrh         break;
14685383ae5cSdrh       }
14690ca3e24bSdrh       case OE_Ignore: {
14708d1b82e4Sdrh         /*assert( seenReplace==0 );*/
1471076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
14720ca3e24bSdrh         break;
14730ca3e24bSdrh       }
14740ca3e24bSdrh     }
147511e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
14768d1b82e4Sdrh     if( ipkTop ){
14778d1b82e4Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
14788d1b82e4Sdrh       sqlite3VdbeJumpHere(v, ipkTop);
1479a05a722fSdrh     }
14800ca3e24bSdrh   }
14810bd1f4eaSdrh 
14820bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
14830bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
148411e85273Sdrh   ** Compute the revised record entries for indices as we go.
1485f8ffb278Sdrh   **
1486f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1487f8ffb278Sdrh   ** WITHOUT ROWID table.
14880bd1f4eaSdrh   */
148926198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
14906934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
14916934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
14926934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
14936934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
14942184fc75Sdrh 
149526198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
149657bf4a8eSdrh     if( bAffinityDone==0 ){
149757bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regNewData+1);
149857bf4a8eSdrh       bAffinityDone = 1;
149957bf4a8eSdrh     }
15006934fc7bSdrh     iThisCur = iIdxCur+ix;
15016934fc7bSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(v);
1502b2fe7d8cSdrh 
1503f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1504b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
150526198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
15066934fc7bSdrh       pParse->ckBase = regNewData+1;
150772bc8208Sdrh       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1508b2b9d3d7Sdrh                             SQLITE_JUMPIFNULL);
1509b2b9d3d7Sdrh       pParse->ckBase = 0;
1510b2b9d3d7Sdrh     }
1511b2b9d3d7Sdrh 
15126934fc7bSdrh     /* Create a record for this index entry as it should appear after
1513f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1514f8ffb278Sdrh     */
151511e85273Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
15169cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
15176934fc7bSdrh       int iField = pIdx->aiColumn[i];
1518f82b9afcSdrh       int x;
15194b92f98cSdrh       if( iField==XN_EXPR ){
15201f9ca2c8Sdrh         pParse->ckBase = regNewData+1;
15211c75c9d7Sdrh         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
15221f9ca2c8Sdrh         pParse->ckBase = 0;
15231f9ca2c8Sdrh         VdbeComment((v, "%s column %d", pIdx->zName, i));
15241f9ca2c8Sdrh       }else{
15254b92f98cSdrh         if( iField==XN_ROWID || iField==pTab->iPKey ){
15265426d809Sdrh           if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
1527f82b9afcSdrh           x = regNewData;
15285426d809Sdrh           regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
15299cfcf5d4Sdrh         }else{
1530f82b9afcSdrh           x = iField + regNewData + 1;
15319cfcf5d4Sdrh         }
1532fed7ac6fSdrh         sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
1533f82b9afcSdrh         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
15349cfcf5d4Sdrh       }
15351f9ca2c8Sdrh     }
153626198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
153726198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
1538bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1539b2fe7d8cSdrh 
1540f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1541f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1542f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1543f8ffb278Sdrh     ** logic below can all be skipped. */
154400012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1545da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1546da475b8dSdrh       continue;
1547da475b8dSdrh     }
1548f8ffb278Sdrh 
15496934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
15509cfcf5d4Sdrh     onError = pIdx->onError;
1551de630353Sdanielk1977     if( onError==OE_None ){
155226198bb4Sdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
155311e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1554de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1555de630353Sdanielk1977     }
15569cfcf5d4Sdrh     if( overrideError!=OE_Default ){
15579cfcf5d4Sdrh       onError = overrideError;
1558a996e477Sdrh     }else if( onError==OE_Default ){
1559a996e477Sdrh       onError = OE_Abort;
15609cfcf5d4Sdrh     }
15615383ae5cSdrh 
1562b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
156326198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
1564688852abSdrh                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
1565f8ffb278Sdrh 
1566f8ffb278Sdrh     /* Generate code to handle collisions */
1567392ee21dSdrh     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
156846d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
156911e85273Sdrh       if( HasRowid(pTab) ){
15706934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
15710978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
15720978d4ffSdrh         ** is different from old-rowid */
1573f8ffb278Sdrh         if( isUpdate ){
15746934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
15753d77dee9Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1576688852abSdrh           VdbeCoverage(v);
1577f8ffb278Sdrh         }
157826198bb4Sdrh       }else{
1579ccc79f02Sdrh         int x;
158026198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
1581da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
1582a021f121Sdrh         if( pIdx!=pPk ){
158326198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
15844b92f98cSdrh             assert( pPk->aiColumn[i]>=0 );
1585ccc79f02Sdrh             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
158626198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
158726198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
158826198bb4Sdrh                          pTab->aCol[pPk->aiColumn[i]].zName));
158926198bb4Sdrh           }
1590da475b8dSdrh         }
1591da475b8dSdrh         if( isUpdate ){
1592e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1593e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
1594e83267daSdan           ** different from the old.
1595e83267daSdan           **
1596e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1597e83267daSdan           ** of the matched index row are different from the original PRIMARY
1598e83267daSdan           ** KEY values of this row before the update.  */
1599e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1600e83267daSdan           int op = OP_Ne;
160148dd1d8eSdrh           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
1602e83267daSdan 
1603e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
1604e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1605ccc79f02Sdrh             x = pPk->aiColumn[i];
16064b92f98cSdrh             assert( x>=0 );
1607e83267daSdan             if( i==(pPk->nKeyCol-1) ){
1608e83267daSdan               addrJump = addrUniqueOk;
1609e83267daSdan               op = OP_Eq;
161011e85273Sdrh             }
1611e83267daSdan             sqlite3VdbeAddOp4(v, op,
1612e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1613e83267daSdan             );
16143d77dee9Sdrh             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
16153d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Eq);
16163d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Ne);
1617da475b8dSdrh           }
161811e85273Sdrh         }
161926198bb4Sdrh       }
162046d03fcbSdrh     }
1621b2fe7d8cSdrh 
1622b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1623b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1624b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
16259cfcf5d4Sdrh     switch( onError ){
16261c92853dSdrh       case OE_Rollback:
16271c92853dSdrh       case OE_Abort:
16281c92853dSdrh       case OE_Fail: {
1629f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
16309cfcf5d4Sdrh         break;
16319cfcf5d4Sdrh       }
16329cfcf5d4Sdrh       case OE_Ignore: {
1633076e85f5Sdrh         sqlite3VdbeGoto(v, ignoreDest);
16349cfcf5d4Sdrh         break;
16359cfcf5d4Sdrh       }
1636098d1684Sdrh       default: {
16372283d46cSdan         Trigger *pTrigger = 0;
1638098d1684Sdrh         assert( onError==OE_Replace );
16391bea559aSdan         sqlite3MultiWrite(pParse);
16402938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
16412283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
16422283d46cSdan         }
164326198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1644b0264eecSdrh             regR, nPkField, 0, OE_Replace,
1645b0264eecSdrh             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
16460ca3e24bSdrh         seenReplace = 1;
16479cfcf5d4Sdrh         break;
16489cfcf5d4Sdrh       }
16499cfcf5d4Sdrh     }
165011e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
1651392ee21dSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1652392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
16539cfcf5d4Sdrh   }
16548d1b82e4Sdrh   if( ipkTop ){
1655076e85f5Sdrh     sqlite3VdbeGoto(v, ipkTop+1);
16568d1b82e4Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
16579cfcf5d4Sdrh   }
1658de630353Sdanielk1977 
1659de630353Sdanielk1977   *pbMayReplace = seenReplace;
1660ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
16619cfcf5d4Sdrh }
16620ca3e24bSdrh 
16630ca3e24bSdrh /*
16640ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
16654adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
16666934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
166704adf416Sdrh ** rowid and the content to be inserted.
16680ca3e24bSdrh **
1669b419a926Sdrh ** The arguments to this routine should be the same as the first six
16704adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
16710ca3e24bSdrh */
16724adee20fSdanielk1977 void sqlite3CompleteInsertion(
16730ca3e24bSdrh   Parse *pParse,      /* The parser context */
16740ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
167526198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
167626198bb4Sdrh   int iIdxCur,        /* First index cursor */
16776934fc7bSdrh   int regNewData,     /* Range of content */
1678aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
167970ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1680de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1681de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
16820ca3e24bSdrh ){
16836934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
16846934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
16856934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
16866934fc7bSdrh   int regData;        /* Content registers (after the rowid) */
168760ec914cSpeter.d.reid   int regRec;         /* Register holding assembled record for the table */
16886934fc7bSdrh   int i;              /* Loop counter */
168957bf4a8eSdrh   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
16900ca3e24bSdrh 
16914adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
16920ca3e24bSdrh   assert( v!=0 );
1693417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1694b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1695aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
169657bf4a8eSdrh     bAffinityDone = 1;
1697b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1698b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1699688852abSdrh       VdbeCoverage(v);
1700b2b9d3d7Sdrh     }
170126198bb4Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
17026546af14Sdrh     pik_flags = 0;
17036546af14Sdrh     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
170448dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
17054308e348Sdrh       assert( pParse->nested==0 );
17066546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1707de630353Sdanielk1977     }
17089b34abeeSdrh     sqlite3VdbeChangeP5(v, pik_flags);
17090ca3e24bSdrh   }
1710ec95c441Sdrh   if( !HasRowid(pTab) ) return;
17116934fc7bSdrh   regData = regNewData + 1;
1712b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
17131db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
171457bf4a8eSdrh   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
1715da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
17164794f735Sdrh   if( pParse->nested ){
17174794f735Sdrh     pik_flags = 0;
17184794f735Sdrh   }else{
171994eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
172094eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
17214794f735Sdrh   }
1722e4d90813Sdrh   if( appendBias ){
1723e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1724e4d90813Sdrh   }
1725de630353Sdanielk1977   if( useSeekResult ){
1726de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1727de630353Sdanielk1977   }
17286934fc7bSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
172994eb6a14Sdanielk1977   if( !pParse->nested ){
1730319eeb7bSdan     sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
173194eb6a14Sdanielk1977   }
1732b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
17330ca3e24bSdrh }
1734cd44690aSdrh 
1735cd44690aSdrh /*
173626198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
173726198bb4Sdrh ** code to open and initialized those cursors.
1738aa9b8963Sdrh **
173926198bb4Sdrh ** The cursor for the object that contains the complete data (normally
174026198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
174126198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
174226198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
174326198bb4Sdrh **
174426198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
174526198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
174626198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
174726198bb4Sdrh **
174826198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
174926198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
175026198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
175126198bb4Sdrh ** pTab->pIndex list.
1752b6b4b79fSdrh **
1753b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the
1754b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized.
1755cd44690aSdrh */
1756aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1757290c1948Sdrh   Parse *pParse,   /* Parsing context */
1758290c1948Sdrh   Table *pTab,     /* Table to be opened */
175926198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
1760b89aeb6aSdrh   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
176126198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
17626a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
176326198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
176426198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
1765290c1948Sdrh ){
1766cd44690aSdrh   int i;
17674cbdda9eSdrh   int iDb;
17686a53499aSdrh   int iDataCur;
1769cd44690aSdrh   Index *pIdx;
17704cbdda9eSdrh   Vdbe *v;
17714cbdda9eSdrh 
177226198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
1773fd261ec6Sdan   assert( op==OP_OpenWrite || p5==0 );
177426198bb4Sdrh   if( IsVirtual(pTab) ){
1775b6b4b79fSdrh     /* This routine is a no-op for virtual tables. Leave the output
1776b6b4b79fSdrh     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
1777b6b4b79fSdrh     ** can detect if they are used by mistake in the caller. */
177826198bb4Sdrh     return 0;
177926198bb4Sdrh   }
17804cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
17814cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1782cd44690aSdrh   assert( v!=0 );
178326198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
17846a53499aSdrh   iDataCur = iBase++;
17856a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
17866a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
17876a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
17886fbe41acSdrh   }else{
178926198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
17906fbe41acSdrh   }
17916a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
179226198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
179326198bb4Sdrh     int iIdxCur = iBase++;
1794da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
179561441c34Sdan     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
179661441c34Sdan       if( piDataCur ) *piDataCur = iIdxCur;
179761441c34Sdan       p5 = 0;
179861441c34Sdan     }
17996a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
18002ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
18012ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1802b89aeb6aSdrh       sqlite3VdbeChangeP5(v, p5);
180361441c34Sdan       VdbeComment((v, "%s", pIdx->zName));
1804b89aeb6aSdrh     }
18056a53499aSdrh   }
180626198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
180726198bb4Sdrh   return i;
1808cd44690aSdrh }
18099d9cf229Sdrh 
181091c58e23Sdrh 
181191c58e23Sdrh #ifdef SQLITE_TEST
181291c58e23Sdrh /*
181391c58e23Sdrh ** The following global variable is incremented whenever the
181491c58e23Sdrh ** transfer optimization is used.  This is used for testing
181591c58e23Sdrh ** purposes only - to make sure the transfer optimization really
181660ec914cSpeter.d.reid ** is happening when it is supposed to.
181791c58e23Sdrh */
181891c58e23Sdrh int sqlite3_xferopt_count;
181991c58e23Sdrh #endif /* SQLITE_TEST */
182091c58e23Sdrh 
182191c58e23Sdrh 
18229d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
18239d9cf229Sdrh /*
18249d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
18259d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
18269d9cf229Sdrh ** for a compatible index:
18279d9cf229Sdrh **
18289d9cf229Sdrh **    *   The index is over the same set of columns
18299d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
18309d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
18319d9cf229Sdrh **    *   The same collating sequence on each column
1832b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
18339d9cf229Sdrh */
18349d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
18359d9cf229Sdrh   int i;
18369d9cf229Sdrh   assert( pDest && pSrc );
18379d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1838bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
18399d9cf229Sdrh     return 0;   /* Different number of columns */
18409d9cf229Sdrh   }
18419d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
18429d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
18439d9cf229Sdrh   }
1844bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
18459d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
18469d9cf229Sdrh       return 0;   /* Different columns indexed */
18479d9cf229Sdrh     }
18484b92f98cSdrh     if( pSrc->aiColumn[i]==XN_EXPR ){
18491f9ca2c8Sdrh       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
18501f9ca2c8Sdrh       if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
18511f9ca2c8Sdrh                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
18521f9ca2c8Sdrh         return 0;   /* Different expressions in the index */
18531f9ca2c8Sdrh       }
18541f9ca2c8Sdrh     }
18559d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
18569d9cf229Sdrh       return 0;   /* Different sort orders */
18579d9cf229Sdrh     }
18580472af91Sdrh     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
185960a713c6Sdrh       return 0;   /* Different collating sequences */
18609d9cf229Sdrh     }
18619d9cf229Sdrh   }
1862619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1863b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1864b2b9d3d7Sdrh   }
18659d9cf229Sdrh 
18669d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
18679d9cf229Sdrh   return 1;
18689d9cf229Sdrh }
18699d9cf229Sdrh 
18709d9cf229Sdrh /*
18719d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
18729d9cf229Sdrh **
18739d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
18749d9cf229Sdrh **
1875ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
187660ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves
1877ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
18789d9cf229Sdrh **
1879ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1880ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1881ccdf1baeSdrh ** embedded in the code for details.
18829d9cf229Sdrh **
1883ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1884ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1885ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1886ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1887ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1888ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1889ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1890ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1891ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
18929d9cf229Sdrh **
1893ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
18949d9cf229Sdrh */
18959d9cf229Sdrh static int xferOptimization(
18969d9cf229Sdrh   Parse *pParse,        /* Parser context */
18979d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
18989d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
18999d9cf229Sdrh   int onError,          /* How to handle constraint errors */
19009d9cf229Sdrh   int iDbDest           /* The database of pDest */
19019d9cf229Sdrh ){
1902e34162b1Sdan   sqlite3 *db = pParse->db;
19039d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
19049d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
19059d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
19069d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
19079d9cf229Sdrh   int i;                           /* Loop counter */
19089d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
19099d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
19109d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
1911da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
1912da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
19139d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
19146a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1915f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1916b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
19179d9cf229Sdrh 
19189d9cf229Sdrh   if( pSelect==0 ){
19199d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
19209d9cf229Sdrh   }
1921ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
1922ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
1923ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
1924ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
1925ebbf08a0Sdan     return 0;
1926ebbf08a0Sdan   }
19272f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
19289d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
19299d9cf229Sdrh   }
19309d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
19317d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
19329d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
19339d9cf229Sdrh   }
19349d9cf229Sdrh #endif
19359d9cf229Sdrh   if( onError==OE_Default ){
1936e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1937e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
19389d9cf229Sdrh   }
19395ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
19409d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
19419d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
19429d9cf229Sdrh   }
19439d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
19449d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
19459d9cf229Sdrh   }
19469d9cf229Sdrh   if( pSelect->pWhere ){
19479d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
19489d9cf229Sdrh   }
19499d9cf229Sdrh   if( pSelect->pOrderBy ){
19509d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
19519d9cf229Sdrh   }
19528103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
19538103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
19549d9cf229Sdrh   if( pSelect->pGroupBy ){
19559d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
19569d9cf229Sdrh   }
19579d9cf229Sdrh   if( pSelect->pLimit ){
19589d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
19599d9cf229Sdrh   }
19608103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
19619d9cf229Sdrh   if( pSelect->pPrior ){
19629d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
19639d9cf229Sdrh   }
19647d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
19659d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
19669d9cf229Sdrh   }
19679d9cf229Sdrh   pEList = pSelect->pEList;
19689d9cf229Sdrh   assert( pEList!=0 );
19699d9cf229Sdrh   if( pEList->nExpr!=1 ){
19709d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
19719d9cf229Sdrh   }
19729d9cf229Sdrh   assert( pEList->a[0].pExpr );
19731a1d3cd2Sdrh   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
19749d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
19759d9cf229Sdrh   }
19769d9cf229Sdrh 
19779d9cf229Sdrh   /* At this point we have established that the statement is of the
19789d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
19799d9cf229Sdrh   ** we have to check the semantics.
19809d9cf229Sdrh   */
19819d9cf229Sdrh   pItem = pSelect->pSrc->a;
198241fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
19839d9cf229Sdrh   if( pSrc==0 ){
19849d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
19859d9cf229Sdrh   }
19869d9cf229Sdrh   if( pSrc==pDest ){
19879d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
19889d9cf229Sdrh   }
198955548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
199055548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
199155548273Sdrh   }
19929d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
19937d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
19949d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
19959d9cf229Sdrh   }
19969d9cf229Sdrh #endif
19979d9cf229Sdrh   if( pSrc->pSelect ){
19989d9cf229Sdrh     return 0;   /* tab2 may not be a view */
19999d9cf229Sdrh   }
20009d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
20019d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
20029d9cf229Sdrh   }
20039d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
20049d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
20059d9cf229Sdrh   }
20069d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
20079940e2aaSdan     Column *pDestCol = &pDest->aCol[i];
20089940e2aaSdan     Column *pSrcCol = &pSrc->aCol[i];
2009ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
2010aaea3143Sdan     if( (db->flags & SQLITE_Vacuum)==0
2011aaea3143Sdan      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2012aaea3143Sdan     ){
2013ba68f8f3Sdan       return 0;    /* Neither table may have __hidden__ columns */
2014ba68f8f3Sdan     }
2015ba68f8f3Sdan #endif
20169940e2aaSdan     if( pDestCol->affinity!=pSrcCol->affinity ){
20179d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
20189d9cf229Sdrh     }
20190472af91Sdrh     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
20209d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
20219d9cf229Sdrh     }
20229940e2aaSdan     if( pDestCol->notNull && !pSrcCol->notNull ){
20239d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
20249d9cf229Sdrh     }
2025453e0261Sdrh     /* Default values for second and subsequent columns need to match. */
202694fa9c41Sdrh     if( i>0 ){
202794fa9c41Sdrh       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
202894fa9c41Sdrh       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
202994fa9c41Sdrh       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
203094fa9c41Sdrh        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
203194fa9c41Sdrh                                        pSrcCol->pDflt->u.zToken)!=0)
20329940e2aaSdan       ){
20339940e2aaSdan         return 0;    /* Default values must be the same for all columns */
20349940e2aaSdan       }
20359d9cf229Sdrh     }
203694fa9c41Sdrh   }
20379d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
20385f1d1d9cSdrh     if( IsUniqueIndex(pDestIdx) ){
2039f33c9fadSdrh       destHasUniqueIdx = 1;
2040f33c9fadSdrh     }
20419d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
20429d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
20439d9cf229Sdrh     }
20449d9cf229Sdrh     if( pSrcIdx==0 ){
20459d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
20469d9cf229Sdrh     }
20479d9cf229Sdrh   }
20487fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
2049619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
20508103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
20518103b7d2Sdrh   }
20527fc2f41bSdrh #endif
2053713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
2054713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
2055713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
2056713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
2057713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
2058713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
2059713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2060713de341Sdrh   */
2061e34162b1Sdan   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
2062713de341Sdrh     return 0;
2063713de341Sdrh   }
2064713de341Sdrh #endif
2065e34162b1Sdan   if( (db->flags & SQLITE_CountRows)!=0 ){
2066ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
20671696124dSdan   }
20689d9cf229Sdrh 
2069ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
2070ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
2071ccdf1baeSdrh   ** table (tab1) is initially empty.
20729d9cf229Sdrh   */
2073dd73521bSdrh #ifdef SQLITE_TEST
2074dd73521bSdrh   sqlite3_xferopt_count++;
2075dd73521bSdrh #endif
2076e34162b1Sdan   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
20779d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
2078f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
20799d9cf229Sdrh   iSrc = pParse->nTab++;
20809d9cf229Sdrh   iDest = pParse->nTab++;
20816a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
208255548273Sdrh   regData = sqlite3GetTempReg(pParse);
208355548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
20849d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2085427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
2086e34162b1Sdan   if( (db->flags & SQLITE_Vacuum)==0 && (
2087e34162b1Sdan       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2088ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
2089ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2090e34162b1Sdan   )){
2091ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
2092e34162b1Sdan     ** only if the destination table is initially empty. Unless the
2093e34162b1Sdan     ** SQLITE_Vacuum flag is set, this block generates code to make
2094e34162b1Sdan     ** that determination. If SQLITE_Vacuum is set, then the destination
2095e34162b1Sdan     ** table is always empty.
2096e34162b1Sdan     **
2097e34162b1Sdan     ** Conditions under which the destination must be empty:
2098f33c9fadSdrh     **
2099ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2100ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
2101ccdf1baeSdrh     **     of index entries might need to change.)
2102ccdf1baeSdrh     **
2103ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
2104ccdf1baeSdrh     **     is unable to test uniqueness.)
2105ccdf1baeSdrh     **
2106ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
21079d9cf229Sdrh     */
2108688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
21092991ba05Sdrh     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
21109d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
21119d9cf229Sdrh   }
2112427ebba1Sdan   if( HasRowid(pSrc) ){
21139d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
2114688852abSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
211542242dedSdrh     if( pDest->iPKey>=0 ){
2116b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2117b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2118688852abSdrh       VdbeCoverage(v);
2119f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
21209d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
2121b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
2122bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
2123b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
212495bad4c7Sdrh     }else{
2125b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
21267d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
212795bad4c7Sdrh     }
2128b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
21299b34abeeSdrh     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
213020f272c9Sdrh                       (char*)pDest, P4_TABLE);
2131b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
2132688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
213355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
213455548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2135da475b8dSdrh   }else{
2136da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2137da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
213855548273Sdrh   }
21399d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
214041b9ca25Sdrh     u8 idxInsFlags = 0;
21411b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
21429d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
21439d9cf229Sdrh     }
21449d9cf229Sdrh     assert( pSrcIdx );
21452ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
21462ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2147d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
21482ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
21492ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
215059885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2151207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
2152688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2153b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2154e34162b1Sdan     if( db->flags & SQLITE_Vacuum ){
2155e34162b1Sdan       /* This INSERT command is part of a VACUUM operation, which guarantees
2156e34162b1Sdan       ** that the destination table is empty. If all indexed columns use
2157e34162b1Sdan       ** collation sequence BINARY, then it can also be assumed that the
2158e34162b1Sdan       ** index will be populated by inserting keys in strictly sorted
2159e34162b1Sdan       ** order. In this case, instead of seeking within the b-tree as part
2160e34162b1Sdan       ** of every OP_IdxInsert opcode, an OP_Last is added before the
2161e34162b1Sdan       ** OP_IdxInsert to seek to the point within the b-tree where each key
2162e34162b1Sdan       ** should be inserted. This is faster.
2163e34162b1Sdan       **
2164e34162b1Sdan       ** If any of the indexed columns use a collation sequence other than
2165e34162b1Sdan       ** BINARY, this optimization is disabled. This is because the user
2166e34162b1Sdan       ** might change the definition of a collation sequence and then run
2167e34162b1Sdan       ** a VACUUM command. In that case keys may not be written in strictly
2168e34162b1Sdan       ** sorted order.  */
2169e34162b1Sdan       for(i=0; i<pSrcIdx->nColumn; i++){
2170f19aa5faSdrh         const char *zColl = pSrcIdx->azColl[i];
2171f19aa5faSdrh         assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
2172f19aa5faSdrh                     || sqlite3StrBINARY==zColl );
2173f19aa5faSdrh         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
2174e34162b1Sdan       }
2175e34162b1Sdan       if( i==pSrcIdx->nColumn ){
217641b9ca25Sdrh         idxInsFlags = OPFLAG_USESEEKRESULT;
2177e34162b1Sdan         sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
2178e34162b1Sdan       }
2179e34162b1Sdan     }
218041b9ca25Sdrh     if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
218141b9ca25Sdrh       idxInsFlags |= OPFLAG_NCHANGE;
218241b9ca25Sdrh     }
2183*9b4eaebcSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
2184*9b4eaebcSdrh     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
2185688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
21869d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
218755548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
218855548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
21899d9cf229Sdrh   }
2190aceb31b1Sdrh   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2191b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2192b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
21939d9cf229Sdrh   if( emptyDestTest ){
21941dd518cfSdrh     sqlite3AutoincrementEnd(pParse);
219566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
21969d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
219766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
21989d9cf229Sdrh     return 0;
21999d9cf229Sdrh   }else{
22009d9cf229Sdrh     return 1;
22019d9cf229Sdrh   }
22029d9cf229Sdrh }
22039d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2204