xref: /sqlite-3.40.0/src/insert.c (revision ea22abe3)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17cce7d176Sdrh /*
18dd9930efSdrh ** Generate code that will open table pTab for reading or writing
19dd9930efSdrh ** on cursor iCur.
20dd9930efSdrh **
21dd9930efSdrh ** Always acquire a table lock.  Always do the open for rowid tables.
22dd9930efSdrh ** For WITHOUT ROWID tables, only do read opens, and then open the
23dd9930efSdrh ** PRIMARY KEY index, not the main table, since the main table doesn't
24dd9930efSdrh ** exist.
25bbb5e4e0Sdrh */
26bbb5e4e0Sdrh void sqlite3OpenTable(
27bbb5e4e0Sdrh   Parse *p,       /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
35bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
37bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
38ec95c441Sdrh   if( HasRowid(pTab) ){
39261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
40dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
41dd9930efSdrh   }else if( opcode==OP_OpenRead ){
42dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
43dd9930efSdrh     assert( pPk!=0 );
44dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
45dd9930efSdrh     sqlite3VdbeAddOp4(v, opcode, iCur, pPk->tnum, iDb,
46dd9930efSdrh                       (char*)sqlite3IndexKeyinfo(p, pPk), P4_KEYINFO_HANDOFF);
47bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
48bbb5e4e0Sdrh   }
49ec95c441Sdrh }
50bbb5e4e0Sdrh 
51bbb5e4e0Sdrh /*
5269f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5369f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5469f8bb9cSdan ** the table, according to the affinity of the column:
553d1bfeaaSdanielk1977 **
563d1bfeaaSdanielk1977 **  Character      Column affinity
573d1bfeaaSdanielk1977 **  ------------------------------
583eda040bSdrh **  'a'            TEXT
593eda040bSdrh **  'b'            NONE
603eda040bSdrh **  'c'            NUMERIC
613eda040bSdrh **  'd'            INTEGER
623eda040bSdrh **  'e'            REAL
632d401ab8Sdrh **
640c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
652d401ab8Sdrh ** rowid that appears as the last column in every index.
6669f8bb9cSdan **
6769f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6869f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
6969f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
703d1bfeaaSdanielk1977 */
7169f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
72a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
73e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
74a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
75e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
76a37cdde0Sdanielk1977     **
77a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
78e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
79a37cdde0Sdanielk1977     ** up.
80a37cdde0Sdanielk1977     */
81a37cdde0Sdanielk1977     int n;
82a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
83abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
84ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
86633e6d57Sdrh       db->mallocFailed = 1;
8769f8bb9cSdan       return 0;
88a37cdde0Sdanielk1977     }
89ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
90ad124329Sdrh       i16 x = pIdx->aiColumn[n];
91ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
92a37cdde0Sdanielk1977     }
932d401ab8Sdrh     pIdx->zColAff[n] = 0;
94a37cdde0Sdanielk1977   }
953d1bfeaaSdanielk1977 
9669f8bb9cSdan   return pIdx->zColAff;
97a37cdde0Sdanielk1977 }
98a37cdde0Sdanielk1977 
99a37cdde0Sdanielk1977 /*
10066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
101a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
102a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
103a37cdde0Sdanielk1977 ** column:
104a37cdde0Sdanielk1977 **
105a37cdde0Sdanielk1977 **  Character      Column affinity
106a37cdde0Sdanielk1977 **  ------------------------------
1073eda040bSdrh **  'a'            TEXT
1083eda040bSdrh **  'b'            NONE
1093eda040bSdrh **  'c'            NUMERIC
1103eda040bSdrh **  'd'            INTEGER
1113eda040bSdrh **  'e'            REAL
112a37cdde0Sdanielk1977 */
113a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1143d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1153d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1163d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1173d1bfeaaSdanielk1977   **
1183d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1193d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1203d1bfeaaSdanielk1977   */
1213d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1223d1bfeaaSdanielk1977     char *zColAff;
1233d1bfeaaSdanielk1977     int i;
124abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1253d1bfeaaSdanielk1977 
126b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1273d1bfeaaSdanielk1977     if( !zColAff ){
128633e6d57Sdrh       db->mallocFailed = 1;
129a37cdde0Sdanielk1977       return;
1303d1bfeaaSdanielk1977     }
1313d1bfeaaSdanielk1977 
1323d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
133a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1343d1bfeaaSdanielk1977     }
1353d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1363d1bfeaaSdanielk1977 
1373d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1383d1bfeaaSdanielk1977   }
1393d1bfeaaSdanielk1977 
1408d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1413d1bfeaaSdanielk1977 }
1423d1bfeaaSdanielk1977 
1434d88778bSdanielk1977 /*
14448d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
14548d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
14648d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
14748d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
14848d1178aSdrh ** run without using temporary table for the results of the SELECT.
1494d88778bSdanielk1977 */
150595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
151595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1524d88778bSdanielk1977   int i;
15348d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
154595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
155595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
156595a523aSdanielk1977 #endif
157595a523aSdanielk1977 
15848d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
15948d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
160ef0bea92Sdrh     assert( pOp!=0 );
161207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16248d1178aSdrh       Index *pIndex;
163207872a4Sdanielk1977       int tnum = pOp->p2;
16448d1178aSdrh       if( tnum==pTab->tnum ){
16548d1178aSdrh         return 1;
16648d1178aSdrh       }
16748d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
16848d1178aSdrh         if( tnum==pIndex->tnum ){
16948d1178aSdrh           return 1;
17048d1178aSdrh         }
17148d1178aSdrh       }
17248d1178aSdrh     }
173543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
174595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1752dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
17666a5167bSdrh       assert( pOp->p4type==P4_VTAB );
17748d1178aSdrh       return 1;
1784d88778bSdanielk1977     }
179543165efSdrh #endif
1804d88778bSdanielk1977   }
1814d88778bSdanielk1977   return 0;
1824d88778bSdanielk1977 }
1833d1bfeaaSdanielk1977 
1849d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1859d9cf229Sdrh /*
1860b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1870b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1880b9f50d8Sdrh ** that holds the maximum rowid.
1899d9cf229Sdrh **
1900b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1910b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1920b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1930b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1940b9f50d8Sdrh ** AutoincInfo structure is used.
1959d9cf229Sdrh **
1960b9f50d8Sdrh ** Three memory locations are allocated:
1970b9f50d8Sdrh **
1980b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
1990b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2000b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2010b9f50d8Sdrh **
2020b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2030b9f50d8Sdrh ** insert routine needs to know about.
2049d9cf229Sdrh */
2059d9cf229Sdrh static int autoIncBegin(
2069d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2079d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2089d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2099d9cf229Sdrh ){
2106a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2117d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21265a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2130b9f50d8Sdrh     AutoincInfo *pInfo;
2140b9f50d8Sdrh 
21565a7cd16Sdan     pInfo = pToplevel->pAinc;
2160b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2170b9f50d8Sdrh     if( pInfo==0 ){
2180b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2190b9f50d8Sdrh       if( pInfo==0 ) return 0;
22065a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22165a7cd16Sdan       pToplevel->pAinc = pInfo;
2220b9f50d8Sdrh       pInfo->pTab = pTab;
2230b9f50d8Sdrh       pInfo->iDb = iDb;
22465a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
22565a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
22665a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2270b9f50d8Sdrh     }
2280b9f50d8Sdrh     memId = pInfo->regCtr;
2299d9cf229Sdrh   }
2309d9cf229Sdrh   return memId;
2319d9cf229Sdrh }
2329d9cf229Sdrh 
2339d9cf229Sdrh /*
2340b9f50d8Sdrh ** This routine generates code that will initialize all of the
2350b9f50d8Sdrh ** register used by the autoincrement tracker.
2360b9f50d8Sdrh */
2370b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2380b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2390b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2400b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2410b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2420b9f50d8Sdrh   int addr;                  /* A VDBE address */
2430b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2440b9f50d8Sdrh 
245345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
246345ba7dbSdrh   ** only called from the top-level */
247345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
248345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
24976d462eeSdan 
2500b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2510b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2520b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2530b9f50d8Sdrh     memId = p->regCtr;
2542120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2550b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
256f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2570b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2580b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2590b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2600b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2610b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2620b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2630b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2640b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2650b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2660b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2670b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2680b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2690b9f50d8Sdrh   }
2700b9f50d8Sdrh }
2710b9f50d8Sdrh 
2720b9f50d8Sdrh /*
2739d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2749d9cf229Sdrh **
2759d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2769d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2779d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2789d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2799d9cf229Sdrh */
2806a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2819d9cf229Sdrh   if( memId>0 ){
2826a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2839d9cf229Sdrh   }
2849d9cf229Sdrh }
2859d9cf229Sdrh 
2869d9cf229Sdrh /*
2870b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2880b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2890b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2900b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2910b9f50d8Sdrh ** routine just before the "exit" code.
2929d9cf229Sdrh */
2930b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2940b9f50d8Sdrh   AutoincInfo *p;
2959d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2960b9f50d8Sdrh   sqlite3 *db = pParse->db;
2976a288a33Sdrh 
2989d9cf229Sdrh   assert( v );
2990b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3000b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3010b9f50d8Sdrh     int j1, j2, j3, j4, j5;
3020b9f50d8Sdrh     int iRec;
3030b9f50d8Sdrh     int memId = p->regCtr;
3040b9f50d8Sdrh 
3050b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3062120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3070b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3086a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
3090b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
3100b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
3110b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3120b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3130b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3140b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3150b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3160b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3170b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3186a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3190b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
320a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3210b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
32235573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3230b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3240b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3259d9cf229Sdrh   }
3269d9cf229Sdrh }
3279d9cf229Sdrh #else
3289d9cf229Sdrh /*
3299d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3309d9cf229Sdrh ** above are all no-ops
3319d9cf229Sdrh */
3329d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
333287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3349d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3359d9cf229Sdrh 
3369d9cf229Sdrh 
3375f085269Sdrh /*
3385f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3395f085269Sdrh ** row at a time.
3405f085269Sdrh **
3415f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3425f085269Sdrh ** Information about the location of co-routine and the registers it will use
3435f085269Sdrh ** is returned by filling in the pDest object.
3445f085269Sdrh **
3455f085269Sdrh ** Registers are allocated as follows:
3465f085269Sdrh **
3475f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3485f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3495f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3505f085269Sdrh **
3515f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3525f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3535f085269Sdrh **                       generated a new result row, or 1 if the subquery
3545f085269Sdrh **                       has completed.  If the Yield is called again
3555f085269Sdrh **                       after this register becomes 1, then the VDBE will
3565f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3575f085269Sdrh **
3585f085269Sdrh **   pDest->iSdst        First result register.
3595f085269Sdrh **
3605f085269Sdrh **   pDest->nSdst        Number of result registers.
3615f085269Sdrh **
3625f085269Sdrh ** This routine handles all of the register allocation and fills in the
3635f085269Sdrh ** pDest structure appropriately.
3645f085269Sdrh **
3655f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3665f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3675f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3685f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3695f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3705f085269Sdrh **
3715f085269Sdrh **         X <- A
3725f085269Sdrh **         EOF <- 0
3735f085269Sdrh **         goto B
3745f085269Sdrh **      A: setup for the SELECT
3755f085269Sdrh **         loop rows in the SELECT
3765f085269Sdrh **           load results into registers R..S
3775f085269Sdrh **           yield X
3785f085269Sdrh **         end loop
3795f085269Sdrh **         cleanup after the SELECT
3805f085269Sdrh **         EOF <- 1
3815f085269Sdrh **         yield X
3825f085269Sdrh **         halt-error
3835f085269Sdrh **      B:
3845f085269Sdrh **
3855f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3865f085269Sdrh **
3875f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3885f085269Sdrh **      S: yield X
3895f085269Sdrh **         if EOF goto E
3905f085269Sdrh **         if skip this row, goto C
3915f085269Sdrh **         if terminate loop, goto E
3925f085269Sdrh **         deal with this row
3935f085269Sdrh **      C: goto S
3945f085269Sdrh **      E:
3955f085269Sdrh */
3965f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3975f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3985f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
3995f085269Sdrh   int addrTop;        /* Top of the co-routine */
4005f085269Sdrh   int j1;             /* Jump instruction */
4015f085269Sdrh   int rc;             /* Result code */
4025f085269Sdrh   Vdbe *v;            /* VDBE under construction */
4035f085269Sdrh 
4045f085269Sdrh   regYield = ++pParse->nMem;
4055f085269Sdrh   regEof = ++pParse->nMem;
4065f085269Sdrh   v = sqlite3GetVdbe(pParse);
4075f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
4085f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
4095f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
4105f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
4115f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4125f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4135f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4145f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4155f085269Sdrh   assert( pParse->nErr==0 || rc );
4165f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4175f085269Sdrh   if( rc ) return rc;
4185f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4195f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4205f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4215f085269Sdrh   VdbeComment((v, "End of coroutine"));
4225f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4235f085269Sdrh   return rc;
4245f085269Sdrh }
4255f085269Sdrh 
4265f085269Sdrh 
4275f085269Sdrh 
4289d9cf229Sdrh /* Forward declaration */
4299d9cf229Sdrh static int xferOptimization(
4309d9cf229Sdrh   Parse *pParse,        /* Parser context */
4319d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4329d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4339d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4349d9cf229Sdrh   int iDbDest           /* The database of pDest */
4359d9cf229Sdrh );
4369d9cf229Sdrh 
4373d1bfeaaSdanielk1977 /*
4381ccde15dSdrh ** This routine is call to handle SQL of the following forms:
439cce7d176Sdrh **
440cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4411ccde15dSdrh **    insert into TABLE (IDLIST) select
442cce7d176Sdrh **
4431ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4441ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
445967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4461ccde15dSdrh **
4471ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4481ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4491ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4501ccde15dSdrh ** data for the insert.
451142e30dfSdrh **
4529d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
453142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
454e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
455e00ee6ebSdrh ** the "1st template"):
456142e30dfSdrh **
457142e30dfSdrh **         open write cursor to <table> and its indices
458ec95c441Sdrh **         put VALUES clause expressions into registers
459142e30dfSdrh **         write the resulting record into <table>
460142e30dfSdrh **         cleanup
461142e30dfSdrh **
4629d9cf229Sdrh ** The three remaining templates assume the statement is of the form
463142e30dfSdrh **
464142e30dfSdrh **   INSERT INTO <table> SELECT ...
465142e30dfSdrh **
4669d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4679d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4689d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4699d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4709d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4719d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4729d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
473e00ee6ebSdrh ** template.  This is the 2nd template.
4749d9cf229Sdrh **
4759d9cf229Sdrh **         open a write cursor to <table>
4769d9cf229Sdrh **         open read cursor on <table2>
4779d9cf229Sdrh **         transfer all records in <table2> over to <table>
4789d9cf229Sdrh **         close cursors
4799d9cf229Sdrh **         foreach index on <table>
4809d9cf229Sdrh **           open a write cursor on the <table> index
4819d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4829d9cf229Sdrh **           transfer all records from the read to the write cursors
4839d9cf229Sdrh **           close cursors
4849d9cf229Sdrh **         end foreach
4859d9cf229Sdrh **
486e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4879d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4889d9cf229Sdrh ** The generated code follows this template:
489142e30dfSdrh **
490e00ee6ebSdrh **         EOF <- 0
491e00ee6ebSdrh **         X <- A
492142e30dfSdrh **         goto B
493142e30dfSdrh **      A: setup for the SELECT
4949d9cf229Sdrh **         loop over the rows in the SELECT
495e00ee6ebSdrh **           load values into registers R..R+n
496e00ee6ebSdrh **           yield X
497142e30dfSdrh **         end loop
498142e30dfSdrh **         cleanup after the SELECT
499e00ee6ebSdrh **         EOF <- 1
500e00ee6ebSdrh **         yield X
501142e30dfSdrh **         goto A
502e00ee6ebSdrh **      B: open write cursor to <table> and its indices
503e00ee6ebSdrh **      C: yield X
504e00ee6ebSdrh **         if EOF goto D
505e00ee6ebSdrh **         insert the select result into <table> from R..R+n
506e00ee6ebSdrh **         goto C
507142e30dfSdrh **      D: cleanup
508142e30dfSdrh **
509e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
510142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
511142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
512142e30dfSdrh ** we have to use a intermediate table to store the results of
513142e30dfSdrh ** the select.  The template is like this:
514142e30dfSdrh **
515e00ee6ebSdrh **         EOF <- 0
516e00ee6ebSdrh **         X <- A
517142e30dfSdrh **         goto B
518142e30dfSdrh **      A: setup for the SELECT
519142e30dfSdrh **         loop over the tables in the SELECT
520e00ee6ebSdrh **           load value into register R..R+n
521e00ee6ebSdrh **           yield X
522142e30dfSdrh **         end loop
523142e30dfSdrh **         cleanup after the SELECT
524e00ee6ebSdrh **         EOF <- 1
525e00ee6ebSdrh **         yield X
526e00ee6ebSdrh **         halt-error
527e00ee6ebSdrh **      B: open temp table
528e00ee6ebSdrh **      L: yield X
529e00ee6ebSdrh **         if EOF goto M
530e00ee6ebSdrh **         insert row from R..R+n into temp table
531e00ee6ebSdrh **         goto L
532e00ee6ebSdrh **      M: open write cursor to <table> and its indices
533e00ee6ebSdrh **         rewind temp table
534e00ee6ebSdrh **      C: loop over rows of intermediate table
535142e30dfSdrh **           transfer values form intermediate table into <table>
536e00ee6ebSdrh **         end loop
537e00ee6ebSdrh **      D: cleanup
538cce7d176Sdrh */
5394adee20fSdanielk1977 void sqlite3Insert(
540cce7d176Sdrh   Parse *pParse,        /* Parser context */
541113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
542cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5435974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5449cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5459cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
546cce7d176Sdrh ){
5476a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5486a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
549113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
550e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5515974a30fSdrh   int i, j, idx;        /* Loop counters */
5525974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5535974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
554967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5556a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
55604adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
5574a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5580ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5594d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
560cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
561e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
562e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
563e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5642eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5656a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5662958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
567e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
568ec95c441Sdrh   int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
569cce7d176Sdrh 
5706a288a33Sdrh   /* Register allocations */
5711bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5726a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5736a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5746a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5756a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5766a288a33Sdrh   int regData;          /* register holding first column to insert */
5771bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
578aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5796a288a33Sdrh 
580798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
581798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5822f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5832f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
584798da52cSdrh #endif
585c3f9bad2Sdanielk1977 
58617435752Sdrh   db = pParse->db;
5871bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
58817435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5896f7adc8aSdrh     goto insert_cleanup;
5906f7adc8aSdrh   }
591daffd0e5Sdrh 
5921ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5931ccde15dSdrh   */
594113088ecSdrh   assert( pTabList->nSrc==1 );
595113088ecSdrh   zTab = pTabList->a[0].zName;
596098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5974adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
598c3f9bad2Sdanielk1977   if( pTab==0 ){
599c3f9bad2Sdanielk1977     goto insert_cleanup;
600c3f9bad2Sdanielk1977   }
601da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
602da184236Sdanielk1977   assert( iDb<db->nDb );
603da184236Sdanielk1977   pDb = &db->aDb[iDb];
6042958a4e6Sdrh   zDb = pDb->zName;
6054adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
6061962bda7Sdrh     goto insert_cleanup;
6071962bda7Sdrh   }
608ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
609c3f9bad2Sdanielk1977 
610b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
611b7f9164eSdrh   ** inserted into is a view
612b7f9164eSdrh   */
613b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6142f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
615b7f9164eSdrh   isView = pTab->pSelect!=0;
616b7f9164eSdrh #else
6172f886d1dSdanielk1977 # define pTrigger 0
6182f886d1dSdanielk1977 # define tmask 0
619b7f9164eSdrh # define isView 0
620b7f9164eSdrh #endif
621b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
622b7f9164eSdrh # undef isView
623b7f9164eSdrh # define isView 0
624b7f9164eSdrh #endif
6252f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
626b7f9164eSdrh 
627f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
628b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
629b3d24bf8Sdanielk1977   ** module table).
630f573c99bSdrh   */
631b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
632f573c99bSdrh     goto insert_cleanup;
633f573c99bSdrh   }
634f573c99bSdrh 
635595a523aSdanielk1977   /* Ensure that:
636595a523aSdanielk1977   *  (a) the table is not read-only,
637595a523aSdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
638595a523aSdanielk1977   */
639595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
640595a523aSdanielk1977     goto insert_cleanup;
641595a523aSdanielk1977   }
642595a523aSdanielk1977 
6431ccde15dSdrh   /* Allocate a VDBE
6441ccde15dSdrh   */
6454adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6465974a30fSdrh   if( v==0 ) goto insert_cleanup;
6474794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6482f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6491ccde15dSdrh 
6509d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6519d9cf229Sdrh   /* If the statement is of the form
6529d9cf229Sdrh   **
6539d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6549d9cf229Sdrh   **
6559d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6569d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
657e00ee6ebSdrh   **
658e00ee6ebSdrh   ** This is the 2nd template.
6599d9cf229Sdrh   */
6609d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6612f886d1dSdanielk1977     assert( !pTrigger );
6629d9cf229Sdrh     assert( pList==0 );
6630b9f50d8Sdrh     goto insert_end;
6649d9cf229Sdrh   }
6659d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6669d9cf229Sdrh 
6672958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6686a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6692958a4e6Sdrh   */
6706a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6712958a4e6Sdrh 
6721ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
673e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
674e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
675e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6761ccde15dSdrh   */
6775974a30fSdrh   if( pSelect ){
6785f085269Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run that
6795f085269Sdrh     ** SELECT. */
6805f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6815f085269Sdrh     if( rc ) goto insert_cleanup;
6821013c932Sdrh 
6835f085269Sdrh     regEof = dest.iSDParm + 1;
6842b596da8Sdrh     regFromSelect = dest.iSdst;
6855974a30fSdrh     assert( pSelect->pEList );
686967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6872b596da8Sdrh     assert( dest.nSdst==nColumn );
688142e30dfSdrh 
689142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
690e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
691e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
692e00ee6ebSdrh     ** the destination table (template 3).
693048c530cSdrh     **
694048c530cSdrh     ** A temp table must be used if the table being updated is also one
695048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
696048c530cSdrh     ** temp table in the case of row triggers.
697142e30dfSdrh     */
698595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
699048c530cSdrh       useTempTable = 1;
700048c530cSdrh     }
701142e30dfSdrh 
702142e30dfSdrh     if( useTempTable ){
703e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
704e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
705e00ee6ebSdrh       ** here is from the 4th template:
706e00ee6ebSdrh       **
707e00ee6ebSdrh       **      B: open temp table
708e00ee6ebSdrh       **      L: yield X
709e00ee6ebSdrh       **         if EOF goto M
710e00ee6ebSdrh       **         insert row from R..R+n into temp table
711e00ee6ebSdrh       **         goto L
712e00ee6ebSdrh       **      M: ...
713142e30dfSdrh       */
714e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
715dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
716e00ee6ebSdrh       int addrTop;         /* Label "L" */
717e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
718b7654111Sdrh 
719142e30dfSdrh       srcTab = pParse->nTab++;
720b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
721dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
722e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7232b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
724e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7251db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
726dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
727dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
728e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
729e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
730b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
731dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
732142e30dfSdrh     }
733142e30dfSdrh   }else{
734142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
735142e30dfSdrh     ** clause
736142e30dfSdrh     */
737b3bce662Sdanielk1977     NameContext sNC;
738b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
739b3bce662Sdanielk1977     sNC.pParse = pParse;
7405974a30fSdrh     srcTab = -1;
74148d1178aSdrh     assert( useTempTable==0 );
742147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
743e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7447d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
745b04a5d87Sdrh         goto insert_cleanup;
746b04a5d87Sdrh       }
747e64e7b20Sdrh     }
7485974a30fSdrh   }
7491ccde15dSdrh 
7501ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7511ccde15dSdrh   ** of columns to be inserted into the table.
7521ccde15dSdrh   */
753034ca14fSdanielk1977   if( IsVirtual(pTab) ){
754034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
755034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
756034ca14fSdanielk1977     }
757034ca14fSdanielk1977   }
758034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7594adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
760da93d238Sdrh        "table %S has %d columns but %d values were supplied",
761d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
762cce7d176Sdrh     goto insert_cleanup;
763cce7d176Sdrh   }
764967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7654adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
766cce7d176Sdrh     goto insert_cleanup;
767cce7d176Sdrh   }
7681ccde15dSdrh 
7691ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7701ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7711ccde15dSdrh   ** remember the column indices.
772c8392586Sdrh   **
773c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
774c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
775c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
776c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
777c8392586Sdrh   ** is appears in the original table.  (The index of the primary
778c8392586Sdrh   ** key in the original table is pTab->iPKey.)
7791ccde15dSdrh   */
780967e8b73Sdrh   if( pColumn ){
781967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
782967e8b73Sdrh       pColumn->a[i].idx = -1;
783cce7d176Sdrh     }
784967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
785cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7864adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
787967e8b73Sdrh           pColumn->a[i].idx = j;
7884a32431cSdrh           if( j==pTab->iPKey ){
789ec95c441Sdrh             keyColumn = i;  assert( !withoutRowid );
7904a32431cSdrh           }
791cce7d176Sdrh           break;
792cce7d176Sdrh         }
793cce7d176Sdrh       }
794cce7d176Sdrh       if( j>=pTab->nCol ){
795ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
796a0217ba7Sdrh           keyColumn = i;
797a0217ba7Sdrh         }else{
7984adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
799da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
8001db95106Sdan           pParse->checkSchema = 1;
801cce7d176Sdrh           goto insert_cleanup;
802cce7d176Sdrh         }
803cce7d176Sdrh       }
804cce7d176Sdrh     }
805a0217ba7Sdrh   }
8061ccde15dSdrh 
807aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
808c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
809c8392586Sdrh   ** in the original table definition.
8104a32431cSdrh   */
811147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
8124a32431cSdrh     keyColumn = pTab->iPKey;
8134a32431cSdrh   }
8144a32431cSdrh 
815c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8161ccde15dSdrh   */
817142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8186a288a33Sdrh     regRowCount = ++pParse->nMem;
8196a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
820c3f9bad2Sdanielk1977   }
821c3f9bad2Sdanielk1977 
822e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
823e448dc4aSdanielk1977   if( !isView ){
824aa9b8963Sdrh     int nIdx;
825aa9b8963Sdrh 
826ec95c441Sdrh     baseCur = pParse->nTab - withoutRowid;
827261c02d9Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, -1, OP_OpenWrite);
8285c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
829aa9b8963Sdrh     if( aRegIdx==0 ){
830aa9b8963Sdrh       goto insert_cleanup;
831aa9b8963Sdrh     }
832aa9b8963Sdrh     for(i=0; i<nIdx; i++){
833aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
834aa9b8963Sdrh     }
835feeb1394Sdrh   }
836feeb1394Sdrh 
837e00ee6ebSdrh   /* This is the top of the main insertion loop */
838142e30dfSdrh   if( useTempTable ){
839e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
840e00ee6ebSdrh     ** following pseudocode (template 4):
841e00ee6ebSdrh     **
842e00ee6ebSdrh     **         rewind temp table
843e00ee6ebSdrh     **      C: loop over rows of intermediate table
844e00ee6ebSdrh     **           transfer values form intermediate table into <table>
845e00ee6ebSdrh     **         end loop
846e00ee6ebSdrh     **      D: ...
847e00ee6ebSdrh     */
848e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
849e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
850142e30dfSdrh   }else if( pSelect ){
851e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
852e00ee6ebSdrh     ** following pseudocode (template 3):
853e00ee6ebSdrh     **
854e00ee6ebSdrh     **      C: yield X
855e00ee6ebSdrh     **         if EOF goto D
856e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
857e00ee6ebSdrh     **         goto C
858e00ee6ebSdrh     **      D: ...
859e00ee6ebSdrh     */
8602b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
861e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
862bed8690fSdrh   }
8631ccde15dSdrh 
8646a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8656a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8666a288a33Sdrh   */
8676a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8686a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8696a288a33Sdrh   if( IsVirtual(pTab) ){
8706a288a33Sdrh     regRowid++;
8716a288a33Sdrh     pParse->nMem++;
8726a288a33Sdrh   }
8736a288a33Sdrh   regData = regRowid+1;
8746a288a33Sdrh 
8755cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
87670ce3f0cSdrh   */
8774adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8782f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
87976d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
880c3f9bad2Sdanielk1977 
88170ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
88270ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
88370ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
88470ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
88570ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
88670ce3f0cSdrh     */
88770ce3f0cSdrh     if( keyColumn<0 ){
88876d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88970ce3f0cSdrh     }else{
8906a288a33Sdrh       int j1;
891ec95c441Sdrh       assert( !withoutRowid );
8927fe45908Sdrh       if( useTempTable ){
89376d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
8947fe45908Sdrh       }else{
895d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89676d462eeSdan         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
8977fe45908Sdrh       }
89876d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89976d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
9006a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
90176d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
90270ce3f0cSdrh     }
90370ce3f0cSdrh 
904034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
905034ca14fSdanielk1977     ** this block would have to account for hidden column.
906034ca14fSdanielk1977     */
907034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
908034ca14fSdanielk1977 
90970ce3f0cSdrh     /* Create the new column data
91070ce3f0cSdrh     */
911c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
912c3f9bad2Sdanielk1977       if( pColumn==0 ){
913c3f9bad2Sdanielk1977         j = i;
914c3f9bad2Sdanielk1977       }else{
915c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
916c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
917c3f9bad2Sdanielk1977         }
918c3f9bad2Sdanielk1977       }
9197ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
92076d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
921142e30dfSdrh       }else if( useTempTable ){
92276d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
923c3f9bad2Sdanielk1977       }else{
924d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
92576d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
926c3f9bad2Sdanielk1977       }
927c3f9bad2Sdanielk1977     }
928a37cdde0Sdanielk1977 
929a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
930a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
931a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
932a37cdde0Sdanielk1977     ** table column affinities.
933a37cdde0Sdanielk1977     */
934a37cdde0Sdanielk1977     if( !isView ){
93576d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
936a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
937a37cdde0Sdanielk1977     }
938c3f9bad2Sdanielk1977 
9395cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
940165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
94194d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
942165921a7Sdan 
94376d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
94470ce3f0cSdrh   }
945c3f9bad2Sdanielk1977 
9464a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
947f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
9484a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
949b419a926Sdrh   ** case the record number is the same as that column.
9501ccde15dSdrh   */
9515cf590c1Sdrh   if( !isView ){
9524cbdda9eSdrh     if( IsVirtual(pTab) ){
9534cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9546a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9554cbdda9eSdrh     }
9564a32431cSdrh     if( keyColumn>=0 ){
957142e30dfSdrh       if( useTempTable ){
9586a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
959142e30dfSdrh       }else if( pSelect ){
960b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
9614a32431cSdrh       }else{
962e4d90813Sdrh         VdbeOp *pOp;
9631db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
96420411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9651b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
966e4d90813Sdrh           appendFlag = 1;
967e4d90813Sdrh           pOp->opcode = OP_NewRowid;
96804adf416Sdrh           pOp->p1 = baseCur;
9696a288a33Sdrh           pOp->p2 = regRowid;
9706a288a33Sdrh           pOp->p3 = regAutoinc;
971e4d90813Sdrh         }
97227a32783Sdrh       }
973f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
974e1e68f49Sdrh       ** to generate a unique primary key value.
975e1e68f49Sdrh       */
976e4d90813Sdrh       if( !appendFlag ){
9771db639ceSdrh         int j1;
978bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9791db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
98004adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
9811db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
982bb50e7adSdanielk1977         }else{
983bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
984bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
985bb50e7adSdanielk1977         }
9863c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
987e4d90813Sdrh       }
988ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9896a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9904a32431cSdrh     }else{
99104adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
992e4d90813Sdrh       appendFlag = 1;
9934a32431cSdrh     }
9946a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9954a32431cSdrh 
996aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
9974a32431cSdrh     ** with the first column.
9984a32431cSdrh     */
999034ca14fSdanielk1977     nHidden = 0;
1000cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
10016a288a33Sdrh       int iRegStore = regRowid+1+i;
10024a32431cSdrh       if( i==pTab->iPKey ){
10034a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
1004aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
1005aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
1006aacc543eSdrh         ** taking up data space with information that will never be used. */
10074c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
10084a32431cSdrh         continue;
10094a32431cSdrh       }
1010967e8b73Sdrh       if( pColumn==0 ){
1011034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1012034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1013034ca14fSdanielk1977           j = -1;
1014034ca14fSdanielk1977           nHidden++;
1015034ca14fSdanielk1977         }else{
1016034ca14fSdanielk1977           j = i - nHidden;
1017034ca14fSdanielk1977         }
1018cce7d176Sdrh       }else{
1019967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1020967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1021cce7d176Sdrh         }
1022cce7d176Sdrh       }
1023034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1024287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1025142e30dfSdrh       }else if( useTempTable ){
1026287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1027142e30dfSdrh       }else if( pSelect ){
1028b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1029cce7d176Sdrh       }else{
1030287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1031cce7d176Sdrh       }
1032cce7d176Sdrh     }
10331ccde15dSdrh 
10340ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10350ca3e24bSdrh     ** do the insertion.
10364a32431cSdrh     */
10374cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10384cbdda9eSdrh     if( IsVirtual(pTab) ){
1039595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10404f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1041595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1042b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1043e0af83acSdan       sqlite3MayAbort(pParse);
10444cbdda9eSdrh     }else
10454cbdda9eSdrh #endif
10464cbdda9eSdrh     {
1047de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1048de630353Sdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
1049de630353Sdanielk1977           keyColumn>=0, 0, onError, endOfLoop, &isReplace
105004adf416Sdrh       );
10518ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
105204adf416Sdrh       sqlite3CompleteInsertion(
10532832ad42Sdan           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
105404adf416Sdrh       );
10555cf590c1Sdrh     }
10564cbdda9eSdrh   }
10571bee3d7bSdrh 
1058feeb1394Sdrh   /* Update the count of rows that are inserted
10591bee3d7bSdrh   */
1060142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10616a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10621bee3d7bSdrh   }
1063c3f9bad2Sdanielk1977 
10642f886d1dSdanielk1977   if( pTrigger ){
1065c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1066165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
106794d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1068c3f9bad2Sdanielk1977   }
10691bee3d7bSdrh 
1070e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1071e00ee6ebSdrh   ** is a SELECT statement.
10721ccde15dSdrh   */
10734adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1074142e30dfSdrh   if( useTempTable ){
1075e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1076e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10772eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1078142e30dfSdrh   }else if( pSelect ){
1079e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1080e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10816b56344dSdrh   }
1082c3f9bad2Sdanielk1977 
1083e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1084c3f9bad2Sdanielk1977     /* Close all tables opened */
1085ec95c441Sdrh     if( !withoutRowid ) sqlite3VdbeAddOp1(v, OP_Close, baseCur);
10866b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
10872eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
1088cce7d176Sdrh     }
1089c3f9bad2Sdanielk1977   }
1090c3f9bad2Sdanielk1977 
10910b9f50d8Sdrh insert_end:
1092f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10930b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10940b9f50d8Sdrh   ** autoincrement tables.
10952958a4e6Sdrh   */
1096165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10970b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10980b9f50d8Sdrh   }
10992958a4e6Sdrh 
11001bee3d7bSdrh   /*
1101e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1102e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1103e7de6f25Sdanielk1977   ** invoke the callback function.
11041bee3d7bSdrh   */
1105165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
11066a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110722322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
110810fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11091bee3d7bSdrh   }
1110cce7d176Sdrh 
1111cce7d176Sdrh insert_cleanup:
1112633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1113633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1114633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1115633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1116633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1117cce7d176Sdrh }
11189cfcf5d4Sdrh 
111975cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
112075cbd984Sdan ** thely may interfere with compilation of other functions in this file
112175cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
112275cbd984Sdan #ifdef isView
112375cbd984Sdan  #undef isView
112475cbd984Sdan #endif
112575cbd984Sdan #ifdef pTrigger
112675cbd984Sdan  #undef pTrigger
112775cbd984Sdan #endif
112875cbd984Sdan #ifdef tmask
112975cbd984Sdan  #undef tmask
113075cbd984Sdan #endif
113175cbd984Sdan 
113275cbd984Sdan 
11339cfcf5d4Sdrh /*
11346a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
11359cfcf5d4Sdrh **
113604adf416Sdrh ** The input is a range of consecutive registers as follows:
11370ca3e24bSdrh **
113865a7cd16Sdan **    1.  The rowid of the row after the update.
11390ca3e24bSdrh **
114065a7cd16Sdan **    2.  The data in the first column of the entry after the update.
11410ca3e24bSdrh **
11420ca3e24bSdrh **    i.  Data from middle columns...
11430ca3e24bSdrh **
11440ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
11450ca3e24bSdrh **
114665a7cd16Sdan ** The regRowid parameter is the index of the register containing (1).
114704adf416Sdrh **
1148*ea22abe3Sdrh ** If isUpdate is true and pkChng is non-zero, then pkChng contains
114965a7cd16Sdan ** the address of a register containing the rowid before the update takes
115065a7cd16Sdan ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
1151*ea22abe3Sdrh ** is false, indicating an INSERT statement, then a non-zero pkChng
115265a7cd16Sdan ** indicates that the rowid was explicitly specified as part of the
1153*ea22abe3Sdrh ** INSERT statement. If pkChng is false, it means that  the rowid is
115465a7cd16Sdan ** computed automatically in an insert or that the rowid value is not
115565a7cd16Sdan ** modified by an update.
11560ca3e24bSdrh **
1157*ea22abe3Sdrh ** The code generated by this routine should store new index entries into
1158aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1159aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1160aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1161aa9b8963Sdrh ** attached to the table.
11629cfcf5d4Sdrh **
11639cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11649cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11651c92853dSdrh ** then the appropriate action is performed.  There are five possible
11661c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11679cfcf5d4Sdrh **
11689cfcf5d4Sdrh **  Constraint type  Action       What Happens
11699cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11701c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
117124b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
11729cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11739cfcf5d4Sdrh **
11741c92853dSdrh **  any              ABORT        Back out changes from the current command
11751c92853dSdrh **                                only (do not do a complete rollback) then
117624b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
11771c92853dSdrh **                                with SQLITE_CONSTRAINT.
11781c92853dSdrh **
1179e4c88c0cSdrh **  any              FAIL         Sqlite3_exec() returns immediately with a
11801c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11811c92853dSdrh **                                transaction is not rolled back and any
11821c92853dSdrh **                                prior changes are retained.
11831c92853dSdrh **
11849cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
11859cfcf5d4Sdrh **                                the stack and there is an immediate jump
11869cfcf5d4Sdrh **                                to label ignoreDest.
11879cfcf5d4Sdrh **
11889cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11899cfcf5d4Sdrh **                                value for that column.  If the default value
11909cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11919cfcf5d4Sdrh **
11929cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
11939cfcf5d4Sdrh **                                being inserted is removed.
11949cfcf5d4Sdrh **
11959cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
11969cfcf5d4Sdrh **
11971c92853dSdrh ** Which action to take is determined by the overrideError parameter.
11981c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
11991c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12001c92853dSdrh ** for the constraint is used.
12019cfcf5d4Sdrh **
1202aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
120304adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
120404adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
12059cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1206aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
12079cfcf5d4Sdrh */
12084adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12099cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
12109cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
1211*ea22abe3Sdrh   int baseCur,        /* A read/write cursor pointing at pTab */
1212*ea22abe3Sdrh   int regRowid,       /* First register in a range holding values to insert */
1213aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1214*ea22abe3Sdrh   int pkChng,         /* Non-zero if the PRIMARY KEY might collide */
1215b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
12169cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1217de630353Sdanielk1977   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
1218de630353Sdanielk1977   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
12199cfcf5d4Sdrh ){
12201b7ecbb4Sdrh   int i;              /* loop counter */
12211b7ecbb4Sdrh   Vdbe *v;            /* VDBE under constrution */
12221b7ecbb4Sdrh   int nCol;           /* Number of columns */
12231b7ecbb4Sdrh   int onError;        /* Conflict resolution strategy */
12241bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
12251bd10f8aSdrh   int j2 = 0, j3;     /* Addresses of jump instructions */
122604adf416Sdrh   int regData;        /* Register containing first data column */
12271b7ecbb4Sdrh   int iCur;           /* Table cursor number */
12281b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
12292938f924Sdrh   sqlite3 *db;         /* Database connection */
12301b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1231*ea22abe3Sdrh   int regOldRowid = (pkChng && isUpdate) ? pkChng : regRowid;
12329cfcf5d4Sdrh 
12332938f924Sdrh   db = pParse->db;
12344adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12359cfcf5d4Sdrh   assert( v!=0 );
1236417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12379cfcf5d4Sdrh   nCol = pTab->nCol;
1238aa9b8963Sdrh   regData = regRowid + 1;
1239aa9b8963Sdrh 
12409cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12419cfcf5d4Sdrh   */
12429cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12430ca3e24bSdrh     if( i==pTab->iPKey ){
12440ca3e24bSdrh       continue;
12450ca3e24bSdrh     }
12469cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12470ca3e24bSdrh     if( onError==OE_None ) continue;
12489cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12499cfcf5d4Sdrh       onError = overrideError;
1250a996e477Sdrh     }else if( onError==OE_Default ){
1251a996e477Sdrh       onError = OE_Abort;
12529cfcf5d4Sdrh     }
12537977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12549cfcf5d4Sdrh       onError = OE_Abort;
12559cfcf5d4Sdrh     }
1256b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1257b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12589cfcf5d4Sdrh     switch( onError ){
12591c92853dSdrh       case OE_Abort:
1260e0af83acSdan         sqlite3MayAbort(pParse);
1261e0af83acSdan       case OE_Rollback:
12621c92853dSdrh       case OE_Fail: {
1263f089aa45Sdrh         char *zMsg;
1264c126e63eSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1265d91c1a17Sdrh                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
12662938f924Sdrh         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
1267f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
126866a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
12699cfcf5d4Sdrh         break;
12709cfcf5d4Sdrh       }
12719cfcf5d4Sdrh       case OE_Ignore: {
12725053a79bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
12739cfcf5d4Sdrh         break;
12749cfcf5d4Sdrh       }
1275098d1684Sdrh       default: {
1276098d1684Sdrh         assert( onError==OE_Replace );
12775053a79bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
127804adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
12795053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
12809cfcf5d4Sdrh         break;
12819cfcf5d4Sdrh       }
12829cfcf5d4Sdrh     }
12839cfcf5d4Sdrh   }
12849cfcf5d4Sdrh 
12859cfcf5d4Sdrh   /* Test all CHECK constraints
12869cfcf5d4Sdrh   */
1287ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
12882938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
12892938f924Sdrh     ExprList *pCheck = pTab->pCheck;
1290aa9b8963Sdrh     pParse->ckBase = regData;
1291aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
12922938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
12932938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
12942d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
12952e06c67cSdrh       if( onError==OE_Ignore ){
129666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1297aa01c7e2Sdrh       }else{
12982938f924Sdrh         char *zConsName = pCheck->a[i].zName;
12996dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
13002938f924Sdrh         if( zConsName ){
13012938f924Sdrh           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
13022938f924Sdrh         }else{
1303f68686aeSdrh           zConsName = 0;
13042938f924Sdrh         }
1305d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1306d91c1a17Sdrh                               onError, zConsName, P4_DYNAMIC);
1307aa01c7e2Sdrh       }
1308ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1309c31c7c1cSdrh     }
13102938f924Sdrh   }
1311ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13129cfcf5d4Sdrh 
13130bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
13140bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
13150bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
13169cfcf5d4Sdrh   */
1317*ea22abe3Sdrh   if( pkChng ){
13180ca3e24bSdrh     onError = pTab->keyConf;
13190ca3e24bSdrh     if( overrideError!=OE_Default ){
13200ca3e24bSdrh       onError = overrideError;
1321a996e477Sdrh     }else if( onError==OE_Default ){
1322a996e477Sdrh       onError = OE_Abort;
13230ca3e24bSdrh     }
1324a0217ba7Sdrh 
132579b0c956Sdrh     if( isUpdate ){
1326*ea22abe3Sdrh       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, pkChng);
132779b0c956Sdrh     }
132804adf416Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
13290ca3e24bSdrh     switch( onError ){
1330a0217ba7Sdrh       default: {
1331a0217ba7Sdrh         onError = OE_Abort;
1332a0217ba7Sdrh         /* Fall thru into the next case */
1333a0217ba7Sdrh       }
13341c92853dSdrh       case OE_Rollback:
13351c92853dSdrh       case OE_Abort:
13361c92853dSdrh       case OE_Fail: {
1337d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1338d91c1a17Sdrh            onError, "PRIMARY KEY must be unique", P4_STATIC);
13390ca3e24bSdrh         break;
13400ca3e24bSdrh       }
13415383ae5cSdrh       case OE_Replace: {
13422283d46cSdan         /* If there are DELETE triggers on this table and the
13432283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1344d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13452283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13462283d46cSdan         **
13472283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1348da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1349da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1350da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1351da730f6eSdan         ** when it is inserted.
1352da730f6eSdan         **
1353da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1354da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1355da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1356da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1357da730f6eSdan         ** but being more selective here allows statements like:
1358da730f6eSdan         **
1359da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1360da730f6eSdan         **
1361da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1362da730f6eSdan         ** table.
1363da730f6eSdan         */
13642283d46cSdan         Trigger *pTrigger = 0;
13652938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
13662283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
13672283d46cSdan         }
1368e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1369da730f6eSdan           sqlite3MultiWrite(pParse);
13702283d46cSdan           sqlite3GenerateRowDelete(
1371ecb31b63Sdrh               pParse, pTab, pTrigger, baseCur, regRowid, 0, 0, OE_Replace
13722283d46cSdan           );
1373da730f6eSdan         }else if( pTab->pIndex ){
1374da730f6eSdan           sqlite3MultiWrite(pParse);
13752d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
13762283d46cSdan         }
13775383ae5cSdrh         seenReplace = 1;
13785383ae5cSdrh         break;
13795383ae5cSdrh       }
13800ca3e24bSdrh       case OE_Ignore: {
13815383ae5cSdrh         assert( seenReplace==0 );
138266a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13830ca3e24bSdrh         break;
13840ca3e24bSdrh       }
13850ca3e24bSdrh     }
1386aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j3);
1387f5905aa7Sdrh     if( isUpdate ){
1388aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j2);
1389a05a722fSdrh     }
13900ca3e24bSdrh   }
13910bd1f4eaSdrh 
13920bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
13930bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
13940bd1f4eaSdrh   ** Add the new records to the indices as we go.
13950bd1f4eaSdrh   */
1396b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
13972d401ab8Sdrh     int regIdx;
13982d401ab8Sdrh     int regR;
1399b2b9d3d7Sdrh     int addrSkipRow = 0;
14002184fc75Sdrh 
1401aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1402b2fe7d8cSdrh 
1403b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1404b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
1405b2b9d3d7Sdrh       addrSkipRow = sqlite3VdbeMakeLabel(v);
1406b2b9d3d7Sdrh       pParse->ckBase = regData;
1407b2b9d3d7Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
1408b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1409b2b9d3d7Sdrh       pParse->ckBase = 0;
1410b2b9d3d7Sdrh     }
1411b2b9d3d7Sdrh 
1412b2fe7d8cSdrh     /* Create a key for accessing the index entry */
1413261c02d9Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
14149cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
1415bbbdc83bSdrh       i16 idx = pIdx->aiColumn[i];
1416bbbdc83bSdrh       if( idx<0 || idx==pTab->iPKey ){
14172d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
14189cfcf5d4Sdrh       }else{
14192d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
14209cfcf5d4Sdrh       }
14219cfcf5d4Sdrh     }
1422bbbdc83bSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[iCur]);
14238d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
1424bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1425b2fe7d8cSdrh 
1426b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
14279cfcf5d4Sdrh     onError = pIdx->onError;
1428de630353Sdanielk1977     if( onError==OE_None ){
1429bbbdc83bSdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
14308a9789b6Sdrh       sqlite3VdbeResolveLabel(v, addrSkipRow);
1431de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1432de630353Sdanielk1977     }
14339cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14349cfcf5d4Sdrh       onError = overrideError;
1435a996e477Sdrh     }else if( onError==OE_Default ){
1436a996e477Sdrh       onError = OE_Abort;
14379cfcf5d4Sdrh     }
14385383ae5cSdrh     if( seenReplace ){
14395383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
14405383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
14415383ae5cSdrh     }
14425383ae5cSdrh 
1443b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
14442d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
144565a7cd16Sdan     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
1446261c02d9Sdrh     j3 = sqlite3VdbeAddOp4Int(v, OP_IsUnique, baseCur+iCur+1, 0, regR, regIdx);
1447bbbdc83bSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
1448b2fe7d8cSdrh 
1449b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1450b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1451b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
14529cfcf5d4Sdrh     switch( onError ){
14531c92853dSdrh       case OE_Rollback:
14541c92853dSdrh       case OE_Abort:
14551c92853dSdrh       case OE_Fail: {
1456098d1684Sdrh         int j;
1457098d1684Sdrh         StrAccum errMsg;
1458098d1684Sdrh         const char *zSep;
1459098d1684Sdrh         char *zErr;
1460098d1684Sdrh 
1461098d1684Sdrh         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
14622938f924Sdrh         errMsg.db = db;
1463bbbdc83bSdrh         zSep = pIdx->nKeyCol>1 ? "columns " : "column ";
1464bbbdc83bSdrh         for(j=0; j<pIdx->nKeyCol; j++){
146537ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1466098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zSep, -1);
1467098d1684Sdrh           zSep = ", ";
1468098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zCol, -1);
146937ed48edSdrh         }
1470098d1684Sdrh         sqlite3StrAccumAppend(&errMsg,
1471bbbdc83bSdrh             pIdx->nKeyCol>1 ? " are not unique" : " is not unique", -1);
1472098d1684Sdrh         zErr = sqlite3StrAccumFinish(&errMsg);
1473d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
1474d91c1a17Sdrh                               onError, zErr, 0);
1475098d1684Sdrh         sqlite3DbFree(errMsg.db, zErr);
14769cfcf5d4Sdrh         break;
14779cfcf5d4Sdrh       }
14789cfcf5d4Sdrh       case OE_Ignore: {
14790ca3e24bSdrh         assert( seenReplace==0 );
148066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14819cfcf5d4Sdrh         break;
14829cfcf5d4Sdrh       }
1483098d1684Sdrh       default: {
14842283d46cSdan         Trigger *pTrigger = 0;
1485098d1684Sdrh         assert( onError==OE_Replace );
14861bea559aSdan         sqlite3MultiWrite(pParse);
14872938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14882283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14892283d46cSdan         }
14902283d46cSdan         sqlite3GenerateRowDelete(
1491ecb31b63Sdrh             pParse, pTab, pTrigger, baseCur, regR, 0, 0, OE_Replace
14922283d46cSdan         );
14930ca3e24bSdrh         seenReplace = 1;
14949cfcf5d4Sdrh         break;
14959cfcf5d4Sdrh       }
14969cfcf5d4Sdrh     }
14972d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
1498b2b9d3d7Sdrh     sqlite3VdbeResolveLabel(v, addrSkipRow);
14992d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
15009cfcf5d4Sdrh   }
1501de630353Sdanielk1977 
1502de630353Sdanielk1977   if( pbMayReplace ){
1503de630353Sdanielk1977     *pbMayReplace = seenReplace;
1504de630353Sdanielk1977   }
15059cfcf5d4Sdrh }
15060ca3e24bSdrh 
15070ca3e24bSdrh /*
15080ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
15094adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
151004adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
151104adf416Sdrh ** rowid and the content to be inserted.
15120ca3e24bSdrh **
1513b419a926Sdrh ** The arguments to this routine should be the same as the first six
15144adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
15150ca3e24bSdrh */
15164adee20fSdanielk1977 void sqlite3CompleteInsertion(
15170ca3e24bSdrh   Parse *pParse,      /* The parser context */
15180ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
151904adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
152004adf416Sdrh   int regRowid,       /* Range of content */
1521aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
152270ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1523de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1524de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
15250ca3e24bSdrh ){
15260ca3e24bSdrh   int i;
15270ca3e24bSdrh   Vdbe *v;
15280ca3e24bSdrh   Index *pIdx;
15291bd10f8aSdrh   u8 pik_flags;
153004adf416Sdrh   int regData;
1531b7654111Sdrh   int regRec;
15320ca3e24bSdrh 
15334adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
15340ca3e24bSdrh   assert( v!=0 );
1535417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1536b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1537aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1538b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1539b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1540b2b9d3d7Sdrh     }
154104adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1542de630353Sdanielk1977     if( useSeekResult ){
1543de630353Sdanielk1977       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1544de630353Sdanielk1977     }
15450ca3e24bSdrh   }
1546ec95c441Sdrh   if( !HasRowid(pTab) ) return;
154704adf416Sdrh   regData = regRowid + 1;
1548b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
15491db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1550a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1551da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
15524794f735Sdrh   if( pParse->nested ){
15534794f735Sdrh     pik_flags = 0;
15544794f735Sdrh   }else{
155594eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
155694eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
15574794f735Sdrh   }
1558e4d90813Sdrh   if( appendBias ){
1559e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1560e4d90813Sdrh   }
1561de630353Sdanielk1977   if( useSeekResult ){
1562de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1563de630353Sdanielk1977   }
1564b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
156594eb6a14Sdanielk1977   if( !pParse->nested ){
15668d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
156794eb6a14Sdanielk1977   }
1568b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
15690ca3e24bSdrh }
1570cd44690aSdrh 
1571cd44690aSdrh /*
1572290c1948Sdrh ** Generate code that will open cursors for a table and for all
157304adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1574cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1575aa9b8963Sdrh **
1576aa9b8963Sdrh ** Return the number of indices on the table.
1577cd44690aSdrh */
1578aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1579290c1948Sdrh   Parse *pParse,   /* Parsing context */
1580290c1948Sdrh   Table *pTab,     /* Table to be opened */
158104adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1582261c02d9Sdrh   int pkCur,       /* Cursor number for the primary key */
1583290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1584290c1948Sdrh ){
1585cd44690aSdrh   int i;
15864cbdda9eSdrh   int iDb;
1587cd44690aSdrh   Index *pIdx;
15884cbdda9eSdrh   Vdbe *v;
15894cbdda9eSdrh 
1590aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
15914cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
15924cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1593cd44690aSdrh   assert( v!=0 );
159404adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1595cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1596b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1597261c02d9Sdrh     int iCur = (pkCur>=0 && pIdx->autoIndex==2) ? pkCur : i+baseCur;
1598da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
1599261c02d9Sdrh     sqlite3VdbeAddOp4(v, op, iCur, pIdx->tnum, iDb,
160066a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1601207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1602cd44690aSdrh   }
1603261c02d9Sdrh   if( pParse->nTab<=i+baseCur ) pParse->nTab = i+baseCur;
1604aa9b8963Sdrh   return i-1;
1605cd44690aSdrh }
16069d9cf229Sdrh 
160791c58e23Sdrh 
160891c58e23Sdrh #ifdef SQLITE_TEST
160991c58e23Sdrh /*
161091c58e23Sdrh ** The following global variable is incremented whenever the
161191c58e23Sdrh ** transfer optimization is used.  This is used for testing
161291c58e23Sdrh ** purposes only - to make sure the transfer optimization really
161391c58e23Sdrh ** is happening when it is suppose to.
161491c58e23Sdrh */
161591c58e23Sdrh int sqlite3_xferopt_count;
161691c58e23Sdrh #endif /* SQLITE_TEST */
161791c58e23Sdrh 
161891c58e23Sdrh 
16199d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
16209d9cf229Sdrh /*
16219d9cf229Sdrh ** Check to collation names to see if they are compatible.
16229d9cf229Sdrh */
16239d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
16249d9cf229Sdrh   if( z1==0 ){
16259d9cf229Sdrh     return z2==0;
16269d9cf229Sdrh   }
16279d9cf229Sdrh   if( z2==0 ){
16289d9cf229Sdrh     return 0;
16299d9cf229Sdrh   }
16309d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
16319d9cf229Sdrh }
16329d9cf229Sdrh 
16339d9cf229Sdrh 
16349d9cf229Sdrh /*
16359d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
16369d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
16379d9cf229Sdrh ** for a compatible index:
16389d9cf229Sdrh **
16399d9cf229Sdrh **    *   The index is over the same set of columns
16409d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
16419d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
16429d9cf229Sdrh **    *   The same collating sequence on each column
1643b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
16449d9cf229Sdrh */
16459d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
16469d9cf229Sdrh   int i;
16479d9cf229Sdrh   assert( pDest && pSrc );
16489d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1649bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
16509d9cf229Sdrh     return 0;   /* Different number of columns */
16519d9cf229Sdrh   }
16529d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
16539d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
16549d9cf229Sdrh   }
1655bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
16569d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
16579d9cf229Sdrh       return 0;   /* Different columns indexed */
16589d9cf229Sdrh     }
16599d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
16609d9cf229Sdrh       return 0;   /* Different sort orders */
16619d9cf229Sdrh     }
16623f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
166360a713c6Sdrh       return 0;   /* Different collating sequences */
16649d9cf229Sdrh     }
16659d9cf229Sdrh   }
1666619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1667b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1668b2b9d3d7Sdrh   }
16699d9cf229Sdrh 
16709d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
16719d9cf229Sdrh   return 1;
16729d9cf229Sdrh }
16739d9cf229Sdrh 
16749d9cf229Sdrh /*
16759d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
16769d9cf229Sdrh **
16779d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
16789d9cf229Sdrh **
1679ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1680ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1681ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
16829d9cf229Sdrh **
1683ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1684ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1685ccdf1baeSdrh ** embedded in the code for details.
16869d9cf229Sdrh **
1687ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1688ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1689ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1690ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1691ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1692ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1693ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1694ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1695ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
16969d9cf229Sdrh **
1697ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
16989d9cf229Sdrh */
16999d9cf229Sdrh static int xferOptimization(
17009d9cf229Sdrh   Parse *pParse,        /* Parser context */
17019d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
17029d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
17039d9cf229Sdrh   int onError,          /* How to handle constraint errors */
17049d9cf229Sdrh   int iDbDest           /* The database of pDest */
17059d9cf229Sdrh ){
17069d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
17079d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
17089d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
17099d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
17109d9cf229Sdrh   int i;                           /* Loop counter */
17119d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
17129d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
17139d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
17149d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
17159d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
17169d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
17179d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
17186a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1719f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1720b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
17219d9cf229Sdrh 
17229d9cf229Sdrh   if( pSelect==0 ){
17239d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
17249d9cf229Sdrh   }
17252f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
17269d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
17279d9cf229Sdrh   }
17289d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17297d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
17309d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
17319d9cf229Sdrh   }
17329d9cf229Sdrh #endif
17339d9cf229Sdrh   if( onError==OE_Default ){
1734e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1735e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
17369d9cf229Sdrh   }
17375ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
17389d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
17399d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
17409d9cf229Sdrh   }
17419d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
17429d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
17439d9cf229Sdrh   }
17449d9cf229Sdrh   if( pSelect->pWhere ){
17459d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
17469d9cf229Sdrh   }
17479d9cf229Sdrh   if( pSelect->pOrderBy ){
17489d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
17499d9cf229Sdrh   }
17508103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
17518103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
17529d9cf229Sdrh   if( pSelect->pGroupBy ){
17539d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
17549d9cf229Sdrh   }
17559d9cf229Sdrh   if( pSelect->pLimit ){
17569d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
17579d9cf229Sdrh   }
17588103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
17599d9cf229Sdrh   if( pSelect->pPrior ){
17609d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
17619d9cf229Sdrh   }
17627d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
17639d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
17649d9cf229Sdrh   }
17659d9cf229Sdrh   pEList = pSelect->pEList;
17669d9cf229Sdrh   assert( pEList!=0 );
17679d9cf229Sdrh   if( pEList->nExpr!=1 ){
17689d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
17699d9cf229Sdrh   }
17709d9cf229Sdrh   assert( pEList->a[0].pExpr );
17719d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
17729d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
17739d9cf229Sdrh   }
17749d9cf229Sdrh 
17759d9cf229Sdrh   /* At this point we have established that the statement is of the
17769d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
17779d9cf229Sdrh   ** we have to check the semantics.
17789d9cf229Sdrh   */
17799d9cf229Sdrh   pItem = pSelect->pSrc->a;
178041fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
17819d9cf229Sdrh   if( pSrc==0 ){
17829d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
17839d9cf229Sdrh   }
17849d9cf229Sdrh   if( pSrc==pDest ){
17859d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
17869d9cf229Sdrh   }
178755548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
178855548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
178955548273Sdrh   }
17909d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17917d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
17929d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
17939d9cf229Sdrh   }
17949d9cf229Sdrh #endif
17959d9cf229Sdrh   if( pSrc->pSelect ){
17969d9cf229Sdrh     return 0;   /* tab2 may not be a view */
17979d9cf229Sdrh   }
17989d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
17999d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
18009d9cf229Sdrh   }
18019d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
18029d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
18039d9cf229Sdrh   }
180455548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
180555548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
180655548273Sdrh   }
18079d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
18089d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
18099d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
18109d9cf229Sdrh     }
18119d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
18129d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
18139d9cf229Sdrh     }
18149d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
18159d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
18169d9cf229Sdrh     }
18179d9cf229Sdrh   }
18189d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1819f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1820f33c9fadSdrh       destHasUniqueIdx = 1;
1821f33c9fadSdrh     }
18229d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
18239d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18249d9cf229Sdrh     }
18259d9cf229Sdrh     if( pSrcIdx==0 ){
18269d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
18279d9cf229Sdrh     }
18289d9cf229Sdrh   }
18297fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1830619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
18318103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
18328103b7d2Sdrh   }
18337fc2f41bSdrh #endif
1834713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1835713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1836713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1837713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1838713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1839713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1840713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1841713de341Sdrh   */
1842713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1843713de341Sdrh     return 0;
1844713de341Sdrh   }
1845713de341Sdrh #endif
18461696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1847ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
18481696124dSdan   }
18499d9cf229Sdrh 
1850ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1851ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1852ccdf1baeSdrh   ** table (tab1) is initially empty.
18539d9cf229Sdrh   */
1854dd73521bSdrh #ifdef SQLITE_TEST
1855dd73521bSdrh   sqlite3_xferopt_count++;
1856dd73521bSdrh #endif
18579d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
18589d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1859f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
18609d9cf229Sdrh   iSrc = pParse->nTab++;
18619d9cf229Sdrh   iDest = pParse->nTab++;
18626a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
186355548273Sdrh   regData = sqlite3GetTempReg(pParse);
186455548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
186555548273Sdrh   if( HasRowid(pSrc) ){
18669d9cf229Sdrh     sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1867ccdf1baeSdrh     if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1868ccdf1baeSdrh      || destHasUniqueIdx                              /* (2) */
1869ccdf1baeSdrh      || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1870ccdf1baeSdrh     ){
1871ccdf1baeSdrh       /* In some circumstances, we are able to run the xfer optimization
1872ccdf1baeSdrh       ** only if the destination table is initially empty.  This code makes
1873ccdf1baeSdrh       ** that determination.  Conditions under which the destination must
1874ccdf1baeSdrh       ** be empty:
1875f33c9fadSdrh       **
1876ccdf1baeSdrh       ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1877ccdf1baeSdrh       **     (If the destination is not initially empty, the rowid fields
1878ccdf1baeSdrh       **     of index entries might need to change.)
1879ccdf1baeSdrh       **
1880ccdf1baeSdrh       ** (2) The destination has a unique index.  (The xfer optimization
1881ccdf1baeSdrh       **     is unable to test uniqueness.)
1882ccdf1baeSdrh       **
1883ccdf1baeSdrh       ** (3) onError is something other than OE_Abort and OE_Rollback.
18849d9cf229Sdrh       */
188566a5167bSdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
188666a5167bSdrh       emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
18879d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr1);
18889d9cf229Sdrh     }else{
18899d9cf229Sdrh       emptyDestTest = 0;
18909d9cf229Sdrh     }
18919d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
189266a5167bSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
189342242dedSdrh     if( pDest->iPKey>=0 ){
1894b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1895b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1896d91c1a17Sdrh       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1897d91c1a17Sdrh           onError, "PRIMARY KEY must be unique", P4_STATIC);
18989d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
1899b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
1900bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
1901b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
190295bad4c7Sdrh     }else{
1903b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
19047d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
190595bad4c7Sdrh     }
1906b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1907b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1908b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
19091f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
191066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
191155548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
191255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
191355548273Sdrh   }
19149d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
19151b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
19169d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19179d9cf229Sdrh     }
19189d9cf229Sdrh     assert( pSrcIdx );
19199d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1920207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1921207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1922d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
19239d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1924207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
192566a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
192659885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
1927207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
192866a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1929b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1930b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
193166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
19329d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
193355548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
193455548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19359d9cf229Sdrh   }
19369d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1937b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1938b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
19399d9cf229Sdrh   if( emptyDestTest ){
194066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
19419d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
194266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19439d9cf229Sdrh     return 0;
19449d9cf229Sdrh   }else{
19459d9cf229Sdrh     return 1;
19469d9cf229Sdrh   }
19479d9cf229Sdrh }
19489d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1949