xref: /sqlite-3.40.0/src/insert.c (revision ebbf08a0)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17cce7d176Sdrh /*
1826198bb4Sdrh ** Generate code that will
19dd9930efSdrh **
2026198bb4Sdrh **   (1) acquire a lock for table pTab then
2126198bb4Sdrh **   (2) open pTab as cursor iCur.
2226198bb4Sdrh **
2326198bb4Sdrh ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
2426198bb4Sdrh ** for that table that is actually opened.
25bbb5e4e0Sdrh */
26bbb5e4e0Sdrh void sqlite3OpenTable(
272ec2fb22Sdrh   Parse *pParse,  /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
352ec2fb22Sdrh   v = sqlite3GetVdbe(pParse);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
372ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
382ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
39ec95c441Sdrh   if( HasRowid(pTab) ){
40261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
41dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
4226198bb4Sdrh   }else{
43dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44dd9930efSdrh     assert( pPk!=0 );
45dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
462ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
472ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
48bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
49bbb5e4e0Sdrh   }
50ec95c441Sdrh }
51bbb5e4e0Sdrh 
52bbb5e4e0Sdrh /*
5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5569f8bb9cSdan ** the table, according to the affinity of the column:
563d1bfeaaSdanielk1977 **
573d1bfeaaSdanielk1977 **  Character      Column affinity
583d1bfeaaSdanielk1977 **  ------------------------------
593eda040bSdrh **  'a'            TEXT
603eda040bSdrh **  'b'            NONE
613eda040bSdrh **  'c'            NUMERIC
623eda040bSdrh **  'd'            INTEGER
633eda040bSdrh **  'e'            REAL
642d401ab8Sdrh **
650c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
662d401ab8Sdrh ** rowid that appears as the last column in every index.
6769f8bb9cSdan **
6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
713d1bfeaaSdanielk1977 */
7269f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
73a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
74e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
75a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
76e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
77a37cdde0Sdanielk1977     **
78a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
79e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80a37cdde0Sdanielk1977     ** up.
81a37cdde0Sdanielk1977     */
82a37cdde0Sdanielk1977     int n;
83a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
84abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
85ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
86a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
87633e6d57Sdrh       db->mallocFailed = 1;
8869f8bb9cSdan       return 0;
89a37cdde0Sdanielk1977     }
90ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
91ad124329Sdrh       i16 x = pIdx->aiColumn[n];
92ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
93a37cdde0Sdanielk1977     }
942d401ab8Sdrh     pIdx->zColAff[n] = 0;
95a37cdde0Sdanielk1977   }
963d1bfeaaSdanielk1977 
9769f8bb9cSdan   return pIdx->zColAff;
98a37cdde0Sdanielk1977 }
99a37cdde0Sdanielk1977 
100a37cdde0Sdanielk1977 /*
10166a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
102a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
103a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
104a37cdde0Sdanielk1977 ** column:
105a37cdde0Sdanielk1977 **
106a37cdde0Sdanielk1977 **  Character      Column affinity
107a37cdde0Sdanielk1977 **  ------------------------------
1083eda040bSdrh **  'a'            TEXT
1093eda040bSdrh **  'b'            NONE
1103eda040bSdrh **  'c'            NUMERIC
1113eda040bSdrh **  'd'            INTEGER
1123eda040bSdrh **  'e'            REAL
113a37cdde0Sdanielk1977 */
114a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1153d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1163d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1173d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1183d1bfeaaSdanielk1977   **
1193d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1203d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1213d1bfeaaSdanielk1977   */
1223d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1233d1bfeaaSdanielk1977     char *zColAff;
1243d1bfeaaSdanielk1977     int i;
125abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1263d1bfeaaSdanielk1977 
127b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1283d1bfeaaSdanielk1977     if( !zColAff ){
129633e6d57Sdrh       db->mallocFailed = 1;
130a37cdde0Sdanielk1977       return;
1313d1bfeaaSdanielk1977     }
1323d1bfeaaSdanielk1977 
1333d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
134a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1353d1bfeaaSdanielk1977     }
1363d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1373d1bfeaaSdanielk1977 
1383d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1393d1bfeaaSdanielk1977   }
1403d1bfeaaSdanielk1977 
1418d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1423d1bfeaaSdanielk1977 }
1433d1bfeaaSdanielk1977 
1444d88778bSdanielk1977 /*
14548d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
14648d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
14748d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
14848d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
14948d1178aSdrh ** run without using temporary table for the results of the SELECT.
1504d88778bSdanielk1977 */
151595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
152595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1534d88778bSdanielk1977   int i;
15448d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
155595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
156595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
157595a523aSdanielk1977 #endif
158595a523aSdanielk1977 
15948d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
16048d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
161ef0bea92Sdrh     assert( pOp!=0 );
162207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16348d1178aSdrh       Index *pIndex;
164207872a4Sdanielk1977       int tnum = pOp->p2;
16548d1178aSdrh       if( tnum==pTab->tnum ){
16648d1178aSdrh         return 1;
16748d1178aSdrh       }
16848d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
16948d1178aSdrh         if( tnum==pIndex->tnum ){
17048d1178aSdrh           return 1;
17148d1178aSdrh         }
17248d1178aSdrh       }
17348d1178aSdrh     }
174543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
175595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1762dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
17766a5167bSdrh       assert( pOp->p4type==P4_VTAB );
17848d1178aSdrh       return 1;
1794d88778bSdanielk1977     }
180543165efSdrh #endif
1814d88778bSdanielk1977   }
1824d88778bSdanielk1977   return 0;
1834d88778bSdanielk1977 }
1843d1bfeaaSdanielk1977 
1859d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1869d9cf229Sdrh /*
1870b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1880b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1890b9f50d8Sdrh ** that holds the maximum rowid.
1909d9cf229Sdrh **
1910b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1920b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1930b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1940b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1950b9f50d8Sdrh ** AutoincInfo structure is used.
1969d9cf229Sdrh **
1970b9f50d8Sdrh ** Three memory locations are allocated:
1980b9f50d8Sdrh **
1990b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
2000b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2010b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2020b9f50d8Sdrh **
2030b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2040b9f50d8Sdrh ** insert routine needs to know about.
2059d9cf229Sdrh */
2069d9cf229Sdrh static int autoIncBegin(
2079d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2089d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2099d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2109d9cf229Sdrh ){
2116a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2127d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21365a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2140b9f50d8Sdrh     AutoincInfo *pInfo;
2150b9f50d8Sdrh 
21665a7cd16Sdan     pInfo = pToplevel->pAinc;
2170b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2180b9f50d8Sdrh     if( pInfo==0 ){
2190b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2200b9f50d8Sdrh       if( pInfo==0 ) return 0;
22165a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22265a7cd16Sdan       pToplevel->pAinc = pInfo;
2230b9f50d8Sdrh       pInfo->pTab = pTab;
2240b9f50d8Sdrh       pInfo->iDb = iDb;
22565a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
22665a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
22765a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2280b9f50d8Sdrh     }
2290b9f50d8Sdrh     memId = pInfo->regCtr;
2309d9cf229Sdrh   }
2319d9cf229Sdrh   return memId;
2329d9cf229Sdrh }
2339d9cf229Sdrh 
2349d9cf229Sdrh /*
2350b9f50d8Sdrh ** This routine generates code that will initialize all of the
2360b9f50d8Sdrh ** register used by the autoincrement tracker.
2370b9f50d8Sdrh */
2380b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2390b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2400b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2410b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2420b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2430b9f50d8Sdrh   int addr;                  /* A VDBE address */
2440b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2450b9f50d8Sdrh 
246345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
247345ba7dbSdrh   ** only called from the top-level */
248345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
249345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
25076d462eeSdan 
2510b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2520b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2530b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2540b9f50d8Sdrh     memId = p->regCtr;
2552120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2560b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
257f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2580b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2590b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2600b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2610b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2620b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2630b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2640b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2650b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2660b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2670b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2680b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2690b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2700b9f50d8Sdrh   }
2710b9f50d8Sdrh }
2720b9f50d8Sdrh 
2730b9f50d8Sdrh /*
2749d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2759d9cf229Sdrh **
2769d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2779d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2789d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2799d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2809d9cf229Sdrh */
2816a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2829d9cf229Sdrh   if( memId>0 ){
2836a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2849d9cf229Sdrh   }
2859d9cf229Sdrh }
2869d9cf229Sdrh 
2879d9cf229Sdrh /*
2880b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2890b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2900b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2910b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2920b9f50d8Sdrh ** routine just before the "exit" code.
2939d9cf229Sdrh */
2940b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2950b9f50d8Sdrh   AutoincInfo *p;
2969d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2970b9f50d8Sdrh   sqlite3 *db = pParse->db;
2986a288a33Sdrh 
2999d9cf229Sdrh   assert( v );
3000b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3010b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3020b9f50d8Sdrh     int j1, j2, j3, j4, j5;
3030b9f50d8Sdrh     int iRec;
3040b9f50d8Sdrh     int memId = p->regCtr;
3050b9f50d8Sdrh 
3060b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3072120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3080b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3096a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
3100b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
3110b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
3120b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3130b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3140b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3150b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3160b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3170b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3180b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3196a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3200b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
321a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3220b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
32335573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3240b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3250b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3269d9cf229Sdrh   }
3279d9cf229Sdrh }
3289d9cf229Sdrh #else
3299d9cf229Sdrh /*
3309d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3319d9cf229Sdrh ** above are all no-ops
3329d9cf229Sdrh */
3339d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
334287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3359d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3369d9cf229Sdrh 
3379d9cf229Sdrh 
3385f085269Sdrh /*
3395f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3405f085269Sdrh ** row at a time.
3415f085269Sdrh **
3425f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3435f085269Sdrh ** Information about the location of co-routine and the registers it will use
3445f085269Sdrh ** is returned by filling in the pDest object.
3455f085269Sdrh **
3465f085269Sdrh ** Registers are allocated as follows:
3475f085269Sdrh **
3485f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3495f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3505f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3515f085269Sdrh **
3525f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3535f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3545f085269Sdrh **                       generated a new result row, or 1 if the subquery
3555f085269Sdrh **                       has completed.  If the Yield is called again
3565f085269Sdrh **                       after this register becomes 1, then the VDBE will
3575f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3585f085269Sdrh **
3595f085269Sdrh **   pDest->iSdst        First result register.
3605f085269Sdrh **
3615f085269Sdrh **   pDest->nSdst        Number of result registers.
3625f085269Sdrh **
3635f085269Sdrh ** This routine handles all of the register allocation and fills in the
3645f085269Sdrh ** pDest structure appropriately.
3655f085269Sdrh **
3665f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3675f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3685f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3695f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3705f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3715f085269Sdrh **
3725f085269Sdrh **         X <- A
3735f085269Sdrh **         EOF <- 0
3745f085269Sdrh **         goto B
3755f085269Sdrh **      A: setup for the SELECT
3765f085269Sdrh **         loop rows in the SELECT
3775f085269Sdrh **           load results into registers R..S
3785f085269Sdrh **           yield X
3795f085269Sdrh **         end loop
3805f085269Sdrh **         cleanup after the SELECT
3815f085269Sdrh **         EOF <- 1
3825f085269Sdrh **         yield X
3835f085269Sdrh **         halt-error
3845f085269Sdrh **      B:
3855f085269Sdrh **
3865f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3875f085269Sdrh **
3885f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3895f085269Sdrh **      S: yield X
3905f085269Sdrh **         if EOF goto E
3915f085269Sdrh **         if skip this row, goto C
3925f085269Sdrh **         if terminate loop, goto E
3935f085269Sdrh **         deal with this row
3945f085269Sdrh **      C: goto S
3955f085269Sdrh **      E:
3965f085269Sdrh */
3975f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3985f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3995f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
4005f085269Sdrh   int addrTop;        /* Top of the co-routine */
4015f085269Sdrh   int j1;             /* Jump instruction */
4025f085269Sdrh   int rc;             /* Result code */
4035f085269Sdrh   Vdbe *v;            /* VDBE under construction */
4045f085269Sdrh 
4055f085269Sdrh   regYield = ++pParse->nMem;
4065f085269Sdrh   regEof = ++pParse->nMem;
4075f085269Sdrh   v = sqlite3GetVdbe(pParse);
4085f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
4095f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
4105f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
4115f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
4125f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4135f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4145f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4155f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4165f085269Sdrh   assert( pParse->nErr==0 || rc );
4175f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4185f085269Sdrh   if( rc ) return rc;
4195f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4205f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4215f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4225f085269Sdrh   VdbeComment((v, "End of coroutine"));
4235f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4245f085269Sdrh   return rc;
4255f085269Sdrh }
4265f085269Sdrh 
4275f085269Sdrh 
4285f085269Sdrh 
4299d9cf229Sdrh /* Forward declaration */
4309d9cf229Sdrh static int xferOptimization(
4319d9cf229Sdrh   Parse *pParse,        /* Parser context */
4329d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4339d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4349d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4359d9cf229Sdrh   int iDbDest           /* The database of pDest */
4369d9cf229Sdrh );
4379d9cf229Sdrh 
4383d1bfeaaSdanielk1977 /*
439d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
440cce7d176Sdrh **
441cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4421ccde15dSdrh **    insert into TABLE (IDLIST) select
443cce7d176Sdrh **
4441ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4451ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
446967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4471ccde15dSdrh **
4481ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4491ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4501ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4511ccde15dSdrh ** data for the insert.
452142e30dfSdrh **
4539d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
454d82b5021Sdrh ** insert with data coming from a VALUES clause, the code executes
455e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
456e00ee6ebSdrh ** the "1st template"):
457142e30dfSdrh **
458142e30dfSdrh **         open write cursor to <table> and its indices
459ec95c441Sdrh **         put VALUES clause expressions into registers
460142e30dfSdrh **         write the resulting record into <table>
461142e30dfSdrh **         cleanup
462142e30dfSdrh **
4639d9cf229Sdrh ** The three remaining templates assume the statement is of the form
464142e30dfSdrh **
465142e30dfSdrh **   INSERT INTO <table> SELECT ...
466142e30dfSdrh **
4679d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4689d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4699d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4709d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4719d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4729d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4739d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
474e00ee6ebSdrh ** template.  This is the 2nd template.
4759d9cf229Sdrh **
4769d9cf229Sdrh **         open a write cursor to <table>
4779d9cf229Sdrh **         open read cursor on <table2>
4789d9cf229Sdrh **         transfer all records in <table2> over to <table>
4799d9cf229Sdrh **         close cursors
4809d9cf229Sdrh **         foreach index on <table>
4819d9cf229Sdrh **           open a write cursor on the <table> index
4829d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4839d9cf229Sdrh **           transfer all records from the read to the write cursors
4849d9cf229Sdrh **           close cursors
4859d9cf229Sdrh **         end foreach
4869d9cf229Sdrh **
487e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4889d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4899d9cf229Sdrh ** The generated code follows this template:
490142e30dfSdrh **
491e00ee6ebSdrh **         EOF <- 0
492e00ee6ebSdrh **         X <- A
493142e30dfSdrh **         goto B
494142e30dfSdrh **      A: setup for the SELECT
4959d9cf229Sdrh **         loop over the rows in the SELECT
496e00ee6ebSdrh **           load values into registers R..R+n
497e00ee6ebSdrh **           yield X
498142e30dfSdrh **         end loop
499142e30dfSdrh **         cleanup after the SELECT
500e00ee6ebSdrh **         EOF <- 1
501e00ee6ebSdrh **         yield X
502142e30dfSdrh **         goto A
503e00ee6ebSdrh **      B: open write cursor to <table> and its indices
504e00ee6ebSdrh **      C: yield X
505e00ee6ebSdrh **         if EOF goto D
506e00ee6ebSdrh **         insert the select result into <table> from R..R+n
507e00ee6ebSdrh **         goto C
508142e30dfSdrh **      D: cleanup
509142e30dfSdrh **
510e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
511142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
512142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
513142e30dfSdrh ** we have to use a intermediate table to store the results of
514142e30dfSdrh ** the select.  The template is like this:
515142e30dfSdrh **
516e00ee6ebSdrh **         EOF <- 0
517e00ee6ebSdrh **         X <- A
518142e30dfSdrh **         goto B
519142e30dfSdrh **      A: setup for the SELECT
520142e30dfSdrh **         loop over the tables in the SELECT
521e00ee6ebSdrh **           load value into register R..R+n
522e00ee6ebSdrh **           yield X
523142e30dfSdrh **         end loop
524142e30dfSdrh **         cleanup after the SELECT
525e00ee6ebSdrh **         EOF <- 1
526e00ee6ebSdrh **         yield X
527e00ee6ebSdrh **         halt-error
528e00ee6ebSdrh **      B: open temp table
529e00ee6ebSdrh **      L: yield X
530e00ee6ebSdrh **         if EOF goto M
531e00ee6ebSdrh **         insert row from R..R+n into temp table
532e00ee6ebSdrh **         goto L
533e00ee6ebSdrh **      M: open write cursor to <table> and its indices
534e00ee6ebSdrh **         rewind temp table
535e00ee6ebSdrh **      C: loop over rows of intermediate table
536142e30dfSdrh **           transfer values form intermediate table into <table>
537e00ee6ebSdrh **         end loop
538e00ee6ebSdrh **      D: cleanup
539cce7d176Sdrh */
5404adee20fSdanielk1977 void sqlite3Insert(
541cce7d176Sdrh   Parse *pParse,        /* Parser context */
542113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
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 */
55626198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
55726198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
558d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5590ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5604d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
561cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
562e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
563e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
564e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5652eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5666a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5672958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
568e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
569ec95c441Sdrh   int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
57075593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
571cce7d176Sdrh 
5726a288a33Sdrh   /* Register allocations */
5731bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5746a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5756a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5766a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5776a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5786a288a33Sdrh   int regData;          /* register holding first column to insert */
5791bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
580aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5816a288a33Sdrh 
582798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
583798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5842f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5852f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
586798da52cSdrh #endif
587c3f9bad2Sdanielk1977 
58817435752Sdrh   db = pParse->db;
5891bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
59017435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5916f7adc8aSdrh     goto insert_cleanup;
5926f7adc8aSdrh   }
593daffd0e5Sdrh 
59475593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
59575593d96Sdrh   ** single row values (the common case) then keep that one row of values
59675593d96Sdrh   ** and go ahead and discard the Select object
59775593d96Sdrh   */
59875593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
59975593d96Sdrh     pList = pSelect->pEList;
60075593d96Sdrh     pSelect->pEList = 0;
60175593d96Sdrh     sqlite3SelectDelete(db, pSelect);
60275593d96Sdrh     pSelect = 0;
60375593d96Sdrh   }
60475593d96Sdrh 
6051ccde15dSdrh   /* Locate the table into which we will be inserting new information.
6061ccde15dSdrh   */
607113088ecSdrh   assert( pTabList->nSrc==1 );
608113088ecSdrh   zTab = pTabList->a[0].zName;
609098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
6104adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
611c3f9bad2Sdanielk1977   if( pTab==0 ){
612c3f9bad2Sdanielk1977     goto insert_cleanup;
613c3f9bad2Sdanielk1977   }
614da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
615da184236Sdanielk1977   assert( iDb<db->nDb );
616da184236Sdanielk1977   pDb = &db->aDb[iDb];
6172958a4e6Sdrh   zDb = pDb->zName;
6184adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
6191962bda7Sdrh     goto insert_cleanup;
6201962bda7Sdrh   }
621ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
622c3f9bad2Sdanielk1977 
623b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
624b7f9164eSdrh   ** inserted into is a view
625b7f9164eSdrh   */
626b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6272f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
628b7f9164eSdrh   isView = pTab->pSelect!=0;
629b7f9164eSdrh #else
6302f886d1dSdanielk1977 # define pTrigger 0
6312f886d1dSdanielk1977 # define tmask 0
632b7f9164eSdrh # define isView 0
633b7f9164eSdrh #endif
634b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
635b7f9164eSdrh # undef isView
636b7f9164eSdrh # define isView 0
637b7f9164eSdrh #endif
6382f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
639b7f9164eSdrh 
640f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
641d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
642f573c99bSdrh   */
643b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
644f573c99bSdrh     goto insert_cleanup;
645f573c99bSdrh   }
646f573c99bSdrh 
647d82b5021Sdrh   /* Cannot insert into a read-only table.
648595a523aSdanielk1977   */
649595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
650595a523aSdanielk1977     goto insert_cleanup;
651595a523aSdanielk1977   }
652595a523aSdanielk1977 
6531ccde15dSdrh   /* Allocate a VDBE
6541ccde15dSdrh   */
6554adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6565974a30fSdrh   if( v==0 ) goto insert_cleanup;
6574794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6582f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6591ccde15dSdrh 
6609d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6619d9cf229Sdrh   /* If the statement is of the form
6629d9cf229Sdrh   **
6639d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6649d9cf229Sdrh   **
6659d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6669d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
667e00ee6ebSdrh   **
668e00ee6ebSdrh   ** This is the 2nd template.
6699d9cf229Sdrh   */
670*ebbf08a0Sdan   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6712f886d1dSdanielk1977     assert( !pTrigger );
6729d9cf229Sdrh     assert( pList==0 );
6730b9f50d8Sdrh     goto insert_end;
6749d9cf229Sdrh   }
6759d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6769d9cf229Sdrh 
6772958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6786a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6792958a4e6Sdrh   */
6806a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6812958a4e6Sdrh 
6821ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
683e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
684e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
685e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6861ccde15dSdrh   */
6875974a30fSdrh   if( pSelect ){
688d82b5021Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
6895f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6905f085269Sdrh     if( rc ) goto insert_cleanup;
6911013c932Sdrh 
6925f085269Sdrh     regEof = dest.iSDParm + 1;
6932b596da8Sdrh     regFromSelect = dest.iSdst;
6945974a30fSdrh     assert( pSelect->pEList );
695967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6962b596da8Sdrh     assert( dest.nSdst==nColumn );
697142e30dfSdrh 
698142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
699e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
700d82b5021Sdrh     ** FALSE if each output row of the SELECT can be written directly into
701e00ee6ebSdrh     ** the destination table (template 3).
702048c530cSdrh     **
703048c530cSdrh     ** A temp table must be used if the table being updated is also one
704048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
705048c530cSdrh     ** temp table in the case of row triggers.
706142e30dfSdrh     */
707595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
708048c530cSdrh       useTempTable = 1;
709048c530cSdrh     }
710142e30dfSdrh 
711142e30dfSdrh     if( useTempTable ){
712e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
713e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
714e00ee6ebSdrh       ** here is from the 4th template:
715e00ee6ebSdrh       **
716e00ee6ebSdrh       **      B: open temp table
717e00ee6ebSdrh       **      L: yield X
718e00ee6ebSdrh       **         if EOF goto M
719e00ee6ebSdrh       **         insert row from R..R+n into temp table
720e00ee6ebSdrh       **         goto L
721e00ee6ebSdrh       **      M: ...
722142e30dfSdrh       */
723e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
724dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
725e00ee6ebSdrh       int addrTop;         /* Label "L" */
726e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
727b7654111Sdrh 
728142e30dfSdrh       srcTab = pParse->nTab++;
729b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
730dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
731e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7322b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
733e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7341db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
735dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
736dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
737e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
738e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
739b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
740dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
741142e30dfSdrh     }
742142e30dfSdrh   }else{
743142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
744142e30dfSdrh     ** clause
745142e30dfSdrh     */
746b3bce662Sdanielk1977     NameContext sNC;
747b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
748b3bce662Sdanielk1977     sNC.pParse = pParse;
7495974a30fSdrh     srcTab = -1;
75048d1178aSdrh     assert( useTempTable==0 );
751147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
752e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7537d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
754b04a5d87Sdrh         goto insert_cleanup;
755b04a5d87Sdrh       }
756e64e7b20Sdrh     }
7575974a30fSdrh   }
7581ccde15dSdrh 
7591ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7601ccde15dSdrh   ** of columns to be inserted into the table.
7611ccde15dSdrh   */
762034ca14fSdanielk1977   if( IsVirtual(pTab) ){
763034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
764034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
765034ca14fSdanielk1977     }
766034ca14fSdanielk1977   }
767034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7684adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
769da93d238Sdrh        "table %S has %d columns but %d values were supplied",
770d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
771cce7d176Sdrh     goto insert_cleanup;
772cce7d176Sdrh   }
773967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7744adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
775cce7d176Sdrh     goto insert_cleanup;
776cce7d176Sdrh   }
7771ccde15dSdrh 
7781ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7791ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7801ccde15dSdrh   ** remember the column indices.
781c8392586Sdrh   **
782c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
783d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
784d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
785c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
786d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
787d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
7881ccde15dSdrh   */
789967e8b73Sdrh   if( pColumn ){
790967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
791967e8b73Sdrh       pColumn->a[i].idx = -1;
792cce7d176Sdrh     }
793967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
794cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7954adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
796967e8b73Sdrh           pColumn->a[i].idx = j;
7974a32431cSdrh           if( j==pTab->iPKey ){
798d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
7994a32431cSdrh           }
800cce7d176Sdrh           break;
801cce7d176Sdrh         }
802cce7d176Sdrh       }
803cce7d176Sdrh       if( j>=pTab->nCol ){
804ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
805d82b5021Sdrh           ipkColumn = i;
806a0217ba7Sdrh         }else{
8074adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
808da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
8091db95106Sdan           pParse->checkSchema = 1;
810cce7d176Sdrh           goto insert_cleanup;
811cce7d176Sdrh         }
812cce7d176Sdrh       }
813cce7d176Sdrh     }
814a0217ba7Sdrh   }
8151ccde15dSdrh 
816aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
817d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
818d82b5021Sdrh   ** column index in the original table definition.
8194a32431cSdrh   */
820147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
821d82b5021Sdrh     ipkColumn = pTab->iPKey;
8224a32431cSdrh   }
8234a32431cSdrh 
824c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8251ccde15dSdrh   */
826142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8276a288a33Sdrh     regRowCount = ++pParse->nMem;
8286a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
829c3f9bad2Sdanielk1977   }
830c3f9bad2Sdanielk1977 
831e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
832e448dc4aSdanielk1977   if( !isView ){
833aa9b8963Sdrh     int nIdx;
8346a53499aSdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
83526198bb4Sdrh                                       &iDataCur, &iIdxCur);
8365c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
837aa9b8963Sdrh     if( aRegIdx==0 ){
838aa9b8963Sdrh       goto insert_cleanup;
839aa9b8963Sdrh     }
840aa9b8963Sdrh     for(i=0; i<nIdx; i++){
841aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
842aa9b8963Sdrh     }
843feeb1394Sdrh   }
844feeb1394Sdrh 
845e00ee6ebSdrh   /* This is the top of the main insertion loop */
846142e30dfSdrh   if( useTempTable ){
847e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
848e00ee6ebSdrh     ** following pseudocode (template 4):
849e00ee6ebSdrh     **
850e00ee6ebSdrh     **         rewind temp table
851e00ee6ebSdrh     **      C: loop over rows of intermediate table
852e00ee6ebSdrh     **           transfer values form intermediate table into <table>
853e00ee6ebSdrh     **         end loop
854e00ee6ebSdrh     **      D: ...
855e00ee6ebSdrh     */
856e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
857e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
858142e30dfSdrh   }else if( pSelect ){
859e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
860e00ee6ebSdrh     ** following pseudocode (template 3):
861e00ee6ebSdrh     **
862e00ee6ebSdrh     **      C: yield X
863e00ee6ebSdrh     **         if EOF goto D
864e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
865e00ee6ebSdrh     **         goto C
866e00ee6ebSdrh     **      D: ...
867e00ee6ebSdrh     */
8682b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
869e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
870bed8690fSdrh   }
8711ccde15dSdrh 
8726a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8736a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8746a288a33Sdrh   */
8756a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8766a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8776a288a33Sdrh   if( IsVirtual(pTab) ){
8786a288a33Sdrh     regRowid++;
8796a288a33Sdrh     pParse->nMem++;
8806a288a33Sdrh   }
8816a288a33Sdrh   regData = regRowid+1;
8826a288a33Sdrh 
8835cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
88470ce3f0cSdrh   */
8854adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8862f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
88776d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
888c3f9bad2Sdanielk1977 
88970ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
89070ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89170ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89270ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
89370ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
89470ce3f0cSdrh     */
895d82b5021Sdrh     if( ipkColumn<0 ){
89676d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89770ce3f0cSdrh     }else{
8986a288a33Sdrh       int j1;
899ec95c441Sdrh       assert( !withoutRowid );
9007fe45908Sdrh       if( useTempTable ){
901d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
9027fe45908Sdrh       }else{
903d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
904d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
9057fe45908Sdrh       }
90676d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
90776d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
9086a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
90976d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
91070ce3f0cSdrh     }
91170ce3f0cSdrh 
912034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
913034ca14fSdanielk1977     ** this block would have to account for hidden column.
914034ca14fSdanielk1977     */
915034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
916034ca14fSdanielk1977 
91770ce3f0cSdrh     /* Create the new column data
91870ce3f0cSdrh     */
919c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
920c3f9bad2Sdanielk1977       if( pColumn==0 ){
921c3f9bad2Sdanielk1977         j = i;
922c3f9bad2Sdanielk1977       }else{
923c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
924c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
925c3f9bad2Sdanielk1977         }
926c3f9bad2Sdanielk1977       }
9277ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
92876d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
929142e30dfSdrh       }else if( useTempTable ){
93076d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
931c3f9bad2Sdanielk1977       }else{
932d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
93376d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
934c3f9bad2Sdanielk1977       }
935c3f9bad2Sdanielk1977     }
936a37cdde0Sdanielk1977 
937a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
938a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
939a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
940a37cdde0Sdanielk1977     ** table column affinities.
941a37cdde0Sdanielk1977     */
942a37cdde0Sdanielk1977     if( !isView ){
94376d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
944a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
945a37cdde0Sdanielk1977     }
946c3f9bad2Sdanielk1977 
9475cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
948165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
94994d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
950165921a7Sdan 
95176d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
95270ce3f0cSdrh   }
953c3f9bad2Sdanielk1977 
954d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
955d82b5021Sdrh   ** registers beginning at regIns.
9561ccde15dSdrh   */
9575cf590c1Sdrh   if( !isView ){
9584cbdda9eSdrh     if( IsVirtual(pTab) ){
9594cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9606a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9614cbdda9eSdrh     }
962d82b5021Sdrh     if( ipkColumn>=0 ){
963142e30dfSdrh       if( useTempTable ){
964d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
965142e30dfSdrh       }else if( pSelect ){
966d82b5021Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid);
9674a32431cSdrh       }else{
968e4d90813Sdrh         VdbeOp *pOp;
969d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
97020411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9711b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
972e4d90813Sdrh           appendFlag = 1;
973e4d90813Sdrh           pOp->opcode = OP_NewRowid;
97426198bb4Sdrh           pOp->p1 = iDataCur;
9756a288a33Sdrh           pOp->p2 = regRowid;
9766a288a33Sdrh           pOp->p3 = regAutoinc;
977e4d90813Sdrh         }
97827a32783Sdrh       }
979f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
980e1e68f49Sdrh       ** to generate a unique primary key value.
981e1e68f49Sdrh       */
982e4d90813Sdrh       if( !appendFlag ){
9831db639ceSdrh         int j1;
984bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9851db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
98626198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
9871db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
988bb50e7adSdanielk1977         }else{
989bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
990bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
991bb50e7adSdanielk1977         }
9923c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
993e4d90813Sdrh       }
994ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9956a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9964a32431cSdrh     }else{
99726198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
998e4d90813Sdrh       appendFlag = 1;
9994a32431cSdrh     }
10006a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
10014a32431cSdrh 
1002d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
10034a32431cSdrh     ** with the first column.
10044a32431cSdrh     */
1005034ca14fSdanielk1977     nHidden = 0;
1006cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
10076a288a33Sdrh       int iRegStore = regRowid+1+i;
10084a32431cSdrh       if( i==pTab->iPKey ){
10094a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
1010d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
1011d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
1012aacc543eSdrh         ** taking up data space with information that will never be used. */
10134c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
10144a32431cSdrh         continue;
10154a32431cSdrh       }
1016967e8b73Sdrh       if( pColumn==0 ){
1017034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1018034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1019034ca14fSdanielk1977           j = -1;
1020034ca14fSdanielk1977           nHidden++;
1021034ca14fSdanielk1977         }else{
1022034ca14fSdanielk1977           j = i - nHidden;
1023034ca14fSdanielk1977         }
1024cce7d176Sdrh       }else{
1025967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1026967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1027cce7d176Sdrh         }
1028cce7d176Sdrh       }
1029034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1030287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1031142e30dfSdrh       }else if( useTempTable ){
1032287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1033142e30dfSdrh       }else if( pSelect ){
1034b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1035cce7d176Sdrh       }else{
1036287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1037cce7d176Sdrh       }
1038cce7d176Sdrh     }
10391ccde15dSdrh 
10400ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10410ca3e24bSdrh     ** do the insertion.
10424a32431cSdrh     */
10434cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10444cbdda9eSdrh     if( IsVirtual(pTab) ){
1045595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10464f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1047595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1048b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1049e0af83acSdan       sqlite3MayAbort(pParse);
10504cbdda9eSdrh     }else
10514cbdda9eSdrh #endif
10524cbdda9eSdrh     {
1053de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1054f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1055f8ffb278Sdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
105604adf416Sdrh       );
10578ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
105826198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
105926198bb4Sdrh                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
10605cf590c1Sdrh     }
10614cbdda9eSdrh   }
10621bee3d7bSdrh 
1063feeb1394Sdrh   /* Update the count of rows that are inserted
10641bee3d7bSdrh   */
1065142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10666a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10671bee3d7bSdrh   }
1068c3f9bad2Sdanielk1977 
10692f886d1dSdanielk1977   if( pTrigger ){
1070c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1071165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
107294d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1073c3f9bad2Sdanielk1977   }
10741bee3d7bSdrh 
1075e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1076e00ee6ebSdrh   ** is a SELECT statement.
10771ccde15dSdrh   */
10784adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1079142e30dfSdrh   if( useTempTable ){
1080e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1081e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10822eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1083142e30dfSdrh   }else if( pSelect ){
1084e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1085e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10866b56344dSdrh   }
1087c3f9bad2Sdanielk1977 
1088e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1089c3f9bad2Sdanielk1977     /* Close all tables opened */
109026198bb4Sdrh     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
109126198bb4Sdrh     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
109226198bb4Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
1093cce7d176Sdrh     }
1094c3f9bad2Sdanielk1977   }
1095c3f9bad2Sdanielk1977 
10960b9f50d8Sdrh insert_end:
1097f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10980b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10990b9f50d8Sdrh   ** autoincrement tables.
11002958a4e6Sdrh   */
1101165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
11020b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
11030b9f50d8Sdrh   }
11042958a4e6Sdrh 
11051bee3d7bSdrh   /*
1106e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1107e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1108e7de6f25Sdanielk1977   ** invoke the callback function.
11091bee3d7bSdrh   */
1110165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
11116a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
111222322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
111310fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11141bee3d7bSdrh   }
1115cce7d176Sdrh 
1116cce7d176Sdrh insert_cleanup:
1117633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1118633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1119633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1120633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1121633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1122cce7d176Sdrh }
11239cfcf5d4Sdrh 
112475cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
112575cbd984Sdan ** thely may interfere with compilation of other functions in this file
112675cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
112775cbd984Sdan #ifdef isView
112875cbd984Sdan  #undef isView
112975cbd984Sdan #endif
113075cbd984Sdan #ifdef pTrigger
113175cbd984Sdan  #undef pTrigger
113275cbd984Sdan #endif
113375cbd984Sdan #ifdef tmask
113475cbd984Sdan  #undef tmask
113575cbd984Sdan #endif
113675cbd984Sdan 
113711e85273Sdrh /*
11386934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
11396934fc7bSdrh ** on table pTab.
11409cfcf5d4Sdrh **
11416934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
11426934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
11436934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
11446934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
11456934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
11466934fc7bSdrh ** contain the content of the first table column.  The third register will
11476934fc7bSdrh ** contain the content of the second table column.  And so forth.
11480ca3e24bSdrh **
1149f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1150f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1151f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1152f8ffb278Sdrh ** checking regOldData for zero.
11530ca3e24bSdrh **
1154f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1155f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1156f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1157f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1158f8ffb278Sdrh **
1159f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1160f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1161f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1162f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1163f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1164f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
11650ca3e24bSdrh **
11666934fc7bSdrh ** The code generated by this routine will store new index entries into
1167aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1168aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1169aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
11706934fc7bSdrh ** at pTab->pIndex.
11716934fc7bSdrh **
11726934fc7bSdrh ** The caller must have already opened writeable cursors on the main
11736934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
11746934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
11756934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
11766934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
11776934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
11786934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
11799cfcf5d4Sdrh **
11809cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11819cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11821c92853dSdrh ** then the appropriate action is performed.  There are five possible
11831c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11849cfcf5d4Sdrh **
11859cfcf5d4Sdrh **  Constraint type  Action       What Happens
11869cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11871c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
11886934fc7bSdrh **                                sqlite3_step() returns immediately with a
11899cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11909cfcf5d4Sdrh **
11911c92853dSdrh **  any              ABORT        Back out changes from the current command
11921c92853dSdrh **                                only (do not do a complete rollback) then
11936934fc7bSdrh **                                cause sqlite3_step() to return immediately
11941c92853dSdrh **                                with SQLITE_CONSTRAINT.
11951c92853dSdrh **
11966934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
11971c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11981c92853dSdrh **                                transaction is not rolled back and any
11996934fc7bSdrh **                                changes to prior rows are retained.
12001c92853dSdrh **
12016934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
12026934fc7bSdrh **                                row is skipped, without throwing an error.
12036934fc7bSdrh **                                Processing continues with the next row.
12046934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
12059cfcf5d4Sdrh **
12069cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
12079cfcf5d4Sdrh **                                value for that column.  If the default value
12089cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
12099cfcf5d4Sdrh **
12109cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
12119cfcf5d4Sdrh **                                being inserted is removed.
12129cfcf5d4Sdrh **
12139cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12149cfcf5d4Sdrh **
12151c92853dSdrh ** Which action to take is determined by the overrideError parameter.
12161c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12171c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12181c92853dSdrh ** for the constraint is used.
12199cfcf5d4Sdrh */
12204adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12219cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
12226934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1223f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
12246934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
122526198bb4Sdrh   int iIdxCur,         /* First index cursor */
12266934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1227f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1228f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1229f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1230de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1231de630353Sdanielk1977   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
12329cfcf5d4Sdrh ){
12331b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
12341b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
123511e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
12362938f924Sdrh   sqlite3 *db;         /* Database connection */
1237f8ffb278Sdrh   int i;               /* loop counter */
1238f8ffb278Sdrh   int ix;              /* Index loop counter */
1239f8ffb278Sdrh   int nCol;            /* Number of columns */
1240f8ffb278Sdrh   int onError;         /* Conflict resolution strategy */
1241f8ffb278Sdrh   int j1;              /* Addresss of jump instruction */
12421b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
12436fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
12448d1b82e4Sdrh   int ipkTop = 0;      /* Top of the rowid change constraint check */
12458d1b82e4Sdrh   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
12468d1b82e4Sdrh   u8 isUpdate;         /* True if this is an UPDATE operation */
12475426d809Sdrh   int regRowid = -1;   /* Register holding ROWID value */
12489cfcf5d4Sdrh 
1249f8ffb278Sdrh   isUpdate = regOldData!=0;
12502938f924Sdrh   db = pParse->db;
12514adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12529cfcf5d4Sdrh   assert( v!=0 );
1253417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12549cfcf5d4Sdrh   nCol = pTab->nCol;
1255aa9b8963Sdrh 
12566934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
12576934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
12586934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
12596934fc7bSdrh   ** number of fields in the true primary key of the table. */
126026198bb4Sdrh   if( HasRowid(pTab) ){
126126198bb4Sdrh     pPk = 0;
126226198bb4Sdrh     nPkField = 1;
126326198bb4Sdrh   }else{
126426198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
126526198bb4Sdrh     nPkField = pPk->nKeyCol;
126626198bb4Sdrh   }
12676fbe41acSdrh 
12686fbe41acSdrh   /* Record that this module has started */
12696fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
12706934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
127111e85273Sdrh 
12729cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12739cfcf5d4Sdrh   */
12749cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12750ca3e24bSdrh     if( i==pTab->iPKey ){
12760ca3e24bSdrh       continue;
12770ca3e24bSdrh     }
12789cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12790ca3e24bSdrh     if( onError==OE_None ) continue;
12809cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12819cfcf5d4Sdrh       onError = overrideError;
1282a996e477Sdrh     }else if( onError==OE_Default ){
1283a996e477Sdrh       onError = OE_Abort;
12849cfcf5d4Sdrh     }
12857977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12869cfcf5d4Sdrh       onError = OE_Abort;
12879cfcf5d4Sdrh     }
1288b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1289b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12909cfcf5d4Sdrh     switch( onError ){
12911c92853dSdrh       case OE_Abort:
1292e0af83acSdan         sqlite3MayAbort(pParse);
12930978d4ffSdrh         /* Fall through */
1294e0af83acSdan       case OE_Rollback:
12951c92853dSdrh       case OE_Fail: {
1296f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1297f9c8ce3cSdrh                                     pTab->aCol[i].zName);
1298f9c8ce3cSdrh         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1299f9c8ce3cSdrh                           regNewData+1+i, zMsg, P4_DYNAMIC);
1300f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
13019cfcf5d4Sdrh         break;
13029cfcf5d4Sdrh       }
13039cfcf5d4Sdrh       case OE_Ignore: {
13046934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
13059cfcf5d4Sdrh         break;
13069cfcf5d4Sdrh       }
1307098d1684Sdrh       default: {
1308098d1684Sdrh         assert( onError==OE_Replace );
13096934fc7bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
13106934fc7bSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
13115053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
13129cfcf5d4Sdrh         break;
13139cfcf5d4Sdrh       }
13149cfcf5d4Sdrh     }
13159cfcf5d4Sdrh   }
13169cfcf5d4Sdrh 
13179cfcf5d4Sdrh   /* Test all CHECK constraints
13189cfcf5d4Sdrh   */
1319ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
13202938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
13212938f924Sdrh     ExprList *pCheck = pTab->pCheck;
13226934fc7bSdrh     pParse->ckBase = regNewData+1;
1323aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
13242938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
13252938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
13262d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
13272e06c67cSdrh       if( onError==OE_Ignore ){
132866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1329aa01c7e2Sdrh       }else{
1330f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1331f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
13326dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1333d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1334f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1335f9c8ce3cSdrh                               P5_ConstraintCheck);
1336aa01c7e2Sdrh       }
1337ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1338c31c7c1cSdrh     }
13392938f924Sdrh   }
1340ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13419cfcf5d4Sdrh 
1342f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1343f8ffb278Sdrh   ** exist in the table.
13449cfcf5d4Sdrh   */
13456fbe41acSdrh   if( pkChng && pPk==0 ){
134611e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
134711e85273Sdrh 
1348f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
13490ca3e24bSdrh     onError = pTab->keyConf;
13500ca3e24bSdrh     if( overrideError!=OE_Default ){
13510ca3e24bSdrh       onError = overrideError;
1352a996e477Sdrh     }else if( onError==OE_Default ){
1353a996e477Sdrh       onError = OE_Abort;
13540ca3e24bSdrh     }
1355a0217ba7Sdrh 
135679b0c956Sdrh     if( isUpdate ){
1357f8ffb278Sdrh       /* pkChng!=0 does not mean that the rowid has change, only that
1358f8ffb278Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1359f8ffb278Sdrh       ** is unchanged. */
13606934fc7bSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
136179b0c956Sdrh     }
1362f8ffb278Sdrh 
13638d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
13648d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
13658d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
13668d1b82e4Sdrh     ** the UNIQUE constraints have run.
13678d1b82e4Sdrh     */
13688d1b82e4Sdrh     if( onError==OE_Replace && overrideError!=OE_Replace ){
13698d1b82e4Sdrh       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
13708d1b82e4Sdrh         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
13718d1b82e4Sdrh           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
13728d1b82e4Sdrh           break;
13738d1b82e4Sdrh         }
13748d1b82e4Sdrh       }
13758d1b82e4Sdrh     }
13768d1b82e4Sdrh 
1377f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1378f8ffb278Sdrh     ** the following conflict logic if it does not. */
13796934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1380f8ffb278Sdrh 
1381f8ffb278Sdrh     /* Generate code that deals with a rowid collision */
13820ca3e24bSdrh     switch( onError ){
1383a0217ba7Sdrh       default: {
1384a0217ba7Sdrh         onError = OE_Abort;
1385a0217ba7Sdrh         /* Fall thru into the next case */
1386a0217ba7Sdrh       }
13871c92853dSdrh       case OE_Rollback:
13881c92853dSdrh       case OE_Abort:
13891c92853dSdrh       case OE_Fail: {
1390f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
13910ca3e24bSdrh         break;
13920ca3e24bSdrh       }
13935383ae5cSdrh       case OE_Replace: {
13942283d46cSdan         /* If there are DELETE triggers on this table and the
13952283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1396d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13972283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13982283d46cSdan         **
13992283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1400da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1401da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1402da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1403da730f6eSdan         ** when it is inserted.
1404da730f6eSdan         **
1405da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1406da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1407da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1408da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1409da730f6eSdan         ** but being more selective here allows statements like:
1410da730f6eSdan         **
1411da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1412da730f6eSdan         **
1413da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1414da730f6eSdan         ** table.
1415da730f6eSdan         */
14162283d46cSdan         Trigger *pTrigger = 0;
14172938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14182283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14192283d46cSdan         }
1420e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1421da730f6eSdan           sqlite3MultiWrite(pParse);
142226198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1423392ee21dSdrh                                    regNewData, 1, 0, OE_Replace, 1);
1424da730f6eSdan         }else if( pTab->pIndex ){
1425da730f6eSdan           sqlite3MultiWrite(pParse);
142626198bb4Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
14272283d46cSdan         }
14285383ae5cSdrh         seenReplace = 1;
14295383ae5cSdrh         break;
14305383ae5cSdrh       }
14310ca3e24bSdrh       case OE_Ignore: {
14328d1b82e4Sdrh         /*assert( seenReplace==0 );*/
143366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14340ca3e24bSdrh         break;
14350ca3e24bSdrh       }
14360ca3e24bSdrh     }
143711e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
14388d1b82e4Sdrh     if( ipkTop ){
14398d1b82e4Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
14408d1b82e4Sdrh       sqlite3VdbeJumpHere(v, ipkTop);
14418d1b82e4Sdrh     }
14420ca3e24bSdrh   }
14430bd1f4eaSdrh 
14440bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
14450bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
144611e85273Sdrh   ** Compute the revised record entries for indices as we go.
1447f8ffb278Sdrh   **
1448f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1449f8ffb278Sdrh   ** WITHOUT ROWID table.
14500bd1f4eaSdrh   */
145126198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
14526934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
14536934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
14546934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
14556934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
14562184fc75Sdrh 
145726198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
14586934fc7bSdrh     iThisCur = iIdxCur+ix;
14596934fc7bSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(v);
1460b2fe7d8cSdrh 
1461f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1462b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
146326198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
14646934fc7bSdrh       pParse->ckBase = regNewData+1;
146511e85273Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1466b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1467b2b9d3d7Sdrh       pParse->ckBase = 0;
1468b2b9d3d7Sdrh     }
1469b2b9d3d7Sdrh 
14706934fc7bSdrh     /* Create a record for this index entry as it should appear after
1471f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1472f8ffb278Sdrh     */
147311e85273Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
14749cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
14756934fc7bSdrh       int iField = pIdx->aiColumn[i];
1476f82b9afcSdrh       int x;
147726198bb4Sdrh       if( iField<0 || iField==pTab->iPKey ){
14785426d809Sdrh         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
1479f82b9afcSdrh         x = regNewData;
14805426d809Sdrh         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
14819cfcf5d4Sdrh       }else{
1482f82b9afcSdrh         x = iField + regNewData + 1;
14839cfcf5d4Sdrh       }
1484f82b9afcSdrh       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
1485f82b9afcSdrh       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
14869cfcf5d4Sdrh     }
148726198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
14888d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
148926198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
1490bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1491b2fe7d8cSdrh 
1492f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1493f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1494f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1495f8ffb278Sdrh     ** logic below can all be skipped. */
149600012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1497da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1498da475b8dSdrh       continue;
1499da475b8dSdrh     }
1500f8ffb278Sdrh 
15016934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
15029cfcf5d4Sdrh     onError = pIdx->onError;
1503de630353Sdanielk1977     if( onError==OE_None ){
150426198bb4Sdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
150511e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1506de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1507de630353Sdanielk1977     }
15089cfcf5d4Sdrh     if( overrideError!=OE_Default ){
15099cfcf5d4Sdrh       onError = overrideError;
1510a996e477Sdrh     }else if( onError==OE_Default ){
1511a996e477Sdrh       onError = OE_Abort;
15129cfcf5d4Sdrh     }
15135383ae5cSdrh 
1514b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
151526198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
15166f225d0dSdrh                          regIdx, pIdx->nKeyCol);
1517f8ffb278Sdrh 
1518f8ffb278Sdrh     /* Generate code to handle collisions */
1519392ee21dSdrh     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
152046d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
152111e85273Sdrh       if( HasRowid(pTab) ){
15226934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
15230978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
15240978d4ffSdrh         ** is different from old-rowid */
1525f8ffb278Sdrh         if( isUpdate ){
15266934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
1527f8ffb278Sdrh         }
152826198bb4Sdrh       }else{
1529ccc79f02Sdrh         int x;
153026198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
1531da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
1532a021f121Sdrh         if( pIdx!=pPk ){
153326198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
1534ccc79f02Sdrh             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
153526198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
153626198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
153726198bb4Sdrh                          pTab->aCol[pPk->aiColumn[i]].zName));
153826198bb4Sdrh           }
1539da475b8dSdrh         }
1540da475b8dSdrh         if( isUpdate ){
1541e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1542e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
1543e83267daSdan           ** different from the old.
1544e83267daSdan           **
1545e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1546e83267daSdan           ** of the matched index row are different from the original PRIMARY
1547e83267daSdan           ** KEY values of this row before the update.  */
1548e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1549e83267daSdan           int op = OP_Ne;
1550e83267daSdan           int regCmp = (pIdx->autoIndex==2 ? regIdx : regR);
1551e83267daSdan 
1552e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
1553e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1554ccc79f02Sdrh             x = pPk->aiColumn[i];
1555e83267daSdan             if( i==(pPk->nKeyCol-1) ){
1556e83267daSdan               addrJump = addrUniqueOk;
1557e83267daSdan               op = OP_Eq;
155811e85273Sdrh             }
1559e83267daSdan             sqlite3VdbeAddOp4(v, op,
1560e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1561e83267daSdan             );
1562da475b8dSdrh           }
156311e85273Sdrh         }
156426198bb4Sdrh       }
156546d03fcbSdrh     }
1566b2fe7d8cSdrh 
1567b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1568b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1569b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
15709cfcf5d4Sdrh     switch( onError ){
15711c92853dSdrh       case OE_Rollback:
15721c92853dSdrh       case OE_Abort:
15731c92853dSdrh       case OE_Fail: {
1574f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
15759cfcf5d4Sdrh         break;
15769cfcf5d4Sdrh       }
15779cfcf5d4Sdrh       case OE_Ignore: {
157866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
15799cfcf5d4Sdrh         break;
15809cfcf5d4Sdrh       }
1581098d1684Sdrh       default: {
15822283d46cSdan         Trigger *pTrigger = 0;
1583098d1684Sdrh         assert( onError==OE_Replace );
15841bea559aSdan         sqlite3MultiWrite(pParse);
15852938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15862283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15872283d46cSdan         }
158826198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1589392ee21dSdrh                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
15900ca3e24bSdrh         seenReplace = 1;
15919cfcf5d4Sdrh         break;
15929cfcf5d4Sdrh       }
15939cfcf5d4Sdrh     }
159411e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
1595392ee21dSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1596392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
15979cfcf5d4Sdrh   }
15988d1b82e4Sdrh   if( ipkTop ){
15998d1b82e4Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
16008d1b82e4Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
16018d1b82e4Sdrh   }
1602de630353Sdanielk1977 
1603de630353Sdanielk1977   *pbMayReplace = seenReplace;
1604ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
16059cfcf5d4Sdrh }
16060ca3e24bSdrh 
16070ca3e24bSdrh /*
16080ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
16094adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
16106934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
161104adf416Sdrh ** rowid and the content to be inserted.
16120ca3e24bSdrh **
1613b419a926Sdrh ** The arguments to this routine should be the same as the first six
16144adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
16150ca3e24bSdrh */
16164adee20fSdanielk1977 void sqlite3CompleteInsertion(
16170ca3e24bSdrh   Parse *pParse,      /* The parser context */
16180ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
161926198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
162026198bb4Sdrh   int iIdxCur,        /* First index cursor */
16216934fc7bSdrh   int regNewData,     /* Range of content */
1622aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
162370ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1624de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1625de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
16260ca3e24bSdrh ){
16276934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
16286934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
16296934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
16306934fc7bSdrh   int regData;        /* Content registers (after the rowid) */
16316934fc7bSdrh   int regRec;         /* Register holding assemblied record for the table */
16326934fc7bSdrh   int i;              /* Loop counter */
16330ca3e24bSdrh 
16344adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
16350ca3e24bSdrh   assert( v!=0 );
1636417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1637b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1638aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1639b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1640b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1641b2b9d3d7Sdrh     }
164226198bb4Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
16436546af14Sdrh     pik_flags = 0;
16446546af14Sdrh     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
16454308e348Sdrh     if( pIdx->autoIndex==2 && !HasRowid(pTab) ){
16464308e348Sdrh       assert( pParse->nested==0 );
16476546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1648de630353Sdanielk1977     }
16496546af14Sdrh     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
16500ca3e24bSdrh   }
1651ec95c441Sdrh   if( !HasRowid(pTab) ) return;
16526934fc7bSdrh   regData = regNewData + 1;
1653b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
16541db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1655a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1656da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
16574794f735Sdrh   if( pParse->nested ){
16584794f735Sdrh     pik_flags = 0;
16594794f735Sdrh   }else{
166094eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
166194eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
16624794f735Sdrh   }
1663e4d90813Sdrh   if( appendBias ){
1664e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1665e4d90813Sdrh   }
1666de630353Sdanielk1977   if( useSeekResult ){
1667de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1668de630353Sdanielk1977   }
16696934fc7bSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
167094eb6a14Sdanielk1977   if( !pParse->nested ){
16718d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
167294eb6a14Sdanielk1977   }
1673b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
16740ca3e24bSdrh }
1675cd44690aSdrh 
1676cd44690aSdrh /*
167726198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
167826198bb4Sdrh ** code to open and initialized those cursors.
1679aa9b8963Sdrh **
168026198bb4Sdrh ** The cursor for the object that contains the complete data (normally
168126198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
168226198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
168326198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
168426198bb4Sdrh **
168526198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
168626198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
168726198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
168826198bb4Sdrh **
168926198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
169026198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
169126198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
169226198bb4Sdrh ** pTab->pIndex list.
1693cd44690aSdrh */
1694aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1695290c1948Sdrh   Parse *pParse,   /* Parsing context */
1696290c1948Sdrh   Table *pTab,     /* Table to be opened */
169726198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
169826198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
16996a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
170026198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
170126198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
1702290c1948Sdrh ){
1703cd44690aSdrh   int i;
17044cbdda9eSdrh   int iDb;
17056a53499aSdrh   int iDataCur;
1706cd44690aSdrh   Index *pIdx;
17074cbdda9eSdrh   Vdbe *v;
17084cbdda9eSdrh 
170926198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
171026198bb4Sdrh   if( IsVirtual(pTab) ){
17116a53499aSdrh     assert( aToOpen==0 );
171226198bb4Sdrh     *piDataCur = 0;
171326198bb4Sdrh     *piIdxCur = 1;
171426198bb4Sdrh     return 0;
171526198bb4Sdrh   }
17164cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
17174cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1718cd44690aSdrh   assert( v!=0 );
171926198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
17206a53499aSdrh   iDataCur = iBase++;
17216a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
17226a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
17236a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
17246fbe41acSdrh   }else{
172526198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
17266fbe41acSdrh   }
17276a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
172826198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
172926198bb4Sdrh     int iIdxCur = iBase++;
1730da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
17316a53499aSdrh     if( pIdx->autoIndex==2 && !HasRowid(pTab) && piDataCur ){
17326a53499aSdrh       *piDataCur = iIdxCur;
17336a53499aSdrh     }
17346a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
17352ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
17362ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1737207872a4Sdanielk1977       VdbeComment((v, "%s", pIdx->zName));
1738cd44690aSdrh     }
17396a53499aSdrh   }
174026198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
174126198bb4Sdrh   return i;
1742cd44690aSdrh }
17439d9cf229Sdrh 
174491c58e23Sdrh 
174591c58e23Sdrh #ifdef SQLITE_TEST
174691c58e23Sdrh /*
174791c58e23Sdrh ** The following global variable is incremented whenever the
174891c58e23Sdrh ** transfer optimization is used.  This is used for testing
174991c58e23Sdrh ** purposes only - to make sure the transfer optimization really
175091c58e23Sdrh ** is happening when it is suppose to.
175191c58e23Sdrh */
175291c58e23Sdrh int sqlite3_xferopt_count;
175391c58e23Sdrh #endif /* SQLITE_TEST */
175491c58e23Sdrh 
175591c58e23Sdrh 
17569d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
17579d9cf229Sdrh /*
17589d9cf229Sdrh ** Check to collation names to see if they are compatible.
17599d9cf229Sdrh */
17609d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
17619d9cf229Sdrh   if( z1==0 ){
17629d9cf229Sdrh     return z2==0;
17639d9cf229Sdrh   }
17649d9cf229Sdrh   if( z2==0 ){
17659d9cf229Sdrh     return 0;
17669d9cf229Sdrh   }
17679d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
17689d9cf229Sdrh }
17699d9cf229Sdrh 
17709d9cf229Sdrh 
17719d9cf229Sdrh /*
17729d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
17739d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
17749d9cf229Sdrh ** for a compatible index:
17759d9cf229Sdrh **
17769d9cf229Sdrh **    *   The index is over the same set of columns
17779d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
17789d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
17799d9cf229Sdrh **    *   The same collating sequence on each column
1780b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
17819d9cf229Sdrh */
17829d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
17839d9cf229Sdrh   int i;
17849d9cf229Sdrh   assert( pDest && pSrc );
17859d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1786bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
17879d9cf229Sdrh     return 0;   /* Different number of columns */
17889d9cf229Sdrh   }
17899d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
17909d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
17919d9cf229Sdrh   }
1792bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
17939d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
17949d9cf229Sdrh       return 0;   /* Different columns indexed */
17959d9cf229Sdrh     }
17969d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
17979d9cf229Sdrh       return 0;   /* Different sort orders */
17989d9cf229Sdrh     }
17993f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
180060a713c6Sdrh       return 0;   /* Different collating sequences */
18019d9cf229Sdrh     }
18029d9cf229Sdrh   }
1803619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1804b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1805b2b9d3d7Sdrh   }
18069d9cf229Sdrh 
18079d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
18089d9cf229Sdrh   return 1;
18099d9cf229Sdrh }
18109d9cf229Sdrh 
18119d9cf229Sdrh /*
18129d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
18139d9cf229Sdrh **
18149d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
18159d9cf229Sdrh **
1816ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1817ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1818ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
18199d9cf229Sdrh **
1820ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1821ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1822ccdf1baeSdrh ** embedded in the code for details.
18239d9cf229Sdrh **
1824ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1825ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1826ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1827ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1828ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1829ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1830ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1831ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1832ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
18339d9cf229Sdrh **
1834ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
18359d9cf229Sdrh */
18369d9cf229Sdrh static int xferOptimization(
18379d9cf229Sdrh   Parse *pParse,        /* Parser context */
18389d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
18399d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
18409d9cf229Sdrh   int onError,          /* How to handle constraint errors */
18419d9cf229Sdrh   int iDbDest           /* The database of pDest */
18429d9cf229Sdrh ){
18439d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
18449d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
18459d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
18469d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
18479d9cf229Sdrh   int i;                           /* Loop counter */
18489d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
18499d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
18509d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
1851da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
1852da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
18539d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
18546a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1855f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1856b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
18579d9cf229Sdrh 
18589d9cf229Sdrh   if( pSelect==0 ){
18599d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
18609d9cf229Sdrh   }
1861*ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
1862*ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
1863*ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
1864*ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
1865*ebbf08a0Sdan     return 0;
1866*ebbf08a0Sdan   }
18672f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
18689d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
18699d9cf229Sdrh   }
18709d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18717d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
18729d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
18739d9cf229Sdrh   }
18749d9cf229Sdrh #endif
18759d9cf229Sdrh   if( onError==OE_Default ){
1876e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1877e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
18789d9cf229Sdrh   }
18795ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
18809d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
18819d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
18829d9cf229Sdrh   }
18839d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
18849d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
18859d9cf229Sdrh   }
18869d9cf229Sdrh   if( pSelect->pWhere ){
18879d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
18889d9cf229Sdrh   }
18899d9cf229Sdrh   if( pSelect->pOrderBy ){
18909d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
18919d9cf229Sdrh   }
18928103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
18938103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
18949d9cf229Sdrh   if( pSelect->pGroupBy ){
18959d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
18969d9cf229Sdrh   }
18979d9cf229Sdrh   if( pSelect->pLimit ){
18989d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
18999d9cf229Sdrh   }
19008103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
19019d9cf229Sdrh   if( pSelect->pPrior ){
19029d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
19039d9cf229Sdrh   }
19047d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
19059d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
19069d9cf229Sdrh   }
19079d9cf229Sdrh   pEList = pSelect->pEList;
19089d9cf229Sdrh   assert( pEList!=0 );
19099d9cf229Sdrh   if( pEList->nExpr!=1 ){
19109d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
19119d9cf229Sdrh   }
19129d9cf229Sdrh   assert( pEList->a[0].pExpr );
19139d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
19149d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
19159d9cf229Sdrh   }
19169d9cf229Sdrh 
19179d9cf229Sdrh   /* At this point we have established that the statement is of the
19189d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
19199d9cf229Sdrh   ** we have to check the semantics.
19209d9cf229Sdrh   */
19219d9cf229Sdrh   pItem = pSelect->pSrc->a;
192241fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
19239d9cf229Sdrh   if( pSrc==0 ){
19249d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
19259d9cf229Sdrh   }
19269d9cf229Sdrh   if( pSrc==pDest ){
19279d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
19289d9cf229Sdrh   }
192955548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
193055548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
193155548273Sdrh   }
19329d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
19337d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
19349d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
19359d9cf229Sdrh   }
19369d9cf229Sdrh #endif
19379d9cf229Sdrh   if( pSrc->pSelect ){
19389d9cf229Sdrh     return 0;   /* tab2 may not be a view */
19399d9cf229Sdrh   }
19409d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
19419d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
19429d9cf229Sdrh   }
19439d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
19449d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
19459d9cf229Sdrh   }
19469d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
19479d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
19489d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
19499d9cf229Sdrh     }
19509d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
19519d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
19529d9cf229Sdrh     }
19539d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
19549d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
19559d9cf229Sdrh     }
19569d9cf229Sdrh   }
19579d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1958f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1959f33c9fadSdrh       destHasUniqueIdx = 1;
1960f33c9fadSdrh     }
19619d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
19629d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19639d9cf229Sdrh     }
19649d9cf229Sdrh     if( pSrcIdx==0 ){
19659d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
19669d9cf229Sdrh     }
19679d9cf229Sdrh   }
19687fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1969619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
19708103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
19718103b7d2Sdrh   }
19727fc2f41bSdrh #endif
1973713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1974713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1975713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1976713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1977713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1978713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1979713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1980713de341Sdrh   */
1981713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1982713de341Sdrh     return 0;
1983713de341Sdrh   }
1984713de341Sdrh #endif
19851696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1986ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
19871696124dSdan   }
19889d9cf229Sdrh 
1989ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1990ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1991ccdf1baeSdrh   ** table (tab1) is initially empty.
19929d9cf229Sdrh   */
1993dd73521bSdrh #ifdef SQLITE_TEST
1994dd73521bSdrh   sqlite3_xferopt_count++;
1995dd73521bSdrh #endif
19969d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
19979d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1998f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
19999d9cf229Sdrh   iSrc = pParse->nTab++;
20009d9cf229Sdrh   iDest = pParse->nTab++;
20016a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
200255548273Sdrh   regData = sqlite3GetTempReg(pParse);
200355548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
20049d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2005427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
2006ccdf1baeSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
2007ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
2008ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
2009ccdf1baeSdrh   ){
2010ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
2011ccdf1baeSdrh     ** only if the destination table is initially empty.  This code makes
2012ccdf1baeSdrh     ** that determination.  Conditions under which the destination must
2013ccdf1baeSdrh     ** be empty:
2014f33c9fadSdrh     **
2015ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2016ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
2017ccdf1baeSdrh     **     of index entries might need to change.)
2018ccdf1baeSdrh     **
2019ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
2020ccdf1baeSdrh     **     is unable to test uniqueness.)
2021ccdf1baeSdrh     **
2022ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
20239d9cf229Sdrh     */
202466a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
202566a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
20269d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
20279d9cf229Sdrh   }
2028427ebba1Sdan   if( HasRowid(pSrc) ){
20299d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
203066a5167bSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
203142242dedSdrh     if( pDest->iPKey>=0 ){
2032b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2033b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2034f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
20359d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
2036b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
2037bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
2038b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
203995bad4c7Sdrh     }else{
2040b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
20417d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
204295bad4c7Sdrh     }
2043b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
2044b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
2045b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
20461f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
204766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
204855548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
204955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2050da475b8dSdrh   }else{
2051da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2052da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
205355548273Sdrh   }
20549d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
20551b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
20569d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
20579d9cf229Sdrh     }
20589d9cf229Sdrh     assert( pSrcIdx );
20592ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
20602ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2061d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
20622ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
20632ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
206459885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2065207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
206666a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
2067b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2068b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
206966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
20709d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
207155548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
207255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20739d9cf229Sdrh   }
20749d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
2075b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2076b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
20779d9cf229Sdrh   if( emptyDestTest ){
207866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
20799d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
208066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20819d9cf229Sdrh     return 0;
20829d9cf229Sdrh   }else{
20839d9cf229Sdrh     return 1;
20849d9cf229Sdrh   }
20859d9cf229Sdrh }
20869d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2087