xref: /sqlite-3.40.0/src/insert.c (revision 0978d4ff)
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 /*
18dd9930efSdrh ** Generate code that will open table pTab for reading or writing
19dd9930efSdrh ** on cursor iCur.
20dd9930efSdrh **
21dd9930efSdrh ** Always acquire a table lock.  Always do the open for rowid tables.
22dd9930efSdrh ** For WITHOUT ROWID tables, only do read opens, and then open the
23dd9930efSdrh ** PRIMARY KEY index, not the main table, since the main table doesn't
24dd9930efSdrh ** exist.
25bbb5e4e0Sdrh */
26bbb5e4e0Sdrh void sqlite3OpenTable(
27bbb5e4e0Sdrh   Parse *p,       /* 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) );
35bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
37bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
38ec95c441Sdrh   if( HasRowid(pTab) ){
39261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
40dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
41dd9930efSdrh   }else if( opcode==OP_OpenRead ){
42dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
43dd9930efSdrh     assert( pPk!=0 );
44dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
45dd9930efSdrh     sqlite3VdbeAddOp4(v, opcode, iCur, pPk->tnum, iDb,
46dd9930efSdrh                       (char*)sqlite3IndexKeyinfo(p, pPk), P4_KEYINFO_HANDOFF);
47bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
48bbb5e4e0Sdrh   }
49ec95c441Sdrh }
50bbb5e4e0Sdrh 
51bbb5e4e0Sdrh /*
5269f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5369f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5469f8bb9cSdan ** the table, according to the affinity of the column:
553d1bfeaaSdanielk1977 **
563d1bfeaaSdanielk1977 **  Character      Column affinity
573d1bfeaaSdanielk1977 **  ------------------------------
583eda040bSdrh **  'a'            TEXT
593eda040bSdrh **  'b'            NONE
603eda040bSdrh **  'c'            NUMERIC
613eda040bSdrh **  'd'            INTEGER
623eda040bSdrh **  'e'            REAL
632d401ab8Sdrh **
640c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
652d401ab8Sdrh ** rowid that appears as the last column in every index.
6669f8bb9cSdan **
6769f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6869f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
6969f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
703d1bfeaaSdanielk1977 */
7169f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
72a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
73e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
74a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
75e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
76a37cdde0Sdanielk1977     **
77a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
78e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
79a37cdde0Sdanielk1977     ** up.
80a37cdde0Sdanielk1977     */
81a37cdde0Sdanielk1977     int n;
82a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
83abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
84ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
86633e6d57Sdrh       db->mallocFailed = 1;
8769f8bb9cSdan       return 0;
88a37cdde0Sdanielk1977     }
89ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
90ad124329Sdrh       i16 x = pIdx->aiColumn[n];
91ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
92a37cdde0Sdanielk1977     }
932d401ab8Sdrh     pIdx->zColAff[n] = 0;
94a37cdde0Sdanielk1977   }
953d1bfeaaSdanielk1977 
9669f8bb9cSdan   return pIdx->zColAff;
97a37cdde0Sdanielk1977 }
98a37cdde0Sdanielk1977 
99a37cdde0Sdanielk1977 /*
10066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
101a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
102a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
103a37cdde0Sdanielk1977 ** column:
104a37cdde0Sdanielk1977 **
105a37cdde0Sdanielk1977 **  Character      Column affinity
106a37cdde0Sdanielk1977 **  ------------------------------
1073eda040bSdrh **  'a'            TEXT
1083eda040bSdrh **  'b'            NONE
1093eda040bSdrh **  'c'            NUMERIC
1103eda040bSdrh **  'd'            INTEGER
1113eda040bSdrh **  'e'            REAL
112a37cdde0Sdanielk1977 */
113a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1143d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1153d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1163d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1173d1bfeaaSdanielk1977   **
1183d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1193d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1203d1bfeaaSdanielk1977   */
1213d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1223d1bfeaaSdanielk1977     char *zColAff;
1233d1bfeaaSdanielk1977     int i;
124abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1253d1bfeaaSdanielk1977 
126b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1273d1bfeaaSdanielk1977     if( !zColAff ){
128633e6d57Sdrh       db->mallocFailed = 1;
129a37cdde0Sdanielk1977       return;
1303d1bfeaaSdanielk1977     }
1313d1bfeaaSdanielk1977 
1323d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
133a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1343d1bfeaaSdanielk1977     }
1353d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1363d1bfeaaSdanielk1977 
1373d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1383d1bfeaaSdanielk1977   }
1393d1bfeaaSdanielk1977 
1408d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1413d1bfeaaSdanielk1977 }
1423d1bfeaaSdanielk1977 
1434d88778bSdanielk1977 /*
14448d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
14548d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
14648d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
14748d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
14848d1178aSdrh ** run without using temporary table for the results of the SELECT.
1494d88778bSdanielk1977 */
150595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
151595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1524d88778bSdanielk1977   int i;
15348d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
154595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
155595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
156595a523aSdanielk1977 #endif
157595a523aSdanielk1977 
15848d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
15948d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
160ef0bea92Sdrh     assert( pOp!=0 );
161207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16248d1178aSdrh       Index *pIndex;
163207872a4Sdanielk1977       int tnum = pOp->p2;
16448d1178aSdrh       if( tnum==pTab->tnum ){
16548d1178aSdrh         return 1;
16648d1178aSdrh       }
16748d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
16848d1178aSdrh         if( tnum==pIndex->tnum ){
16948d1178aSdrh           return 1;
17048d1178aSdrh         }
17148d1178aSdrh       }
17248d1178aSdrh     }
173543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
174595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1752dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
17666a5167bSdrh       assert( pOp->p4type==P4_VTAB );
17748d1178aSdrh       return 1;
1784d88778bSdanielk1977     }
179543165efSdrh #endif
1804d88778bSdanielk1977   }
1814d88778bSdanielk1977   return 0;
1824d88778bSdanielk1977 }
1833d1bfeaaSdanielk1977 
1849d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1859d9cf229Sdrh /*
1860b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1870b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1880b9f50d8Sdrh ** that holds the maximum rowid.
1899d9cf229Sdrh **
1900b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1910b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1920b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1930b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1940b9f50d8Sdrh ** AutoincInfo structure is used.
1959d9cf229Sdrh **
1960b9f50d8Sdrh ** Three memory locations are allocated:
1970b9f50d8Sdrh **
1980b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
1990b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2000b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2010b9f50d8Sdrh **
2020b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2030b9f50d8Sdrh ** insert routine needs to know about.
2049d9cf229Sdrh */
2059d9cf229Sdrh static int autoIncBegin(
2069d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2079d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2089d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2099d9cf229Sdrh ){
2106a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2117d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21265a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2130b9f50d8Sdrh     AutoincInfo *pInfo;
2140b9f50d8Sdrh 
21565a7cd16Sdan     pInfo = pToplevel->pAinc;
2160b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2170b9f50d8Sdrh     if( pInfo==0 ){
2180b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2190b9f50d8Sdrh       if( pInfo==0 ) return 0;
22065a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22165a7cd16Sdan       pToplevel->pAinc = pInfo;
2220b9f50d8Sdrh       pInfo->pTab = pTab;
2230b9f50d8Sdrh       pInfo->iDb = iDb;
22465a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
22565a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
22665a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2270b9f50d8Sdrh     }
2280b9f50d8Sdrh     memId = pInfo->regCtr;
2299d9cf229Sdrh   }
2309d9cf229Sdrh   return memId;
2319d9cf229Sdrh }
2329d9cf229Sdrh 
2339d9cf229Sdrh /*
2340b9f50d8Sdrh ** This routine generates code that will initialize all of the
2350b9f50d8Sdrh ** register used by the autoincrement tracker.
2360b9f50d8Sdrh */
2370b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2380b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2390b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2400b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2410b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2420b9f50d8Sdrh   int addr;                  /* A VDBE address */
2430b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2440b9f50d8Sdrh 
245345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
246345ba7dbSdrh   ** only called from the top-level */
247345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
248345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
24976d462eeSdan 
2500b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2510b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2520b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2530b9f50d8Sdrh     memId = p->regCtr;
2542120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2550b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
256f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2570b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2580b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2590b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2600b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2610b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2620b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2630b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2640b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2650b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2660b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2670b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2680b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2690b9f50d8Sdrh   }
2700b9f50d8Sdrh }
2710b9f50d8Sdrh 
2720b9f50d8Sdrh /*
2739d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2749d9cf229Sdrh **
2759d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2769d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2779d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2789d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2799d9cf229Sdrh */
2806a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2819d9cf229Sdrh   if( memId>0 ){
2826a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2839d9cf229Sdrh   }
2849d9cf229Sdrh }
2859d9cf229Sdrh 
2869d9cf229Sdrh /*
2870b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2880b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2890b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2900b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2910b9f50d8Sdrh ** routine just before the "exit" code.
2929d9cf229Sdrh */
2930b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2940b9f50d8Sdrh   AutoincInfo *p;
2959d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2960b9f50d8Sdrh   sqlite3 *db = pParse->db;
2976a288a33Sdrh 
2989d9cf229Sdrh   assert( v );
2990b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3000b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3010b9f50d8Sdrh     int j1, j2, j3, j4, j5;
3020b9f50d8Sdrh     int iRec;
3030b9f50d8Sdrh     int memId = p->regCtr;
3040b9f50d8Sdrh 
3050b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3062120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3070b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3086a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
3090b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
3100b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
3110b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3120b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3130b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3140b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3150b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3160b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3170b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3186a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3190b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
320a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3210b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
32235573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3230b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3240b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3259d9cf229Sdrh   }
3269d9cf229Sdrh }
3279d9cf229Sdrh #else
3289d9cf229Sdrh /*
3299d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3309d9cf229Sdrh ** above are all no-ops
3319d9cf229Sdrh */
3329d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
333287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3349d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3359d9cf229Sdrh 
3369d9cf229Sdrh 
3375f085269Sdrh /*
3385f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3395f085269Sdrh ** row at a time.
3405f085269Sdrh **
3415f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3425f085269Sdrh ** Information about the location of co-routine and the registers it will use
3435f085269Sdrh ** is returned by filling in the pDest object.
3445f085269Sdrh **
3455f085269Sdrh ** Registers are allocated as follows:
3465f085269Sdrh **
3475f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3485f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3495f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3505f085269Sdrh **
3515f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3525f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3535f085269Sdrh **                       generated a new result row, or 1 if the subquery
3545f085269Sdrh **                       has completed.  If the Yield is called again
3555f085269Sdrh **                       after this register becomes 1, then the VDBE will
3565f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3575f085269Sdrh **
3585f085269Sdrh **   pDest->iSdst        First result register.
3595f085269Sdrh **
3605f085269Sdrh **   pDest->nSdst        Number of result registers.
3615f085269Sdrh **
3625f085269Sdrh ** This routine handles all of the register allocation and fills in the
3635f085269Sdrh ** pDest structure appropriately.
3645f085269Sdrh **
3655f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3665f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3675f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3685f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3695f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3705f085269Sdrh **
3715f085269Sdrh **         X <- A
3725f085269Sdrh **         EOF <- 0
3735f085269Sdrh **         goto B
3745f085269Sdrh **      A: setup for the SELECT
3755f085269Sdrh **         loop rows in the SELECT
3765f085269Sdrh **           load results into registers R..S
3775f085269Sdrh **           yield X
3785f085269Sdrh **         end loop
3795f085269Sdrh **         cleanup after the SELECT
3805f085269Sdrh **         EOF <- 1
3815f085269Sdrh **         yield X
3825f085269Sdrh **         halt-error
3835f085269Sdrh **      B:
3845f085269Sdrh **
3855f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3865f085269Sdrh **
3875f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3885f085269Sdrh **      S: yield X
3895f085269Sdrh **         if EOF goto E
3905f085269Sdrh **         if skip this row, goto C
3915f085269Sdrh **         if terminate loop, goto E
3925f085269Sdrh **         deal with this row
3935f085269Sdrh **      C: goto S
3945f085269Sdrh **      E:
3955f085269Sdrh */
3965f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3975f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3985f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
3995f085269Sdrh   int addrTop;        /* Top of the co-routine */
4005f085269Sdrh   int j1;             /* Jump instruction */
4015f085269Sdrh   int rc;             /* Result code */
4025f085269Sdrh   Vdbe *v;            /* VDBE under construction */
4035f085269Sdrh 
4045f085269Sdrh   regYield = ++pParse->nMem;
4055f085269Sdrh   regEof = ++pParse->nMem;
4065f085269Sdrh   v = sqlite3GetVdbe(pParse);
4075f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
4085f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
4095f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
4105f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
4115f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4125f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4135f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4145f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4155f085269Sdrh   assert( pParse->nErr==0 || rc );
4165f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4175f085269Sdrh   if( rc ) return rc;
4185f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4195f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4205f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4215f085269Sdrh   VdbeComment((v, "End of coroutine"));
4225f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4235f085269Sdrh   return rc;
4245f085269Sdrh }
4255f085269Sdrh 
4265f085269Sdrh 
4275f085269Sdrh 
4289d9cf229Sdrh /* Forward declaration */
4299d9cf229Sdrh static int xferOptimization(
4309d9cf229Sdrh   Parse *pParse,        /* Parser context */
4319d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4329d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4339d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4349d9cf229Sdrh   int iDbDest           /* The database of pDest */
4359d9cf229Sdrh );
4369d9cf229Sdrh 
4373d1bfeaaSdanielk1977 /*
438d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
439cce7d176Sdrh **
440cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4411ccde15dSdrh **    insert into TABLE (IDLIST) select
442cce7d176Sdrh **
4431ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4441ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
445967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4461ccde15dSdrh **
4471ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4481ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4491ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4501ccde15dSdrh ** data for the insert.
451142e30dfSdrh **
4529d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
453d82b5021Sdrh ** insert with data coming from a VALUES clause, the code executes
454e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
455e00ee6ebSdrh ** the "1st template"):
456142e30dfSdrh **
457142e30dfSdrh **         open write cursor to <table> and its indices
458ec95c441Sdrh **         put VALUES clause expressions into registers
459142e30dfSdrh **         write the resulting record into <table>
460142e30dfSdrh **         cleanup
461142e30dfSdrh **
4629d9cf229Sdrh ** The three remaining templates assume the statement is of the form
463142e30dfSdrh **
464142e30dfSdrh **   INSERT INTO <table> SELECT ...
465142e30dfSdrh **
4669d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4679d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4689d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4699d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4709d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4719d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4729d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
473e00ee6ebSdrh ** template.  This is the 2nd template.
4749d9cf229Sdrh **
4759d9cf229Sdrh **         open a write cursor to <table>
4769d9cf229Sdrh **         open read cursor on <table2>
4779d9cf229Sdrh **         transfer all records in <table2> over to <table>
4789d9cf229Sdrh **         close cursors
4799d9cf229Sdrh **         foreach index on <table>
4809d9cf229Sdrh **           open a write cursor on the <table> index
4819d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4829d9cf229Sdrh **           transfer all records from the read to the write cursors
4839d9cf229Sdrh **           close cursors
4849d9cf229Sdrh **         end foreach
4859d9cf229Sdrh **
486e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4879d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4889d9cf229Sdrh ** The generated code follows this template:
489142e30dfSdrh **
490e00ee6ebSdrh **         EOF <- 0
491e00ee6ebSdrh **         X <- A
492142e30dfSdrh **         goto B
493142e30dfSdrh **      A: setup for the SELECT
4949d9cf229Sdrh **         loop over the rows in the SELECT
495e00ee6ebSdrh **           load values into registers R..R+n
496e00ee6ebSdrh **           yield X
497142e30dfSdrh **         end loop
498142e30dfSdrh **         cleanup after the SELECT
499e00ee6ebSdrh **         EOF <- 1
500e00ee6ebSdrh **         yield X
501142e30dfSdrh **         goto A
502e00ee6ebSdrh **      B: open write cursor to <table> and its indices
503e00ee6ebSdrh **      C: yield X
504e00ee6ebSdrh **         if EOF goto D
505e00ee6ebSdrh **         insert the select result into <table> from R..R+n
506e00ee6ebSdrh **         goto C
507142e30dfSdrh **      D: cleanup
508142e30dfSdrh **
509e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
510142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
511142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
512142e30dfSdrh ** we have to use a intermediate table to store the results of
513142e30dfSdrh ** the select.  The template is like this:
514142e30dfSdrh **
515e00ee6ebSdrh **         EOF <- 0
516e00ee6ebSdrh **         X <- A
517142e30dfSdrh **         goto B
518142e30dfSdrh **      A: setup for the SELECT
519142e30dfSdrh **         loop over the tables in the SELECT
520e00ee6ebSdrh **           load value into register R..R+n
521e00ee6ebSdrh **           yield X
522142e30dfSdrh **         end loop
523142e30dfSdrh **         cleanup after the SELECT
524e00ee6ebSdrh **         EOF <- 1
525e00ee6ebSdrh **         yield X
526e00ee6ebSdrh **         halt-error
527e00ee6ebSdrh **      B: open temp table
528e00ee6ebSdrh **      L: yield X
529e00ee6ebSdrh **         if EOF goto M
530e00ee6ebSdrh **         insert row from R..R+n into temp table
531e00ee6ebSdrh **         goto L
532e00ee6ebSdrh **      M: open write cursor to <table> and its indices
533e00ee6ebSdrh **         rewind temp table
534e00ee6ebSdrh **      C: loop over rows of intermediate table
535142e30dfSdrh **           transfer values form intermediate table into <table>
536e00ee6ebSdrh **         end loop
537e00ee6ebSdrh **      D: cleanup
538cce7d176Sdrh */
5394adee20fSdanielk1977 void sqlite3Insert(
540cce7d176Sdrh   Parse *pParse,        /* Parser context */
541113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
542cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5435974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5449cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5459cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
546cce7d176Sdrh ){
5476a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5486a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
549113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
550e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5515974a30fSdrh   int i, j, idx;        /* Loop counters */
5525974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5535974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
554967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5556a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
55604adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
557d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5580ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5594d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
560cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
561e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
562e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
563e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5642eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5656a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5662958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
567e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
568ec95c441Sdrh   int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
569cce7d176Sdrh 
5706a288a33Sdrh   /* Register allocations */
5711bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5726a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5736a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5746a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5756a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5766a288a33Sdrh   int regData;          /* register holding first column to insert */
5771bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
578aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5796a288a33Sdrh 
580798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
581798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5822f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5832f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
584798da52cSdrh #endif
585c3f9bad2Sdanielk1977 
58617435752Sdrh   db = pParse->db;
5871bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
58817435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5896f7adc8aSdrh     goto insert_cleanup;
5906f7adc8aSdrh   }
591daffd0e5Sdrh 
5921ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5931ccde15dSdrh   */
594113088ecSdrh   assert( pTabList->nSrc==1 );
595113088ecSdrh   zTab = pTabList->a[0].zName;
596098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5974adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
598c3f9bad2Sdanielk1977   if( pTab==0 ){
599c3f9bad2Sdanielk1977     goto insert_cleanup;
600c3f9bad2Sdanielk1977   }
601da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
602da184236Sdanielk1977   assert( iDb<db->nDb );
603da184236Sdanielk1977   pDb = &db->aDb[iDb];
6042958a4e6Sdrh   zDb = pDb->zName;
6054adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
6061962bda7Sdrh     goto insert_cleanup;
6071962bda7Sdrh   }
608ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
609c3f9bad2Sdanielk1977 
610b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
611b7f9164eSdrh   ** inserted into is a view
612b7f9164eSdrh   */
613b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6142f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
615b7f9164eSdrh   isView = pTab->pSelect!=0;
616b7f9164eSdrh #else
6172f886d1dSdanielk1977 # define pTrigger 0
6182f886d1dSdanielk1977 # define tmask 0
619b7f9164eSdrh # define isView 0
620b7f9164eSdrh #endif
621b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
622b7f9164eSdrh # undef isView
623b7f9164eSdrh # define isView 0
624b7f9164eSdrh #endif
6252f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
626b7f9164eSdrh 
627f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
628d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
629f573c99bSdrh   */
630b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
631f573c99bSdrh     goto insert_cleanup;
632f573c99bSdrh   }
633f573c99bSdrh 
634d82b5021Sdrh   /* Cannot insert into a read-only table.
635595a523aSdanielk1977   */
636595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
637595a523aSdanielk1977     goto insert_cleanup;
638595a523aSdanielk1977   }
639595a523aSdanielk1977 
6401ccde15dSdrh   /* Allocate a VDBE
6411ccde15dSdrh   */
6424adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6435974a30fSdrh   if( v==0 ) goto insert_cleanup;
6444794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6452f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6461ccde15dSdrh 
6479d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6489d9cf229Sdrh   /* If the statement is of the form
6499d9cf229Sdrh   **
6509d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6519d9cf229Sdrh   **
6529d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6539d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
654e00ee6ebSdrh   **
655e00ee6ebSdrh   ** This is the 2nd template.
6569d9cf229Sdrh   */
6579d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6582f886d1dSdanielk1977     assert( !pTrigger );
6599d9cf229Sdrh     assert( pList==0 );
6600b9f50d8Sdrh     goto insert_end;
6619d9cf229Sdrh   }
6629d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6639d9cf229Sdrh 
6642958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6656a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6662958a4e6Sdrh   */
6676a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6682958a4e6Sdrh 
6691ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
670e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
671e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
672e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6731ccde15dSdrh   */
6745974a30fSdrh   if( pSelect ){
675d82b5021Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
6765f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6775f085269Sdrh     if( rc ) goto insert_cleanup;
6781013c932Sdrh 
6795f085269Sdrh     regEof = dest.iSDParm + 1;
6802b596da8Sdrh     regFromSelect = dest.iSdst;
6815974a30fSdrh     assert( pSelect->pEList );
682967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6832b596da8Sdrh     assert( dest.nSdst==nColumn );
684142e30dfSdrh 
685142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
686e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
687d82b5021Sdrh     ** FALSE if each output row of the SELECT can be written directly into
688e00ee6ebSdrh     ** the destination table (template 3).
689048c530cSdrh     **
690048c530cSdrh     ** A temp table must be used if the table being updated is also one
691048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
692048c530cSdrh     ** temp table in the case of row triggers.
693142e30dfSdrh     */
694595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
695048c530cSdrh       useTempTable = 1;
696048c530cSdrh     }
697142e30dfSdrh 
698142e30dfSdrh     if( useTempTable ){
699e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
700e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
701e00ee6ebSdrh       ** here is from the 4th template:
702e00ee6ebSdrh       **
703e00ee6ebSdrh       **      B: open temp table
704e00ee6ebSdrh       **      L: yield X
705e00ee6ebSdrh       **         if EOF goto M
706e00ee6ebSdrh       **         insert row from R..R+n into temp table
707e00ee6ebSdrh       **         goto L
708e00ee6ebSdrh       **      M: ...
709142e30dfSdrh       */
710e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
711dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
712e00ee6ebSdrh       int addrTop;         /* Label "L" */
713e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
714b7654111Sdrh 
715142e30dfSdrh       srcTab = pParse->nTab++;
716b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
717dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
718e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7192b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
720e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7211db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
722dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
723dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
724e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
725e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
726b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
727dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
728142e30dfSdrh     }
729142e30dfSdrh   }else{
730142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
731142e30dfSdrh     ** clause
732142e30dfSdrh     */
733b3bce662Sdanielk1977     NameContext sNC;
734b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
735b3bce662Sdanielk1977     sNC.pParse = pParse;
7365974a30fSdrh     srcTab = -1;
73748d1178aSdrh     assert( useTempTable==0 );
738147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
739e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7407d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
741b04a5d87Sdrh         goto insert_cleanup;
742b04a5d87Sdrh       }
743e64e7b20Sdrh     }
7445974a30fSdrh   }
7451ccde15dSdrh 
7461ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7471ccde15dSdrh   ** of columns to be inserted into the table.
7481ccde15dSdrh   */
749034ca14fSdanielk1977   if( IsVirtual(pTab) ){
750034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
751034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
752034ca14fSdanielk1977     }
753034ca14fSdanielk1977   }
754034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7554adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
756da93d238Sdrh        "table %S has %d columns but %d values were supplied",
757d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
758cce7d176Sdrh     goto insert_cleanup;
759cce7d176Sdrh   }
760967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7614adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
762cce7d176Sdrh     goto insert_cleanup;
763cce7d176Sdrh   }
7641ccde15dSdrh 
7651ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7661ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7671ccde15dSdrh   ** remember the column indices.
768c8392586Sdrh   **
769c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
770d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
771d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
772c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
773d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
774d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
7751ccde15dSdrh   */
776967e8b73Sdrh   if( pColumn ){
777967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
778967e8b73Sdrh       pColumn->a[i].idx = -1;
779cce7d176Sdrh     }
780967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
781cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7824adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
783967e8b73Sdrh           pColumn->a[i].idx = j;
7844a32431cSdrh           if( j==pTab->iPKey ){
785d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
7864a32431cSdrh           }
787cce7d176Sdrh           break;
788cce7d176Sdrh         }
789cce7d176Sdrh       }
790cce7d176Sdrh       if( j>=pTab->nCol ){
791ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
792d82b5021Sdrh           ipkColumn = i;
793a0217ba7Sdrh         }else{
7944adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
795da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
7961db95106Sdan           pParse->checkSchema = 1;
797cce7d176Sdrh           goto insert_cleanup;
798cce7d176Sdrh         }
799cce7d176Sdrh       }
800cce7d176Sdrh     }
801a0217ba7Sdrh   }
8021ccde15dSdrh 
803aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
804d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
805d82b5021Sdrh   ** column index in the original table definition.
8064a32431cSdrh   */
807147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
808d82b5021Sdrh     ipkColumn = pTab->iPKey;
8094a32431cSdrh   }
8104a32431cSdrh 
811c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8121ccde15dSdrh   */
813142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8146a288a33Sdrh     regRowCount = ++pParse->nMem;
8156a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
816c3f9bad2Sdanielk1977   }
817c3f9bad2Sdanielk1977 
818e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
819e448dc4aSdanielk1977   if( !isView ){
820aa9b8963Sdrh     int nIdx;
821aa9b8963Sdrh 
822ec95c441Sdrh     baseCur = pParse->nTab - withoutRowid;
823261c02d9Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, -1, OP_OpenWrite);
8245c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
825aa9b8963Sdrh     if( aRegIdx==0 ){
826aa9b8963Sdrh       goto insert_cleanup;
827aa9b8963Sdrh     }
828aa9b8963Sdrh     for(i=0; i<nIdx; i++){
829aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
830aa9b8963Sdrh     }
831feeb1394Sdrh   }
832feeb1394Sdrh 
833e00ee6ebSdrh   /* This is the top of the main insertion loop */
834142e30dfSdrh   if( useTempTable ){
835e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
836e00ee6ebSdrh     ** following pseudocode (template 4):
837e00ee6ebSdrh     **
838e00ee6ebSdrh     **         rewind temp table
839e00ee6ebSdrh     **      C: loop over rows of intermediate table
840e00ee6ebSdrh     **           transfer values form intermediate table into <table>
841e00ee6ebSdrh     **         end loop
842e00ee6ebSdrh     **      D: ...
843e00ee6ebSdrh     */
844e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
845e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
846142e30dfSdrh   }else if( pSelect ){
847e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
848e00ee6ebSdrh     ** following pseudocode (template 3):
849e00ee6ebSdrh     **
850e00ee6ebSdrh     **      C: yield X
851e00ee6ebSdrh     **         if EOF goto D
852e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
853e00ee6ebSdrh     **         goto C
854e00ee6ebSdrh     **      D: ...
855e00ee6ebSdrh     */
8562b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
857e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
858bed8690fSdrh   }
8591ccde15dSdrh 
8606a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8616a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8626a288a33Sdrh   */
8636a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8646a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8656a288a33Sdrh   if( IsVirtual(pTab) ){
8666a288a33Sdrh     regRowid++;
8676a288a33Sdrh     pParse->nMem++;
8686a288a33Sdrh   }
8696a288a33Sdrh   regData = regRowid+1;
8706a288a33Sdrh 
8715cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
87270ce3f0cSdrh   */
8734adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8742f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
87576d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
876c3f9bad2Sdanielk1977 
87770ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
87870ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
87970ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
88070ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
88170ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
88270ce3f0cSdrh     */
883d82b5021Sdrh     if( ipkColumn<0 ){
88476d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88570ce3f0cSdrh     }else{
8866a288a33Sdrh       int j1;
887ec95c441Sdrh       assert( !withoutRowid );
8887fe45908Sdrh       if( useTempTable ){
889d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
8907fe45908Sdrh       }else{
891d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
892d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
8937fe45908Sdrh       }
89476d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89576d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
8966a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
89776d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89870ce3f0cSdrh     }
89970ce3f0cSdrh 
900034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
901034ca14fSdanielk1977     ** this block would have to account for hidden column.
902034ca14fSdanielk1977     */
903034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
904034ca14fSdanielk1977 
90570ce3f0cSdrh     /* Create the new column data
90670ce3f0cSdrh     */
907c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
908c3f9bad2Sdanielk1977       if( pColumn==0 ){
909c3f9bad2Sdanielk1977         j = i;
910c3f9bad2Sdanielk1977       }else{
911c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
912c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
913c3f9bad2Sdanielk1977         }
914c3f9bad2Sdanielk1977       }
9157ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91676d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
917142e30dfSdrh       }else if( useTempTable ){
91876d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
919c3f9bad2Sdanielk1977       }else{
920d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
92176d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
922c3f9bad2Sdanielk1977       }
923c3f9bad2Sdanielk1977     }
924a37cdde0Sdanielk1977 
925a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
926a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
927a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
928a37cdde0Sdanielk1977     ** table column affinities.
929a37cdde0Sdanielk1977     */
930a37cdde0Sdanielk1977     if( !isView ){
93176d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
932a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
933a37cdde0Sdanielk1977     }
934c3f9bad2Sdanielk1977 
9355cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
936165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
93794d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
938165921a7Sdan 
93976d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
94070ce3f0cSdrh   }
941c3f9bad2Sdanielk1977 
942d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
943d82b5021Sdrh   ** registers beginning at regIns.
9441ccde15dSdrh   */
9455cf590c1Sdrh   if( !isView ){
9464cbdda9eSdrh     if( IsVirtual(pTab) ){
9474cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9486a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9494cbdda9eSdrh     }
950d82b5021Sdrh     if( ipkColumn>=0 ){
951142e30dfSdrh       if( useTempTable ){
952d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
953142e30dfSdrh       }else if( pSelect ){
954d82b5021Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid);
9554a32431cSdrh       }else{
956e4d90813Sdrh         VdbeOp *pOp;
957d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
95820411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9591b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
960e4d90813Sdrh           appendFlag = 1;
961e4d90813Sdrh           pOp->opcode = OP_NewRowid;
96204adf416Sdrh           pOp->p1 = baseCur;
9636a288a33Sdrh           pOp->p2 = regRowid;
9646a288a33Sdrh           pOp->p3 = regAutoinc;
965e4d90813Sdrh         }
96627a32783Sdrh       }
967f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
968e1e68f49Sdrh       ** to generate a unique primary key value.
969e1e68f49Sdrh       */
970e4d90813Sdrh       if( !appendFlag ){
9711db639ceSdrh         int j1;
972bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9731db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
97404adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
9751db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
976bb50e7adSdanielk1977         }else{
977bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
978bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
979bb50e7adSdanielk1977         }
9803c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
981e4d90813Sdrh       }
982ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9836a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9844a32431cSdrh     }else{
98504adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
986e4d90813Sdrh       appendFlag = 1;
9874a32431cSdrh     }
9886a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9894a32431cSdrh 
990d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
9914a32431cSdrh     ** with the first column.
9924a32431cSdrh     */
993034ca14fSdanielk1977     nHidden = 0;
994cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9956a288a33Sdrh       int iRegStore = regRowid+1+i;
9964a32431cSdrh       if( i==pTab->iPKey ){
9974a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
998d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
999d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
1000aacc543eSdrh         ** taking up data space with information that will never be used. */
10014c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
10024a32431cSdrh         continue;
10034a32431cSdrh       }
1004967e8b73Sdrh       if( pColumn==0 ){
1005034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1006034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1007034ca14fSdanielk1977           j = -1;
1008034ca14fSdanielk1977           nHidden++;
1009034ca14fSdanielk1977         }else{
1010034ca14fSdanielk1977           j = i - nHidden;
1011034ca14fSdanielk1977         }
1012cce7d176Sdrh       }else{
1013967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1014967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1015cce7d176Sdrh         }
1016cce7d176Sdrh       }
1017034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1018287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1019142e30dfSdrh       }else if( useTempTable ){
1020287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1021142e30dfSdrh       }else if( pSelect ){
1022b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1023cce7d176Sdrh       }else{
1024287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1025cce7d176Sdrh       }
1026cce7d176Sdrh     }
10271ccde15dSdrh 
10280ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10290ca3e24bSdrh     ** do the insertion.
10304a32431cSdrh     */
10314cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10324cbdda9eSdrh     if( IsVirtual(pTab) ){
1033595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10344f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1035595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1036b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1037e0af83acSdan       sqlite3MayAbort(pParse);
10384cbdda9eSdrh     }else
10394cbdda9eSdrh #endif
10404cbdda9eSdrh     {
1041de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1042de630353Sdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
1043d82b5021Sdrh           ipkColumn>=0, 0, onError, endOfLoop, &isReplace
104404adf416Sdrh       );
10458ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
104604adf416Sdrh       sqlite3CompleteInsertion(
10472832ad42Sdan           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
104804adf416Sdrh       );
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 */
1079ec95c441Sdrh     if( !withoutRowid ) sqlite3VdbeAddOp1(v, OP_Close, baseCur);
10806b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
10812eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
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 /*
112711e85273Sdrh ** If regFirst is a set of value for a table row in table order and pPk
112811e85273Sdrh ** is the PRIMARY KEY index for that table, then return the index of the
112911e85273Sdrh ** first register in a contiguous array of registers that are the primary
113011e85273Sdrh ** key values for the table row.
113111e85273Sdrh **
113211e85273Sdrh ** For the common cases where the PRIMARY KEY has only a single value or
113311e85273Sdrh ** where a multi-value PRIMARY KEY is contiguous in table order, this
113411e85273Sdrh ** routine simply returns a pointer into the regFirst array.  But if there
113511e85273Sdrh ** is a multi-value PRIMARY KEY with the values out-of-order, this routine
113611e85273Sdrh ** has to generate code that will copy PRIMARY KEY values into newly
113711e85273Sdrh ** allocated contiguous registers.
113811e85273Sdrh */
113911e85273Sdrh static int sqlite3PrimaryKeyRegisters(Parse *pParse, Index *pPk, int regFirst){
114011e85273Sdrh   int i;
114111e85273Sdrh   int nKeyCol = pPk->nKeyCol;
114211e85273Sdrh   int regPk;
114311e85273Sdrh   assert( pParse->pVdbe!=0 );
114411e85273Sdrh   if( nKeyCol==1 ){
114511e85273Sdrh     return regFirst + pPk->aiColumn[0];
114611e85273Sdrh   }
114711e85273Sdrh   for(i=1; i<nKeyCol; i++){
114811e85273Sdrh     if( pPk->aiColumn[i-1]+1!=pPk->aiColumn[i] ) break;
114911e85273Sdrh   }
115011e85273Sdrh   if( i==nKeyCol ){
115111e85273Sdrh     return regFirst + pPk->aiColumn[0];
115211e85273Sdrh   }
115311e85273Sdrh   regPk = pParse->nMem+1;
115411e85273Sdrh   pParse->nMem += nKeyCol;
115511e85273Sdrh   for(i=0; i<nKeyCol; i++){
115611e85273Sdrh     int x = pPk->aiColumn[i];
115711e85273Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, regFirst+x, regPk+i);
115811e85273Sdrh   }
115911e85273Sdrh   return regPk;
116011e85273Sdrh }
116111e85273Sdrh 
116275cbd984Sdan 
11639cfcf5d4Sdrh /*
11646a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
11659cfcf5d4Sdrh **
116604adf416Sdrh ** The input is a range of consecutive registers as follows:
11670ca3e24bSdrh **
116811e85273Sdrh **    1.  The rowid of the row after the update, or NULL
116911e85273Sdrh **        for WITHOUT ROWID tables.
11700ca3e24bSdrh **
117165a7cd16Sdan **    2.  The data in the first column of the entry after the update.
11720ca3e24bSdrh **
11730ca3e24bSdrh **    i.  Data from middle columns...
11740ca3e24bSdrh **
11750ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
11760ca3e24bSdrh **
117765a7cd16Sdan ** The regRowid parameter is the index of the register containing (1).
117804adf416Sdrh **
1179ea22abe3Sdrh ** If isUpdate is true and pkChng is non-zero, then pkChng contains
1180d82b5021Sdrh ** the address of a range of registers containing the rowid or PRIMARY KEY
1181d82b5021Sdrh ** value before the update takes place. isUpdate is true for UPDATEs and
1182d82b5021Sdrh ** false for INSERTs. If isUpdate is false then a non-zero pkChng
118365a7cd16Sdan ** indicates that the rowid was explicitly specified as part of the
1184ea22abe3Sdrh ** INSERT statement. If pkChng is false, it means that  the rowid is
1185*0978d4ffSdrh ** computed automatically in an insert and is therefore guaranteed to
1186*0978d4ffSdrh ** be unique. The pkChng parameter is always false for inserts
1187d82b5021Sdrh ** into a WITHOUT ROWID table.
11880ca3e24bSdrh **
1189ea22abe3Sdrh ** The code generated by this routine should store new index entries into
1190aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1191aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1192aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1193aa9b8963Sdrh ** attached to the table.
11949cfcf5d4Sdrh **
11959cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11969cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11971c92853dSdrh ** then the appropriate action is performed.  There are five possible
11981c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11999cfcf5d4Sdrh **
12009cfcf5d4Sdrh **  Constraint type  Action       What Happens
12019cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
12021c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
120324b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
12049cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
12059cfcf5d4Sdrh **
12061c92853dSdrh **  any              ABORT        Back out changes from the current command
12071c92853dSdrh **                                only (do not do a complete rollback) then
120824b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
12091c92853dSdrh **                                with SQLITE_CONSTRAINT.
12101c92853dSdrh **
1211e4c88c0cSdrh **  any              FAIL         Sqlite3_exec() returns immediately with a
12121c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
12131c92853dSdrh **                                transaction is not rolled back and any
12141c92853dSdrh **                                prior changes are retained.
12151c92853dSdrh **
12169cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
12179cfcf5d4Sdrh **                                the stack and there is an immediate jump
12189cfcf5d4Sdrh **                                to label ignoreDest.
12199cfcf5d4Sdrh **
12209cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
12219cfcf5d4Sdrh **                                value for that column.  If the default value
12229cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
12239cfcf5d4Sdrh **
12249cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
12259cfcf5d4Sdrh **                                being inserted is removed.
12269cfcf5d4Sdrh **
12279cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12289cfcf5d4Sdrh **
12291c92853dSdrh ** Which action to take is determined by the overrideError parameter.
12301c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12311c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12321c92853dSdrh ** for the constraint is used.
12339cfcf5d4Sdrh **
1234aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
123504adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
123604adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
12379cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1238aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
12399cfcf5d4Sdrh */
12404adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12419cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
12429cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
1243ea22abe3Sdrh   int baseCur,        /* A read/write cursor pointing at pTab */
1244ea22abe3Sdrh   int regRowid,       /* First register in a range holding values to insert */
1245aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
124611e85273Sdrh   int pkChng,         /* Non-zero if the rowid or PRIMARY KEY changed */
1247b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
12489cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1249de630353Sdanielk1977   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
1250de630353Sdanielk1977   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
12519cfcf5d4Sdrh ){
12521b7ecbb4Sdrh   int i;              /* loop counter */
12531b7ecbb4Sdrh   Vdbe *v;            /* VDBE under constrution */
12541b7ecbb4Sdrh   int nCol;           /* Number of columns */
12551b7ecbb4Sdrh   int onError;        /* Conflict resolution strategy */
12561bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
125704adf416Sdrh   int regData;        /* Register containing first data column */
12581b7ecbb4Sdrh   int iCur;           /* Table cursor number */
12591b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
126011e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
12612938f924Sdrh   sqlite3 *db;         /* Database connection */
12621b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
126311e85273Sdrh   int regOldPk;        /* Previous rowid or PRIMARY KEY value */
126411e85273Sdrh   int regNewPk = 0;    /* New PRIMARY KEY value */
126511e85273Sdrh   int pkCur = 0;       /* Cursor used by the PRIMARY KEY */
12669cfcf5d4Sdrh 
126711e85273Sdrh   regOldPk = (pkChng && isUpdate) ? pkChng : regRowid;
12682938f924Sdrh   db = pParse->db;
12694adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12709cfcf5d4Sdrh   assert( v!=0 );
1271417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12729cfcf5d4Sdrh   nCol = pTab->nCol;
1273aa9b8963Sdrh   regData = regRowid + 1;
1274aa9b8963Sdrh 
127511e85273Sdrh   /* For WITHOUT ROWID tables, we'll need to know the Index and the cursor
127611e85273Sdrh   ** number for the PRIMARY KEY index */
127711e85273Sdrh   if( !HasRowid(pTab) ){
1278*0978d4ffSdrh     assert( pkChng==0 || isUpdate!=0 );
127911e85273Sdrh     pkCur = baseCur+1;
128011e85273Sdrh     pPk = pTab->pIndex;
128111e85273Sdrh     while( ALWAYS(pPk) && pPk->autoIndex!=2 ){
128211e85273Sdrh       pPk=pPk->pNext;
128311e85273Sdrh       pkCur++;
128411e85273Sdrh     }
128511e85273Sdrh   }
128611e85273Sdrh 
12879cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12889cfcf5d4Sdrh   */
12899cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12900ca3e24bSdrh     if( i==pTab->iPKey ){
12910ca3e24bSdrh       continue;
12920ca3e24bSdrh     }
12939cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12940ca3e24bSdrh     if( onError==OE_None ) continue;
12959cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12969cfcf5d4Sdrh       onError = overrideError;
1297a996e477Sdrh     }else if( onError==OE_Default ){
1298a996e477Sdrh       onError = OE_Abort;
12999cfcf5d4Sdrh     }
13007977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
13019cfcf5d4Sdrh       onError = OE_Abort;
13029cfcf5d4Sdrh     }
1303b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1304b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
13059cfcf5d4Sdrh     switch( onError ){
13061c92853dSdrh       case OE_Abort:
1307e0af83acSdan         sqlite3MayAbort(pParse);
1308*0978d4ffSdrh         /* Fall through */
1309e0af83acSdan       case OE_Rollback:
13101c92853dSdrh       case OE_Fail: {
1311f089aa45Sdrh         char *zMsg;
1312c126e63eSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1313d91c1a17Sdrh                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
13142938f924Sdrh         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
1315f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
131666a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
13179cfcf5d4Sdrh         break;
13189cfcf5d4Sdrh       }
13199cfcf5d4Sdrh       case OE_Ignore: {
13205053a79bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
13219cfcf5d4Sdrh         break;
13229cfcf5d4Sdrh       }
1323098d1684Sdrh       default: {
1324098d1684Sdrh         assert( onError==OE_Replace );
13255053a79bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
132604adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
13275053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
13289cfcf5d4Sdrh         break;
13299cfcf5d4Sdrh       }
13309cfcf5d4Sdrh     }
13319cfcf5d4Sdrh   }
13329cfcf5d4Sdrh 
13339cfcf5d4Sdrh   /* Test all CHECK constraints
13349cfcf5d4Sdrh   */
1335ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
13362938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
13372938f924Sdrh     ExprList *pCheck = pTab->pCheck;
1338aa9b8963Sdrh     pParse->ckBase = regData;
1339aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
13402938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
13412938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
13422d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
13432e06c67cSdrh       if( onError==OE_Ignore ){
134466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1345aa01c7e2Sdrh       }else{
13462938f924Sdrh         char *zConsName = pCheck->a[i].zName;
13476dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
13482938f924Sdrh         if( zConsName ){
13492938f924Sdrh           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
13502938f924Sdrh         }else{
1351f68686aeSdrh           zConsName = 0;
13522938f924Sdrh         }
1353d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1354d91c1a17Sdrh                               onError, zConsName, P4_DYNAMIC);
1355aa01c7e2Sdrh       }
1356ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1357c31c7c1cSdrh     }
13582938f924Sdrh   }
1359ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13609cfcf5d4Sdrh 
1361*0978d4ffSdrh   /* If there is an INTEGER PRIMARY KEY, make sure the primary key
13620bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
13630bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
136411e85273Sdrh   **
136511e85273Sdrh   ** This block only runs for tables that have a rowid.
13669cfcf5d4Sdrh   */
136711e85273Sdrh   if( pkChng && pkCur==0 ){
136811e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
136911e85273Sdrh 
13700ca3e24bSdrh     onError = pTab->keyConf;
13710ca3e24bSdrh     if( overrideError!=OE_Default ){
13720ca3e24bSdrh       onError = overrideError;
1373a996e477Sdrh     }else if( onError==OE_Default ){
1374a996e477Sdrh       onError = OE_Abort;
13750ca3e24bSdrh     }
1376a0217ba7Sdrh 
137779b0c956Sdrh     if( isUpdate ){
137811e85273Sdrh       sqlite3VdbeAddOp3(v, OP_Eq, regRowid, addrRowidOk, pkChng);
137979b0c956Sdrh     }
138011e85273Sdrh     sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, addrRowidOk, regRowid);
13810ca3e24bSdrh     switch( onError ){
1382a0217ba7Sdrh       default: {
1383a0217ba7Sdrh         onError = OE_Abort;
1384a0217ba7Sdrh         /* Fall thru into the next case */
1385a0217ba7Sdrh       }
13861c92853dSdrh       case OE_Rollback:
13871c92853dSdrh       case OE_Abort:
13881c92853dSdrh       case OE_Fail: {
1389d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1390d91c1a17Sdrh            onError, "PRIMARY KEY must be unique", P4_STATIC);
13910ca3e24bSdrh         break;
13920ca3e24bSdrh       }
13935383ae5cSdrh       case OE_Replace: {
13942283d46cSdan         /* If there are DELETE triggers on this table and the
13952283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1396d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13972283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13982283d46cSdan         **
13992283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1400da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1401da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1402da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1403da730f6eSdan         ** when it is inserted.
1404da730f6eSdan         **
1405da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1406da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1407da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1408da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1409da730f6eSdan         ** but being more selective here allows statements like:
1410da730f6eSdan         **
1411da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1412da730f6eSdan         **
1413da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1414da730f6eSdan         ** table.
1415da730f6eSdan         */
14162283d46cSdan         Trigger *pTrigger = 0;
14172938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14182283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14192283d46cSdan         }
1420e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1421da730f6eSdan           sqlite3MultiWrite(pParse);
14222283d46cSdan           sqlite3GenerateRowDelete(
1423ecb31b63Sdrh               pParse, pTab, pTrigger, baseCur, regRowid, 0, 0, OE_Replace
14242283d46cSdan           );
1425da730f6eSdan         }else if( pTab->pIndex ){
1426da730f6eSdan           sqlite3MultiWrite(pParse);
14272d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
14282283d46cSdan         }
14295383ae5cSdrh         seenReplace = 1;
14305383ae5cSdrh         break;
14315383ae5cSdrh       }
14320ca3e24bSdrh       case OE_Ignore: {
14335383ae5cSdrh         assert( seenReplace==0 );
143466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14350ca3e24bSdrh         break;
14360ca3e24bSdrh       }
14370ca3e24bSdrh     }
143811e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
14390ca3e24bSdrh   }
14400bd1f4eaSdrh 
14410bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
14420bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
144311e85273Sdrh   ** Compute the revised record entries for indices as we go.
14440bd1f4eaSdrh   */
1445b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
14462d401ab8Sdrh     int regIdx;
14472d401ab8Sdrh     int regR;
144811e85273Sdrh     int idxCur = baseCur+iCur+1;
144911e85273Sdrh     int addrUniqueOk = sqlite3VdbeMakeLabel(v);
14502184fc75Sdrh 
1451*0978d4ffSdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip indices that do not change */
1452b2fe7d8cSdrh 
1453b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1454b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
1455b2b9d3d7Sdrh       pParse->ckBase = regData;
145611e85273Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1457b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1458b2b9d3d7Sdrh       pParse->ckBase = 0;
1459b2b9d3d7Sdrh     }
1460b2b9d3d7Sdrh 
1461b2fe7d8cSdrh     /* Create a key for accessing the index entry */
146211e85273Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
14639cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
1464bbbdc83bSdrh       i16 idx = pIdx->aiColumn[i];
1465bbbdc83bSdrh       if( idx<0 || idx==pTab->iPKey ){
14662d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
14679cfcf5d4Sdrh       }else{
14682d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
14699cfcf5d4Sdrh       }
14709cfcf5d4Sdrh     }
1471bbbdc83bSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[iCur]);
14728d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
1473bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1474b2fe7d8cSdrh 
1475b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
14769cfcf5d4Sdrh     onError = pIdx->onError;
1477de630353Sdanielk1977     if( onError==OE_None ){
1478bbbdc83bSdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
147911e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1480de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1481de630353Sdanielk1977     }
14829cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14839cfcf5d4Sdrh       onError = overrideError;
1484a996e477Sdrh     }else if( onError==OE_Default ){
1485a996e477Sdrh       onError = OE_Abort;
14869cfcf5d4Sdrh     }
14875383ae5cSdrh     if( seenReplace ){
14885383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
14895383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
14905383ae5cSdrh     }
14915383ae5cSdrh 
1492b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
14932d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
149411e85273Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, idxCur, addrUniqueOk,
14956f225d0dSdrh                          regIdx, pIdx->nKeyCol);
1496*0978d4ffSdrh #if 0
1497*0978d4ffSdrh     if( !isUpdate ){
1498*0978d4ffSdrh       /* A pre-existing row is always a conflict on an insert */
1499*0978d4ffSdrh     }else
1500*0978d4ffSdrh #endif
150111e85273Sdrh     if( HasRowid(pTab) ){
1502*0978d4ffSdrh       /* Conflict only if the rowid of the existing index entry
1503*0978d4ffSdrh       ** is different from old-rowid */
150411e85273Sdrh       sqlite3VdbeAddOp2(v, OP_IdxRowid, idxCur, regR);
150511e85273Sdrh       sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldPk);
150611e85273Sdrh     }else if( pIdx->autoIndex==2 ){
1507*0978d4ffSdrh       /* For PRIMARY KEY index on a WITHOUT ROWID table, conflict only
1508*0978d4ffSdrh       ** if the PRIMARY KEY has changed.  If the PRIMARY KEY is unchanged,
1509*0978d4ffSdrh       ** then the matching entry is just the original row that is being
1510*0978d4ffSdrh       ** modified. */
151111e85273Sdrh       int addrPkConflict = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
151211e85273Sdrh       for(i=0; i<pPk->nKeyCol-1; i++){
151311e85273Sdrh         sqlite3VdbeAddOp3(v, OP_Ne,
151411e85273Sdrh                           regOldPk+pPk->aiColumn[i], addrPkConflict, regIdx+i);
151511e85273Sdrh       }
151611e85273Sdrh       sqlite3VdbeAddOp3(v, OP_Eq,
151711e85273Sdrh                         regOldPk+pPk->aiColumn[i], addrUniqueOk, regIdx+i);
151811e85273Sdrh     }else{
1519*0978d4ffSdrh       /* For a UNIQUE index on a WITHOUT ROWID table, conflict only if the
1520*0978d4ffSdrh       ** PRIMARY KEY value of the match is different from the old PRIMARY KEY
1521*0978d4ffSdrh       ** value from before the update. */
152211e85273Sdrh       int addrConflict = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol*2;
152311e85273Sdrh       assert( pIdx->nKeyCol + pPk->nKeyCol == pIdx->nColumn );
152411e85273Sdrh       for(i=0; i<pPk->nKeyCol-1; i++){
152511e85273Sdrh         sqlite3VdbeAddOp3(v, OP_Column, idxCur, pIdx->nKeyCol+i, regR);
152611e85273Sdrh         sqlite3VdbeAddOp3(v, OP_Ne,
152711e85273Sdrh                           regOldPk+pPk->aiColumn[i], addrConflict, regR);
152811e85273Sdrh       }
152911e85273Sdrh       sqlite3VdbeAddOp3(v, OP_Column, idxCur, pIdx->nKeyCol+i, regR);
153011e85273Sdrh       sqlite3VdbeAddOp3(v, OP_Eq,
153111e85273Sdrh                         regOldPk+pPk->aiColumn[i], addrUniqueOk, regR);
153211e85273Sdrh     }
153311e85273Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1534b2fe7d8cSdrh 
1535b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1536b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1537b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
15389cfcf5d4Sdrh     switch( onError ){
15391c92853dSdrh       case OE_Rollback:
15401c92853dSdrh       case OE_Abort:
15411c92853dSdrh       case OE_Fail: {
1542098d1684Sdrh         int j;
1543098d1684Sdrh         StrAccum errMsg;
1544098d1684Sdrh         const char *zSep;
1545098d1684Sdrh         char *zErr;
1546098d1684Sdrh 
1547098d1684Sdrh         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
15482938f924Sdrh         errMsg.db = db;
1549bbbdc83bSdrh         zSep = pIdx->nKeyCol>1 ? "columns " : "column ";
1550bbbdc83bSdrh         for(j=0; j<pIdx->nKeyCol; j++){
155137ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1552098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zSep, -1);
1553098d1684Sdrh           zSep = ", ";
1554098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zCol, -1);
155537ed48edSdrh         }
1556098d1684Sdrh         sqlite3StrAccumAppend(&errMsg,
1557bbbdc83bSdrh             pIdx->nKeyCol>1 ? " are not unique" : " is not unique", -1);
1558098d1684Sdrh         zErr = sqlite3StrAccumFinish(&errMsg);
1559d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
1560d91c1a17Sdrh                               onError, zErr, 0);
1561098d1684Sdrh         sqlite3DbFree(errMsg.db, zErr);
15629cfcf5d4Sdrh         break;
15639cfcf5d4Sdrh       }
15649cfcf5d4Sdrh       case OE_Ignore: {
15650ca3e24bSdrh         assert( seenReplace==0 );
156666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
15679cfcf5d4Sdrh         break;
15689cfcf5d4Sdrh       }
1569098d1684Sdrh       default: {
15702283d46cSdan         Trigger *pTrigger = 0;
1571098d1684Sdrh         assert( onError==OE_Replace );
15721bea559aSdan         sqlite3MultiWrite(pParse);
15732938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15742283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15752283d46cSdan         }
15762283d46cSdan         sqlite3GenerateRowDelete(
1577ecb31b63Sdrh             pParse, pTab, pTrigger, baseCur, regR, 0, 0, OE_Replace
15782283d46cSdan         );
15790ca3e24bSdrh         seenReplace = 1;
15809cfcf5d4Sdrh         break;
15819cfcf5d4Sdrh       }
15829cfcf5d4Sdrh     }
158311e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
15842d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
15859cfcf5d4Sdrh   }
1586de630353Sdanielk1977 
1587de630353Sdanielk1977   if( pbMayReplace ){
1588de630353Sdanielk1977     *pbMayReplace = seenReplace;
1589de630353Sdanielk1977   }
15909cfcf5d4Sdrh }
15910ca3e24bSdrh 
15920ca3e24bSdrh /*
15930ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
15944adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
159504adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
159604adf416Sdrh ** rowid and the content to be inserted.
15970ca3e24bSdrh **
1598b419a926Sdrh ** The arguments to this routine should be the same as the first six
15994adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
16000ca3e24bSdrh */
16014adee20fSdanielk1977 void sqlite3CompleteInsertion(
16020ca3e24bSdrh   Parse *pParse,      /* The parser context */
16030ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
160404adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
160504adf416Sdrh   int regRowid,       /* Range of content */
1606aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
160770ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1608de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1609de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
16100ca3e24bSdrh ){
16110ca3e24bSdrh   int i;
16120ca3e24bSdrh   Vdbe *v;
16130ca3e24bSdrh   Index *pIdx;
16141bd10f8aSdrh   u8 pik_flags;
161504adf416Sdrh   int regData;
1616b7654111Sdrh   int regRec;
16170ca3e24bSdrh 
16184adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
16190ca3e24bSdrh   assert( v!=0 );
1620417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1621b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1622aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1623b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1624b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1625b2b9d3d7Sdrh     }
162604adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1627de630353Sdanielk1977     if( useSeekResult ){
1628de630353Sdanielk1977       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1629de630353Sdanielk1977     }
16300ca3e24bSdrh   }
1631ec95c441Sdrh   if( !HasRowid(pTab) ) return;
163204adf416Sdrh   regData = regRowid + 1;
1633b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
16341db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1635a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1636da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
16374794f735Sdrh   if( pParse->nested ){
16384794f735Sdrh     pik_flags = 0;
16394794f735Sdrh   }else{
164094eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
164194eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
16424794f735Sdrh   }
1643e4d90813Sdrh   if( appendBias ){
1644e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1645e4d90813Sdrh   }
1646de630353Sdanielk1977   if( useSeekResult ){
1647de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1648de630353Sdanielk1977   }
1649b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
165094eb6a14Sdanielk1977   if( !pParse->nested ){
16518d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
165294eb6a14Sdanielk1977   }
1653b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
16540ca3e24bSdrh }
1655cd44690aSdrh 
1656cd44690aSdrh /*
1657290c1948Sdrh ** Generate code that will open cursors for a table and for all
165804adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1659cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1660aa9b8963Sdrh **
1661aa9b8963Sdrh ** Return the number of indices on the table.
1662cd44690aSdrh */
1663aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1664290c1948Sdrh   Parse *pParse,   /* Parsing context */
1665290c1948Sdrh   Table *pTab,     /* Table to be opened */
166604adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1667261c02d9Sdrh   int pkCur,       /* Cursor number for the primary key */
1668290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1669290c1948Sdrh ){
1670cd44690aSdrh   int i;
16714cbdda9eSdrh   int iDb;
1672cd44690aSdrh   Index *pIdx;
16734cbdda9eSdrh   Vdbe *v;
16744cbdda9eSdrh 
1675aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
16764cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
16774cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1678cd44690aSdrh   assert( v!=0 );
167904adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1680cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1681b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1682261c02d9Sdrh     int iCur = (pkCur>=0 && pIdx->autoIndex==2) ? pkCur : i+baseCur;
1683da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
1684261c02d9Sdrh     sqlite3VdbeAddOp4(v, op, iCur, pIdx->tnum, iDb,
168566a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1686207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1687cd44690aSdrh   }
1688261c02d9Sdrh   if( pParse->nTab<=i+baseCur ) pParse->nTab = i+baseCur;
1689aa9b8963Sdrh   return i-1;
1690cd44690aSdrh }
16919d9cf229Sdrh 
169291c58e23Sdrh 
169391c58e23Sdrh #ifdef SQLITE_TEST
169491c58e23Sdrh /*
169591c58e23Sdrh ** The following global variable is incremented whenever the
169691c58e23Sdrh ** transfer optimization is used.  This is used for testing
169791c58e23Sdrh ** purposes only - to make sure the transfer optimization really
169891c58e23Sdrh ** is happening when it is suppose to.
169991c58e23Sdrh */
170091c58e23Sdrh int sqlite3_xferopt_count;
170191c58e23Sdrh #endif /* SQLITE_TEST */
170291c58e23Sdrh 
170391c58e23Sdrh 
17049d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
17059d9cf229Sdrh /*
17069d9cf229Sdrh ** Check to collation names to see if they are compatible.
17079d9cf229Sdrh */
17089d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
17099d9cf229Sdrh   if( z1==0 ){
17109d9cf229Sdrh     return z2==0;
17119d9cf229Sdrh   }
17129d9cf229Sdrh   if( z2==0 ){
17139d9cf229Sdrh     return 0;
17149d9cf229Sdrh   }
17159d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
17169d9cf229Sdrh }
17179d9cf229Sdrh 
17189d9cf229Sdrh 
17199d9cf229Sdrh /*
17209d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
17219d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
17229d9cf229Sdrh ** for a compatible index:
17239d9cf229Sdrh **
17249d9cf229Sdrh **    *   The index is over the same set of columns
17259d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
17269d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
17279d9cf229Sdrh **    *   The same collating sequence on each column
1728b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
17299d9cf229Sdrh */
17309d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
17319d9cf229Sdrh   int i;
17329d9cf229Sdrh   assert( pDest && pSrc );
17339d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1734bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
17359d9cf229Sdrh     return 0;   /* Different number of columns */
17369d9cf229Sdrh   }
17379d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
17389d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
17399d9cf229Sdrh   }
1740bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
17419d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
17429d9cf229Sdrh       return 0;   /* Different columns indexed */
17439d9cf229Sdrh     }
17449d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
17459d9cf229Sdrh       return 0;   /* Different sort orders */
17469d9cf229Sdrh     }
17473f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
174860a713c6Sdrh       return 0;   /* Different collating sequences */
17499d9cf229Sdrh     }
17509d9cf229Sdrh   }
1751619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1752b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1753b2b9d3d7Sdrh   }
17549d9cf229Sdrh 
17559d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
17569d9cf229Sdrh   return 1;
17579d9cf229Sdrh }
17589d9cf229Sdrh 
17599d9cf229Sdrh /*
17609d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
17619d9cf229Sdrh **
17629d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
17639d9cf229Sdrh **
1764ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1765ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1766ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
17679d9cf229Sdrh **
1768ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1769ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1770ccdf1baeSdrh ** embedded in the code for details.
17719d9cf229Sdrh **
1772ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1773ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1774ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1775ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1776ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1777ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1778ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1779ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1780ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
17819d9cf229Sdrh **
1782ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
17839d9cf229Sdrh */
17849d9cf229Sdrh static int xferOptimization(
17859d9cf229Sdrh   Parse *pParse,        /* Parser context */
17869d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
17879d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
17889d9cf229Sdrh   int onError,          /* How to handle constraint errors */
17899d9cf229Sdrh   int iDbDest           /* The database of pDest */
17909d9cf229Sdrh ){
17919d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
17929d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
17939d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
17949d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
17959d9cf229Sdrh   int i;                           /* Loop counter */
17969d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
17979d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
17989d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
17999d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
18009d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
18019d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
18029d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
18036a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1804f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1805b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
18069d9cf229Sdrh 
18079d9cf229Sdrh   if( pSelect==0 ){
18089d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
18099d9cf229Sdrh   }
18102f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
18119d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
18129d9cf229Sdrh   }
18139d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18147d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
18159d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
18169d9cf229Sdrh   }
18179d9cf229Sdrh #endif
18189d9cf229Sdrh   if( onError==OE_Default ){
1819e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1820e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
18219d9cf229Sdrh   }
18225ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
18239d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
18249d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
18259d9cf229Sdrh   }
18269d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
18279d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
18289d9cf229Sdrh   }
18299d9cf229Sdrh   if( pSelect->pWhere ){
18309d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
18319d9cf229Sdrh   }
18329d9cf229Sdrh   if( pSelect->pOrderBy ){
18339d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
18349d9cf229Sdrh   }
18358103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
18368103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
18379d9cf229Sdrh   if( pSelect->pGroupBy ){
18389d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
18399d9cf229Sdrh   }
18409d9cf229Sdrh   if( pSelect->pLimit ){
18419d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
18429d9cf229Sdrh   }
18438103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
18449d9cf229Sdrh   if( pSelect->pPrior ){
18459d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
18469d9cf229Sdrh   }
18477d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
18489d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
18499d9cf229Sdrh   }
18509d9cf229Sdrh   pEList = pSelect->pEList;
18519d9cf229Sdrh   assert( pEList!=0 );
18529d9cf229Sdrh   if( pEList->nExpr!=1 ){
18539d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
18549d9cf229Sdrh   }
18559d9cf229Sdrh   assert( pEList->a[0].pExpr );
18569d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
18579d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
18589d9cf229Sdrh   }
18599d9cf229Sdrh 
18609d9cf229Sdrh   /* At this point we have established that the statement is of the
18619d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
18629d9cf229Sdrh   ** we have to check the semantics.
18639d9cf229Sdrh   */
18649d9cf229Sdrh   pItem = pSelect->pSrc->a;
186541fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
18669d9cf229Sdrh   if( pSrc==0 ){
18679d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
18689d9cf229Sdrh   }
18699d9cf229Sdrh   if( pSrc==pDest ){
18709d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
18719d9cf229Sdrh   }
187255548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
187355548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
187455548273Sdrh   }
18759d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18767d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
18779d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
18789d9cf229Sdrh   }
18799d9cf229Sdrh #endif
18809d9cf229Sdrh   if( pSrc->pSelect ){
18819d9cf229Sdrh     return 0;   /* tab2 may not be a view */
18829d9cf229Sdrh   }
18839d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
18849d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
18859d9cf229Sdrh   }
18869d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
18879d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
18889d9cf229Sdrh   }
188955548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
189055548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
189155548273Sdrh   }
18929d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
18939d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
18949d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
18959d9cf229Sdrh     }
18969d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
18979d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
18989d9cf229Sdrh     }
18999d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
19009d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
19019d9cf229Sdrh     }
19029d9cf229Sdrh   }
19039d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1904f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1905f33c9fadSdrh       destHasUniqueIdx = 1;
1906f33c9fadSdrh     }
19079d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
19089d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19099d9cf229Sdrh     }
19109d9cf229Sdrh     if( pSrcIdx==0 ){
19119d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
19129d9cf229Sdrh     }
19139d9cf229Sdrh   }
19147fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1915619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
19168103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
19178103b7d2Sdrh   }
19187fc2f41bSdrh #endif
1919713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1920713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1921713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1922713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1923713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1924713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1925713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1926713de341Sdrh   */
1927713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1928713de341Sdrh     return 0;
1929713de341Sdrh   }
1930713de341Sdrh #endif
19311696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1932ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
19331696124dSdan   }
19349d9cf229Sdrh 
1935ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1936ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1937ccdf1baeSdrh   ** table (tab1) is initially empty.
19389d9cf229Sdrh   */
1939dd73521bSdrh #ifdef SQLITE_TEST
1940dd73521bSdrh   sqlite3_xferopt_count++;
1941dd73521bSdrh #endif
19429d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
19439d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1944f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
19459d9cf229Sdrh   iSrc = pParse->nTab++;
19469d9cf229Sdrh   iDest = pParse->nTab++;
19476a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
194855548273Sdrh   regData = sqlite3GetTempReg(pParse);
194955548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
195055548273Sdrh   if( HasRowid(pSrc) ){
19519d9cf229Sdrh     sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1952ccdf1baeSdrh     if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1953ccdf1baeSdrh      || destHasUniqueIdx                              /* (2) */
1954ccdf1baeSdrh      || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1955ccdf1baeSdrh     ){
1956ccdf1baeSdrh       /* In some circumstances, we are able to run the xfer optimization
1957ccdf1baeSdrh       ** only if the destination table is initially empty.  This code makes
1958ccdf1baeSdrh       ** that determination.  Conditions under which the destination must
1959ccdf1baeSdrh       ** be empty:
1960f33c9fadSdrh       **
1961ccdf1baeSdrh       ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1962ccdf1baeSdrh       **     (If the destination is not initially empty, the rowid fields
1963ccdf1baeSdrh       **     of index entries might need to change.)
1964ccdf1baeSdrh       **
1965ccdf1baeSdrh       ** (2) The destination has a unique index.  (The xfer optimization
1966ccdf1baeSdrh       **     is unable to test uniqueness.)
1967ccdf1baeSdrh       **
1968ccdf1baeSdrh       ** (3) onError is something other than OE_Abort and OE_Rollback.
19699d9cf229Sdrh       */
197066a5167bSdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
197166a5167bSdrh       emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
19729d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr1);
19739d9cf229Sdrh     }else{
19749d9cf229Sdrh       emptyDestTest = 0;
19759d9cf229Sdrh     }
19769d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
197766a5167bSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
197842242dedSdrh     if( pDest->iPKey>=0 ){
1979b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1980b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1981d91c1a17Sdrh       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1982d91c1a17Sdrh           onError, "PRIMARY KEY must be unique", P4_STATIC);
19839d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
1984b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
1985bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
1986b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
198795bad4c7Sdrh     }else{
1988b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
19897d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
199095bad4c7Sdrh     }
1991b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1992b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1993b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
19941f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
199566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
199655548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
199755548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
199855548273Sdrh   }
19999d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
20001b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
20019d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
20029d9cf229Sdrh     }
20039d9cf229Sdrh     assert( pSrcIdx );
20049d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
2005207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
2006207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
2007d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
20089d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
2009207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
201066a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
201159885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2012207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
201366a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
2014b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2015b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
201666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
20179d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
201855548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
201955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20209d9cf229Sdrh   }
20219d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
2022b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2023b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
20249d9cf229Sdrh   if( emptyDestTest ){
202566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
20269d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
202766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20289d9cf229Sdrh     return 0;
20299d9cf229Sdrh   }else{
20309d9cf229Sdrh     return 1;
20319d9cf229Sdrh   }
20329d9cf229Sdrh }
20339d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2034