xref: /sqlite-3.40.0/src/insert.c (revision bbbdc83b)
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 /*
18bbb5e4e0Sdrh ** Generate code that will open a table for reading.
19bbb5e4e0Sdrh */
20bbb5e4e0Sdrh void sqlite3OpenTable(
21bbb5e4e0Sdrh   Parse *p,       /* Generate code into this VDBE */
22bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
23bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
24bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
25bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
26bbb5e4e0Sdrh ){
27bbb5e4e0Sdrh   Vdbe *v;
285f53aac2Sdrh   assert( !IsVirtual(pTab) );
29bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
30bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
31bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
32bbb5e4e0Sdrh   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
33bbb5e4e0Sdrh   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
34bbb5e4e0Sdrh   VdbeComment((v, "%s", pTab->zName));
35bbb5e4e0Sdrh }
36bbb5e4e0Sdrh 
37bbb5e4e0Sdrh /*
3869f8bb9cSdan ** Return a pointer to the column affinity string associated with index
3969f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
4069f8bb9cSdan ** the table, according to the affinity of the column:
413d1bfeaaSdanielk1977 **
423d1bfeaaSdanielk1977 **  Character      Column affinity
433d1bfeaaSdanielk1977 **  ------------------------------
443eda040bSdrh **  'a'            TEXT
453eda040bSdrh **  'b'            NONE
463eda040bSdrh **  'c'            NUMERIC
473eda040bSdrh **  'd'            INTEGER
483eda040bSdrh **  'e'            REAL
492d401ab8Sdrh **
500c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
512d401ab8Sdrh ** rowid that appears as the last column in every index.
5269f8bb9cSdan **
5369f8bb9cSdan ** Memory for the buffer containing the column index affinity string
5469f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
5569f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
563d1bfeaaSdanielk1977 */
5769f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
58a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
59e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
60a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
61e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
62a37cdde0Sdanielk1977     **
63a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
64e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
65a37cdde0Sdanielk1977     ** up.
66a37cdde0Sdanielk1977     */
67a37cdde0Sdanielk1977     int n;
68a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
69abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
70*bbbdc83bSdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nKeyCol+2);
71a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
72633e6d57Sdrh       db->mallocFailed = 1;
7369f8bb9cSdan       return 0;
74a37cdde0Sdanielk1977     }
75*bbbdc83bSdrh     for(n=0; n<pIdx->nKeyCol; n++){
76a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
77a37cdde0Sdanielk1977     }
780c733f67Sdan     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
792d401ab8Sdrh     pIdx->zColAff[n] = 0;
80a37cdde0Sdanielk1977   }
813d1bfeaaSdanielk1977 
8269f8bb9cSdan   return pIdx->zColAff;
83a37cdde0Sdanielk1977 }
84a37cdde0Sdanielk1977 
85a37cdde0Sdanielk1977 /*
8666a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
87a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
88a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
89a37cdde0Sdanielk1977 ** column:
90a37cdde0Sdanielk1977 **
91a37cdde0Sdanielk1977 **  Character      Column affinity
92a37cdde0Sdanielk1977 **  ------------------------------
933eda040bSdrh **  'a'            TEXT
943eda040bSdrh **  'b'            NONE
953eda040bSdrh **  'c'            NUMERIC
963eda040bSdrh **  'd'            INTEGER
973eda040bSdrh **  'e'            REAL
98a37cdde0Sdanielk1977 */
99a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1003d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1013d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1023d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1033d1bfeaaSdanielk1977   **
1043d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1053d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1063d1bfeaaSdanielk1977   */
1073d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1083d1bfeaaSdanielk1977     char *zColAff;
1093d1bfeaaSdanielk1977     int i;
110abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1113d1bfeaaSdanielk1977 
112b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1133d1bfeaaSdanielk1977     if( !zColAff ){
114633e6d57Sdrh       db->mallocFailed = 1;
115a37cdde0Sdanielk1977       return;
1163d1bfeaaSdanielk1977     }
1173d1bfeaaSdanielk1977 
1183d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
119a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1203d1bfeaaSdanielk1977     }
1213d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1223d1bfeaaSdanielk1977 
1233d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1243d1bfeaaSdanielk1977   }
1253d1bfeaaSdanielk1977 
1268d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1273d1bfeaaSdanielk1977 }
1283d1bfeaaSdanielk1977 
1294d88778bSdanielk1977 /*
13048d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
13148d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
13248d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
13348d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
13448d1178aSdrh ** run without using temporary table for the results of the SELECT.
1354d88778bSdanielk1977 */
136595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
137595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1384d88778bSdanielk1977   int i;
13948d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
140595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
141595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
142595a523aSdanielk1977 #endif
143595a523aSdanielk1977 
14448d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
14548d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
146ef0bea92Sdrh     assert( pOp!=0 );
147207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
14848d1178aSdrh       Index *pIndex;
149207872a4Sdanielk1977       int tnum = pOp->p2;
15048d1178aSdrh       if( tnum==pTab->tnum ){
15148d1178aSdrh         return 1;
15248d1178aSdrh       }
15348d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
15448d1178aSdrh         if( tnum==pIndex->tnum ){
15548d1178aSdrh           return 1;
15648d1178aSdrh         }
15748d1178aSdrh       }
15848d1178aSdrh     }
159543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
160595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1612dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
16266a5167bSdrh       assert( pOp->p4type==P4_VTAB );
16348d1178aSdrh       return 1;
1644d88778bSdanielk1977     }
165543165efSdrh #endif
1664d88778bSdanielk1977   }
1674d88778bSdanielk1977   return 0;
1684d88778bSdanielk1977 }
1693d1bfeaaSdanielk1977 
1709d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1719d9cf229Sdrh /*
1720b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1730b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1740b9f50d8Sdrh ** that holds the maximum rowid.
1759d9cf229Sdrh **
1760b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1770b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1780b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1790b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1800b9f50d8Sdrh ** AutoincInfo structure is used.
1819d9cf229Sdrh **
1820b9f50d8Sdrh ** Three memory locations are allocated:
1830b9f50d8Sdrh **
1840b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
1850b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
1860b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
1870b9f50d8Sdrh **
1880b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
1890b9f50d8Sdrh ** insert routine needs to know about.
1909d9cf229Sdrh */
1919d9cf229Sdrh static int autoIncBegin(
1929d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1939d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1949d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1959d9cf229Sdrh ){
1966a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
1977d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
19865a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
1990b9f50d8Sdrh     AutoincInfo *pInfo;
2000b9f50d8Sdrh 
20165a7cd16Sdan     pInfo = pToplevel->pAinc;
2020b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2030b9f50d8Sdrh     if( pInfo==0 ){
2040b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2050b9f50d8Sdrh       if( pInfo==0 ) return 0;
20665a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
20765a7cd16Sdan       pToplevel->pAinc = pInfo;
2080b9f50d8Sdrh       pInfo->pTab = pTab;
2090b9f50d8Sdrh       pInfo->iDb = iDb;
21065a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
21165a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
21265a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2130b9f50d8Sdrh     }
2140b9f50d8Sdrh     memId = pInfo->regCtr;
2159d9cf229Sdrh   }
2169d9cf229Sdrh   return memId;
2179d9cf229Sdrh }
2189d9cf229Sdrh 
2199d9cf229Sdrh /*
2200b9f50d8Sdrh ** This routine generates code that will initialize all of the
2210b9f50d8Sdrh ** register used by the autoincrement tracker.
2220b9f50d8Sdrh */
2230b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2240b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2250b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2260b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2270b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2280b9f50d8Sdrh   int addr;                  /* A VDBE address */
2290b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2300b9f50d8Sdrh 
231345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
232345ba7dbSdrh   ** only called from the top-level */
233345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
234345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
23576d462eeSdan 
2360b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2370b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2380b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2390b9f50d8Sdrh     memId = p->regCtr;
2402120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2410b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
242f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2430b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2440b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2450b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2460b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2470b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2480b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2490b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2500b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2510b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2520b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2530b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2540b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2550b9f50d8Sdrh   }
2560b9f50d8Sdrh }
2570b9f50d8Sdrh 
2580b9f50d8Sdrh /*
2599d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2609d9cf229Sdrh **
2619d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2629d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2639d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2649d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2659d9cf229Sdrh */
2666a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2679d9cf229Sdrh   if( memId>0 ){
2686a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2699d9cf229Sdrh   }
2709d9cf229Sdrh }
2719d9cf229Sdrh 
2729d9cf229Sdrh /*
2730b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2740b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2750b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2760b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2770b9f50d8Sdrh ** routine just before the "exit" code.
2789d9cf229Sdrh */
2790b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2800b9f50d8Sdrh   AutoincInfo *p;
2819d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2820b9f50d8Sdrh   sqlite3 *db = pParse->db;
2836a288a33Sdrh 
2849d9cf229Sdrh   assert( v );
2850b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2860b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
2870b9f50d8Sdrh     int j1, j2, j3, j4, j5;
2880b9f50d8Sdrh     int iRec;
2890b9f50d8Sdrh     int memId = p->regCtr;
2900b9f50d8Sdrh 
2910b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
2922120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2930b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2946a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
2950b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
2960b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
2970b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
2980b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
2990b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3000b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3010b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3020b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3030b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3046a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3050b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
306a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3070b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
30835573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3090b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3100b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3119d9cf229Sdrh   }
3129d9cf229Sdrh }
3139d9cf229Sdrh #else
3149d9cf229Sdrh /*
3159d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3169d9cf229Sdrh ** above are all no-ops
3179d9cf229Sdrh */
3189d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
319287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3209d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3219d9cf229Sdrh 
3229d9cf229Sdrh 
3235f085269Sdrh /*
3245f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3255f085269Sdrh ** row at a time.
3265f085269Sdrh **
3275f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3285f085269Sdrh ** Information about the location of co-routine and the registers it will use
3295f085269Sdrh ** is returned by filling in the pDest object.
3305f085269Sdrh **
3315f085269Sdrh ** Registers are allocated as follows:
3325f085269Sdrh **
3335f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3345f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3355f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3365f085269Sdrh **
3375f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3385f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3395f085269Sdrh **                       generated a new result row, or 1 if the subquery
3405f085269Sdrh **                       has completed.  If the Yield is called again
3415f085269Sdrh **                       after this register becomes 1, then the VDBE will
3425f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3435f085269Sdrh **
3445f085269Sdrh **   pDest->iSdst        First result register.
3455f085269Sdrh **
3465f085269Sdrh **   pDest->nSdst        Number of result registers.
3475f085269Sdrh **
3485f085269Sdrh ** This routine handles all of the register allocation and fills in the
3495f085269Sdrh ** pDest structure appropriately.
3505f085269Sdrh **
3515f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3525f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3535f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3545f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3555f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3565f085269Sdrh **
3575f085269Sdrh **         X <- A
3585f085269Sdrh **         EOF <- 0
3595f085269Sdrh **         goto B
3605f085269Sdrh **      A: setup for the SELECT
3615f085269Sdrh **         loop rows in the SELECT
3625f085269Sdrh **           load results into registers R..S
3635f085269Sdrh **           yield X
3645f085269Sdrh **         end loop
3655f085269Sdrh **         cleanup after the SELECT
3665f085269Sdrh **         EOF <- 1
3675f085269Sdrh **         yield X
3685f085269Sdrh **         halt-error
3695f085269Sdrh **      B:
3705f085269Sdrh **
3715f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3725f085269Sdrh **
3735f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3745f085269Sdrh **      S: yield X
3755f085269Sdrh **         if EOF goto E
3765f085269Sdrh **         if skip this row, goto C
3775f085269Sdrh **         if terminate loop, goto E
3785f085269Sdrh **         deal with this row
3795f085269Sdrh **      C: goto S
3805f085269Sdrh **      E:
3815f085269Sdrh */
3825f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3835f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3845f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
3855f085269Sdrh   int addrTop;        /* Top of the co-routine */
3865f085269Sdrh   int j1;             /* Jump instruction */
3875f085269Sdrh   int rc;             /* Result code */
3885f085269Sdrh   Vdbe *v;            /* VDBE under construction */
3895f085269Sdrh 
3905f085269Sdrh   regYield = ++pParse->nMem;
3915f085269Sdrh   regEof = ++pParse->nMem;
3925f085269Sdrh   v = sqlite3GetVdbe(pParse);
3935f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
3945f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
3955f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
3965f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
3975f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
3985f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
3995f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4005f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4015f085269Sdrh   assert( pParse->nErr==0 || rc );
4025f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4035f085269Sdrh   if( rc ) return rc;
4045f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4055f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4065f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4075f085269Sdrh   VdbeComment((v, "End of coroutine"));
4085f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4095f085269Sdrh   return rc;
4105f085269Sdrh }
4115f085269Sdrh 
4125f085269Sdrh 
4135f085269Sdrh 
4149d9cf229Sdrh /* Forward declaration */
4159d9cf229Sdrh static int xferOptimization(
4169d9cf229Sdrh   Parse *pParse,        /* Parser context */
4179d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4189d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4199d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4209d9cf229Sdrh   int iDbDest           /* The database of pDest */
4219d9cf229Sdrh );
4229d9cf229Sdrh 
4233d1bfeaaSdanielk1977 /*
4241ccde15dSdrh ** This routine is call to handle SQL of the following forms:
425cce7d176Sdrh **
426cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4271ccde15dSdrh **    insert into TABLE (IDLIST) select
428cce7d176Sdrh **
4291ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4301ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
431967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4321ccde15dSdrh **
4331ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4341ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4351ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4361ccde15dSdrh ** data for the insert.
437142e30dfSdrh **
4389d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
439142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
440e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
441e00ee6ebSdrh ** the "1st template"):
442142e30dfSdrh **
443142e30dfSdrh **         open write cursor to <table> and its indices
444142e30dfSdrh **         puts VALUES clause expressions onto the stack
445142e30dfSdrh **         write the resulting record into <table>
446142e30dfSdrh **         cleanup
447142e30dfSdrh **
4489d9cf229Sdrh ** The three remaining templates assume the statement is of the form
449142e30dfSdrh **
450142e30dfSdrh **   INSERT INTO <table> SELECT ...
451142e30dfSdrh **
4529d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4539d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4549d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4559d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4569d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4579d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4589d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
459e00ee6ebSdrh ** template.  This is the 2nd template.
4609d9cf229Sdrh **
4619d9cf229Sdrh **         open a write cursor to <table>
4629d9cf229Sdrh **         open read cursor on <table2>
4639d9cf229Sdrh **         transfer all records in <table2> over to <table>
4649d9cf229Sdrh **         close cursors
4659d9cf229Sdrh **         foreach index on <table>
4669d9cf229Sdrh **           open a write cursor on the <table> index
4679d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4689d9cf229Sdrh **           transfer all records from the read to the write cursors
4699d9cf229Sdrh **           close cursors
4709d9cf229Sdrh **         end foreach
4719d9cf229Sdrh **
472e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4739d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4749d9cf229Sdrh ** The generated code follows this template:
475142e30dfSdrh **
476e00ee6ebSdrh **         EOF <- 0
477e00ee6ebSdrh **         X <- A
478142e30dfSdrh **         goto B
479142e30dfSdrh **      A: setup for the SELECT
4809d9cf229Sdrh **         loop over the rows in the SELECT
481e00ee6ebSdrh **           load values into registers R..R+n
482e00ee6ebSdrh **           yield X
483142e30dfSdrh **         end loop
484142e30dfSdrh **         cleanup after the SELECT
485e00ee6ebSdrh **         EOF <- 1
486e00ee6ebSdrh **         yield X
487142e30dfSdrh **         goto A
488e00ee6ebSdrh **      B: open write cursor to <table> and its indices
489e00ee6ebSdrh **      C: yield X
490e00ee6ebSdrh **         if EOF goto D
491e00ee6ebSdrh **         insert the select result into <table> from R..R+n
492e00ee6ebSdrh **         goto C
493142e30dfSdrh **      D: cleanup
494142e30dfSdrh **
495e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
496142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
497142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
498142e30dfSdrh ** we have to use a intermediate table to store the results of
499142e30dfSdrh ** the select.  The template is like this:
500142e30dfSdrh **
501e00ee6ebSdrh **         EOF <- 0
502e00ee6ebSdrh **         X <- A
503142e30dfSdrh **         goto B
504142e30dfSdrh **      A: setup for the SELECT
505142e30dfSdrh **         loop over the tables in the SELECT
506e00ee6ebSdrh **           load value into register R..R+n
507e00ee6ebSdrh **           yield X
508142e30dfSdrh **         end loop
509142e30dfSdrh **         cleanup after the SELECT
510e00ee6ebSdrh **         EOF <- 1
511e00ee6ebSdrh **         yield X
512e00ee6ebSdrh **         halt-error
513e00ee6ebSdrh **      B: open temp table
514e00ee6ebSdrh **      L: yield X
515e00ee6ebSdrh **         if EOF goto M
516e00ee6ebSdrh **         insert row from R..R+n into temp table
517e00ee6ebSdrh **         goto L
518e00ee6ebSdrh **      M: open write cursor to <table> and its indices
519e00ee6ebSdrh **         rewind temp table
520e00ee6ebSdrh **      C: loop over rows of intermediate table
521142e30dfSdrh **           transfer values form intermediate table into <table>
522e00ee6ebSdrh **         end loop
523e00ee6ebSdrh **      D: cleanup
524cce7d176Sdrh */
5254adee20fSdanielk1977 void sqlite3Insert(
526cce7d176Sdrh   Parse *pParse,        /* Parser context */
527113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
528cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5295974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5309cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5319cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
532cce7d176Sdrh ){
5336a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5346a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
535113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
536e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5375974a30fSdrh   int i, j, idx;        /* Loop counters */
5385974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5395974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
540967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5416a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
54204adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
5434a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5440ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5454d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
546cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
547e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
548e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
549e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5502eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5516a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5522958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
553e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
554cce7d176Sdrh 
5556a288a33Sdrh   /* Register allocations */
5561bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5576a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5586a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5596a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5606a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5616a288a33Sdrh   int regData;          /* register holding first column to insert */
5621bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
563aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5646a288a33Sdrh 
565798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
566798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5672f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5682f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
569798da52cSdrh #endif
570c3f9bad2Sdanielk1977 
57117435752Sdrh   db = pParse->db;
5721bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
57317435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5746f7adc8aSdrh     goto insert_cleanup;
5756f7adc8aSdrh   }
576daffd0e5Sdrh 
5771ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5781ccde15dSdrh   */
579113088ecSdrh   assert( pTabList->nSrc==1 );
580113088ecSdrh   zTab = pTabList->a[0].zName;
581098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5824adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
583c3f9bad2Sdanielk1977   if( pTab==0 ){
584c3f9bad2Sdanielk1977     goto insert_cleanup;
585c3f9bad2Sdanielk1977   }
586da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
587da184236Sdanielk1977   assert( iDb<db->nDb );
588da184236Sdanielk1977   pDb = &db->aDb[iDb];
5892958a4e6Sdrh   zDb = pDb->zName;
5904adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
5911962bda7Sdrh     goto insert_cleanup;
5921962bda7Sdrh   }
593c3f9bad2Sdanielk1977 
594b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
595b7f9164eSdrh   ** inserted into is a view
596b7f9164eSdrh   */
597b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
5982f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
599b7f9164eSdrh   isView = pTab->pSelect!=0;
600b7f9164eSdrh #else
6012f886d1dSdanielk1977 # define pTrigger 0
6022f886d1dSdanielk1977 # define tmask 0
603b7f9164eSdrh # define isView 0
604b7f9164eSdrh #endif
605b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
606b7f9164eSdrh # undef isView
607b7f9164eSdrh # define isView 0
608b7f9164eSdrh #endif
6092f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
610b7f9164eSdrh 
611f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
612b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
613b3d24bf8Sdanielk1977   ** module table).
614f573c99bSdrh   */
615b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
616f573c99bSdrh     goto insert_cleanup;
617f573c99bSdrh   }
618f573c99bSdrh 
619595a523aSdanielk1977   /* Ensure that:
620595a523aSdanielk1977   *  (a) the table is not read-only,
621595a523aSdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
622595a523aSdanielk1977   */
623595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
624595a523aSdanielk1977     goto insert_cleanup;
625595a523aSdanielk1977   }
626595a523aSdanielk1977 
6271ccde15dSdrh   /* Allocate a VDBE
6281ccde15dSdrh   */
6294adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6305974a30fSdrh   if( v==0 ) goto insert_cleanup;
6314794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6322f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6331ccde15dSdrh 
6349d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6359d9cf229Sdrh   /* If the statement is of the form
6369d9cf229Sdrh   **
6379d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6389d9cf229Sdrh   **
6399d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6409d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
641e00ee6ebSdrh   **
642e00ee6ebSdrh   ** This is the 2nd template.
6439d9cf229Sdrh   */
6449d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6452f886d1dSdanielk1977     assert( !pTrigger );
6469d9cf229Sdrh     assert( pList==0 );
6470b9f50d8Sdrh     goto insert_end;
6489d9cf229Sdrh   }
6499d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6509d9cf229Sdrh 
6512958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6526a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6532958a4e6Sdrh   */
6546a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6552958a4e6Sdrh 
6561ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
657e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
658e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
659e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6601ccde15dSdrh   */
6615974a30fSdrh   if( pSelect ){
6625f085269Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run that
6635f085269Sdrh     ** SELECT. */
6645f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6655f085269Sdrh     if( rc ) goto insert_cleanup;
6661013c932Sdrh 
6675f085269Sdrh     regEof = dest.iSDParm + 1;
6682b596da8Sdrh     regFromSelect = dest.iSdst;
6695974a30fSdrh     assert( pSelect->pEList );
670967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6712b596da8Sdrh     assert( dest.nSdst==nColumn );
672142e30dfSdrh 
673142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
674e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
675e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
676e00ee6ebSdrh     ** the destination table (template 3).
677048c530cSdrh     **
678048c530cSdrh     ** A temp table must be used if the table being updated is also one
679048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
680048c530cSdrh     ** temp table in the case of row triggers.
681142e30dfSdrh     */
682595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
683048c530cSdrh       useTempTable = 1;
684048c530cSdrh     }
685142e30dfSdrh 
686142e30dfSdrh     if( useTempTable ){
687e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
688e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
689e00ee6ebSdrh       ** here is from the 4th template:
690e00ee6ebSdrh       **
691e00ee6ebSdrh       **      B: open temp table
692e00ee6ebSdrh       **      L: yield X
693e00ee6ebSdrh       **         if EOF goto M
694e00ee6ebSdrh       **         insert row from R..R+n into temp table
695e00ee6ebSdrh       **         goto L
696e00ee6ebSdrh       **      M: ...
697142e30dfSdrh       */
698e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
699dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
700e00ee6ebSdrh       int addrTop;         /* Label "L" */
701e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
702b7654111Sdrh 
703142e30dfSdrh       srcTab = pParse->nTab++;
704b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
705dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
706e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7072b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
708e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7091db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
710dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
711dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
712e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
713e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
714b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
715dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
716142e30dfSdrh     }
717142e30dfSdrh   }else{
718142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
719142e30dfSdrh     ** clause
720142e30dfSdrh     */
721b3bce662Sdanielk1977     NameContext sNC;
722b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
723b3bce662Sdanielk1977     sNC.pParse = pParse;
7245974a30fSdrh     srcTab = -1;
72548d1178aSdrh     assert( useTempTable==0 );
726147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
727e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7287d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
729b04a5d87Sdrh         goto insert_cleanup;
730b04a5d87Sdrh       }
731e64e7b20Sdrh     }
7325974a30fSdrh   }
7331ccde15dSdrh 
7341ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7351ccde15dSdrh   ** of columns to be inserted into the table.
7361ccde15dSdrh   */
737034ca14fSdanielk1977   if( IsVirtual(pTab) ){
738034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
739034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
740034ca14fSdanielk1977     }
741034ca14fSdanielk1977   }
742034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7434adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
744da93d238Sdrh        "table %S has %d columns but %d values were supplied",
745d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
746cce7d176Sdrh     goto insert_cleanup;
747cce7d176Sdrh   }
748967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7494adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
750cce7d176Sdrh     goto insert_cleanup;
751cce7d176Sdrh   }
7521ccde15dSdrh 
7531ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7541ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7551ccde15dSdrh   ** remember the column indices.
756c8392586Sdrh   **
757c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
758c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
759c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
760c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
761c8392586Sdrh   ** is appears in the original table.  (The index of the primary
762c8392586Sdrh   ** key in the original table is pTab->iPKey.)
7631ccde15dSdrh   */
764967e8b73Sdrh   if( pColumn ){
765967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
766967e8b73Sdrh       pColumn->a[i].idx = -1;
767cce7d176Sdrh     }
768967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
769cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7704adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
771967e8b73Sdrh           pColumn->a[i].idx = j;
7724a32431cSdrh           if( j==pTab->iPKey ){
7739aa028daSdrh             keyColumn = i;
7744a32431cSdrh           }
775cce7d176Sdrh           break;
776cce7d176Sdrh         }
777cce7d176Sdrh       }
778cce7d176Sdrh       if( j>=pTab->nCol ){
7794adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
780a0217ba7Sdrh           keyColumn = i;
781a0217ba7Sdrh         }else{
7824adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
783da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
7841db95106Sdan           pParse->checkSchema = 1;
785cce7d176Sdrh           goto insert_cleanup;
786cce7d176Sdrh         }
787cce7d176Sdrh       }
788cce7d176Sdrh     }
789a0217ba7Sdrh   }
7901ccde15dSdrh 
791aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
792c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
793c8392586Sdrh   ** in the original table definition.
7944a32431cSdrh   */
795147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
7964a32431cSdrh     keyColumn = pTab->iPKey;
7974a32431cSdrh   }
7984a32431cSdrh 
799c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8001ccde15dSdrh   */
801142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8026a288a33Sdrh     regRowCount = ++pParse->nMem;
8036a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
804c3f9bad2Sdanielk1977   }
805c3f9bad2Sdanielk1977 
806e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
807e448dc4aSdanielk1977   if( !isView ){
808aa9b8963Sdrh     int nIdx;
809aa9b8963Sdrh 
81004adf416Sdrh     baseCur = pParse->nTab;
81104adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
8125c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
813aa9b8963Sdrh     if( aRegIdx==0 ){
814aa9b8963Sdrh       goto insert_cleanup;
815aa9b8963Sdrh     }
816aa9b8963Sdrh     for(i=0; i<nIdx; i++){
817aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
818aa9b8963Sdrh     }
819feeb1394Sdrh   }
820feeb1394Sdrh 
821e00ee6ebSdrh   /* This is the top of the main insertion loop */
822142e30dfSdrh   if( useTempTable ){
823e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
824e00ee6ebSdrh     ** following pseudocode (template 4):
825e00ee6ebSdrh     **
826e00ee6ebSdrh     **         rewind temp table
827e00ee6ebSdrh     **      C: loop over rows of intermediate table
828e00ee6ebSdrh     **           transfer values form intermediate table into <table>
829e00ee6ebSdrh     **         end loop
830e00ee6ebSdrh     **      D: ...
831e00ee6ebSdrh     */
832e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
833e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
834142e30dfSdrh   }else if( pSelect ){
835e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
836e00ee6ebSdrh     ** following pseudocode (template 3):
837e00ee6ebSdrh     **
838e00ee6ebSdrh     **      C: yield X
839e00ee6ebSdrh     **         if EOF goto D
840e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
841e00ee6ebSdrh     **         goto C
842e00ee6ebSdrh     **      D: ...
843e00ee6ebSdrh     */
8442b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
845e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
846bed8690fSdrh   }
8471ccde15dSdrh 
8486a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8496a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8506a288a33Sdrh   */
8516a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8526a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8536a288a33Sdrh   if( IsVirtual(pTab) ){
8546a288a33Sdrh     regRowid++;
8556a288a33Sdrh     pParse->nMem++;
8566a288a33Sdrh   }
8576a288a33Sdrh   regData = regRowid+1;
8586a288a33Sdrh 
8595cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
86070ce3f0cSdrh   */
8614adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8622f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
86376d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
864c3f9bad2Sdanielk1977 
86570ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
86670ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
86770ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
86870ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
86970ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
87070ce3f0cSdrh     */
87170ce3f0cSdrh     if( keyColumn<0 ){
87276d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
87370ce3f0cSdrh     }else{
8746a288a33Sdrh       int j1;
8757fe45908Sdrh       if( useTempTable ){
87676d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
8777fe45908Sdrh       }else{
878d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
87976d462eeSdan         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
8807fe45908Sdrh       }
88176d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
88276d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
8836a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
88476d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
88570ce3f0cSdrh     }
88670ce3f0cSdrh 
887034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
888034ca14fSdanielk1977     ** this block would have to account for hidden column.
889034ca14fSdanielk1977     */
890034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
891034ca14fSdanielk1977 
89270ce3f0cSdrh     /* Create the new column data
89370ce3f0cSdrh     */
894c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
895c3f9bad2Sdanielk1977       if( pColumn==0 ){
896c3f9bad2Sdanielk1977         j = i;
897c3f9bad2Sdanielk1977       }else{
898c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
899c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
900c3f9bad2Sdanielk1977         }
901c3f9bad2Sdanielk1977       }
9027ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
90376d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
904142e30dfSdrh       }else if( useTempTable ){
90576d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
906c3f9bad2Sdanielk1977       }else{
907d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
90876d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
909c3f9bad2Sdanielk1977       }
910c3f9bad2Sdanielk1977     }
911a37cdde0Sdanielk1977 
912a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
913a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
914a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
915a37cdde0Sdanielk1977     ** table column affinities.
916a37cdde0Sdanielk1977     */
917a37cdde0Sdanielk1977     if( !isView ){
91876d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
919a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
920a37cdde0Sdanielk1977     }
921c3f9bad2Sdanielk1977 
9225cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
923165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
92494d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
925165921a7Sdan 
92676d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
92770ce3f0cSdrh   }
928c3f9bad2Sdanielk1977 
9294a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
930f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
9314a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
932b419a926Sdrh   ** case the record number is the same as that column.
9331ccde15dSdrh   */
9345cf590c1Sdrh   if( !isView ){
9354cbdda9eSdrh     if( IsVirtual(pTab) ){
9364cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9376a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9384cbdda9eSdrh     }
9394a32431cSdrh     if( keyColumn>=0 ){
940142e30dfSdrh       if( useTempTable ){
9416a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
942142e30dfSdrh       }else if( pSelect ){
943b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
9444a32431cSdrh       }else{
945e4d90813Sdrh         VdbeOp *pOp;
9461db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
94720411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9481b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
949e4d90813Sdrh           appendFlag = 1;
950e4d90813Sdrh           pOp->opcode = OP_NewRowid;
95104adf416Sdrh           pOp->p1 = baseCur;
9526a288a33Sdrh           pOp->p2 = regRowid;
9536a288a33Sdrh           pOp->p3 = regAutoinc;
954e4d90813Sdrh         }
95527a32783Sdrh       }
956f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
957e1e68f49Sdrh       ** to generate a unique primary key value.
958e1e68f49Sdrh       */
959e4d90813Sdrh       if( !appendFlag ){
9601db639ceSdrh         int j1;
961bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9621db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
96304adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
9641db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
965bb50e7adSdanielk1977         }else{
966bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
967bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
968bb50e7adSdanielk1977         }
9693c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
970e4d90813Sdrh       }
9714cbdda9eSdrh     }else if( IsVirtual(pTab) ){
9726a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9734a32431cSdrh     }else{
97404adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
975e4d90813Sdrh       appendFlag = 1;
9764a32431cSdrh     }
9776a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9784a32431cSdrh 
979aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
9804a32431cSdrh     ** with the first column.
9814a32431cSdrh     */
982034ca14fSdanielk1977     nHidden = 0;
983cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9846a288a33Sdrh       int iRegStore = regRowid+1+i;
9854a32431cSdrh       if( i==pTab->iPKey ){
9864a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
987aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
988aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
989aacc543eSdrh         ** taking up data space with information that will never be used. */
9904c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
9914a32431cSdrh         continue;
9924a32431cSdrh       }
993967e8b73Sdrh       if( pColumn==0 ){
994034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
995034ca14fSdanielk1977           assert( IsVirtual(pTab) );
996034ca14fSdanielk1977           j = -1;
997034ca14fSdanielk1977           nHidden++;
998034ca14fSdanielk1977         }else{
999034ca14fSdanielk1977           j = i - nHidden;
1000034ca14fSdanielk1977         }
1001cce7d176Sdrh       }else{
1002967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1003967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1004cce7d176Sdrh         }
1005cce7d176Sdrh       }
1006034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1007287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1008142e30dfSdrh       }else if( useTempTable ){
1009287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1010142e30dfSdrh       }else if( pSelect ){
1011b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1012cce7d176Sdrh       }else{
1013287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1014cce7d176Sdrh       }
1015cce7d176Sdrh     }
10161ccde15dSdrh 
10170ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10180ca3e24bSdrh     ** do the insertion.
10194a32431cSdrh     */
10204cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10214cbdda9eSdrh     if( IsVirtual(pTab) ){
1022595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10234f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1024595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1025b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1026e0af83acSdan       sqlite3MayAbort(pParse);
10274cbdda9eSdrh     }else
10284cbdda9eSdrh #endif
10294cbdda9eSdrh     {
1030de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1031de630353Sdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
1032de630353Sdanielk1977           keyColumn>=0, 0, onError, endOfLoop, &isReplace
103304adf416Sdrh       );
10348ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
103504adf416Sdrh       sqlite3CompleteInsertion(
10362832ad42Sdan           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
103704adf416Sdrh       );
10385cf590c1Sdrh     }
10394cbdda9eSdrh   }
10401bee3d7bSdrh 
1041feeb1394Sdrh   /* Update the count of rows that are inserted
10421bee3d7bSdrh   */
1043142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10446a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10451bee3d7bSdrh   }
1046c3f9bad2Sdanielk1977 
10472f886d1dSdanielk1977   if( pTrigger ){
1048c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1049165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
105094d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1051c3f9bad2Sdanielk1977   }
10521bee3d7bSdrh 
1053e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1054e00ee6ebSdrh   ** is a SELECT statement.
10551ccde15dSdrh   */
10564adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1057142e30dfSdrh   if( useTempTable ){
1058e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1059e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10602eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1061142e30dfSdrh   }else if( pSelect ){
1062e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1063e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10646b56344dSdrh   }
1065c3f9bad2Sdanielk1977 
1066e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1067c3f9bad2Sdanielk1977     /* Close all tables opened */
10682eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
10696b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
10702eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
1071cce7d176Sdrh     }
1072c3f9bad2Sdanielk1977   }
1073c3f9bad2Sdanielk1977 
10740b9f50d8Sdrh insert_end:
1075f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10760b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10770b9f50d8Sdrh   ** autoincrement tables.
10782958a4e6Sdrh   */
1079165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10800b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10810b9f50d8Sdrh   }
10822958a4e6Sdrh 
10831bee3d7bSdrh   /*
1084e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1085e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1086e7de6f25Sdanielk1977   ** invoke the callback function.
10871bee3d7bSdrh   */
1088165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
10896a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
109022322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
109110fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
10921bee3d7bSdrh   }
1093cce7d176Sdrh 
1094cce7d176Sdrh insert_cleanup:
1095633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1096633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1097633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1098633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1099633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1100cce7d176Sdrh }
11019cfcf5d4Sdrh 
110275cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
110375cbd984Sdan ** thely may interfere with compilation of other functions in this file
110475cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
110575cbd984Sdan #ifdef isView
110675cbd984Sdan  #undef isView
110775cbd984Sdan #endif
110875cbd984Sdan #ifdef pTrigger
110975cbd984Sdan  #undef pTrigger
111075cbd984Sdan #endif
111175cbd984Sdan #ifdef tmask
111275cbd984Sdan  #undef tmask
111375cbd984Sdan #endif
111475cbd984Sdan 
111575cbd984Sdan 
11169cfcf5d4Sdrh /*
11176a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
11189cfcf5d4Sdrh **
111904adf416Sdrh ** The input is a range of consecutive registers as follows:
11200ca3e24bSdrh **
112165a7cd16Sdan **    1.  The rowid of the row after the update.
11220ca3e24bSdrh **
112365a7cd16Sdan **    2.  The data in the first column of the entry after the update.
11240ca3e24bSdrh **
11250ca3e24bSdrh **    i.  Data from middle columns...
11260ca3e24bSdrh **
11270ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
11280ca3e24bSdrh **
112965a7cd16Sdan ** The regRowid parameter is the index of the register containing (1).
113004adf416Sdrh **
113165a7cd16Sdan ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
113265a7cd16Sdan ** the address of a register containing the rowid before the update takes
113365a7cd16Sdan ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
113465a7cd16Sdan ** is false, indicating an INSERT statement, then a non-zero rowidChng
113565a7cd16Sdan ** indicates that the rowid was explicitly specified as part of the
113665a7cd16Sdan ** INSERT statement. If rowidChng is false, it means that  the rowid is
113765a7cd16Sdan ** computed automatically in an insert or that the rowid value is not
113865a7cd16Sdan ** modified by an update.
11390ca3e24bSdrh **
1140aa9b8963Sdrh ** The code generated by this routine store new index entries into
1141aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1142aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1143aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1144aa9b8963Sdrh ** attached to the table.
11459cfcf5d4Sdrh **
11469cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11479cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11481c92853dSdrh ** then the appropriate action is performed.  There are five possible
11491c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11509cfcf5d4Sdrh **
11519cfcf5d4Sdrh **  Constraint type  Action       What Happens
11529cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11531c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
115424b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
11559cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11569cfcf5d4Sdrh **
11571c92853dSdrh **  any              ABORT        Back out changes from the current command
11581c92853dSdrh **                                only (do not do a complete rollback) then
115924b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
11601c92853dSdrh **                                with SQLITE_CONSTRAINT.
11611c92853dSdrh **
1162e4c88c0cSdrh **  any              FAIL         Sqlite3_exec() returns immediately with a
11631c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11641c92853dSdrh **                                transaction is not rolled back and any
11651c92853dSdrh **                                prior changes are retained.
11661c92853dSdrh **
11679cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
11689cfcf5d4Sdrh **                                the stack and there is an immediate jump
11699cfcf5d4Sdrh **                                to label ignoreDest.
11709cfcf5d4Sdrh **
11719cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11729cfcf5d4Sdrh **                                value for that column.  If the default value
11739cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11749cfcf5d4Sdrh **
11759cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
11769cfcf5d4Sdrh **                                being inserted is removed.
11779cfcf5d4Sdrh **
11789cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
11799cfcf5d4Sdrh **
11801c92853dSdrh ** Which action to take is determined by the overrideError parameter.
11811c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
11821c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
11831c92853dSdrh ** for the constraint is used.
11849cfcf5d4Sdrh **
1185aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
118604adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
118704adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
11889cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1189aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
11909cfcf5d4Sdrh */
11914adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
11929cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
11939cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
119404adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
119504adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1196aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1197a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1198b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
11999cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1200de630353Sdanielk1977   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
1201de630353Sdanielk1977   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
12029cfcf5d4Sdrh ){
12031b7ecbb4Sdrh   int i;              /* loop counter */
12041b7ecbb4Sdrh   Vdbe *v;            /* VDBE under constrution */
12051b7ecbb4Sdrh   int nCol;           /* Number of columns */
12061b7ecbb4Sdrh   int onError;        /* Conflict resolution strategy */
12071bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
12081bd10f8aSdrh   int j2 = 0, j3;     /* Addresses of jump instructions */
120904adf416Sdrh   int regData;        /* Register containing first data column */
12101b7ecbb4Sdrh   int iCur;           /* Table cursor number */
12111b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
12122938f924Sdrh   sqlite3 *db;         /* Database connection */
12131b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
121465a7cd16Sdan   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
12159cfcf5d4Sdrh 
12162938f924Sdrh   db = pParse->db;
12174adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12189cfcf5d4Sdrh   assert( v!=0 );
1219417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12209cfcf5d4Sdrh   nCol = pTab->nCol;
1221aa9b8963Sdrh   regData = regRowid + 1;
1222aa9b8963Sdrh 
12239cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12249cfcf5d4Sdrh   */
12259cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12260ca3e24bSdrh     if( i==pTab->iPKey ){
12270ca3e24bSdrh       continue;
12280ca3e24bSdrh     }
12299cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12300ca3e24bSdrh     if( onError==OE_None ) continue;
12319cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12329cfcf5d4Sdrh       onError = overrideError;
1233a996e477Sdrh     }else if( onError==OE_Default ){
1234a996e477Sdrh       onError = OE_Abort;
12359cfcf5d4Sdrh     }
12367977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12379cfcf5d4Sdrh       onError = OE_Abort;
12389cfcf5d4Sdrh     }
1239b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1240b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12419cfcf5d4Sdrh     switch( onError ){
12421c92853dSdrh       case OE_Abort:
1243e0af83acSdan         sqlite3MayAbort(pParse);
1244e0af83acSdan       case OE_Rollback:
12451c92853dSdrh       case OE_Fail: {
1246f089aa45Sdrh         char *zMsg;
1247c126e63eSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1248d91c1a17Sdrh                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
12492938f924Sdrh         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
1250f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
125166a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
12529cfcf5d4Sdrh         break;
12539cfcf5d4Sdrh       }
12549cfcf5d4Sdrh       case OE_Ignore: {
12555053a79bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
12569cfcf5d4Sdrh         break;
12579cfcf5d4Sdrh       }
1258098d1684Sdrh       default: {
1259098d1684Sdrh         assert( onError==OE_Replace );
12605053a79bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
126104adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
12625053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
12639cfcf5d4Sdrh         break;
12649cfcf5d4Sdrh       }
12659cfcf5d4Sdrh     }
12669cfcf5d4Sdrh   }
12679cfcf5d4Sdrh 
12689cfcf5d4Sdrh   /* Test all CHECK constraints
12699cfcf5d4Sdrh   */
1270ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
12712938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
12722938f924Sdrh     ExprList *pCheck = pTab->pCheck;
1273aa9b8963Sdrh     pParse->ckBase = regData;
1274aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
12752938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
12762938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
12772d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
12782e06c67cSdrh       if( onError==OE_Ignore ){
127966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1280aa01c7e2Sdrh       }else{
12812938f924Sdrh         char *zConsName = pCheck->a[i].zName;
12826dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
12832938f924Sdrh         if( zConsName ){
12842938f924Sdrh           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
12852938f924Sdrh         }else{
1286f68686aeSdrh           zConsName = 0;
12872938f924Sdrh         }
1288d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1289d91c1a17Sdrh                               onError, zConsName, P4_DYNAMIC);
1290aa01c7e2Sdrh       }
1291ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1292c31c7c1cSdrh     }
12932938f924Sdrh   }
1294ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
12959cfcf5d4Sdrh 
12960bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
12970bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
12980bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
12999cfcf5d4Sdrh   */
1300f0863fe5Sdrh   if( rowidChng ){
13010ca3e24bSdrh     onError = pTab->keyConf;
13020ca3e24bSdrh     if( overrideError!=OE_Default ){
13030ca3e24bSdrh       onError = overrideError;
1304a996e477Sdrh     }else if( onError==OE_Default ){
1305a996e477Sdrh       onError = OE_Abort;
13060ca3e24bSdrh     }
1307a0217ba7Sdrh 
130879b0c956Sdrh     if( isUpdate ){
130976d462eeSdan       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
131079b0c956Sdrh     }
131104adf416Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
13120ca3e24bSdrh     switch( onError ){
1313a0217ba7Sdrh       default: {
1314a0217ba7Sdrh         onError = OE_Abort;
1315a0217ba7Sdrh         /* Fall thru into the next case */
1316a0217ba7Sdrh       }
13171c92853dSdrh       case OE_Rollback:
13181c92853dSdrh       case OE_Abort:
13191c92853dSdrh       case OE_Fail: {
1320d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1321d91c1a17Sdrh            onError, "PRIMARY KEY must be unique", P4_STATIC);
13220ca3e24bSdrh         break;
13230ca3e24bSdrh       }
13245383ae5cSdrh       case OE_Replace: {
13252283d46cSdan         /* If there are DELETE triggers on this table and the
13262283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1327d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13282283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13292283d46cSdan         **
13302283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1331da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1332da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1333da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1334da730f6eSdan         ** when it is inserted.
1335da730f6eSdan         **
1336da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1337da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1338da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1339da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1340da730f6eSdan         ** but being more selective here allows statements like:
1341da730f6eSdan         **
1342da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1343da730f6eSdan         **
1344da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1345da730f6eSdan         ** table.
1346da730f6eSdan         */
13472283d46cSdan         Trigger *pTrigger = 0;
13482938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
13492283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
13502283d46cSdan         }
1351e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1352da730f6eSdan           sqlite3MultiWrite(pParse);
13532283d46cSdan           sqlite3GenerateRowDelete(
13542283d46cSdan               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
13552283d46cSdan           );
1356da730f6eSdan         }else if( pTab->pIndex ){
1357da730f6eSdan           sqlite3MultiWrite(pParse);
13582d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
13592283d46cSdan         }
13605383ae5cSdrh         seenReplace = 1;
13615383ae5cSdrh         break;
13625383ae5cSdrh       }
13630ca3e24bSdrh       case OE_Ignore: {
13645383ae5cSdrh         assert( seenReplace==0 );
136566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13660ca3e24bSdrh         break;
13670ca3e24bSdrh       }
13680ca3e24bSdrh     }
1369aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j3);
1370f5905aa7Sdrh     if( isUpdate ){
1371aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j2);
1372a05a722fSdrh     }
13730ca3e24bSdrh   }
13740bd1f4eaSdrh 
13750bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
13760bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
13770bd1f4eaSdrh   ** Add the new records to the indices as we go.
13780bd1f4eaSdrh   */
1379b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
13802d401ab8Sdrh     int regIdx;
13812d401ab8Sdrh     int regR;
1382b2b9d3d7Sdrh     int addrSkipRow = 0;
13832184fc75Sdrh 
1384aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1385b2fe7d8cSdrh 
1386b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1387b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
1388b2b9d3d7Sdrh       addrSkipRow = sqlite3VdbeMakeLabel(v);
1389b2b9d3d7Sdrh       pParse->ckBase = regData;
1390b2b9d3d7Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
1391b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1392b2b9d3d7Sdrh       pParse->ckBase = 0;
1393b2b9d3d7Sdrh     }
1394b2b9d3d7Sdrh 
1395b2fe7d8cSdrh     /* Create a key for accessing the index entry */
1396*bbbdc83bSdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nKeyCol+1);
13979cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
1398*bbbdc83bSdrh       i16 idx = pIdx->aiColumn[i];
1399*bbbdc83bSdrh       if( idx<0 || idx==pTab->iPKey ){
14002d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
14019cfcf5d4Sdrh       }else{
14022d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
14039cfcf5d4Sdrh       }
14049cfcf5d4Sdrh     }
1405*bbbdc83bSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[iCur]);
14068d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
1407*bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1408b2fe7d8cSdrh 
1409b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
14109cfcf5d4Sdrh     onError = pIdx->onError;
1411de630353Sdanielk1977     if( onError==OE_None ){
1412*bbbdc83bSdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
14138a9789b6Sdrh       sqlite3VdbeResolveLabel(v, addrSkipRow);
1414de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1415de630353Sdanielk1977     }
14169cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14179cfcf5d4Sdrh       onError = overrideError;
1418a996e477Sdrh     }else if( onError==OE_Default ){
1419a996e477Sdrh       onError = OE_Abort;
14209cfcf5d4Sdrh     }
14215383ae5cSdrh     if( seenReplace ){
14225383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
14235383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
14245383ae5cSdrh     }
14255383ae5cSdrh 
1426b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
14272d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
142865a7cd16Sdan     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
14292d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1430de630353Sdanielk1977                            regR, SQLITE_INT_TO_PTR(regIdx),
1431a9e852b6Smlcreech                            P4_INT32);
1432*bbbdc83bSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
1433b2fe7d8cSdrh 
1434b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1435b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1436b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
14379cfcf5d4Sdrh     switch( onError ){
14381c92853dSdrh       case OE_Rollback:
14391c92853dSdrh       case OE_Abort:
14401c92853dSdrh       case OE_Fail: {
1441098d1684Sdrh         int j;
1442098d1684Sdrh         StrAccum errMsg;
1443098d1684Sdrh         const char *zSep;
1444098d1684Sdrh         char *zErr;
1445098d1684Sdrh 
1446098d1684Sdrh         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
14472938f924Sdrh         errMsg.db = db;
1448*bbbdc83bSdrh         zSep = pIdx->nKeyCol>1 ? "columns " : "column ";
1449*bbbdc83bSdrh         for(j=0; j<pIdx->nKeyCol; j++){
145037ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1451098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zSep, -1);
1452098d1684Sdrh           zSep = ", ";
1453098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zCol, -1);
145437ed48edSdrh         }
1455098d1684Sdrh         sqlite3StrAccumAppend(&errMsg,
1456*bbbdc83bSdrh             pIdx->nKeyCol>1 ? " are not unique" : " is not unique", -1);
1457098d1684Sdrh         zErr = sqlite3StrAccumFinish(&errMsg);
1458d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
1459d91c1a17Sdrh                               onError, zErr, 0);
1460098d1684Sdrh         sqlite3DbFree(errMsg.db, zErr);
14619cfcf5d4Sdrh         break;
14629cfcf5d4Sdrh       }
14639cfcf5d4Sdrh       case OE_Ignore: {
14640ca3e24bSdrh         assert( seenReplace==0 );
146566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14669cfcf5d4Sdrh         break;
14679cfcf5d4Sdrh       }
1468098d1684Sdrh       default: {
14692283d46cSdan         Trigger *pTrigger = 0;
1470098d1684Sdrh         assert( onError==OE_Replace );
14711bea559aSdan         sqlite3MultiWrite(pParse);
14722938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14732283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14742283d46cSdan         }
14752283d46cSdan         sqlite3GenerateRowDelete(
14762283d46cSdan             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
14772283d46cSdan         );
14780ca3e24bSdrh         seenReplace = 1;
14799cfcf5d4Sdrh         break;
14809cfcf5d4Sdrh       }
14819cfcf5d4Sdrh     }
14822d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
1483b2b9d3d7Sdrh     sqlite3VdbeResolveLabel(v, addrSkipRow);
14842d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
14859cfcf5d4Sdrh   }
1486de630353Sdanielk1977 
1487de630353Sdanielk1977   if( pbMayReplace ){
1488de630353Sdanielk1977     *pbMayReplace = seenReplace;
1489de630353Sdanielk1977   }
14909cfcf5d4Sdrh }
14910ca3e24bSdrh 
14920ca3e24bSdrh /*
14930ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
14944adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
149504adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
149604adf416Sdrh ** rowid and the content to be inserted.
14970ca3e24bSdrh **
1498b419a926Sdrh ** The arguments to this routine should be the same as the first six
14994adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
15000ca3e24bSdrh */
15014adee20fSdanielk1977 void sqlite3CompleteInsertion(
15020ca3e24bSdrh   Parse *pParse,      /* The parser context */
15030ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
150404adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
150504adf416Sdrh   int regRowid,       /* Range of content */
1506aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
150770ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1508de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1509de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
15100ca3e24bSdrh ){
15110ca3e24bSdrh   int i;
15120ca3e24bSdrh   Vdbe *v;
15130ca3e24bSdrh   Index *pIdx;
15141bd10f8aSdrh   u8 pik_flags;
151504adf416Sdrh   int regData;
1516b7654111Sdrh   int regRec;
15170ca3e24bSdrh 
15184adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
15190ca3e24bSdrh   assert( v!=0 );
1520417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1521b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1522aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1523b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1524b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1525b2b9d3d7Sdrh     }
152604adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1527de630353Sdanielk1977     if( useSeekResult ){
1528de630353Sdanielk1977       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1529de630353Sdanielk1977     }
15300ca3e24bSdrh   }
153104adf416Sdrh   regData = regRowid + 1;
1532b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
15331db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1534a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1535da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
15364794f735Sdrh   if( pParse->nested ){
15374794f735Sdrh     pik_flags = 0;
15384794f735Sdrh   }else{
153994eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
154094eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
15414794f735Sdrh   }
1542e4d90813Sdrh   if( appendBias ){
1543e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1544e4d90813Sdrh   }
1545de630353Sdanielk1977   if( useSeekResult ){
1546de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1547de630353Sdanielk1977   }
1548b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
154994eb6a14Sdanielk1977   if( !pParse->nested ){
15508d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
155194eb6a14Sdanielk1977   }
1552b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
15530ca3e24bSdrh }
1554cd44690aSdrh 
1555cd44690aSdrh /*
1556290c1948Sdrh ** Generate code that will open cursors for a table and for all
155704adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1558cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1559aa9b8963Sdrh **
1560aa9b8963Sdrh ** Return the number of indices on the table.
1561cd44690aSdrh */
1562aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1563290c1948Sdrh   Parse *pParse,   /* Parsing context */
1564290c1948Sdrh   Table *pTab,     /* Table to be opened */
156504adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1566290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1567290c1948Sdrh ){
1568cd44690aSdrh   int i;
15694cbdda9eSdrh   int iDb;
1570cd44690aSdrh   Index *pIdx;
15714cbdda9eSdrh   Vdbe *v;
15724cbdda9eSdrh 
1573aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
15744cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
15754cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1576cd44690aSdrh   assert( v!=0 );
157704adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1578cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1579b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1580da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
158104adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
158266a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1583207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1584cd44690aSdrh   }
15851b7ecbb4Sdrh   if( pParse->nTab<baseCur+i ){
158604adf416Sdrh     pParse->nTab = baseCur+i;
1587290c1948Sdrh   }
1588aa9b8963Sdrh   return i-1;
1589cd44690aSdrh }
15909d9cf229Sdrh 
159191c58e23Sdrh 
159291c58e23Sdrh #ifdef SQLITE_TEST
159391c58e23Sdrh /*
159491c58e23Sdrh ** The following global variable is incremented whenever the
159591c58e23Sdrh ** transfer optimization is used.  This is used for testing
159691c58e23Sdrh ** purposes only - to make sure the transfer optimization really
159791c58e23Sdrh ** is happening when it is suppose to.
159891c58e23Sdrh */
159991c58e23Sdrh int sqlite3_xferopt_count;
160091c58e23Sdrh #endif /* SQLITE_TEST */
160191c58e23Sdrh 
160291c58e23Sdrh 
16039d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
16049d9cf229Sdrh /*
16059d9cf229Sdrh ** Check to collation names to see if they are compatible.
16069d9cf229Sdrh */
16079d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
16089d9cf229Sdrh   if( z1==0 ){
16099d9cf229Sdrh     return z2==0;
16109d9cf229Sdrh   }
16119d9cf229Sdrh   if( z2==0 ){
16129d9cf229Sdrh     return 0;
16139d9cf229Sdrh   }
16149d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
16159d9cf229Sdrh }
16169d9cf229Sdrh 
16179d9cf229Sdrh 
16189d9cf229Sdrh /*
16199d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
16209d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
16219d9cf229Sdrh ** for a compatible index:
16229d9cf229Sdrh **
16239d9cf229Sdrh **    *   The index is over the same set of columns
16249d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
16259d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
16269d9cf229Sdrh **    *   The same collating sequence on each column
1627b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
16289d9cf229Sdrh */
16299d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
16309d9cf229Sdrh   int i;
16319d9cf229Sdrh   assert( pDest && pSrc );
16329d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1633*bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
16349d9cf229Sdrh     return 0;   /* Different number of columns */
16359d9cf229Sdrh   }
16369d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
16379d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
16389d9cf229Sdrh   }
1639*bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
16409d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
16419d9cf229Sdrh       return 0;   /* Different columns indexed */
16429d9cf229Sdrh     }
16439d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
16449d9cf229Sdrh       return 0;   /* Different sort orders */
16459d9cf229Sdrh     }
16463f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
164760a713c6Sdrh       return 0;   /* Different collating sequences */
16489d9cf229Sdrh     }
16499d9cf229Sdrh   }
1650619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1651b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1652b2b9d3d7Sdrh   }
16539d9cf229Sdrh 
16549d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
16559d9cf229Sdrh   return 1;
16569d9cf229Sdrh }
16579d9cf229Sdrh 
16589d9cf229Sdrh /*
16599d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
16609d9cf229Sdrh **
16619d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
16629d9cf229Sdrh **
1663ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1664ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1665ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
16669d9cf229Sdrh **
1667ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1668ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1669ccdf1baeSdrh ** embedded in the code for details.
16709d9cf229Sdrh **
1671ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1672ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1673ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1674ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1675ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1676ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1677ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1678ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1679ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
16809d9cf229Sdrh **
1681ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
16829d9cf229Sdrh */
16839d9cf229Sdrh static int xferOptimization(
16849d9cf229Sdrh   Parse *pParse,        /* Parser context */
16859d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
16869d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
16879d9cf229Sdrh   int onError,          /* How to handle constraint errors */
16889d9cf229Sdrh   int iDbDest           /* The database of pDest */
16899d9cf229Sdrh ){
16909d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
16919d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
16929d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
16939d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
16949d9cf229Sdrh   int i;                           /* Loop counter */
16959d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
16969d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
16979d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
16989d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
16999d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
17009d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
17019d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
17026a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1703f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1704b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
17059d9cf229Sdrh 
17069d9cf229Sdrh   if( pSelect==0 ){
17079d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
17089d9cf229Sdrh   }
17092f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
17109d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
17119d9cf229Sdrh   }
17129d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17137d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
17149d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
17159d9cf229Sdrh   }
17169d9cf229Sdrh #endif
17179d9cf229Sdrh   if( onError==OE_Default ){
1718e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1719e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
17209d9cf229Sdrh   }
17215ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
17229d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
17239d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
17249d9cf229Sdrh   }
17259d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
17269d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
17279d9cf229Sdrh   }
17289d9cf229Sdrh   if( pSelect->pWhere ){
17299d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
17309d9cf229Sdrh   }
17319d9cf229Sdrh   if( pSelect->pOrderBy ){
17329d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
17339d9cf229Sdrh   }
17348103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
17358103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
17369d9cf229Sdrh   if( pSelect->pGroupBy ){
17379d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
17389d9cf229Sdrh   }
17399d9cf229Sdrh   if( pSelect->pLimit ){
17409d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
17419d9cf229Sdrh   }
17428103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
17439d9cf229Sdrh   if( pSelect->pPrior ){
17449d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
17459d9cf229Sdrh   }
17467d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
17479d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
17489d9cf229Sdrh   }
17499d9cf229Sdrh   pEList = pSelect->pEList;
17509d9cf229Sdrh   assert( pEList!=0 );
17519d9cf229Sdrh   if( pEList->nExpr!=1 ){
17529d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
17539d9cf229Sdrh   }
17549d9cf229Sdrh   assert( pEList->a[0].pExpr );
17559d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
17569d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
17579d9cf229Sdrh   }
17589d9cf229Sdrh 
17599d9cf229Sdrh   /* At this point we have established that the statement is of the
17609d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
17619d9cf229Sdrh   ** we have to check the semantics.
17629d9cf229Sdrh   */
17639d9cf229Sdrh   pItem = pSelect->pSrc->a;
176441fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
17659d9cf229Sdrh   if( pSrc==0 ){
17669d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
17679d9cf229Sdrh   }
17689d9cf229Sdrh   if( pSrc==pDest ){
17699d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
17709d9cf229Sdrh   }
17719d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17727d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
17739d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
17749d9cf229Sdrh   }
17759d9cf229Sdrh #endif
17769d9cf229Sdrh   if( pSrc->pSelect ){
17779d9cf229Sdrh     return 0;   /* tab2 may not be a view */
17789d9cf229Sdrh   }
17799d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
17809d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
17819d9cf229Sdrh   }
17829d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
17839d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
17849d9cf229Sdrh   }
17859d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
17869d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
17879d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
17889d9cf229Sdrh     }
17899d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
17909d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
17919d9cf229Sdrh     }
17929d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
17939d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
17949d9cf229Sdrh     }
17959d9cf229Sdrh   }
17969d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1797f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1798f33c9fadSdrh       destHasUniqueIdx = 1;
1799f33c9fadSdrh     }
18009d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
18019d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18029d9cf229Sdrh     }
18039d9cf229Sdrh     if( pSrcIdx==0 ){
18049d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
18059d9cf229Sdrh     }
18069d9cf229Sdrh   }
18077fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1808619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
18098103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
18108103b7d2Sdrh   }
18117fc2f41bSdrh #endif
1812713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1813713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1814713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1815713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1816713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1817713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1818713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1819713de341Sdrh   */
1820713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1821713de341Sdrh     return 0;
1822713de341Sdrh   }
1823713de341Sdrh #endif
18241696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1825ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
18261696124dSdan   }
18279d9cf229Sdrh 
1828ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1829ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1830ccdf1baeSdrh   ** table (tab1) is initially empty.
18319d9cf229Sdrh   */
1832dd73521bSdrh #ifdef SQLITE_TEST
1833dd73521bSdrh   sqlite3_xferopt_count++;
1834dd73521bSdrh #endif
18359d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
18369d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1837f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
18389d9cf229Sdrh   iSrc = pParse->nTab++;
18399d9cf229Sdrh   iDest = pParse->nTab++;
18406a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
18419d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1842ccdf1baeSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1843ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
1844ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1845ccdf1baeSdrh   ){
1846ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
1847ccdf1baeSdrh     ** only if the destination table is initially empty.  This code makes
1848ccdf1baeSdrh     ** that determination.  Conditions under which the destination must
1849ccdf1baeSdrh     ** be empty:
1850f33c9fadSdrh     **
1851ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1852ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
1853ccdf1baeSdrh     **     of index entries might need to change.)
1854ccdf1baeSdrh     **
1855ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
1856ccdf1baeSdrh     **     is unable to test uniqueness.)
1857ccdf1baeSdrh     **
1858ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
18599d9cf229Sdrh     */
186066a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
186166a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
18629d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
18639d9cf229Sdrh   }else{
18649d9cf229Sdrh     emptyDestTest = 0;
18659d9cf229Sdrh   }
18669d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
186766a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1868b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1869b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
187042242dedSdrh   if( pDest->iPKey>=0 ){
1871b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1872b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1873d91c1a17Sdrh     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1874d91c1a17Sdrh         onError, "PRIMARY KEY must be unique", P4_STATIC);
18759d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1876b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1877bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1878b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
187995bad4c7Sdrh   }else{
1880b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
18817d10d5a6Sdrh     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
188295bad4c7Sdrh   }
1883b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1884b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1885b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
18861f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
188766a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
18889d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
18891b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
18909d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18919d9cf229Sdrh     }
18929d9cf229Sdrh     assert( pSrcIdx );
189366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
189466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
18959d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1896207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1897207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1898d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
18999d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1900207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
190166a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
190259885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
1903207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
190466a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1905b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1906b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
190766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
19089d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
19099d9cf229Sdrh   }
19109d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1911b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1912b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
191366a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
191466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19159d9cf229Sdrh   if( emptyDestTest ){
191666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
19179d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
191866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19199d9cf229Sdrh     return 0;
19209d9cf229Sdrh   }else{
19219d9cf229Sdrh     return 1;
19229d9cf229Sdrh   }
19239d9cf229Sdrh }
19249d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1925