xref: /sqlite-3.40.0/src/insert.c (revision dd9930ef)
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 /*
18*dd9930efSdrh ** Generate code that will open table pTab for reading or writing
19*dd9930efSdrh ** on cursor iCur.
20*dd9930efSdrh **
21*dd9930efSdrh ** Always acquire a table lock.  Always do the open for rowid tables.
22*dd9930efSdrh ** For WITHOUT ROWID tables, only do read opens, and then open the
23*dd9930efSdrh ** PRIMARY KEY index, not the main table, since the main table doesn't
24*dd9930efSdrh ** exist.
25bbb5e4e0Sdrh */
26bbb5e4e0Sdrh void sqlite3OpenTable(
27bbb5e4e0Sdrh   Parse *p,       /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
35bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
37bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
38ec95c441Sdrh   if( HasRowid(pTab) ){
39*dd9930efSdrh     sqlite3VdbeAddOp4(v, opcode, iCur, pTab->tnum, iDb,
40*dd9930efSdrh                       SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
41*dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
42*dd9930efSdrh   }else if( opcode==OP_OpenRead ){
43*dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44*dd9930efSdrh     assert( pPk!=0 );
45*dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
46*dd9930efSdrh     sqlite3VdbeAddOp4(v, opcode, iCur, pPk->tnum, iDb,
47*dd9930efSdrh                       (char*)sqlite3IndexKeyinfo(p, pPk), P4_KEYINFO_HANDOFF);
48bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
49bbb5e4e0Sdrh   }
50ec95c441Sdrh }
51bbb5e4e0Sdrh 
52bbb5e4e0Sdrh /*
5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5569f8bb9cSdan ** the table, according to the affinity of the column:
563d1bfeaaSdanielk1977 **
573d1bfeaaSdanielk1977 **  Character      Column affinity
583d1bfeaaSdanielk1977 **  ------------------------------
593eda040bSdrh **  'a'            TEXT
603eda040bSdrh **  'b'            NONE
613eda040bSdrh **  'c'            NUMERIC
623eda040bSdrh **  'd'            INTEGER
633eda040bSdrh **  'e'            REAL
642d401ab8Sdrh **
650c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
662d401ab8Sdrh ** rowid that appears as the last column in every index.
6769f8bb9cSdan **
6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
713d1bfeaaSdanielk1977 */
7269f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
73a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
74e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
75a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
76e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
77a37cdde0Sdanielk1977     **
78a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
79e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80a37cdde0Sdanielk1977     ** up.
81a37cdde0Sdanielk1977     */
82a37cdde0Sdanielk1977     int n;
83a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
84abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
85ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
86a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
87633e6d57Sdrh       db->mallocFailed = 1;
8869f8bb9cSdan       return 0;
89a37cdde0Sdanielk1977     }
90ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
91ad124329Sdrh       i16 x = pIdx->aiColumn[n];
92ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
93a37cdde0Sdanielk1977     }
942d401ab8Sdrh     pIdx->zColAff[n] = 0;
95a37cdde0Sdanielk1977   }
963d1bfeaaSdanielk1977 
9769f8bb9cSdan   return pIdx->zColAff;
98a37cdde0Sdanielk1977 }
99a37cdde0Sdanielk1977 
100a37cdde0Sdanielk1977 /*
10166a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
102a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
103a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
104a37cdde0Sdanielk1977 ** column:
105a37cdde0Sdanielk1977 **
106a37cdde0Sdanielk1977 **  Character      Column affinity
107a37cdde0Sdanielk1977 **  ------------------------------
1083eda040bSdrh **  'a'            TEXT
1093eda040bSdrh **  'b'            NONE
1103eda040bSdrh **  'c'            NUMERIC
1113eda040bSdrh **  'd'            INTEGER
1123eda040bSdrh **  'e'            REAL
113a37cdde0Sdanielk1977 */
114a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1153d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1163d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1173d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1183d1bfeaaSdanielk1977   **
1193d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1203d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1213d1bfeaaSdanielk1977   */
1223d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1233d1bfeaaSdanielk1977     char *zColAff;
1243d1bfeaaSdanielk1977     int i;
125abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1263d1bfeaaSdanielk1977 
127b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1283d1bfeaaSdanielk1977     if( !zColAff ){
129633e6d57Sdrh       db->mallocFailed = 1;
130a37cdde0Sdanielk1977       return;
1313d1bfeaaSdanielk1977     }
1323d1bfeaaSdanielk1977 
1333d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
134a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1353d1bfeaaSdanielk1977     }
1363d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1373d1bfeaaSdanielk1977 
1383d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1393d1bfeaaSdanielk1977   }
1403d1bfeaaSdanielk1977 
1418d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1423d1bfeaaSdanielk1977 }
1433d1bfeaaSdanielk1977 
1444d88778bSdanielk1977 /*
14548d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
14648d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
14748d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
14848d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
14948d1178aSdrh ** run without using temporary table for the results of the SELECT.
1504d88778bSdanielk1977 */
151595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
152595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1534d88778bSdanielk1977   int i;
15448d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
155595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
156595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
157595a523aSdanielk1977 #endif
158595a523aSdanielk1977 
15948d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
16048d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
161ef0bea92Sdrh     assert( pOp!=0 );
162207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16348d1178aSdrh       Index *pIndex;
164207872a4Sdanielk1977       int tnum = pOp->p2;
16548d1178aSdrh       if( tnum==pTab->tnum ){
16648d1178aSdrh         return 1;
16748d1178aSdrh       }
16848d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
16948d1178aSdrh         if( tnum==pIndex->tnum ){
17048d1178aSdrh           return 1;
17148d1178aSdrh         }
17248d1178aSdrh       }
17348d1178aSdrh     }
174543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
175595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1762dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
17766a5167bSdrh       assert( pOp->p4type==P4_VTAB );
17848d1178aSdrh       return 1;
1794d88778bSdanielk1977     }
180543165efSdrh #endif
1814d88778bSdanielk1977   }
1824d88778bSdanielk1977   return 0;
1834d88778bSdanielk1977 }
1843d1bfeaaSdanielk1977 
1859d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1869d9cf229Sdrh /*
1870b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1880b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1890b9f50d8Sdrh ** that holds the maximum rowid.
1909d9cf229Sdrh **
1910b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1920b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1930b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1940b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1950b9f50d8Sdrh ** AutoincInfo structure is used.
1969d9cf229Sdrh **
1970b9f50d8Sdrh ** Three memory locations are allocated:
1980b9f50d8Sdrh **
1990b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
2000b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2010b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2020b9f50d8Sdrh **
2030b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2040b9f50d8Sdrh ** insert routine needs to know about.
2059d9cf229Sdrh */
2069d9cf229Sdrh static int autoIncBegin(
2079d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2089d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2099d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2109d9cf229Sdrh ){
2116a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2127d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21365a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2140b9f50d8Sdrh     AutoincInfo *pInfo;
2150b9f50d8Sdrh 
21665a7cd16Sdan     pInfo = pToplevel->pAinc;
2170b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2180b9f50d8Sdrh     if( pInfo==0 ){
2190b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2200b9f50d8Sdrh       if( pInfo==0 ) return 0;
22165a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22265a7cd16Sdan       pToplevel->pAinc = pInfo;
2230b9f50d8Sdrh       pInfo->pTab = pTab;
2240b9f50d8Sdrh       pInfo->iDb = iDb;
22565a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
22665a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
22765a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2280b9f50d8Sdrh     }
2290b9f50d8Sdrh     memId = pInfo->regCtr;
2309d9cf229Sdrh   }
2319d9cf229Sdrh   return memId;
2329d9cf229Sdrh }
2339d9cf229Sdrh 
2349d9cf229Sdrh /*
2350b9f50d8Sdrh ** This routine generates code that will initialize all of the
2360b9f50d8Sdrh ** register used by the autoincrement tracker.
2370b9f50d8Sdrh */
2380b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2390b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2400b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2410b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2420b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2430b9f50d8Sdrh   int addr;                  /* A VDBE address */
2440b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2450b9f50d8Sdrh 
246345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
247345ba7dbSdrh   ** only called from the top-level */
248345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
249345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
25076d462eeSdan 
2510b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2520b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2530b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2540b9f50d8Sdrh     memId = p->regCtr;
2552120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2560b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
257f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2580b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2590b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2600b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2610b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2620b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2630b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2640b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2650b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2660b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2670b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2680b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2690b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2700b9f50d8Sdrh   }
2710b9f50d8Sdrh }
2720b9f50d8Sdrh 
2730b9f50d8Sdrh /*
2749d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2759d9cf229Sdrh **
2769d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2779d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2789d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2799d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2809d9cf229Sdrh */
2816a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2829d9cf229Sdrh   if( memId>0 ){
2836a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2849d9cf229Sdrh   }
2859d9cf229Sdrh }
2869d9cf229Sdrh 
2879d9cf229Sdrh /*
2880b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2890b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2900b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2910b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2920b9f50d8Sdrh ** routine just before the "exit" code.
2939d9cf229Sdrh */
2940b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2950b9f50d8Sdrh   AutoincInfo *p;
2969d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2970b9f50d8Sdrh   sqlite3 *db = pParse->db;
2986a288a33Sdrh 
2999d9cf229Sdrh   assert( v );
3000b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3010b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3020b9f50d8Sdrh     int j1, j2, j3, j4, j5;
3030b9f50d8Sdrh     int iRec;
3040b9f50d8Sdrh     int memId = p->regCtr;
3050b9f50d8Sdrh 
3060b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3072120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3080b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3096a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
3100b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
3110b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
3120b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3130b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3140b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3150b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3160b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3170b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3180b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3196a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3200b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
321a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3220b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
32335573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3240b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3250b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3269d9cf229Sdrh   }
3279d9cf229Sdrh }
3289d9cf229Sdrh #else
3299d9cf229Sdrh /*
3309d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3319d9cf229Sdrh ** above are all no-ops
3329d9cf229Sdrh */
3339d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
334287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3359d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3369d9cf229Sdrh 
3379d9cf229Sdrh 
3385f085269Sdrh /*
3395f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3405f085269Sdrh ** row at a time.
3415f085269Sdrh **
3425f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3435f085269Sdrh ** Information about the location of co-routine and the registers it will use
3445f085269Sdrh ** is returned by filling in the pDest object.
3455f085269Sdrh **
3465f085269Sdrh ** Registers are allocated as follows:
3475f085269Sdrh **
3485f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3495f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3505f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3515f085269Sdrh **
3525f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3535f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3545f085269Sdrh **                       generated a new result row, or 1 if the subquery
3555f085269Sdrh **                       has completed.  If the Yield is called again
3565f085269Sdrh **                       after this register becomes 1, then the VDBE will
3575f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3585f085269Sdrh **
3595f085269Sdrh **   pDest->iSdst        First result register.
3605f085269Sdrh **
3615f085269Sdrh **   pDest->nSdst        Number of result registers.
3625f085269Sdrh **
3635f085269Sdrh ** This routine handles all of the register allocation and fills in the
3645f085269Sdrh ** pDest structure appropriately.
3655f085269Sdrh **
3665f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3675f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3685f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3695f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3705f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3715f085269Sdrh **
3725f085269Sdrh **         X <- A
3735f085269Sdrh **         EOF <- 0
3745f085269Sdrh **         goto B
3755f085269Sdrh **      A: setup for the SELECT
3765f085269Sdrh **         loop rows in the SELECT
3775f085269Sdrh **           load results into registers R..S
3785f085269Sdrh **           yield X
3795f085269Sdrh **         end loop
3805f085269Sdrh **         cleanup after the SELECT
3815f085269Sdrh **         EOF <- 1
3825f085269Sdrh **         yield X
3835f085269Sdrh **         halt-error
3845f085269Sdrh **      B:
3855f085269Sdrh **
3865f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3875f085269Sdrh **
3885f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3895f085269Sdrh **      S: yield X
3905f085269Sdrh **         if EOF goto E
3915f085269Sdrh **         if skip this row, goto C
3925f085269Sdrh **         if terminate loop, goto E
3935f085269Sdrh **         deal with this row
3945f085269Sdrh **      C: goto S
3955f085269Sdrh **      E:
3965f085269Sdrh */
3975f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3985f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3995f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
4005f085269Sdrh   int addrTop;        /* Top of the co-routine */
4015f085269Sdrh   int j1;             /* Jump instruction */
4025f085269Sdrh   int rc;             /* Result code */
4035f085269Sdrh   Vdbe *v;            /* VDBE under construction */
4045f085269Sdrh 
4055f085269Sdrh   regYield = ++pParse->nMem;
4065f085269Sdrh   regEof = ++pParse->nMem;
4075f085269Sdrh   v = sqlite3GetVdbe(pParse);
4085f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
4095f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
4105f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
4115f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
4125f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4135f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4145f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4155f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4165f085269Sdrh   assert( pParse->nErr==0 || rc );
4175f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4185f085269Sdrh   if( rc ) return rc;
4195f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4205f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4215f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4225f085269Sdrh   VdbeComment((v, "End of coroutine"));
4235f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4245f085269Sdrh   return rc;
4255f085269Sdrh }
4265f085269Sdrh 
4275f085269Sdrh 
4285f085269Sdrh 
4299d9cf229Sdrh /* Forward declaration */
4309d9cf229Sdrh static int xferOptimization(
4319d9cf229Sdrh   Parse *pParse,        /* Parser context */
4329d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4339d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4349d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4359d9cf229Sdrh   int iDbDest           /* The database of pDest */
4369d9cf229Sdrh );
4379d9cf229Sdrh 
4383d1bfeaaSdanielk1977 /*
4391ccde15dSdrh ** This routine is call to handle SQL of the following forms:
440cce7d176Sdrh **
441cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4421ccde15dSdrh **    insert into TABLE (IDLIST) select
443cce7d176Sdrh **
4441ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4451ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
446967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4471ccde15dSdrh **
4481ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4491ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4501ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4511ccde15dSdrh ** data for the insert.
452142e30dfSdrh **
4539d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
454142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
455e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
456e00ee6ebSdrh ** the "1st template"):
457142e30dfSdrh **
458142e30dfSdrh **         open write cursor to <table> and its indices
459ec95c441Sdrh **         put VALUES clause expressions into registers
460142e30dfSdrh **         write the resulting record into <table>
461142e30dfSdrh **         cleanup
462142e30dfSdrh **
4639d9cf229Sdrh ** The three remaining templates assume the statement is of the form
464142e30dfSdrh **
465142e30dfSdrh **   INSERT INTO <table> SELECT ...
466142e30dfSdrh **
4679d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4689d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4699d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4709d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4719d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4729d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4739d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
474e00ee6ebSdrh ** template.  This is the 2nd template.
4759d9cf229Sdrh **
4769d9cf229Sdrh **         open a write cursor to <table>
4779d9cf229Sdrh **         open read cursor on <table2>
4789d9cf229Sdrh **         transfer all records in <table2> over to <table>
4799d9cf229Sdrh **         close cursors
4809d9cf229Sdrh **         foreach index on <table>
4819d9cf229Sdrh **           open a write cursor on the <table> index
4829d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4839d9cf229Sdrh **           transfer all records from the read to the write cursors
4849d9cf229Sdrh **           close cursors
4859d9cf229Sdrh **         end foreach
4869d9cf229Sdrh **
487e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4889d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4899d9cf229Sdrh ** The generated code follows this template:
490142e30dfSdrh **
491e00ee6ebSdrh **         EOF <- 0
492e00ee6ebSdrh **         X <- A
493142e30dfSdrh **         goto B
494142e30dfSdrh **      A: setup for the SELECT
4959d9cf229Sdrh **         loop over the rows in the SELECT
496e00ee6ebSdrh **           load values into registers R..R+n
497e00ee6ebSdrh **           yield X
498142e30dfSdrh **         end loop
499142e30dfSdrh **         cleanup after the SELECT
500e00ee6ebSdrh **         EOF <- 1
501e00ee6ebSdrh **         yield X
502142e30dfSdrh **         goto A
503e00ee6ebSdrh **      B: open write cursor to <table> and its indices
504e00ee6ebSdrh **      C: yield X
505e00ee6ebSdrh **         if EOF goto D
506e00ee6ebSdrh **         insert the select result into <table> from R..R+n
507e00ee6ebSdrh **         goto C
508142e30dfSdrh **      D: cleanup
509142e30dfSdrh **
510e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
511142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
512142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
513142e30dfSdrh ** we have to use a intermediate table to store the results of
514142e30dfSdrh ** the select.  The template is like this:
515142e30dfSdrh **
516e00ee6ebSdrh **         EOF <- 0
517e00ee6ebSdrh **         X <- A
518142e30dfSdrh **         goto B
519142e30dfSdrh **      A: setup for the SELECT
520142e30dfSdrh **         loop over the tables in the SELECT
521e00ee6ebSdrh **           load value into register R..R+n
522e00ee6ebSdrh **           yield X
523142e30dfSdrh **         end loop
524142e30dfSdrh **         cleanup after the SELECT
525e00ee6ebSdrh **         EOF <- 1
526e00ee6ebSdrh **         yield X
527e00ee6ebSdrh **         halt-error
528e00ee6ebSdrh **      B: open temp table
529e00ee6ebSdrh **      L: yield X
530e00ee6ebSdrh **         if EOF goto M
531e00ee6ebSdrh **         insert row from R..R+n into temp table
532e00ee6ebSdrh **         goto L
533e00ee6ebSdrh **      M: open write cursor to <table> and its indices
534e00ee6ebSdrh **         rewind temp table
535e00ee6ebSdrh **      C: loop over rows of intermediate table
536142e30dfSdrh **           transfer values form intermediate table into <table>
537e00ee6ebSdrh **         end loop
538e00ee6ebSdrh **      D: cleanup
539cce7d176Sdrh */
5404adee20fSdanielk1977 void sqlite3Insert(
541cce7d176Sdrh   Parse *pParse,        /* Parser context */
542113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
543cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5445974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5459cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5469cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
547cce7d176Sdrh ){
5486a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5496a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
550113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
551e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5525974a30fSdrh   int i, j, idx;        /* Loop counters */
5535974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5545974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
555967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5566a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
55704adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
5584a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5590ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5604d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
561cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
562e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
563e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
564e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5652eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5666a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5672958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
568e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
569ec95c441Sdrh   int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
570cce7d176Sdrh 
5716a288a33Sdrh   /* Register allocations */
5721bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5736a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5746a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5756a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5766a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5776a288a33Sdrh   int regData;          /* register holding first column to insert */
5781bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
579aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5806a288a33Sdrh 
581798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
582798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5832f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5842f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
585798da52cSdrh #endif
586c3f9bad2Sdanielk1977 
58717435752Sdrh   db = pParse->db;
5881bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
58917435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5906f7adc8aSdrh     goto insert_cleanup;
5916f7adc8aSdrh   }
592daffd0e5Sdrh 
5931ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5941ccde15dSdrh   */
595113088ecSdrh   assert( pTabList->nSrc==1 );
596113088ecSdrh   zTab = pTabList->a[0].zName;
597098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5984adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
599c3f9bad2Sdanielk1977   if( pTab==0 ){
600c3f9bad2Sdanielk1977     goto insert_cleanup;
601c3f9bad2Sdanielk1977   }
602da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
603da184236Sdanielk1977   assert( iDb<db->nDb );
604da184236Sdanielk1977   pDb = &db->aDb[iDb];
6052958a4e6Sdrh   zDb = pDb->zName;
6064adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
6071962bda7Sdrh     goto insert_cleanup;
6081962bda7Sdrh   }
609ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
610c3f9bad2Sdanielk1977 
611b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
612b7f9164eSdrh   ** inserted into is a view
613b7f9164eSdrh   */
614b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6152f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
616b7f9164eSdrh   isView = pTab->pSelect!=0;
617b7f9164eSdrh #else
6182f886d1dSdanielk1977 # define pTrigger 0
6192f886d1dSdanielk1977 # define tmask 0
620b7f9164eSdrh # define isView 0
621b7f9164eSdrh #endif
622b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
623b7f9164eSdrh # undef isView
624b7f9164eSdrh # define isView 0
625b7f9164eSdrh #endif
6262f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
627b7f9164eSdrh 
628f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
629b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
630b3d24bf8Sdanielk1977   ** module table).
631f573c99bSdrh   */
632b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
633f573c99bSdrh     goto insert_cleanup;
634f573c99bSdrh   }
635f573c99bSdrh 
636595a523aSdanielk1977   /* Ensure that:
637595a523aSdanielk1977   *  (a) the table is not read-only,
638595a523aSdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
639595a523aSdanielk1977   */
640595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
641595a523aSdanielk1977     goto insert_cleanup;
642595a523aSdanielk1977   }
643595a523aSdanielk1977 
6441ccde15dSdrh   /* Allocate a VDBE
6451ccde15dSdrh   */
6464adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6475974a30fSdrh   if( v==0 ) goto insert_cleanup;
6484794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6492f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6501ccde15dSdrh 
6519d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6529d9cf229Sdrh   /* If the statement is of the form
6539d9cf229Sdrh   **
6549d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6559d9cf229Sdrh   **
6569d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6579d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
658e00ee6ebSdrh   **
659e00ee6ebSdrh   ** This is the 2nd template.
6609d9cf229Sdrh   */
6619d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6622f886d1dSdanielk1977     assert( !pTrigger );
6639d9cf229Sdrh     assert( pList==0 );
6640b9f50d8Sdrh     goto insert_end;
6659d9cf229Sdrh   }
6669d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6679d9cf229Sdrh 
6682958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6696a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6702958a4e6Sdrh   */
6716a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6722958a4e6Sdrh 
6731ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
674e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
675e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
676e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6771ccde15dSdrh   */
6785974a30fSdrh   if( pSelect ){
6795f085269Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run that
6805f085269Sdrh     ** SELECT. */
6815f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6825f085269Sdrh     if( rc ) goto insert_cleanup;
6831013c932Sdrh 
6845f085269Sdrh     regEof = dest.iSDParm + 1;
6852b596da8Sdrh     regFromSelect = dest.iSdst;
6865974a30fSdrh     assert( pSelect->pEList );
687967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6882b596da8Sdrh     assert( dest.nSdst==nColumn );
689142e30dfSdrh 
690142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
691e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
692e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
693e00ee6ebSdrh     ** the destination table (template 3).
694048c530cSdrh     **
695048c530cSdrh     ** A temp table must be used if the table being updated is also one
696048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
697048c530cSdrh     ** temp table in the case of row triggers.
698142e30dfSdrh     */
699595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
700048c530cSdrh       useTempTable = 1;
701048c530cSdrh     }
702142e30dfSdrh 
703142e30dfSdrh     if( useTempTable ){
704e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
705e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
706e00ee6ebSdrh       ** here is from the 4th template:
707e00ee6ebSdrh       **
708e00ee6ebSdrh       **      B: open temp table
709e00ee6ebSdrh       **      L: yield X
710e00ee6ebSdrh       **         if EOF goto M
711e00ee6ebSdrh       **         insert row from R..R+n into temp table
712e00ee6ebSdrh       **         goto L
713e00ee6ebSdrh       **      M: ...
714142e30dfSdrh       */
715e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
716dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
717e00ee6ebSdrh       int addrTop;         /* Label "L" */
718e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
719b7654111Sdrh 
720142e30dfSdrh       srcTab = pParse->nTab++;
721b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
722dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
723e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7242b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
725e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7261db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
727dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
728dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
729e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
730e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
731b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
732dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
733142e30dfSdrh     }
734142e30dfSdrh   }else{
735142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
736142e30dfSdrh     ** clause
737142e30dfSdrh     */
738b3bce662Sdanielk1977     NameContext sNC;
739b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
740b3bce662Sdanielk1977     sNC.pParse = pParse;
7415974a30fSdrh     srcTab = -1;
74248d1178aSdrh     assert( useTempTable==0 );
743147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
744e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7457d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
746b04a5d87Sdrh         goto insert_cleanup;
747b04a5d87Sdrh       }
748e64e7b20Sdrh     }
7495974a30fSdrh   }
7501ccde15dSdrh 
7511ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7521ccde15dSdrh   ** of columns to be inserted into the table.
7531ccde15dSdrh   */
754034ca14fSdanielk1977   if( IsVirtual(pTab) ){
755034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
756034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
757034ca14fSdanielk1977     }
758034ca14fSdanielk1977   }
759034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7604adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
761da93d238Sdrh        "table %S has %d columns but %d values were supplied",
762d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
763cce7d176Sdrh     goto insert_cleanup;
764cce7d176Sdrh   }
765967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7664adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
767cce7d176Sdrh     goto insert_cleanup;
768cce7d176Sdrh   }
7691ccde15dSdrh 
7701ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7711ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7721ccde15dSdrh   ** remember the column indices.
773c8392586Sdrh   **
774c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
775c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
776c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
777c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
778c8392586Sdrh   ** is appears in the original table.  (The index of the primary
779c8392586Sdrh   ** key in the original table is pTab->iPKey.)
7801ccde15dSdrh   */
781967e8b73Sdrh   if( pColumn ){
782967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
783967e8b73Sdrh       pColumn->a[i].idx = -1;
784cce7d176Sdrh     }
785967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
786cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7874adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
788967e8b73Sdrh           pColumn->a[i].idx = j;
7894a32431cSdrh           if( j==pTab->iPKey ){
790ec95c441Sdrh             keyColumn = i;  assert( !withoutRowid );
7914a32431cSdrh           }
792cce7d176Sdrh           break;
793cce7d176Sdrh         }
794cce7d176Sdrh       }
795cce7d176Sdrh       if( j>=pTab->nCol ){
796ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
797a0217ba7Sdrh           keyColumn = i;
798a0217ba7Sdrh         }else{
7994adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
800da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
8011db95106Sdan           pParse->checkSchema = 1;
802cce7d176Sdrh           goto insert_cleanup;
803cce7d176Sdrh         }
804cce7d176Sdrh       }
805cce7d176Sdrh     }
806a0217ba7Sdrh   }
8071ccde15dSdrh 
808aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
809c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
810c8392586Sdrh   ** in the original table definition.
8114a32431cSdrh   */
812147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
8134a32431cSdrh     keyColumn = pTab->iPKey;
8144a32431cSdrh   }
8154a32431cSdrh 
816c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8171ccde15dSdrh   */
818142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8196a288a33Sdrh     regRowCount = ++pParse->nMem;
8206a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
821c3f9bad2Sdanielk1977   }
822c3f9bad2Sdanielk1977 
823e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
824e448dc4aSdanielk1977   if( !isView ){
825aa9b8963Sdrh     int nIdx;
826aa9b8963Sdrh 
827ec95c441Sdrh     baseCur = pParse->nTab - withoutRowid;
82804adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
8295c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
830aa9b8963Sdrh     if( aRegIdx==0 ){
831aa9b8963Sdrh       goto insert_cleanup;
832aa9b8963Sdrh     }
833aa9b8963Sdrh     for(i=0; i<nIdx; i++){
834aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
835aa9b8963Sdrh     }
836feeb1394Sdrh   }
837feeb1394Sdrh 
838e00ee6ebSdrh   /* This is the top of the main insertion loop */
839142e30dfSdrh   if( useTempTable ){
840e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
841e00ee6ebSdrh     ** following pseudocode (template 4):
842e00ee6ebSdrh     **
843e00ee6ebSdrh     **         rewind temp table
844e00ee6ebSdrh     **      C: loop over rows of intermediate table
845e00ee6ebSdrh     **           transfer values form intermediate table into <table>
846e00ee6ebSdrh     **         end loop
847e00ee6ebSdrh     **      D: ...
848e00ee6ebSdrh     */
849e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
850e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
851142e30dfSdrh   }else if( pSelect ){
852e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
853e00ee6ebSdrh     ** following pseudocode (template 3):
854e00ee6ebSdrh     **
855e00ee6ebSdrh     **      C: yield X
856e00ee6ebSdrh     **         if EOF goto D
857e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
858e00ee6ebSdrh     **         goto C
859e00ee6ebSdrh     **      D: ...
860e00ee6ebSdrh     */
8612b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
862e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
863bed8690fSdrh   }
8641ccde15dSdrh 
8656a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8666a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8676a288a33Sdrh   */
8686a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8696a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8706a288a33Sdrh   if( IsVirtual(pTab) ){
8716a288a33Sdrh     regRowid++;
8726a288a33Sdrh     pParse->nMem++;
8736a288a33Sdrh   }
8746a288a33Sdrh   regData = regRowid+1;
8756a288a33Sdrh 
8765cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
87770ce3f0cSdrh   */
8784adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8792f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
88076d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
881c3f9bad2Sdanielk1977 
88270ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
88370ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
88470ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
88570ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
88670ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
88770ce3f0cSdrh     */
88870ce3f0cSdrh     if( keyColumn<0 ){
88976d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89070ce3f0cSdrh     }else{
8916a288a33Sdrh       int j1;
892ec95c441Sdrh       assert( !withoutRowid );
8937fe45908Sdrh       if( useTempTable ){
89476d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
8957fe45908Sdrh       }else{
896d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89776d462eeSdan         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
8987fe45908Sdrh       }
89976d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
90076d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
9016a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
90276d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
90370ce3f0cSdrh     }
90470ce3f0cSdrh 
905034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
906034ca14fSdanielk1977     ** this block would have to account for hidden column.
907034ca14fSdanielk1977     */
908034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
909034ca14fSdanielk1977 
91070ce3f0cSdrh     /* Create the new column data
91170ce3f0cSdrh     */
912c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
913c3f9bad2Sdanielk1977       if( pColumn==0 ){
914c3f9bad2Sdanielk1977         j = i;
915c3f9bad2Sdanielk1977       }else{
916c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
917c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
918c3f9bad2Sdanielk1977         }
919c3f9bad2Sdanielk1977       }
9207ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
92176d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
922142e30dfSdrh       }else if( useTempTable ){
92376d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
924c3f9bad2Sdanielk1977       }else{
925d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
92676d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
927c3f9bad2Sdanielk1977       }
928c3f9bad2Sdanielk1977     }
929a37cdde0Sdanielk1977 
930a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
931a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
932a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
933a37cdde0Sdanielk1977     ** table column affinities.
934a37cdde0Sdanielk1977     */
935a37cdde0Sdanielk1977     if( !isView ){
93676d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
937a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
938a37cdde0Sdanielk1977     }
939c3f9bad2Sdanielk1977 
9405cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
941165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
94294d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
943165921a7Sdan 
94476d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
94570ce3f0cSdrh   }
946c3f9bad2Sdanielk1977 
9474a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
948f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
9494a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
950b419a926Sdrh   ** case the record number is the same as that column.
9511ccde15dSdrh   */
9525cf590c1Sdrh   if( !isView ){
9534cbdda9eSdrh     if( IsVirtual(pTab) ){
9544cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9556a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9564cbdda9eSdrh     }
9574a32431cSdrh     if( keyColumn>=0 ){
958142e30dfSdrh       if( useTempTable ){
9596a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
960142e30dfSdrh       }else if( pSelect ){
961b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
9624a32431cSdrh       }else{
963e4d90813Sdrh         VdbeOp *pOp;
9641db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
96520411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9661b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
967e4d90813Sdrh           appendFlag = 1;
968e4d90813Sdrh           pOp->opcode = OP_NewRowid;
96904adf416Sdrh           pOp->p1 = baseCur;
9706a288a33Sdrh           pOp->p2 = regRowid;
9716a288a33Sdrh           pOp->p3 = regAutoinc;
972e4d90813Sdrh         }
97327a32783Sdrh       }
974f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
975e1e68f49Sdrh       ** to generate a unique primary key value.
976e1e68f49Sdrh       */
977e4d90813Sdrh       if( !appendFlag ){
9781db639ceSdrh         int j1;
979bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9801db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
98104adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
9821db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
983bb50e7adSdanielk1977         }else{
984bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
985bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
986bb50e7adSdanielk1977         }
9873c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
988e4d90813Sdrh       }
989ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9906a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9914a32431cSdrh     }else{
99204adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
993e4d90813Sdrh       appendFlag = 1;
9944a32431cSdrh     }
9956a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9964a32431cSdrh 
997aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
9984a32431cSdrh     ** with the first column.
9994a32431cSdrh     */
1000034ca14fSdanielk1977     nHidden = 0;
1001cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
10026a288a33Sdrh       int iRegStore = regRowid+1+i;
10034a32431cSdrh       if( i==pTab->iPKey ){
10044a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
1005aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
1006aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
1007aacc543eSdrh         ** taking up data space with information that will never be used. */
10084c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
10094a32431cSdrh         continue;
10104a32431cSdrh       }
1011967e8b73Sdrh       if( pColumn==0 ){
1012034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1013034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1014034ca14fSdanielk1977           j = -1;
1015034ca14fSdanielk1977           nHidden++;
1016034ca14fSdanielk1977         }else{
1017034ca14fSdanielk1977           j = i - nHidden;
1018034ca14fSdanielk1977         }
1019cce7d176Sdrh       }else{
1020967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1021967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1022cce7d176Sdrh         }
1023cce7d176Sdrh       }
1024034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1025287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1026142e30dfSdrh       }else if( useTempTable ){
1027287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1028142e30dfSdrh       }else if( pSelect ){
1029b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1030cce7d176Sdrh       }else{
1031287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1032cce7d176Sdrh       }
1033cce7d176Sdrh     }
10341ccde15dSdrh 
10350ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10360ca3e24bSdrh     ** do the insertion.
10374a32431cSdrh     */
10384cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10394cbdda9eSdrh     if( IsVirtual(pTab) ){
1040595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10414f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1042595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1043b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1044e0af83acSdan       sqlite3MayAbort(pParse);
10454cbdda9eSdrh     }else
10464cbdda9eSdrh #endif
10474cbdda9eSdrh     {
1048de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1049de630353Sdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
1050de630353Sdanielk1977           keyColumn>=0, 0, onError, endOfLoop, &isReplace
105104adf416Sdrh       );
10528ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
105304adf416Sdrh       sqlite3CompleteInsertion(
10542832ad42Sdan           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
105504adf416Sdrh       );
10565cf590c1Sdrh     }
10574cbdda9eSdrh   }
10581bee3d7bSdrh 
1059feeb1394Sdrh   /* Update the count of rows that are inserted
10601bee3d7bSdrh   */
1061142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10626a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10631bee3d7bSdrh   }
1064c3f9bad2Sdanielk1977 
10652f886d1dSdanielk1977   if( pTrigger ){
1066c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1067165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
106894d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1069c3f9bad2Sdanielk1977   }
10701bee3d7bSdrh 
1071e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1072e00ee6ebSdrh   ** is a SELECT statement.
10731ccde15dSdrh   */
10744adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1075142e30dfSdrh   if( useTempTable ){
1076e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1077e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10782eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1079142e30dfSdrh   }else if( pSelect ){
1080e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1081e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10826b56344dSdrh   }
1083c3f9bad2Sdanielk1977 
1084e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1085c3f9bad2Sdanielk1977     /* Close all tables opened */
1086ec95c441Sdrh     if( !withoutRowid ) sqlite3VdbeAddOp1(v, OP_Close, baseCur);
10876b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
10882eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
1089cce7d176Sdrh     }
1090c3f9bad2Sdanielk1977   }
1091c3f9bad2Sdanielk1977 
10920b9f50d8Sdrh insert_end:
1093f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10940b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10950b9f50d8Sdrh   ** autoincrement tables.
10962958a4e6Sdrh   */
1097165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10980b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10990b9f50d8Sdrh   }
11002958a4e6Sdrh 
11011bee3d7bSdrh   /*
1102e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1103e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1104e7de6f25Sdanielk1977   ** invoke the callback function.
11051bee3d7bSdrh   */
1106165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
11076a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110822322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
110910fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11101bee3d7bSdrh   }
1111cce7d176Sdrh 
1112cce7d176Sdrh insert_cleanup:
1113633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1114633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1115633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1116633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1117633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1118cce7d176Sdrh }
11199cfcf5d4Sdrh 
112075cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
112175cbd984Sdan ** thely may interfere with compilation of other functions in this file
112275cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
112375cbd984Sdan #ifdef isView
112475cbd984Sdan  #undef isView
112575cbd984Sdan #endif
112675cbd984Sdan #ifdef pTrigger
112775cbd984Sdan  #undef pTrigger
112875cbd984Sdan #endif
112975cbd984Sdan #ifdef tmask
113075cbd984Sdan  #undef tmask
113175cbd984Sdan #endif
113275cbd984Sdan 
113375cbd984Sdan 
11349cfcf5d4Sdrh /*
11356a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
11369cfcf5d4Sdrh **
113704adf416Sdrh ** The input is a range of consecutive registers as follows:
11380ca3e24bSdrh **
113965a7cd16Sdan **    1.  The rowid of the row after the update.
11400ca3e24bSdrh **
114165a7cd16Sdan **    2.  The data in the first column of the entry after the update.
11420ca3e24bSdrh **
11430ca3e24bSdrh **    i.  Data from middle columns...
11440ca3e24bSdrh **
11450ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
11460ca3e24bSdrh **
114765a7cd16Sdan ** The regRowid parameter is the index of the register containing (1).
114804adf416Sdrh **
114965a7cd16Sdan ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
115065a7cd16Sdan ** the address of a register containing the rowid before the update takes
115165a7cd16Sdan ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
115265a7cd16Sdan ** is false, indicating an INSERT statement, then a non-zero rowidChng
115365a7cd16Sdan ** indicates that the rowid was explicitly specified as part of the
115465a7cd16Sdan ** INSERT statement. If rowidChng is false, it means that  the rowid is
115565a7cd16Sdan ** computed automatically in an insert or that the rowid value is not
115665a7cd16Sdan ** modified by an update.
11570ca3e24bSdrh **
1158aa9b8963Sdrh ** The code generated by this routine store new index entries into
1159aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1160aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1161aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1162aa9b8963Sdrh ** attached to the table.
11639cfcf5d4Sdrh **
11649cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11659cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11661c92853dSdrh ** then the appropriate action is performed.  There are five possible
11671c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11689cfcf5d4Sdrh **
11699cfcf5d4Sdrh **  Constraint type  Action       What Happens
11709cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11711c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
117224b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
11739cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11749cfcf5d4Sdrh **
11751c92853dSdrh **  any              ABORT        Back out changes from the current command
11761c92853dSdrh **                                only (do not do a complete rollback) then
117724b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
11781c92853dSdrh **                                with SQLITE_CONSTRAINT.
11791c92853dSdrh **
1180e4c88c0cSdrh **  any              FAIL         Sqlite3_exec() returns immediately with a
11811c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11821c92853dSdrh **                                transaction is not rolled back and any
11831c92853dSdrh **                                prior changes are retained.
11841c92853dSdrh **
11859cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
11869cfcf5d4Sdrh **                                the stack and there is an immediate jump
11879cfcf5d4Sdrh **                                to label ignoreDest.
11889cfcf5d4Sdrh **
11899cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11909cfcf5d4Sdrh **                                value for that column.  If the default value
11919cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11929cfcf5d4Sdrh **
11939cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
11949cfcf5d4Sdrh **                                being inserted is removed.
11959cfcf5d4Sdrh **
11969cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
11979cfcf5d4Sdrh **
11981c92853dSdrh ** Which action to take is determined by the overrideError parameter.
11991c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12001c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12011c92853dSdrh ** for the constraint is used.
12029cfcf5d4Sdrh **
1203aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
120404adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
120504adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
12069cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1207aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
12089cfcf5d4Sdrh */
12094adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12109cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
12119cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
121204adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
121304adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1214aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1215a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1216b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
12179cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1218de630353Sdanielk1977   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
1219de630353Sdanielk1977   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
12209cfcf5d4Sdrh ){
12211b7ecbb4Sdrh   int i;              /* loop counter */
12221b7ecbb4Sdrh   Vdbe *v;            /* VDBE under constrution */
12231b7ecbb4Sdrh   int nCol;           /* Number of columns */
12241b7ecbb4Sdrh   int onError;        /* Conflict resolution strategy */
12251bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
12261bd10f8aSdrh   int j2 = 0, j3;     /* Addresses of jump instructions */
122704adf416Sdrh   int regData;        /* Register containing first data column */
12281b7ecbb4Sdrh   int iCur;           /* Table cursor number */
12291b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
12302938f924Sdrh   sqlite3 *db;         /* Database connection */
12311b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
123265a7cd16Sdan   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
12339cfcf5d4Sdrh 
12342938f924Sdrh   db = pParse->db;
12354adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12369cfcf5d4Sdrh   assert( v!=0 );
1237417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12389cfcf5d4Sdrh   nCol = pTab->nCol;
1239aa9b8963Sdrh   regData = regRowid + 1;
1240aa9b8963Sdrh 
12419cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12429cfcf5d4Sdrh   */
12439cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12440ca3e24bSdrh     if( i==pTab->iPKey ){
12450ca3e24bSdrh       continue;
12460ca3e24bSdrh     }
12479cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12480ca3e24bSdrh     if( onError==OE_None ) continue;
12499cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12509cfcf5d4Sdrh       onError = overrideError;
1251a996e477Sdrh     }else if( onError==OE_Default ){
1252a996e477Sdrh       onError = OE_Abort;
12539cfcf5d4Sdrh     }
12547977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12559cfcf5d4Sdrh       onError = OE_Abort;
12569cfcf5d4Sdrh     }
1257b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1258b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12599cfcf5d4Sdrh     switch( onError ){
12601c92853dSdrh       case OE_Abort:
1261e0af83acSdan         sqlite3MayAbort(pParse);
1262e0af83acSdan       case OE_Rollback:
12631c92853dSdrh       case OE_Fail: {
1264f089aa45Sdrh         char *zMsg;
1265c126e63eSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1266d91c1a17Sdrh                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
12672938f924Sdrh         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
1268f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
126966a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
12709cfcf5d4Sdrh         break;
12719cfcf5d4Sdrh       }
12729cfcf5d4Sdrh       case OE_Ignore: {
12735053a79bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
12749cfcf5d4Sdrh         break;
12759cfcf5d4Sdrh       }
1276098d1684Sdrh       default: {
1277098d1684Sdrh         assert( onError==OE_Replace );
12785053a79bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
127904adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
12805053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
12819cfcf5d4Sdrh         break;
12829cfcf5d4Sdrh       }
12839cfcf5d4Sdrh     }
12849cfcf5d4Sdrh   }
12859cfcf5d4Sdrh 
12869cfcf5d4Sdrh   /* Test all CHECK constraints
12879cfcf5d4Sdrh   */
1288ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
12892938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
12902938f924Sdrh     ExprList *pCheck = pTab->pCheck;
1291aa9b8963Sdrh     pParse->ckBase = regData;
1292aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
12932938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
12942938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
12952d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
12962e06c67cSdrh       if( onError==OE_Ignore ){
129766a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1298aa01c7e2Sdrh       }else{
12992938f924Sdrh         char *zConsName = pCheck->a[i].zName;
13006dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
13012938f924Sdrh         if( zConsName ){
13022938f924Sdrh           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
13032938f924Sdrh         }else{
1304f68686aeSdrh           zConsName = 0;
13052938f924Sdrh         }
1306d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1307d91c1a17Sdrh                               onError, zConsName, P4_DYNAMIC);
1308aa01c7e2Sdrh       }
1309ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1310c31c7c1cSdrh     }
13112938f924Sdrh   }
1312ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13139cfcf5d4Sdrh 
13140bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
13150bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
13160bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
13179cfcf5d4Sdrh   */
1318f0863fe5Sdrh   if( rowidChng ){
13190ca3e24bSdrh     onError = pTab->keyConf;
13200ca3e24bSdrh     if( overrideError!=OE_Default ){
13210ca3e24bSdrh       onError = overrideError;
1322a996e477Sdrh     }else if( onError==OE_Default ){
1323a996e477Sdrh       onError = OE_Abort;
13240ca3e24bSdrh     }
1325a0217ba7Sdrh 
132679b0c956Sdrh     if( isUpdate ){
132776d462eeSdan       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
132879b0c956Sdrh     }
132904adf416Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
13300ca3e24bSdrh     switch( onError ){
1331a0217ba7Sdrh       default: {
1332a0217ba7Sdrh         onError = OE_Abort;
1333a0217ba7Sdrh         /* Fall thru into the next case */
1334a0217ba7Sdrh       }
13351c92853dSdrh       case OE_Rollback:
13361c92853dSdrh       case OE_Abort:
13371c92853dSdrh       case OE_Fail: {
1338d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1339d91c1a17Sdrh            onError, "PRIMARY KEY must be unique", P4_STATIC);
13400ca3e24bSdrh         break;
13410ca3e24bSdrh       }
13425383ae5cSdrh       case OE_Replace: {
13432283d46cSdan         /* If there are DELETE triggers on this table and the
13442283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1345d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13462283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13472283d46cSdan         **
13482283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1349da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1350da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1351da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1352da730f6eSdan         ** when it is inserted.
1353da730f6eSdan         **
1354da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1355da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1356da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1357da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1358da730f6eSdan         ** but being more selective here allows statements like:
1359da730f6eSdan         **
1360da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1361da730f6eSdan         **
1362da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1363da730f6eSdan         ** table.
1364da730f6eSdan         */
13652283d46cSdan         Trigger *pTrigger = 0;
13662938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
13672283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
13682283d46cSdan         }
1369e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1370da730f6eSdan           sqlite3MultiWrite(pParse);
13712283d46cSdan           sqlite3GenerateRowDelete(
13722283d46cSdan               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
13732283d46cSdan           );
1374da730f6eSdan         }else if( pTab->pIndex ){
1375da730f6eSdan           sqlite3MultiWrite(pParse);
13762d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
13772283d46cSdan         }
13785383ae5cSdrh         seenReplace = 1;
13795383ae5cSdrh         break;
13805383ae5cSdrh       }
13810ca3e24bSdrh       case OE_Ignore: {
13825383ae5cSdrh         assert( seenReplace==0 );
138366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13840ca3e24bSdrh         break;
13850ca3e24bSdrh       }
13860ca3e24bSdrh     }
1387aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j3);
1388f5905aa7Sdrh     if( isUpdate ){
1389aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j2);
1390a05a722fSdrh     }
13910ca3e24bSdrh   }
13920bd1f4eaSdrh 
13930bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
13940bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
13950bd1f4eaSdrh   ** Add the new records to the indices as we go.
13960bd1f4eaSdrh   */
1397b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
13982d401ab8Sdrh     int regIdx;
13992d401ab8Sdrh     int regR;
1400b2b9d3d7Sdrh     int addrSkipRow = 0;
14012184fc75Sdrh 
1402aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1403b2fe7d8cSdrh 
1404b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1405b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
1406b2b9d3d7Sdrh       addrSkipRow = sqlite3VdbeMakeLabel(v);
1407b2b9d3d7Sdrh       pParse->ckBase = regData;
1408b2b9d3d7Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
1409b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1410b2b9d3d7Sdrh       pParse->ckBase = 0;
1411b2b9d3d7Sdrh     }
1412b2b9d3d7Sdrh 
1413b2fe7d8cSdrh     /* Create a key for accessing the index entry */
1414bbbdc83bSdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nKeyCol+1);
14159cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
1416bbbdc83bSdrh       i16 idx = pIdx->aiColumn[i];
1417bbbdc83bSdrh       if( idx<0 || idx==pTab->iPKey ){
14182d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
14199cfcf5d4Sdrh       }else{
14202d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
14219cfcf5d4Sdrh       }
14229cfcf5d4Sdrh     }
1423bbbdc83bSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[iCur]);
14248d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
1425bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1426b2fe7d8cSdrh 
1427b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
14289cfcf5d4Sdrh     onError = pIdx->onError;
1429de630353Sdanielk1977     if( onError==OE_None ){
1430bbbdc83bSdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
14318a9789b6Sdrh       sqlite3VdbeResolveLabel(v, addrSkipRow);
1432de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1433de630353Sdanielk1977     }
14349cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14359cfcf5d4Sdrh       onError = overrideError;
1436a996e477Sdrh     }else if( onError==OE_Default ){
1437a996e477Sdrh       onError = OE_Abort;
14389cfcf5d4Sdrh     }
14395383ae5cSdrh     if( seenReplace ){
14405383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
14415383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
14425383ae5cSdrh     }
14435383ae5cSdrh 
1444b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
14452d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
144665a7cd16Sdan     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
14472d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1448de630353Sdanielk1977                            regR, SQLITE_INT_TO_PTR(regIdx),
1449a9e852b6Smlcreech                            P4_INT32);
1450bbbdc83bSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
1451b2fe7d8cSdrh 
1452b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1453b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1454b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
14559cfcf5d4Sdrh     switch( onError ){
14561c92853dSdrh       case OE_Rollback:
14571c92853dSdrh       case OE_Abort:
14581c92853dSdrh       case OE_Fail: {
1459098d1684Sdrh         int j;
1460098d1684Sdrh         StrAccum errMsg;
1461098d1684Sdrh         const char *zSep;
1462098d1684Sdrh         char *zErr;
1463098d1684Sdrh 
1464098d1684Sdrh         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
14652938f924Sdrh         errMsg.db = db;
1466bbbdc83bSdrh         zSep = pIdx->nKeyCol>1 ? "columns " : "column ";
1467bbbdc83bSdrh         for(j=0; j<pIdx->nKeyCol; j++){
146837ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1469098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zSep, -1);
1470098d1684Sdrh           zSep = ", ";
1471098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zCol, -1);
147237ed48edSdrh         }
1473098d1684Sdrh         sqlite3StrAccumAppend(&errMsg,
1474bbbdc83bSdrh             pIdx->nKeyCol>1 ? " are not unique" : " is not unique", -1);
1475098d1684Sdrh         zErr = sqlite3StrAccumFinish(&errMsg);
1476d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
1477d91c1a17Sdrh                               onError, zErr, 0);
1478098d1684Sdrh         sqlite3DbFree(errMsg.db, zErr);
14799cfcf5d4Sdrh         break;
14809cfcf5d4Sdrh       }
14819cfcf5d4Sdrh       case OE_Ignore: {
14820ca3e24bSdrh         assert( seenReplace==0 );
148366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14849cfcf5d4Sdrh         break;
14859cfcf5d4Sdrh       }
1486098d1684Sdrh       default: {
14872283d46cSdan         Trigger *pTrigger = 0;
1488098d1684Sdrh         assert( onError==OE_Replace );
14891bea559aSdan         sqlite3MultiWrite(pParse);
14902938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14912283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14922283d46cSdan         }
14932283d46cSdan         sqlite3GenerateRowDelete(
14942283d46cSdan             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
14952283d46cSdan         );
14960ca3e24bSdrh         seenReplace = 1;
14979cfcf5d4Sdrh         break;
14989cfcf5d4Sdrh       }
14999cfcf5d4Sdrh     }
15002d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
1501b2b9d3d7Sdrh     sqlite3VdbeResolveLabel(v, addrSkipRow);
15022d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
15039cfcf5d4Sdrh   }
1504de630353Sdanielk1977 
1505de630353Sdanielk1977   if( pbMayReplace ){
1506de630353Sdanielk1977     *pbMayReplace = seenReplace;
1507de630353Sdanielk1977   }
15089cfcf5d4Sdrh }
15090ca3e24bSdrh 
15100ca3e24bSdrh /*
15110ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
15124adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
151304adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
151404adf416Sdrh ** rowid and the content to be inserted.
15150ca3e24bSdrh **
1516b419a926Sdrh ** The arguments to this routine should be the same as the first six
15174adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
15180ca3e24bSdrh */
15194adee20fSdanielk1977 void sqlite3CompleteInsertion(
15200ca3e24bSdrh   Parse *pParse,      /* The parser context */
15210ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
152204adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
152304adf416Sdrh   int regRowid,       /* Range of content */
1524aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
152570ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1526de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1527de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
15280ca3e24bSdrh ){
15290ca3e24bSdrh   int i;
15300ca3e24bSdrh   Vdbe *v;
15310ca3e24bSdrh   Index *pIdx;
15321bd10f8aSdrh   u8 pik_flags;
153304adf416Sdrh   int regData;
1534b7654111Sdrh   int regRec;
15350ca3e24bSdrh 
15364adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
15370ca3e24bSdrh   assert( v!=0 );
1538417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1539b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1540aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1541b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1542b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1543b2b9d3d7Sdrh     }
154404adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1545de630353Sdanielk1977     if( useSeekResult ){
1546de630353Sdanielk1977       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1547de630353Sdanielk1977     }
15480ca3e24bSdrh   }
1549ec95c441Sdrh   if( !HasRowid(pTab) ) return;
155004adf416Sdrh   regData = regRowid + 1;
1551b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
15521db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1553a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1554da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
15554794f735Sdrh   if( pParse->nested ){
15564794f735Sdrh     pik_flags = 0;
15574794f735Sdrh   }else{
155894eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
155994eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
15604794f735Sdrh   }
1561e4d90813Sdrh   if( appendBias ){
1562e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1563e4d90813Sdrh   }
1564de630353Sdanielk1977   if( useSeekResult ){
1565de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1566de630353Sdanielk1977   }
1567b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
156894eb6a14Sdanielk1977   if( !pParse->nested ){
15698d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
157094eb6a14Sdanielk1977   }
1571b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
15720ca3e24bSdrh }
1573cd44690aSdrh 
1574cd44690aSdrh /*
1575290c1948Sdrh ** Generate code that will open cursors for a table and for all
157604adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1577cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1578aa9b8963Sdrh **
1579aa9b8963Sdrh ** Return the number of indices on the table.
1580cd44690aSdrh */
1581aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1582290c1948Sdrh   Parse *pParse,   /* Parsing context */
1583290c1948Sdrh   Table *pTab,     /* Table to be opened */
158404adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1585290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1586290c1948Sdrh ){
1587cd44690aSdrh   int i;
15884cbdda9eSdrh   int iDb;
1589cd44690aSdrh   Index *pIdx;
15904cbdda9eSdrh   Vdbe *v;
15914cbdda9eSdrh 
1592aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
15934cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
15944cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1595cd44690aSdrh   assert( v!=0 );
159604adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1597cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1598b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1599da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
160004adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
160166a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1602207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1603cd44690aSdrh   }
16041b7ecbb4Sdrh   if( pParse->nTab<baseCur+i ){
160504adf416Sdrh     pParse->nTab = baseCur+i;
1606290c1948Sdrh   }
1607aa9b8963Sdrh   return i-1;
1608cd44690aSdrh }
16099d9cf229Sdrh 
161091c58e23Sdrh 
161191c58e23Sdrh #ifdef SQLITE_TEST
161291c58e23Sdrh /*
161391c58e23Sdrh ** The following global variable is incremented whenever the
161491c58e23Sdrh ** transfer optimization is used.  This is used for testing
161591c58e23Sdrh ** purposes only - to make sure the transfer optimization really
161691c58e23Sdrh ** is happening when it is suppose to.
161791c58e23Sdrh */
161891c58e23Sdrh int sqlite3_xferopt_count;
161991c58e23Sdrh #endif /* SQLITE_TEST */
162091c58e23Sdrh 
162191c58e23Sdrh 
16229d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
16239d9cf229Sdrh /*
16249d9cf229Sdrh ** Check to collation names to see if they are compatible.
16259d9cf229Sdrh */
16269d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
16279d9cf229Sdrh   if( z1==0 ){
16289d9cf229Sdrh     return z2==0;
16299d9cf229Sdrh   }
16309d9cf229Sdrh   if( z2==0 ){
16319d9cf229Sdrh     return 0;
16329d9cf229Sdrh   }
16339d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
16349d9cf229Sdrh }
16359d9cf229Sdrh 
16369d9cf229Sdrh 
16379d9cf229Sdrh /*
16389d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
16399d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
16409d9cf229Sdrh ** for a compatible index:
16419d9cf229Sdrh **
16429d9cf229Sdrh **    *   The index is over the same set of columns
16439d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
16449d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
16459d9cf229Sdrh **    *   The same collating sequence on each column
1646b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
16479d9cf229Sdrh */
16489d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
16499d9cf229Sdrh   int i;
16509d9cf229Sdrh   assert( pDest && pSrc );
16519d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1652bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
16539d9cf229Sdrh     return 0;   /* Different number of columns */
16549d9cf229Sdrh   }
16559d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
16569d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
16579d9cf229Sdrh   }
1658bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
16599d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
16609d9cf229Sdrh       return 0;   /* Different columns indexed */
16619d9cf229Sdrh     }
16629d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
16639d9cf229Sdrh       return 0;   /* Different sort orders */
16649d9cf229Sdrh     }
16653f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
166660a713c6Sdrh       return 0;   /* Different collating sequences */
16679d9cf229Sdrh     }
16689d9cf229Sdrh   }
1669619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1670b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1671b2b9d3d7Sdrh   }
16729d9cf229Sdrh 
16739d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
16749d9cf229Sdrh   return 1;
16759d9cf229Sdrh }
16769d9cf229Sdrh 
16779d9cf229Sdrh /*
16789d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
16799d9cf229Sdrh **
16809d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
16819d9cf229Sdrh **
1682ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1683ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1684ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
16859d9cf229Sdrh **
1686ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1687ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1688ccdf1baeSdrh ** embedded in the code for details.
16899d9cf229Sdrh **
1690ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1691ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1692ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1693ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1694ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1695ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1696ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1697ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1698ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
16999d9cf229Sdrh **
1700ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
17019d9cf229Sdrh */
17029d9cf229Sdrh static int xferOptimization(
17039d9cf229Sdrh   Parse *pParse,        /* Parser context */
17049d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
17059d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
17069d9cf229Sdrh   int onError,          /* How to handle constraint errors */
17079d9cf229Sdrh   int iDbDest           /* The database of pDest */
17089d9cf229Sdrh ){
17099d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
17109d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
17119d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
17129d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
17139d9cf229Sdrh   int i;                           /* Loop counter */
17149d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
17159d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
17169d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
17179d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
17189d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
17199d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
17209d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
17216a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1722f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1723b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
17249d9cf229Sdrh 
17259d9cf229Sdrh   if( pSelect==0 ){
17269d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
17279d9cf229Sdrh   }
17282f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
17299d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
17309d9cf229Sdrh   }
17319d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17327d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
17339d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
17349d9cf229Sdrh   }
17359d9cf229Sdrh #endif
17369d9cf229Sdrh   if( onError==OE_Default ){
1737e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1738e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
17399d9cf229Sdrh   }
17405ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
17419d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
17429d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
17439d9cf229Sdrh   }
17449d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
17459d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
17469d9cf229Sdrh   }
17479d9cf229Sdrh   if( pSelect->pWhere ){
17489d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
17499d9cf229Sdrh   }
17509d9cf229Sdrh   if( pSelect->pOrderBy ){
17519d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
17529d9cf229Sdrh   }
17538103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
17548103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
17559d9cf229Sdrh   if( pSelect->pGroupBy ){
17569d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
17579d9cf229Sdrh   }
17589d9cf229Sdrh   if( pSelect->pLimit ){
17599d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
17609d9cf229Sdrh   }
17618103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
17629d9cf229Sdrh   if( pSelect->pPrior ){
17639d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
17649d9cf229Sdrh   }
17657d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
17669d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
17679d9cf229Sdrh   }
17689d9cf229Sdrh   pEList = pSelect->pEList;
17699d9cf229Sdrh   assert( pEList!=0 );
17709d9cf229Sdrh   if( pEList->nExpr!=1 ){
17719d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
17729d9cf229Sdrh   }
17739d9cf229Sdrh   assert( pEList->a[0].pExpr );
17749d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
17759d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
17769d9cf229Sdrh   }
17779d9cf229Sdrh 
17789d9cf229Sdrh   /* At this point we have established that the statement is of the
17799d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
17809d9cf229Sdrh   ** we have to check the semantics.
17819d9cf229Sdrh   */
17829d9cf229Sdrh   pItem = pSelect->pSrc->a;
178341fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
17849d9cf229Sdrh   if( pSrc==0 ){
17859d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
17869d9cf229Sdrh   }
17879d9cf229Sdrh   if( pSrc==pDest ){
17889d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
17899d9cf229Sdrh   }
179055548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
179155548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
179255548273Sdrh   }
17939d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17947d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
17959d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
17969d9cf229Sdrh   }
17979d9cf229Sdrh #endif
17989d9cf229Sdrh   if( pSrc->pSelect ){
17999d9cf229Sdrh     return 0;   /* tab2 may not be a view */
18009d9cf229Sdrh   }
18019d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
18029d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
18039d9cf229Sdrh   }
18049d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
18059d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
18069d9cf229Sdrh   }
180755548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
180855548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
180955548273Sdrh   }
18109d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
18119d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
18129d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
18139d9cf229Sdrh     }
18149d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
18159d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
18169d9cf229Sdrh     }
18179d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
18189d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
18199d9cf229Sdrh     }
18209d9cf229Sdrh   }
18219d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1822f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1823f33c9fadSdrh       destHasUniqueIdx = 1;
1824f33c9fadSdrh     }
18259d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
18269d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18279d9cf229Sdrh     }
18289d9cf229Sdrh     if( pSrcIdx==0 ){
18299d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
18309d9cf229Sdrh     }
18319d9cf229Sdrh   }
18327fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1833619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
18348103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
18358103b7d2Sdrh   }
18367fc2f41bSdrh #endif
1837713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1838713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1839713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1840713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1841713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1842713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1843713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1844713de341Sdrh   */
1845713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1846713de341Sdrh     return 0;
1847713de341Sdrh   }
1848713de341Sdrh #endif
18491696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1850ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
18511696124dSdan   }
18529d9cf229Sdrh 
1853ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1854ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1855ccdf1baeSdrh   ** table (tab1) is initially empty.
18569d9cf229Sdrh   */
1857dd73521bSdrh #ifdef SQLITE_TEST
1858dd73521bSdrh   sqlite3_xferopt_count++;
1859dd73521bSdrh #endif
18609d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
18619d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1862f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
18639d9cf229Sdrh   iSrc = pParse->nTab++;
18649d9cf229Sdrh   iDest = pParse->nTab++;
18656a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
186655548273Sdrh   regData = sqlite3GetTempReg(pParse);
186755548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
186855548273Sdrh   if( HasRowid(pSrc) ){
18699d9cf229Sdrh     sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1870ccdf1baeSdrh     if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1871ccdf1baeSdrh      || destHasUniqueIdx                              /* (2) */
1872ccdf1baeSdrh      || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1873ccdf1baeSdrh     ){
1874ccdf1baeSdrh       /* In some circumstances, we are able to run the xfer optimization
1875ccdf1baeSdrh       ** only if the destination table is initially empty.  This code makes
1876ccdf1baeSdrh       ** that determination.  Conditions under which the destination must
1877ccdf1baeSdrh       ** be empty:
1878f33c9fadSdrh       **
1879ccdf1baeSdrh       ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1880ccdf1baeSdrh       **     (If the destination is not initially empty, the rowid fields
1881ccdf1baeSdrh       **     of index entries might need to change.)
1882ccdf1baeSdrh       **
1883ccdf1baeSdrh       ** (2) The destination has a unique index.  (The xfer optimization
1884ccdf1baeSdrh       **     is unable to test uniqueness.)
1885ccdf1baeSdrh       **
1886ccdf1baeSdrh       ** (3) onError is something other than OE_Abort and OE_Rollback.
18879d9cf229Sdrh       */
188866a5167bSdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
188966a5167bSdrh       emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
18909d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr1);
18919d9cf229Sdrh     }else{
18929d9cf229Sdrh       emptyDestTest = 0;
18939d9cf229Sdrh     }
18949d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
189566a5167bSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
189642242dedSdrh     if( pDest->iPKey>=0 ){
1897b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1898b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1899d91c1a17Sdrh       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1900d91c1a17Sdrh           onError, "PRIMARY KEY must be unique", P4_STATIC);
19019d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
1902b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
1903bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
1904b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
190595bad4c7Sdrh     }else{
1906b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
19077d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
190895bad4c7Sdrh     }
1909b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1910b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1911b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
19121f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
191366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
191455548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
191555548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
191655548273Sdrh   }
19179d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
19181b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
19199d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19209d9cf229Sdrh     }
19219d9cf229Sdrh     assert( pSrcIdx );
19229d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1923207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1924207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1925d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
19269d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1927207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
192866a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
192959885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
1930207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
193166a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1932b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1933b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
193466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
19359d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
193655548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
193755548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19389d9cf229Sdrh   }
19399d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1940b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1941b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
19429d9cf229Sdrh   if( emptyDestTest ){
194366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
19449d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
194566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19469d9cf229Sdrh     return 0;
19479d9cf229Sdrh   }else{
19489d9cf229Sdrh     return 1;
19499d9cf229Sdrh   }
19509d9cf229Sdrh }
19519d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1952