xref: /sqlite-3.40.0/src/insert.c (revision 2ec2fb22)
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(
27*2ec2fb22Sdrh   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) );
35*2ec2fb22Sdrh   v = sqlite3GetVdbe(pParse);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
37*2ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
38*2ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
39ec95c441Sdrh   if( HasRowid(pTab) ){
40261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
41dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
4226198bb4Sdrh   }else{
43dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44dd9930efSdrh     assert( pPk!=0 );
45dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
46*2ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
47*2ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
48bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
49bbb5e4e0Sdrh   }
50ec95c441Sdrh }
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 **  ------------------------------
593eda040bSdrh **  'a'            TEXT
603eda040bSdrh **  'b'            NONE
613eda040bSdrh **  'c'            NUMERIC
623eda040bSdrh **  'd'            INTEGER
633eda040bSdrh **  'e'            REAL
642d401ab8Sdrh **
650c733f67Sdan ** 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 */
7269f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, 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;
84abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
85ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
86a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
87633e6d57Sdrh       db->mallocFailed = 1;
8869f8bb9cSdan       return 0;
89a37cdde0Sdanielk1977     }
90ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
91ad124329Sdrh       i16 x = pIdx->aiColumn[n];
92ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
93a37cdde0Sdanielk1977     }
942d401ab8Sdrh     pIdx->zColAff[n] = 0;
95a37cdde0Sdanielk1977   }
963d1bfeaaSdanielk1977 
9769f8bb9cSdan   return pIdx->zColAff;
98a37cdde0Sdanielk1977 }
99a37cdde0Sdanielk1977 
100a37cdde0Sdanielk1977 /*
10166a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
102a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
103a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
104a37cdde0Sdanielk1977 ** column:
105a37cdde0Sdanielk1977 **
106a37cdde0Sdanielk1977 **  Character      Column affinity
107a37cdde0Sdanielk1977 **  ------------------------------
1083eda040bSdrh **  'a'            TEXT
1093eda040bSdrh **  'b'            NONE
1103eda040bSdrh **  'c'            NUMERIC
1113eda040bSdrh **  'd'            INTEGER
1123eda040bSdrh **  'e'            REAL
113a37cdde0Sdanielk1977 */
114a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1153d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1163d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1173d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1183d1bfeaaSdanielk1977   **
1193d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1203d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1213d1bfeaaSdanielk1977   */
1223d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1233d1bfeaaSdanielk1977     char *zColAff;
1243d1bfeaaSdanielk1977     int i;
125abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1263d1bfeaaSdanielk1977 
127b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1283d1bfeaaSdanielk1977     if( !zColAff ){
129633e6d57Sdrh       db->mallocFailed = 1;
130a37cdde0Sdanielk1977       return;
1313d1bfeaaSdanielk1977     }
1323d1bfeaaSdanielk1977 
1333d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
134a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1353d1bfeaaSdanielk1977     }
1363d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1373d1bfeaaSdanielk1977 
1383d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1393d1bfeaaSdanielk1977   }
1403d1bfeaaSdanielk1977 
1418d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1423d1bfeaaSdanielk1977 }
1433d1bfeaaSdanielk1977 
1444d88778bSdanielk1977 /*
14548d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
14648d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
14748d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
14848d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
14948d1178aSdrh ** run without using temporary table for the results of the SELECT.
1504d88778bSdanielk1977 */
151595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
152595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1534d88778bSdanielk1977   int i;
15448d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
155595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
156595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
157595a523aSdanielk1977 #endif
158595a523aSdanielk1977 
15948d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
16048d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
161ef0bea92Sdrh     assert( pOp!=0 );
162207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16348d1178aSdrh       Index *pIndex;
164207872a4Sdanielk1977       int tnum = pOp->p2;
16548d1178aSdrh       if( tnum==pTab->tnum ){
16648d1178aSdrh         return 1;
16748d1178aSdrh       }
16848d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
16948d1178aSdrh         if( tnum==pIndex->tnum ){
17048d1178aSdrh           return 1;
17148d1178aSdrh         }
17248d1178aSdrh       }
17348d1178aSdrh     }
174543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
175595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1762dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
17766a5167bSdrh       assert( pOp->p4type==P4_VTAB );
17848d1178aSdrh       return 1;
1794d88778bSdanielk1977     }
180543165efSdrh #endif
1814d88778bSdanielk1977   }
1824d88778bSdanielk1977   return 0;
1834d88778bSdanielk1977 }
1843d1bfeaaSdanielk1977 
1859d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1869d9cf229Sdrh /*
1870b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1880b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1890b9f50d8Sdrh ** that holds the maximum rowid.
1909d9cf229Sdrh **
1910b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1920b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1930b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1940b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1950b9f50d8Sdrh ** AutoincInfo structure is used.
1969d9cf229Sdrh **
1970b9f50d8Sdrh ** Three memory locations are allocated:
1980b9f50d8Sdrh **
1990b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
2000b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2010b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2020b9f50d8Sdrh **
2030b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2040b9f50d8Sdrh ** insert routine needs to know about.
2059d9cf229Sdrh */
2069d9cf229Sdrh static int autoIncBegin(
2079d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2089d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2099d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2109d9cf229Sdrh ){
2116a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2127d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21365a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2140b9f50d8Sdrh     AutoincInfo *pInfo;
2150b9f50d8Sdrh 
21665a7cd16Sdan     pInfo = pToplevel->pAinc;
2170b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2180b9f50d8Sdrh     if( pInfo==0 ){
2190b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2200b9f50d8Sdrh       if( pInfo==0 ) return 0;
22165a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22265a7cd16Sdan       pToplevel->pAinc = pInfo;
2230b9f50d8Sdrh       pInfo->pTab = pTab;
2240b9f50d8Sdrh       pInfo->iDb = iDb;
22565a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
22665a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
22765a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2280b9f50d8Sdrh     }
2290b9f50d8Sdrh     memId = pInfo->regCtr;
2309d9cf229Sdrh   }
2319d9cf229Sdrh   return memId;
2329d9cf229Sdrh }
2339d9cf229Sdrh 
2349d9cf229Sdrh /*
2350b9f50d8Sdrh ** This routine generates code that will initialize all of the
2360b9f50d8Sdrh ** register used by the autoincrement tracker.
2370b9f50d8Sdrh */
2380b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2390b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2400b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2410b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2420b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2430b9f50d8Sdrh   int addr;                  /* A VDBE address */
2440b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2450b9f50d8Sdrh 
246345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
247345ba7dbSdrh   ** only called from the top-level */
248345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
249345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
25076d462eeSdan 
2510b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2520b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2530b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2540b9f50d8Sdrh     memId = p->regCtr;
2552120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2560b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
257f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2580b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2590b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2600b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2610b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2620b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2630b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2640b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2650b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2660b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2670b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2680b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2690b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2700b9f50d8Sdrh   }
2710b9f50d8Sdrh }
2720b9f50d8Sdrh 
2730b9f50d8Sdrh /*
2749d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2759d9cf229Sdrh **
2769d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2779d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2789d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2799d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2809d9cf229Sdrh */
2816a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2829d9cf229Sdrh   if( memId>0 ){
2836a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2849d9cf229Sdrh   }
2859d9cf229Sdrh }
2869d9cf229Sdrh 
2879d9cf229Sdrh /*
2880b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2890b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2900b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2910b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2920b9f50d8Sdrh ** routine just before the "exit" code.
2939d9cf229Sdrh */
2940b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2950b9f50d8Sdrh   AutoincInfo *p;
2969d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2970b9f50d8Sdrh   sqlite3 *db = pParse->db;
2986a288a33Sdrh 
2999d9cf229Sdrh   assert( v );
3000b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3010b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3020b9f50d8Sdrh     int j1, j2, j3, j4, j5;
3030b9f50d8Sdrh     int iRec;
3040b9f50d8Sdrh     int memId = p->regCtr;
3050b9f50d8Sdrh 
3060b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3072120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3080b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3096a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
3100b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
3110b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
3120b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3130b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3140b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3150b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3160b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3170b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3180b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3196a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3200b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
321a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3220b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
32335573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3240b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3250b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3269d9cf229Sdrh   }
3279d9cf229Sdrh }
3289d9cf229Sdrh #else
3299d9cf229Sdrh /*
3309d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3319d9cf229Sdrh ** above are all no-ops
3329d9cf229Sdrh */
3339d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
334287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3359d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3369d9cf229Sdrh 
3379d9cf229Sdrh 
3385f085269Sdrh /*
3395f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3405f085269Sdrh ** row at a time.
3415f085269Sdrh **
3425f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3435f085269Sdrh ** Information about the location of co-routine and the registers it will use
3445f085269Sdrh ** is returned by filling in the pDest object.
3455f085269Sdrh **
3465f085269Sdrh ** Registers are allocated as follows:
3475f085269Sdrh **
3485f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3495f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3505f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3515f085269Sdrh **
3525f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3535f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3545f085269Sdrh **                       generated a new result row, or 1 if the subquery
3555f085269Sdrh **                       has completed.  If the Yield is called again
3565f085269Sdrh **                       after this register becomes 1, then the VDBE will
3575f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3585f085269Sdrh **
3595f085269Sdrh **   pDest->iSdst        First result register.
3605f085269Sdrh **
3615f085269Sdrh **   pDest->nSdst        Number of result registers.
3625f085269Sdrh **
3635f085269Sdrh ** This routine handles all of the register allocation and fills in the
3645f085269Sdrh ** pDest structure appropriately.
3655f085269Sdrh **
3665f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3675f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3685f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3695f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3705f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3715f085269Sdrh **
3725f085269Sdrh **         X <- A
3735f085269Sdrh **         EOF <- 0
3745f085269Sdrh **         goto B
3755f085269Sdrh **      A: setup for the SELECT
3765f085269Sdrh **         loop rows in the SELECT
3775f085269Sdrh **           load results into registers R..S
3785f085269Sdrh **           yield X
3795f085269Sdrh **         end loop
3805f085269Sdrh **         cleanup after the SELECT
3815f085269Sdrh **         EOF <- 1
3825f085269Sdrh **         yield X
3835f085269Sdrh **         halt-error
3845f085269Sdrh **      B:
3855f085269Sdrh **
3865f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3875f085269Sdrh **
3885f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3895f085269Sdrh **      S: yield X
3905f085269Sdrh **         if EOF goto E
3915f085269Sdrh **         if skip this row, goto C
3925f085269Sdrh **         if terminate loop, goto E
3935f085269Sdrh **         deal with this row
3945f085269Sdrh **      C: goto S
3955f085269Sdrh **      E:
3965f085269Sdrh */
3975f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3985f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3995f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
4005f085269Sdrh   int addrTop;        /* Top of the co-routine */
4015f085269Sdrh   int j1;             /* Jump instruction */
4025f085269Sdrh   int rc;             /* Result code */
4035f085269Sdrh   Vdbe *v;            /* VDBE under construction */
4045f085269Sdrh 
4055f085269Sdrh   regYield = ++pParse->nMem;
4065f085269Sdrh   regEof = ++pParse->nMem;
4075f085269Sdrh   v = sqlite3GetVdbe(pParse);
4085f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
4095f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
4105f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
4115f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
4125f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4135f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4145f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4155f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4165f085269Sdrh   assert( pParse->nErr==0 || rc );
4175f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4185f085269Sdrh   if( rc ) return rc;
4195f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4205f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4215f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4225f085269Sdrh   VdbeComment((v, "End of coroutine"));
4235f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4245f085269Sdrh   return rc;
4255f085269Sdrh }
4265f085269Sdrh 
4275f085269Sdrh 
4285f085269Sdrh 
4299d9cf229Sdrh /* Forward declaration */
4309d9cf229Sdrh static int xferOptimization(
4319d9cf229Sdrh   Parse *pParse,        /* Parser context */
4329d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4339d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4349d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4359d9cf229Sdrh   int iDbDest           /* The database of pDest */
4369d9cf229Sdrh );
4379d9cf229Sdrh 
4383d1bfeaaSdanielk1977 /*
439d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
440cce7d176Sdrh **
441cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4421ccde15dSdrh **    insert into TABLE (IDLIST) select
443cce7d176Sdrh **
4441ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4451ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
446967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4471ccde15dSdrh **
4481ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4491ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4501ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4511ccde15dSdrh ** data for the insert.
452142e30dfSdrh **
4539d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
454d82b5021Sdrh ** insert with data coming from a VALUES clause, the code executes
455e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
456e00ee6ebSdrh ** the "1st template"):
457142e30dfSdrh **
458142e30dfSdrh **         open write cursor to <table> and its indices
459ec95c441Sdrh **         put VALUES clause expressions into registers
460142e30dfSdrh **         write the resulting record into <table>
461142e30dfSdrh **         cleanup
462142e30dfSdrh **
4639d9cf229Sdrh ** The three remaining templates assume the statement is of the form
464142e30dfSdrh **
465142e30dfSdrh **   INSERT INTO <table> SELECT ...
466142e30dfSdrh **
4679d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4689d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4699d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4709d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4719d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4729d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4739d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
474e00ee6ebSdrh ** template.  This is the 2nd template.
4759d9cf229Sdrh **
4769d9cf229Sdrh **         open a write cursor to <table>
4779d9cf229Sdrh **         open read cursor on <table2>
4789d9cf229Sdrh **         transfer all records in <table2> over to <table>
4799d9cf229Sdrh **         close cursors
4809d9cf229Sdrh **         foreach index on <table>
4819d9cf229Sdrh **           open a write cursor on the <table> index
4829d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4839d9cf229Sdrh **           transfer all records from the read to the write cursors
4849d9cf229Sdrh **           close cursors
4859d9cf229Sdrh **         end foreach
4869d9cf229Sdrh **
487e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4889d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4899d9cf229Sdrh ** The generated code follows this template:
490142e30dfSdrh **
491e00ee6ebSdrh **         EOF <- 0
492e00ee6ebSdrh **         X <- A
493142e30dfSdrh **         goto B
494142e30dfSdrh **      A: setup for the SELECT
4959d9cf229Sdrh **         loop over the rows in the SELECT
496e00ee6ebSdrh **           load values into registers R..R+n
497e00ee6ebSdrh **           yield X
498142e30dfSdrh **         end loop
499142e30dfSdrh **         cleanup after the SELECT
500e00ee6ebSdrh **         EOF <- 1
501e00ee6ebSdrh **         yield X
502142e30dfSdrh **         goto A
503e00ee6ebSdrh **      B: open write cursor to <table> and its indices
504e00ee6ebSdrh **      C: yield X
505e00ee6ebSdrh **         if EOF goto D
506e00ee6ebSdrh **         insert the select result into <table> from R..R+n
507e00ee6ebSdrh **         goto C
508142e30dfSdrh **      D: cleanup
509142e30dfSdrh **
510e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
511142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
512142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
513142e30dfSdrh ** we have to use a intermediate table to store the results of
514142e30dfSdrh ** the select.  The template is like this:
515142e30dfSdrh **
516e00ee6ebSdrh **         EOF <- 0
517e00ee6ebSdrh **         X <- A
518142e30dfSdrh **         goto B
519142e30dfSdrh **      A: setup for the SELECT
520142e30dfSdrh **         loop over the tables in the SELECT
521e00ee6ebSdrh **           load value into register R..R+n
522e00ee6ebSdrh **           yield X
523142e30dfSdrh **         end loop
524142e30dfSdrh **         cleanup after the SELECT
525e00ee6ebSdrh **         EOF <- 1
526e00ee6ebSdrh **         yield X
527e00ee6ebSdrh **         halt-error
528e00ee6ebSdrh **      B: open temp table
529e00ee6ebSdrh **      L: yield X
530e00ee6ebSdrh **         if EOF goto M
531e00ee6ebSdrh **         insert row from R..R+n into temp table
532e00ee6ebSdrh **         goto L
533e00ee6ebSdrh **      M: open write cursor to <table> and its indices
534e00ee6ebSdrh **         rewind temp table
535e00ee6ebSdrh **      C: loop over rows of intermediate table
536142e30dfSdrh **           transfer values form intermediate table into <table>
537e00ee6ebSdrh **         end loop
538e00ee6ebSdrh **      D: cleanup
539cce7d176Sdrh */
5404adee20fSdanielk1977 void sqlite3Insert(
541cce7d176Sdrh   Parse *pParse,        /* Parser context */
542113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
543cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5445974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5459cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5469cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
547cce7d176Sdrh ){
5486a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5496a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
550113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
551e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5525974a30fSdrh   int i, j, idx;        /* Loop counters */
5535974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5545974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
555967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5566a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
55726198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
55826198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
559d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5600ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5614d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
562cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
563e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
564e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
565e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5662eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5676a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5682958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
569e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
570ec95c441Sdrh   int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
571cce7d176Sdrh 
5726a288a33Sdrh   /* Register allocations */
5731bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5746a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5756a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5766a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5776a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5786a288a33Sdrh   int regData;          /* register holding first column to insert */
5791bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
580aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5816a288a33Sdrh 
582798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
583798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5842f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5852f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
586798da52cSdrh #endif
587c3f9bad2Sdanielk1977 
58817435752Sdrh   db = pParse->db;
5891bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
59017435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5916f7adc8aSdrh     goto insert_cleanup;
5926f7adc8aSdrh   }
593daffd0e5Sdrh 
5941ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5951ccde15dSdrh   */
596113088ecSdrh   assert( pTabList->nSrc==1 );
597113088ecSdrh   zTab = pTabList->a[0].zName;
598098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5994adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
600c3f9bad2Sdanielk1977   if( pTab==0 ){
601c3f9bad2Sdanielk1977     goto insert_cleanup;
602c3f9bad2Sdanielk1977   }
603da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
604da184236Sdanielk1977   assert( iDb<db->nDb );
605da184236Sdanielk1977   pDb = &db->aDb[iDb];
6062958a4e6Sdrh   zDb = pDb->zName;
6074adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
6081962bda7Sdrh     goto insert_cleanup;
6091962bda7Sdrh   }
610ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
611c3f9bad2Sdanielk1977 
612b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
613b7f9164eSdrh   ** inserted into is a view
614b7f9164eSdrh   */
615b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6162f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
617b7f9164eSdrh   isView = pTab->pSelect!=0;
618b7f9164eSdrh #else
6192f886d1dSdanielk1977 # define pTrigger 0
6202f886d1dSdanielk1977 # define tmask 0
621b7f9164eSdrh # define isView 0
622b7f9164eSdrh #endif
623b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
624b7f9164eSdrh # undef isView
625b7f9164eSdrh # define isView 0
626b7f9164eSdrh #endif
6272f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
628b7f9164eSdrh 
629f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
630d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
631f573c99bSdrh   */
632b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
633f573c99bSdrh     goto insert_cleanup;
634f573c99bSdrh   }
635f573c99bSdrh 
636d82b5021Sdrh   /* Cannot insert into a read-only table.
637595a523aSdanielk1977   */
638595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
639595a523aSdanielk1977     goto insert_cleanup;
640595a523aSdanielk1977   }
641595a523aSdanielk1977 
6421ccde15dSdrh   /* Allocate a VDBE
6431ccde15dSdrh   */
6444adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6455974a30fSdrh   if( v==0 ) goto insert_cleanup;
6464794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6472f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6481ccde15dSdrh 
6499d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6509d9cf229Sdrh   /* If the statement is of the form
6519d9cf229Sdrh   **
6529d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6539d9cf229Sdrh   **
6549d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6559d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
656e00ee6ebSdrh   **
657e00ee6ebSdrh   ** This is the 2nd template.
6589d9cf229Sdrh   */
6599d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6602f886d1dSdanielk1977     assert( !pTrigger );
6619d9cf229Sdrh     assert( pList==0 );
6620b9f50d8Sdrh     goto insert_end;
6639d9cf229Sdrh   }
6649d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6659d9cf229Sdrh 
6662958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6676a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6682958a4e6Sdrh   */
6696a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6702958a4e6Sdrh 
6711ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
672e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
673e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
674e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6751ccde15dSdrh   */
6765974a30fSdrh   if( pSelect ){
677d82b5021Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
6785f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6795f085269Sdrh     if( rc ) goto insert_cleanup;
6801013c932Sdrh 
6815f085269Sdrh     regEof = dest.iSDParm + 1;
6822b596da8Sdrh     regFromSelect = dest.iSdst;
6835974a30fSdrh     assert( pSelect->pEList );
684967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6852b596da8Sdrh     assert( dest.nSdst==nColumn );
686142e30dfSdrh 
687142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
688e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
689d82b5021Sdrh     ** FALSE if each output row of the SELECT can be written directly into
690e00ee6ebSdrh     ** the destination table (template 3).
691048c530cSdrh     **
692048c530cSdrh     ** A temp table must be used if the table being updated is also one
693048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
694048c530cSdrh     ** temp table in the case of row triggers.
695142e30dfSdrh     */
696595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
697048c530cSdrh       useTempTable = 1;
698048c530cSdrh     }
699142e30dfSdrh 
700142e30dfSdrh     if( useTempTable ){
701e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
702e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
703e00ee6ebSdrh       ** here is from the 4th template:
704e00ee6ebSdrh       **
705e00ee6ebSdrh       **      B: open temp table
706e00ee6ebSdrh       **      L: yield X
707e00ee6ebSdrh       **         if EOF goto M
708e00ee6ebSdrh       **         insert row from R..R+n into temp table
709e00ee6ebSdrh       **         goto L
710e00ee6ebSdrh       **      M: ...
711142e30dfSdrh       */
712e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
713dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
714e00ee6ebSdrh       int addrTop;         /* Label "L" */
715e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
716b7654111Sdrh 
717142e30dfSdrh       srcTab = pParse->nTab++;
718b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
719dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
720e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7212b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
722e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7231db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
724dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
725dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
726e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
727e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
728b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
729dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
730142e30dfSdrh     }
731142e30dfSdrh   }else{
732142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
733142e30dfSdrh     ** clause
734142e30dfSdrh     */
735b3bce662Sdanielk1977     NameContext sNC;
736b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
737b3bce662Sdanielk1977     sNC.pParse = pParse;
7385974a30fSdrh     srcTab = -1;
73948d1178aSdrh     assert( useTempTable==0 );
740147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
741e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7427d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
743b04a5d87Sdrh         goto insert_cleanup;
744b04a5d87Sdrh       }
745e64e7b20Sdrh     }
7465974a30fSdrh   }
7471ccde15dSdrh 
7481ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7491ccde15dSdrh   ** of columns to be inserted into the table.
7501ccde15dSdrh   */
751034ca14fSdanielk1977   if( IsVirtual(pTab) ){
752034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
753034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
754034ca14fSdanielk1977     }
755034ca14fSdanielk1977   }
756034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7574adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
758da93d238Sdrh        "table %S has %d columns but %d values were supplied",
759d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
760cce7d176Sdrh     goto insert_cleanup;
761cce7d176Sdrh   }
762967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7634adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
764cce7d176Sdrh     goto insert_cleanup;
765cce7d176Sdrh   }
7661ccde15dSdrh 
7671ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7681ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7691ccde15dSdrh   ** remember the column indices.
770c8392586Sdrh   **
771c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
772d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
773d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
774c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
775d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
776d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
7771ccde15dSdrh   */
778967e8b73Sdrh   if( pColumn ){
779967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
780967e8b73Sdrh       pColumn->a[i].idx = -1;
781cce7d176Sdrh     }
782967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
783cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7844adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
785967e8b73Sdrh           pColumn->a[i].idx = j;
7864a32431cSdrh           if( j==pTab->iPKey ){
787d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
7884a32431cSdrh           }
789cce7d176Sdrh           break;
790cce7d176Sdrh         }
791cce7d176Sdrh       }
792cce7d176Sdrh       if( j>=pTab->nCol ){
793ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
794d82b5021Sdrh           ipkColumn = i;
795a0217ba7Sdrh         }else{
7964adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
797da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
7981db95106Sdan           pParse->checkSchema = 1;
799cce7d176Sdrh           goto insert_cleanup;
800cce7d176Sdrh         }
801cce7d176Sdrh       }
802cce7d176Sdrh     }
803a0217ba7Sdrh   }
8041ccde15dSdrh 
805aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
806d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
807d82b5021Sdrh   ** column index in the original table definition.
8084a32431cSdrh   */
809147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
810d82b5021Sdrh     ipkColumn = pTab->iPKey;
8114a32431cSdrh   }
8124a32431cSdrh 
813c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8141ccde15dSdrh   */
815142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8166a288a33Sdrh     regRowCount = ++pParse->nMem;
8176a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
818c3f9bad2Sdanielk1977   }
819c3f9bad2Sdanielk1977 
820e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
821e448dc4aSdanielk1977   if( !isView ){
822aa9b8963Sdrh     int nIdx;
82326198bb4Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1,
82426198bb4Sdrh                                       &iDataCur, &iIdxCur);
8255c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
826aa9b8963Sdrh     if( aRegIdx==0 ){
827aa9b8963Sdrh       goto insert_cleanup;
828aa9b8963Sdrh     }
829aa9b8963Sdrh     for(i=0; i<nIdx; i++){
830aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
831aa9b8963Sdrh     }
832feeb1394Sdrh   }
833feeb1394Sdrh 
834e00ee6ebSdrh   /* This is the top of the main insertion loop */
835142e30dfSdrh   if( useTempTable ){
836e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
837e00ee6ebSdrh     ** following pseudocode (template 4):
838e00ee6ebSdrh     **
839e00ee6ebSdrh     **         rewind temp table
840e00ee6ebSdrh     **      C: loop over rows of intermediate table
841e00ee6ebSdrh     **           transfer values form intermediate table into <table>
842e00ee6ebSdrh     **         end loop
843e00ee6ebSdrh     **      D: ...
844e00ee6ebSdrh     */
845e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
846e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
847142e30dfSdrh   }else if( pSelect ){
848e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
849e00ee6ebSdrh     ** following pseudocode (template 3):
850e00ee6ebSdrh     **
851e00ee6ebSdrh     **      C: yield X
852e00ee6ebSdrh     **         if EOF goto D
853e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
854e00ee6ebSdrh     **         goto C
855e00ee6ebSdrh     **      D: ...
856e00ee6ebSdrh     */
8572b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
858e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
859bed8690fSdrh   }
8601ccde15dSdrh 
8616a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8626a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8636a288a33Sdrh   */
8646a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8656a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8666a288a33Sdrh   if( IsVirtual(pTab) ){
8676a288a33Sdrh     regRowid++;
8686a288a33Sdrh     pParse->nMem++;
8696a288a33Sdrh   }
8706a288a33Sdrh   regData = regRowid+1;
8716a288a33Sdrh 
8725cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
87370ce3f0cSdrh   */
8744adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8752f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
87676d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
877c3f9bad2Sdanielk1977 
87870ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
87970ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
88070ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
88170ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
88270ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
88370ce3f0cSdrh     */
884d82b5021Sdrh     if( ipkColumn<0 ){
88576d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88670ce3f0cSdrh     }else{
8876a288a33Sdrh       int j1;
888ec95c441Sdrh       assert( !withoutRowid );
8897fe45908Sdrh       if( useTempTable ){
890d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
8917fe45908Sdrh       }else{
892d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
893d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
8947fe45908Sdrh       }
89576d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89676d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
8976a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
89876d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89970ce3f0cSdrh     }
90070ce3f0cSdrh 
901034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
902034ca14fSdanielk1977     ** this block would have to account for hidden column.
903034ca14fSdanielk1977     */
904034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
905034ca14fSdanielk1977 
90670ce3f0cSdrh     /* Create the new column data
90770ce3f0cSdrh     */
908c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
909c3f9bad2Sdanielk1977       if( pColumn==0 ){
910c3f9bad2Sdanielk1977         j = i;
911c3f9bad2Sdanielk1977       }else{
912c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
913c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
914c3f9bad2Sdanielk1977         }
915c3f9bad2Sdanielk1977       }
9167ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91776d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
918142e30dfSdrh       }else if( useTempTable ){
91976d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
920c3f9bad2Sdanielk1977       }else{
921d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
92276d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
923c3f9bad2Sdanielk1977       }
924c3f9bad2Sdanielk1977     }
925a37cdde0Sdanielk1977 
926a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
927a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
928a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
929a37cdde0Sdanielk1977     ** table column affinities.
930a37cdde0Sdanielk1977     */
931a37cdde0Sdanielk1977     if( !isView ){
93276d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
933a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
934a37cdde0Sdanielk1977     }
935c3f9bad2Sdanielk1977 
9365cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
937165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
93894d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
939165921a7Sdan 
94076d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
94170ce3f0cSdrh   }
942c3f9bad2Sdanielk1977 
943d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
944d82b5021Sdrh   ** registers beginning at regIns.
9451ccde15dSdrh   */
9465cf590c1Sdrh   if( !isView ){
9474cbdda9eSdrh     if( IsVirtual(pTab) ){
9484cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9496a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9504cbdda9eSdrh     }
951d82b5021Sdrh     if( ipkColumn>=0 ){
952142e30dfSdrh       if( useTempTable ){
953d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
954142e30dfSdrh       }else if( pSelect ){
955d82b5021Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid);
9564a32431cSdrh       }else{
957e4d90813Sdrh         VdbeOp *pOp;
958d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
95920411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9601b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
961e4d90813Sdrh           appendFlag = 1;
962e4d90813Sdrh           pOp->opcode = OP_NewRowid;
96326198bb4Sdrh           pOp->p1 = iDataCur;
9646a288a33Sdrh           pOp->p2 = regRowid;
9656a288a33Sdrh           pOp->p3 = regAutoinc;
966e4d90813Sdrh         }
96727a32783Sdrh       }
968f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
969e1e68f49Sdrh       ** to generate a unique primary key value.
970e1e68f49Sdrh       */
971e4d90813Sdrh       if( !appendFlag ){
9721db639ceSdrh         int j1;
973bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9741db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
97526198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
9761db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
977bb50e7adSdanielk1977         }else{
978bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
979bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
980bb50e7adSdanielk1977         }
9813c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
982e4d90813Sdrh       }
983ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9846a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9854a32431cSdrh     }else{
98626198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
987e4d90813Sdrh       appendFlag = 1;
9884a32431cSdrh     }
9896a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9904a32431cSdrh 
991d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
9924a32431cSdrh     ** with the first column.
9934a32431cSdrh     */
994034ca14fSdanielk1977     nHidden = 0;
995cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9966a288a33Sdrh       int iRegStore = regRowid+1+i;
9974a32431cSdrh       if( i==pTab->iPKey ){
9984a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
999d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
1000d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
1001aacc543eSdrh         ** taking up data space with information that will never be used. */
10024c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
10034a32431cSdrh         continue;
10044a32431cSdrh       }
1005967e8b73Sdrh       if( pColumn==0 ){
1006034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1007034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1008034ca14fSdanielk1977           j = -1;
1009034ca14fSdanielk1977           nHidden++;
1010034ca14fSdanielk1977         }else{
1011034ca14fSdanielk1977           j = i - nHidden;
1012034ca14fSdanielk1977         }
1013cce7d176Sdrh       }else{
1014967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1015967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1016cce7d176Sdrh         }
1017cce7d176Sdrh       }
1018034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1019287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1020142e30dfSdrh       }else if( useTempTable ){
1021287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1022142e30dfSdrh       }else if( pSelect ){
1023b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1024cce7d176Sdrh       }else{
1025287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1026cce7d176Sdrh       }
1027cce7d176Sdrh     }
10281ccde15dSdrh 
10290ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10300ca3e24bSdrh     ** do the insertion.
10314a32431cSdrh     */
10324cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10334cbdda9eSdrh     if( IsVirtual(pTab) ){
1034595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10354f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1036595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1037b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1038e0af83acSdan       sqlite3MayAbort(pParse);
10394cbdda9eSdrh     }else
10404cbdda9eSdrh #endif
10414cbdda9eSdrh     {
1042de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1043f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1044f8ffb278Sdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
104504adf416Sdrh       );
10468ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
104726198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
104826198bb4Sdrh                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
10495cf590c1Sdrh     }
10504cbdda9eSdrh   }
10511bee3d7bSdrh 
1052feeb1394Sdrh   /* Update the count of rows that are inserted
10531bee3d7bSdrh   */
1054142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10556a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10561bee3d7bSdrh   }
1057c3f9bad2Sdanielk1977 
10582f886d1dSdanielk1977   if( pTrigger ){
1059c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1060165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
106194d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1062c3f9bad2Sdanielk1977   }
10631bee3d7bSdrh 
1064e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1065e00ee6ebSdrh   ** is a SELECT statement.
10661ccde15dSdrh   */
10674adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1068142e30dfSdrh   if( useTempTable ){
1069e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1070e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10712eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1072142e30dfSdrh   }else if( pSelect ){
1073e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1074e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10756b56344dSdrh   }
1076c3f9bad2Sdanielk1977 
1077e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1078c3f9bad2Sdanielk1977     /* Close all tables opened */
107926198bb4Sdrh     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
108026198bb4Sdrh     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
108126198bb4Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
1082cce7d176Sdrh     }
1083c3f9bad2Sdanielk1977   }
1084c3f9bad2Sdanielk1977 
10850b9f50d8Sdrh insert_end:
1086f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10870b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10880b9f50d8Sdrh   ** autoincrement tables.
10892958a4e6Sdrh   */
1090165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10910b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10920b9f50d8Sdrh   }
10932958a4e6Sdrh 
10941bee3d7bSdrh   /*
1095e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1096e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1097e7de6f25Sdanielk1977   ** invoke the callback function.
10981bee3d7bSdrh   */
1099165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
11006a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110122322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
110210fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11031bee3d7bSdrh   }
1104cce7d176Sdrh 
1105cce7d176Sdrh insert_cleanup:
1106633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1107633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1108633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1109633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1110633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1111cce7d176Sdrh }
11129cfcf5d4Sdrh 
111375cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
111475cbd984Sdan ** thely may interfere with compilation of other functions in this file
111575cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
111675cbd984Sdan #ifdef isView
111775cbd984Sdan  #undef isView
111875cbd984Sdan #endif
111975cbd984Sdan #ifdef pTrigger
112075cbd984Sdan  #undef pTrigger
112175cbd984Sdan #endif
112275cbd984Sdan #ifdef tmask
112375cbd984Sdan  #undef tmask
112475cbd984Sdan #endif
112575cbd984Sdan 
112611e85273Sdrh /*
11276934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
11286934fc7bSdrh ** on table pTab.
11299cfcf5d4Sdrh **
11306934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
11316934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
11326934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
11336934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
11346934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
11356934fc7bSdrh ** contain the content of the first table column.  The third register will
11366934fc7bSdrh ** contain the content of the second table column.  And so forth.
11370ca3e24bSdrh **
1138f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1139f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1140f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1141f8ffb278Sdrh ** checking regOldData for zero.
11420ca3e24bSdrh **
1143f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1144f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1145f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1146f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1147f8ffb278Sdrh **
1148f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1149f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1150f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1151f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1152f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1153f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
11540ca3e24bSdrh **
11556934fc7bSdrh ** The code generated by this routine will store new index entries into
1156aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1157aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1158aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
11596934fc7bSdrh ** at pTab->pIndex.
11606934fc7bSdrh **
11616934fc7bSdrh ** The caller must have already opened writeable cursors on the main
11626934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
11636934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
11646934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
11656934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
11666934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
11676934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
11689cfcf5d4Sdrh **
11699cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11709cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11711c92853dSdrh ** then the appropriate action is performed.  There are five possible
11721c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11739cfcf5d4Sdrh **
11749cfcf5d4Sdrh **  Constraint type  Action       What Happens
11759cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11761c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
11776934fc7bSdrh **                                sqlite3_step() returns immediately with a
11789cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11799cfcf5d4Sdrh **
11801c92853dSdrh **  any              ABORT        Back out changes from the current command
11811c92853dSdrh **                                only (do not do a complete rollback) then
11826934fc7bSdrh **                                cause sqlite3_step() to return immediately
11831c92853dSdrh **                                with SQLITE_CONSTRAINT.
11841c92853dSdrh **
11856934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
11861c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11871c92853dSdrh **                                transaction is not rolled back and any
11886934fc7bSdrh **                                changes to prior rows are retained.
11891c92853dSdrh **
11906934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
11916934fc7bSdrh **                                row is skipped, without throwing an error.
11926934fc7bSdrh **                                Processing continues with the next row.
11936934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
11949cfcf5d4Sdrh **
11959cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11969cfcf5d4Sdrh **                                value for that column.  If the default value
11979cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11989cfcf5d4Sdrh **
11999cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
12009cfcf5d4Sdrh **                                being inserted is removed.
12019cfcf5d4Sdrh **
12029cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12039cfcf5d4Sdrh **
12041c92853dSdrh ** Which action to take is determined by the overrideError parameter.
12051c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12061c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12071c92853dSdrh ** for the constraint is used.
12089cfcf5d4Sdrh */
12094adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12109cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
12116934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1212f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
12136934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
121426198bb4Sdrh   int iIdxCur,         /* First index cursor */
12156934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1216f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1217f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1218f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1219de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1220de630353Sdanielk1977   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
12219cfcf5d4Sdrh ){
12221b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
12231b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
122411e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
12252938f924Sdrh   sqlite3 *db;         /* Database connection */
1226f8ffb278Sdrh   int i;               /* loop counter */
1227f8ffb278Sdrh   int ix;              /* Index loop counter */
1228f8ffb278Sdrh   int nCol;            /* Number of columns */
1229f8ffb278Sdrh   int onError;         /* Conflict resolution strategy */
1230f8ffb278Sdrh   int j1;              /* Addresss of jump instruction */
12311b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
12326fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
12338d1b82e4Sdrh   int ipkTop = 0;      /* Top of the rowid change constraint check */
12348d1b82e4Sdrh   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
12358d1b82e4Sdrh   u8 isUpdate;         /* True if this is an UPDATE operation */
12369cfcf5d4Sdrh 
1237f8ffb278Sdrh   isUpdate = regOldData!=0;
12382938f924Sdrh   db = pParse->db;
12394adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12409cfcf5d4Sdrh   assert( v!=0 );
1241417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12429cfcf5d4Sdrh   nCol = pTab->nCol;
1243aa9b8963Sdrh 
12446934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
12456934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
12466934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
12476934fc7bSdrh   ** number of fields in the true primary key of the table. */
124826198bb4Sdrh   if( HasRowid(pTab) ){
124926198bb4Sdrh     pPk = 0;
125026198bb4Sdrh     nPkField = 1;
125126198bb4Sdrh   }else{
125226198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
125326198bb4Sdrh     nPkField = pPk->nKeyCol;
125426198bb4Sdrh   }
12556fbe41acSdrh 
12566fbe41acSdrh   /* Record that this module has started */
12576fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
12586934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
125911e85273Sdrh 
12609cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12619cfcf5d4Sdrh   */
12629cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12630ca3e24bSdrh     if( i==pTab->iPKey ){
12640ca3e24bSdrh       continue;
12650ca3e24bSdrh     }
12669cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12670ca3e24bSdrh     if( onError==OE_None ) continue;
12689cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12699cfcf5d4Sdrh       onError = overrideError;
1270a996e477Sdrh     }else if( onError==OE_Default ){
1271a996e477Sdrh       onError = OE_Abort;
12729cfcf5d4Sdrh     }
12737977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12749cfcf5d4Sdrh       onError = OE_Abort;
12759cfcf5d4Sdrh     }
1276b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1277b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12789cfcf5d4Sdrh     switch( onError ){
12791c92853dSdrh       case OE_Abort:
1280e0af83acSdan         sqlite3MayAbort(pParse);
12810978d4ffSdrh         /* Fall through */
1282e0af83acSdan       case OE_Rollback:
12831c92853dSdrh       case OE_Fail: {
1284f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1285f9c8ce3cSdrh                                     pTab->aCol[i].zName);
1286f9c8ce3cSdrh         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1287f9c8ce3cSdrh                           regNewData+1+i, zMsg, P4_DYNAMIC);
1288f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
12899cfcf5d4Sdrh         break;
12909cfcf5d4Sdrh       }
12919cfcf5d4Sdrh       case OE_Ignore: {
12926934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
12939cfcf5d4Sdrh         break;
12949cfcf5d4Sdrh       }
1295098d1684Sdrh       default: {
1296098d1684Sdrh         assert( onError==OE_Replace );
12976934fc7bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
12986934fc7bSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
12995053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
13009cfcf5d4Sdrh         break;
13019cfcf5d4Sdrh       }
13029cfcf5d4Sdrh     }
13039cfcf5d4Sdrh   }
13049cfcf5d4Sdrh 
13059cfcf5d4Sdrh   /* Test all CHECK constraints
13069cfcf5d4Sdrh   */
1307ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
13082938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
13092938f924Sdrh     ExprList *pCheck = pTab->pCheck;
13106934fc7bSdrh     pParse->ckBase = regNewData+1;
1311aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
13122938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
13132938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
13142d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
13152e06c67cSdrh       if( onError==OE_Ignore ){
131666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1317aa01c7e2Sdrh       }else{
1318f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1319f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
13206dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1321d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1322f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1323f9c8ce3cSdrh                               P5_ConstraintCheck);
1324aa01c7e2Sdrh       }
1325ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1326c31c7c1cSdrh     }
13272938f924Sdrh   }
1328ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13299cfcf5d4Sdrh 
1330f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1331f8ffb278Sdrh   ** exist in the table.
13329cfcf5d4Sdrh   */
13336fbe41acSdrh   if( pkChng && pPk==0 ){
133411e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
133511e85273Sdrh 
1336f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
13370ca3e24bSdrh     onError = pTab->keyConf;
13380ca3e24bSdrh     if( overrideError!=OE_Default ){
13390ca3e24bSdrh       onError = overrideError;
1340a996e477Sdrh     }else if( onError==OE_Default ){
1341a996e477Sdrh       onError = OE_Abort;
13420ca3e24bSdrh     }
1343a0217ba7Sdrh 
134479b0c956Sdrh     if( isUpdate ){
1345f8ffb278Sdrh       /* pkChng!=0 does not mean that the rowid has change, only that
1346f8ffb278Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1347f8ffb278Sdrh       ** is unchanged. */
13486934fc7bSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
134979b0c956Sdrh     }
1350f8ffb278Sdrh 
13518d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
13528d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
13538d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
13548d1b82e4Sdrh     ** the UNIQUE constraints have run.
13558d1b82e4Sdrh     */
13568d1b82e4Sdrh     if( onError==OE_Replace && overrideError!=OE_Replace ){
13578d1b82e4Sdrh       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
13588d1b82e4Sdrh         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
13598d1b82e4Sdrh           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
13608d1b82e4Sdrh           break;
13618d1b82e4Sdrh         }
13628d1b82e4Sdrh       }
13638d1b82e4Sdrh     }
13648d1b82e4Sdrh 
1365f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1366f8ffb278Sdrh     ** the following conflict logic if it does not. */
13676934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1368f8ffb278Sdrh 
1369f8ffb278Sdrh     /* Generate code that deals with a rowid collision */
13700ca3e24bSdrh     switch( onError ){
1371a0217ba7Sdrh       default: {
1372a0217ba7Sdrh         onError = OE_Abort;
1373a0217ba7Sdrh         /* Fall thru into the next case */
1374a0217ba7Sdrh       }
13751c92853dSdrh       case OE_Rollback:
13761c92853dSdrh       case OE_Abort:
13771c92853dSdrh       case OE_Fail: {
1378f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
13790ca3e24bSdrh         break;
13800ca3e24bSdrh       }
13815383ae5cSdrh       case OE_Replace: {
13822283d46cSdan         /* If there are DELETE triggers on this table and the
13832283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1384d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13852283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13862283d46cSdan         **
13872283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1388da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1389da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1390da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1391da730f6eSdan         ** when it is inserted.
1392da730f6eSdan         **
1393da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1394da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1395da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1396da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1397da730f6eSdan         ** but being more selective here allows statements like:
1398da730f6eSdan         **
1399da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1400da730f6eSdan         **
1401da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1402da730f6eSdan         ** table.
1403da730f6eSdan         */
14042283d46cSdan         Trigger *pTrigger = 0;
14052938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14062283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14072283d46cSdan         }
1408e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1409da730f6eSdan           sqlite3MultiWrite(pParse);
141026198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
14116934fc7bSdrh                                    regNewData, 1, 0, OE_Replace);
1412da730f6eSdan         }else if( pTab->pIndex ){
1413da730f6eSdan           sqlite3MultiWrite(pParse);
141426198bb4Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
14152283d46cSdan         }
14165383ae5cSdrh         seenReplace = 1;
14175383ae5cSdrh         break;
14185383ae5cSdrh       }
14190ca3e24bSdrh       case OE_Ignore: {
14208d1b82e4Sdrh         /*assert( seenReplace==0 );*/
142166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14220ca3e24bSdrh         break;
14230ca3e24bSdrh       }
14240ca3e24bSdrh     }
142511e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
14268d1b82e4Sdrh     if( ipkTop ){
14278d1b82e4Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
14288d1b82e4Sdrh       sqlite3VdbeJumpHere(v, ipkTop);
14298d1b82e4Sdrh     }
14300ca3e24bSdrh   }
14310bd1f4eaSdrh 
14320bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
14330bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
143411e85273Sdrh   ** Compute the revised record entries for indices as we go.
1435f8ffb278Sdrh   **
1436f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1437f8ffb278Sdrh   ** WITHOUT ROWID table.
14380bd1f4eaSdrh   */
143926198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
14406934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
14416934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
14426934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
14436934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
14442184fc75Sdrh 
144526198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
14466934fc7bSdrh     iThisCur = iIdxCur+ix;
14476934fc7bSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(v);
1448b2fe7d8cSdrh 
1449f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1450b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
145126198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
14526934fc7bSdrh       pParse->ckBase = regNewData+1;
145311e85273Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1454b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1455b2b9d3d7Sdrh       pParse->ckBase = 0;
1456b2b9d3d7Sdrh     }
1457b2b9d3d7Sdrh 
14586934fc7bSdrh     /* Create a record for this index entry as it should appear after
1459f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1460f8ffb278Sdrh     */
146111e85273Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
14629cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
14636934fc7bSdrh       int iField = pIdx->aiColumn[i];
1464f82b9afcSdrh       int x;
146526198bb4Sdrh       if( iField<0 || iField==pTab->iPKey ){
1466f82b9afcSdrh         x = regNewData;
14679cfcf5d4Sdrh       }else{
1468f82b9afcSdrh         x = iField + regNewData + 1;
14699cfcf5d4Sdrh       }
1470f82b9afcSdrh       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
1471f82b9afcSdrh       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
14729cfcf5d4Sdrh     }
147326198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
14748d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
147526198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
1476bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1477b2fe7d8cSdrh 
1478f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1479f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1480f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1481f8ffb278Sdrh     ** logic below can all be skipped. */
148200012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1483da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1484da475b8dSdrh       continue;
1485da475b8dSdrh     }
1486f8ffb278Sdrh 
14876934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
14889cfcf5d4Sdrh     onError = pIdx->onError;
1489de630353Sdanielk1977     if( onError==OE_None ){
149026198bb4Sdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
149111e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1492de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1493de630353Sdanielk1977     }
14949cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14959cfcf5d4Sdrh       onError = overrideError;
1496a996e477Sdrh     }else if( onError==OE_Default ){
1497a996e477Sdrh       onError = OE_Abort;
14989cfcf5d4Sdrh     }
14995383ae5cSdrh 
1500b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
15016fbe41acSdrh     regR = sqlite3GetTempRange(pParse, nPkField);
150226198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
15036f225d0dSdrh                          regIdx, pIdx->nKeyCol);
1504f8ffb278Sdrh 
1505f8ffb278Sdrh     /* Generate code to handle collisions */
150611e85273Sdrh     if( HasRowid(pTab) ){
15076934fc7bSdrh       sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
15080978d4ffSdrh       /* Conflict only if the rowid of the existing index entry
15090978d4ffSdrh       ** is different from old-rowid */
1510f8ffb278Sdrh       if( isUpdate ){
15116934fc7bSdrh         sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
1512f8ffb278Sdrh       }
151326198bb4Sdrh     }else{
1514ccc79f02Sdrh       int x;
151526198bb4Sdrh       /* Extract the PRIMARY KEY from the end of the index entry and
1516da475b8dSdrh       ** store it in registers regR..regR+nPk-1 */
1517da475b8dSdrh       if( isUpdate || onError==OE_Replace ){
151826198bb4Sdrh         for(i=0; i<pPk->nKeyCol; i++){
1519ccc79f02Sdrh           x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
152026198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
152126198bb4Sdrh           VdbeComment((v, "%s.%s", pTab->zName,
152226198bb4Sdrh                        pTab->aCol[pPk->aiColumn[i]].zName));
152326198bb4Sdrh         }
1524da475b8dSdrh       }
1525da475b8dSdrh       if( isUpdate ){
1526e83267daSdan         /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1527e83267daSdan         ** table, only conflict if the new PRIMARY KEY values are actually
1528e83267daSdan         ** different from the old.
1529e83267daSdan         **
1530e83267daSdan         ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1531e83267daSdan         ** of the matched index row are different from the original PRIMARY
1532e83267daSdan         ** KEY values of this row before the update.  */
1533e83267daSdan         int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1534e83267daSdan         int op = OP_Ne;
1535e83267daSdan         int regCmp = (pIdx->autoIndex==2 ? regIdx : regR);
1536e83267daSdan 
1537e83267daSdan         for(i=0; i<pPk->nKeyCol; i++){
1538e83267daSdan           char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1539ccc79f02Sdrh           x = pPk->aiColumn[i];
1540e83267daSdan           if( i==(pPk->nKeyCol-1) ){
1541e83267daSdan             addrJump = addrUniqueOk;
1542e83267daSdan             op = OP_Eq;
154311e85273Sdrh           }
1544e83267daSdan           sqlite3VdbeAddOp4(v, op,
1545e83267daSdan               regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1546e83267daSdan           );
1547da475b8dSdrh         }
154811e85273Sdrh       }
154926198bb4Sdrh     }
155011e85273Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1551b2fe7d8cSdrh 
1552b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1553b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1554b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
15559cfcf5d4Sdrh     switch( onError ){
15561c92853dSdrh       case OE_Rollback:
15571c92853dSdrh       case OE_Abort:
15581c92853dSdrh       case OE_Fail: {
1559f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
15609cfcf5d4Sdrh         break;
15619cfcf5d4Sdrh       }
15629cfcf5d4Sdrh       case OE_Ignore: {
156366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
15649cfcf5d4Sdrh         break;
15659cfcf5d4Sdrh       }
1566098d1684Sdrh       default: {
15672283d46cSdan         Trigger *pTrigger = 0;
1568098d1684Sdrh         assert( onError==OE_Replace );
15691bea559aSdan         sqlite3MultiWrite(pParse);
15702938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15712283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15722283d46cSdan         }
157326198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
15746fbe41acSdrh                                  regR, nPkField, 0, OE_Replace);
15750ca3e24bSdrh         seenReplace = 1;
15769cfcf5d4Sdrh         break;
15779cfcf5d4Sdrh       }
15789cfcf5d4Sdrh     }
157911e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
158026198bb4Sdrh     sqlite3ReleaseTempRange(pParse, regR, nPkField);
15819cfcf5d4Sdrh   }
15828d1b82e4Sdrh   if( ipkTop ){
15838d1b82e4Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
15848d1b82e4Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
15858d1b82e4Sdrh   }
1586de630353Sdanielk1977 
1587de630353Sdanielk1977   if( pbMayReplace ){
1588de630353Sdanielk1977     *pbMayReplace = seenReplace;
1589de630353Sdanielk1977   }
15906fbe41acSdrh   VdbeModuleComment((v, "END: GenCnstCks()"));
15919cfcf5d4Sdrh }
15920ca3e24bSdrh 
15930ca3e24bSdrh /*
15940ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
15954adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
15966934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
159704adf416Sdrh ** rowid and the content to be inserted.
15980ca3e24bSdrh **
1599b419a926Sdrh ** The arguments to this routine should be the same as the first six
16004adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
16010ca3e24bSdrh */
16024adee20fSdanielk1977 void sqlite3CompleteInsertion(
16030ca3e24bSdrh   Parse *pParse,      /* The parser context */
16040ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
160526198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
160626198bb4Sdrh   int iIdxCur,        /* First index cursor */
16076934fc7bSdrh   int regNewData,     /* Range of content */
1608aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
160970ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1610de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1611de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
16120ca3e24bSdrh ){
16136934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
16146934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
16156934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
16166934fc7bSdrh   int regData;        /* Content registers (after the rowid) */
16176934fc7bSdrh   int regRec;         /* Register holding assemblied record for the table */
16186934fc7bSdrh   int i;              /* Loop counter */
16190ca3e24bSdrh 
16204adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
16210ca3e24bSdrh   assert( v!=0 );
1622417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1623b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1624aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1625b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1626b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1627b2b9d3d7Sdrh     }
162826198bb4Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
16296546af14Sdrh     pik_flags = 0;
16306546af14Sdrh     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
16316546af14Sdrh     if( pIdx->autoIndex==2 && !HasRowid(pTab) && pParse->nested==0 ){
16326546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1633de630353Sdanielk1977     }
16346546af14Sdrh     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
16350ca3e24bSdrh   }
1636ec95c441Sdrh   if( !HasRowid(pTab) ) return;
16376934fc7bSdrh   regData = regNewData + 1;
1638b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
16391db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1640a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1641da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
16424794f735Sdrh   if( pParse->nested ){
16434794f735Sdrh     pik_flags = 0;
16444794f735Sdrh   }else{
164594eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
164694eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
16474794f735Sdrh   }
1648e4d90813Sdrh   if( appendBias ){
1649e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1650e4d90813Sdrh   }
1651de630353Sdanielk1977   if( useSeekResult ){
1652de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1653de630353Sdanielk1977   }
16546934fc7bSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
165594eb6a14Sdanielk1977   if( !pParse->nested ){
16568d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
165794eb6a14Sdanielk1977   }
1658b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
16590ca3e24bSdrh }
1660cd44690aSdrh 
1661cd44690aSdrh /*
166226198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
166326198bb4Sdrh ** code to open and initialized those cursors.
1664aa9b8963Sdrh **
166526198bb4Sdrh ** The cursor for the object that contains the complete data (normally
166626198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
166726198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
166826198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
166926198bb4Sdrh **
167026198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
167126198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
167226198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
167326198bb4Sdrh **
167426198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
167526198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
167626198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
167726198bb4Sdrh ** pTab->pIndex list.
1678cd44690aSdrh */
1679aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1680290c1948Sdrh   Parse *pParse,   /* Parsing context */
1681290c1948Sdrh   Table *pTab,     /* Table to be opened */
168226198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
168326198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
168426198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
168526198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
1686290c1948Sdrh ){
1687cd44690aSdrh   int i;
16884cbdda9eSdrh   int iDb;
1689cd44690aSdrh   Index *pIdx;
16904cbdda9eSdrh   Vdbe *v;
16914cbdda9eSdrh 
169226198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
169326198bb4Sdrh   if( IsVirtual(pTab) ){
169426198bb4Sdrh     *piDataCur = 0;
169526198bb4Sdrh     *piIdxCur = 1;
169626198bb4Sdrh     return 0;
169726198bb4Sdrh   }
16984cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
16994cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1700cd44690aSdrh   assert( v!=0 );
170126198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
170226198bb4Sdrh   if( HasRowid(pTab) ){
170326198bb4Sdrh     *piDataCur = iBase++;
170426198bb4Sdrh     sqlite3OpenTable(pParse, *piDataCur, iDb, pTab, op);
17056fbe41acSdrh   }else{
170626198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
17076fbe41acSdrh   }
170826198bb4Sdrh   *piIdxCur = iBase;
170926198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
171026198bb4Sdrh     int iIdxCur = iBase++;
1711da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
171226198bb4Sdrh     if( pIdx->autoIndex==2 && !HasRowid(pTab) ) *piDataCur = iIdxCur;
1713*2ec2fb22Sdrh     sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
1714*2ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1715207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1716cd44690aSdrh   }
171726198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
171826198bb4Sdrh   return i;
1719cd44690aSdrh }
17209d9cf229Sdrh 
172191c58e23Sdrh 
172291c58e23Sdrh #ifdef SQLITE_TEST
172391c58e23Sdrh /*
172491c58e23Sdrh ** The following global variable is incremented whenever the
172591c58e23Sdrh ** transfer optimization is used.  This is used for testing
172691c58e23Sdrh ** purposes only - to make sure the transfer optimization really
172791c58e23Sdrh ** is happening when it is suppose to.
172891c58e23Sdrh */
172991c58e23Sdrh int sqlite3_xferopt_count;
173091c58e23Sdrh #endif /* SQLITE_TEST */
173191c58e23Sdrh 
173291c58e23Sdrh 
17339d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
17349d9cf229Sdrh /*
17359d9cf229Sdrh ** Check to collation names to see if they are compatible.
17369d9cf229Sdrh */
17379d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
17389d9cf229Sdrh   if( z1==0 ){
17399d9cf229Sdrh     return z2==0;
17409d9cf229Sdrh   }
17419d9cf229Sdrh   if( z2==0 ){
17429d9cf229Sdrh     return 0;
17439d9cf229Sdrh   }
17449d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
17459d9cf229Sdrh }
17469d9cf229Sdrh 
17479d9cf229Sdrh 
17489d9cf229Sdrh /*
17499d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
17509d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
17519d9cf229Sdrh ** for a compatible index:
17529d9cf229Sdrh **
17539d9cf229Sdrh **    *   The index is over the same set of columns
17549d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
17559d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
17569d9cf229Sdrh **    *   The same collating sequence on each column
1757b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
17589d9cf229Sdrh */
17599d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
17609d9cf229Sdrh   int i;
17619d9cf229Sdrh   assert( pDest && pSrc );
17629d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1763bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
17649d9cf229Sdrh     return 0;   /* Different number of columns */
17659d9cf229Sdrh   }
17669d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
17679d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
17689d9cf229Sdrh   }
1769bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
17709d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
17719d9cf229Sdrh       return 0;   /* Different columns indexed */
17729d9cf229Sdrh     }
17739d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
17749d9cf229Sdrh       return 0;   /* Different sort orders */
17759d9cf229Sdrh     }
17763f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
177760a713c6Sdrh       return 0;   /* Different collating sequences */
17789d9cf229Sdrh     }
17799d9cf229Sdrh   }
1780619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1781b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1782b2b9d3d7Sdrh   }
17839d9cf229Sdrh 
17849d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
17859d9cf229Sdrh   return 1;
17869d9cf229Sdrh }
17879d9cf229Sdrh 
17889d9cf229Sdrh /*
17899d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
17909d9cf229Sdrh **
17919d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
17929d9cf229Sdrh **
1793ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1794ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1795ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
17969d9cf229Sdrh **
1797ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1798ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1799ccdf1baeSdrh ** embedded in the code for details.
18009d9cf229Sdrh **
1801ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1802ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1803ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1804ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1805ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1806ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1807ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1808ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1809ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
18109d9cf229Sdrh **
1811ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
18129d9cf229Sdrh */
18139d9cf229Sdrh static int xferOptimization(
18149d9cf229Sdrh   Parse *pParse,        /* Parser context */
18159d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
18169d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
18179d9cf229Sdrh   int onError,          /* How to handle constraint errors */
18189d9cf229Sdrh   int iDbDest           /* The database of pDest */
18199d9cf229Sdrh ){
18209d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
18219d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
18229d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
18239d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
18249d9cf229Sdrh   int i;                           /* Loop counter */
18259d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
18269d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
18279d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
1828da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
1829da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
18309d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
18316a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1832f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1833b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
18349d9cf229Sdrh 
18359d9cf229Sdrh   if( pSelect==0 ){
18369d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
18379d9cf229Sdrh   }
18382f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
18399d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
18409d9cf229Sdrh   }
18419d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18427d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
18439d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
18449d9cf229Sdrh   }
18459d9cf229Sdrh #endif
18469d9cf229Sdrh   if( onError==OE_Default ){
1847e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1848e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
18499d9cf229Sdrh   }
18505ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
18519d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
18529d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
18539d9cf229Sdrh   }
18549d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
18559d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
18569d9cf229Sdrh   }
18579d9cf229Sdrh   if( pSelect->pWhere ){
18589d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
18599d9cf229Sdrh   }
18609d9cf229Sdrh   if( pSelect->pOrderBy ){
18619d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
18629d9cf229Sdrh   }
18638103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
18648103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
18659d9cf229Sdrh   if( pSelect->pGroupBy ){
18669d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
18679d9cf229Sdrh   }
18689d9cf229Sdrh   if( pSelect->pLimit ){
18699d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
18709d9cf229Sdrh   }
18718103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
18729d9cf229Sdrh   if( pSelect->pPrior ){
18739d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
18749d9cf229Sdrh   }
18757d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
18769d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
18779d9cf229Sdrh   }
18789d9cf229Sdrh   pEList = pSelect->pEList;
18799d9cf229Sdrh   assert( pEList!=0 );
18809d9cf229Sdrh   if( pEList->nExpr!=1 ){
18819d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
18829d9cf229Sdrh   }
18839d9cf229Sdrh   assert( pEList->a[0].pExpr );
18849d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
18859d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
18869d9cf229Sdrh   }
18879d9cf229Sdrh 
18889d9cf229Sdrh   /* At this point we have established that the statement is of the
18899d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
18909d9cf229Sdrh   ** we have to check the semantics.
18919d9cf229Sdrh   */
18929d9cf229Sdrh   pItem = pSelect->pSrc->a;
189341fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
18949d9cf229Sdrh   if( pSrc==0 ){
18959d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
18969d9cf229Sdrh   }
18979d9cf229Sdrh   if( pSrc==pDest ){
18989d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
18999d9cf229Sdrh   }
190055548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
190155548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
190255548273Sdrh   }
19039d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
19047d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
19059d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
19069d9cf229Sdrh   }
19079d9cf229Sdrh #endif
19089d9cf229Sdrh   if( pSrc->pSelect ){
19099d9cf229Sdrh     return 0;   /* tab2 may not be a view */
19109d9cf229Sdrh   }
19119d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
19129d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
19139d9cf229Sdrh   }
19149d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
19159d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
19169d9cf229Sdrh   }
19179d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
19189d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
19199d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
19209d9cf229Sdrh     }
19219d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
19229d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
19239d9cf229Sdrh     }
19249d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
19259d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
19269d9cf229Sdrh     }
19279d9cf229Sdrh   }
19289d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1929f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1930f33c9fadSdrh       destHasUniqueIdx = 1;
1931f33c9fadSdrh     }
19329d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
19339d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19349d9cf229Sdrh     }
19359d9cf229Sdrh     if( pSrcIdx==0 ){
19369d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
19379d9cf229Sdrh     }
19389d9cf229Sdrh   }
19397fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1940619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
19418103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
19428103b7d2Sdrh   }
19437fc2f41bSdrh #endif
1944713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1945713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1946713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1947713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1948713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1949713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1950713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1951713de341Sdrh   */
1952713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1953713de341Sdrh     return 0;
1954713de341Sdrh   }
1955713de341Sdrh #endif
19561696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1957ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
19581696124dSdan   }
19599d9cf229Sdrh 
1960ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1961ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1962ccdf1baeSdrh   ** table (tab1) is initially empty.
19639d9cf229Sdrh   */
1964dd73521bSdrh #ifdef SQLITE_TEST
1965dd73521bSdrh   sqlite3_xferopt_count++;
1966dd73521bSdrh #endif
19679d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
19689d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1969f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
19709d9cf229Sdrh   iSrc = pParse->nTab++;
19719d9cf229Sdrh   iDest = pParse->nTab++;
19726a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
197355548273Sdrh   regData = sqlite3GetTempReg(pParse);
197455548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
19759d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1976427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
1977ccdf1baeSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1978ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
1979ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1980ccdf1baeSdrh   ){
1981ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
1982ccdf1baeSdrh     ** only if the destination table is initially empty.  This code makes
1983ccdf1baeSdrh     ** that determination.  Conditions under which the destination must
1984ccdf1baeSdrh     ** be empty:
1985f33c9fadSdrh     **
1986ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1987ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
1988ccdf1baeSdrh     **     of index entries might need to change.)
1989ccdf1baeSdrh     **
1990ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
1991ccdf1baeSdrh     **     is unable to test uniqueness.)
1992ccdf1baeSdrh     **
1993ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
19949d9cf229Sdrh     */
199566a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
199666a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
19979d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
19989d9cf229Sdrh   }
1999427ebba1Sdan   if( HasRowid(pSrc) ){
20009d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
200166a5167bSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
200242242dedSdrh     if( pDest->iPKey>=0 ){
2003b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2004b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2005f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
20069d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
2007b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
2008bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
2009b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
201095bad4c7Sdrh     }else{
2011b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
20127d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
201395bad4c7Sdrh     }
2014b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
2015b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
2016b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
20171f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
201866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
201955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
202055548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2021da475b8dSdrh   }else{
2022da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2023da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
202455548273Sdrh   }
20259d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
20261b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
20279d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
20289d9cf229Sdrh     }
20299d9cf229Sdrh     assert( pSrcIdx );
2030*2ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
2031*2ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2032d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
2033*2ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
2034*2ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
203559885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2036207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
203766a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
2038b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2039b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
204066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
20419d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
204255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
204355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20449d9cf229Sdrh   }
20459d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
2046b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2047b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
20489d9cf229Sdrh   if( emptyDestTest ){
204966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
20509d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
205166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20529d9cf229Sdrh     return 0;
20539d9cf229Sdrh   }else{
20549d9cf229Sdrh     return 1;
20559d9cf229Sdrh   }
20569d9cf229Sdrh }
20579d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2058