xref: /sqlite-3.40.0/src/insert.c (revision e83267da)
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(
27bbb5e4e0Sdrh   Parse *p,       /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
35bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
37bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
38ec95c441Sdrh   if( HasRowid(pTab) ){
39261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
40dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
4126198bb4Sdrh   }else{
42dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
43dd9930efSdrh     assert( pPk!=0 );
44dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
45dd9930efSdrh     sqlite3VdbeAddOp4(v, opcode, iCur, pPk->tnum, iDb,
46dd9930efSdrh                       (char*)sqlite3IndexKeyinfo(p, pPk), P4_KEYINFO_HANDOFF);
47bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
48bbb5e4e0Sdrh   }
49ec95c441Sdrh }
50bbb5e4e0Sdrh 
51bbb5e4e0Sdrh /*
5269f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5369f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5469f8bb9cSdan ** the table, according to the affinity of the column:
553d1bfeaaSdanielk1977 **
563d1bfeaaSdanielk1977 **  Character      Column affinity
573d1bfeaaSdanielk1977 **  ------------------------------
583eda040bSdrh **  'a'            TEXT
593eda040bSdrh **  'b'            NONE
603eda040bSdrh **  'c'            NUMERIC
613eda040bSdrh **  'd'            INTEGER
623eda040bSdrh **  'e'            REAL
632d401ab8Sdrh **
640c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
652d401ab8Sdrh ** rowid that appears as the last column in every index.
6669f8bb9cSdan **
6769f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6869f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
6969f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
703d1bfeaaSdanielk1977 */
7169f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
72a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
73e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
74a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
75e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
76a37cdde0Sdanielk1977     **
77a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
78e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
79a37cdde0Sdanielk1977     ** up.
80a37cdde0Sdanielk1977     */
81a37cdde0Sdanielk1977     int n;
82a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
83abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
84ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
86633e6d57Sdrh       db->mallocFailed = 1;
8769f8bb9cSdan       return 0;
88a37cdde0Sdanielk1977     }
89ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
90ad124329Sdrh       i16 x = pIdx->aiColumn[n];
91ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
92a37cdde0Sdanielk1977     }
932d401ab8Sdrh     pIdx->zColAff[n] = 0;
94a37cdde0Sdanielk1977   }
953d1bfeaaSdanielk1977 
9669f8bb9cSdan   return pIdx->zColAff;
97a37cdde0Sdanielk1977 }
98a37cdde0Sdanielk1977 
99a37cdde0Sdanielk1977 /*
10066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
101a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
102a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
103a37cdde0Sdanielk1977 ** column:
104a37cdde0Sdanielk1977 **
105a37cdde0Sdanielk1977 **  Character      Column affinity
106a37cdde0Sdanielk1977 **  ------------------------------
1073eda040bSdrh **  'a'            TEXT
1083eda040bSdrh **  'b'            NONE
1093eda040bSdrh **  'c'            NUMERIC
1103eda040bSdrh **  'd'            INTEGER
1113eda040bSdrh **  'e'            REAL
112a37cdde0Sdanielk1977 */
113a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1143d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1153d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1163d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1173d1bfeaaSdanielk1977   **
1183d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1193d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1203d1bfeaaSdanielk1977   */
1213d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1223d1bfeaaSdanielk1977     char *zColAff;
1233d1bfeaaSdanielk1977     int i;
124abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1253d1bfeaaSdanielk1977 
126b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1273d1bfeaaSdanielk1977     if( !zColAff ){
128633e6d57Sdrh       db->mallocFailed = 1;
129a37cdde0Sdanielk1977       return;
1303d1bfeaaSdanielk1977     }
1313d1bfeaaSdanielk1977 
1323d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
133a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1343d1bfeaaSdanielk1977     }
1353d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1363d1bfeaaSdanielk1977 
1373d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1383d1bfeaaSdanielk1977   }
1393d1bfeaaSdanielk1977 
1408d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1413d1bfeaaSdanielk1977 }
1423d1bfeaaSdanielk1977 
1434d88778bSdanielk1977 /*
14448d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
14548d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
14648d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
14748d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
14848d1178aSdrh ** run without using temporary table for the results of the SELECT.
1494d88778bSdanielk1977 */
150595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
151595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1524d88778bSdanielk1977   int i;
15348d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
154595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
155595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
156595a523aSdanielk1977 #endif
157595a523aSdanielk1977 
15848d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
15948d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
160ef0bea92Sdrh     assert( pOp!=0 );
161207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16248d1178aSdrh       Index *pIndex;
163207872a4Sdanielk1977       int tnum = pOp->p2;
16448d1178aSdrh       if( tnum==pTab->tnum ){
16548d1178aSdrh         return 1;
16648d1178aSdrh       }
16748d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
16848d1178aSdrh         if( tnum==pIndex->tnum ){
16948d1178aSdrh           return 1;
17048d1178aSdrh         }
17148d1178aSdrh       }
17248d1178aSdrh     }
173543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
174595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1752dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
17666a5167bSdrh       assert( pOp->p4type==P4_VTAB );
17748d1178aSdrh       return 1;
1784d88778bSdanielk1977     }
179543165efSdrh #endif
1804d88778bSdanielk1977   }
1814d88778bSdanielk1977   return 0;
1824d88778bSdanielk1977 }
1833d1bfeaaSdanielk1977 
1849d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1859d9cf229Sdrh /*
1860b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1870b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1880b9f50d8Sdrh ** that holds the maximum rowid.
1899d9cf229Sdrh **
1900b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1910b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1920b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1930b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1940b9f50d8Sdrh ** AutoincInfo structure is used.
1959d9cf229Sdrh **
1960b9f50d8Sdrh ** Three memory locations are allocated:
1970b9f50d8Sdrh **
1980b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
1990b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2000b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2010b9f50d8Sdrh **
2020b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2030b9f50d8Sdrh ** insert routine needs to know about.
2049d9cf229Sdrh */
2059d9cf229Sdrh static int autoIncBegin(
2069d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2079d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2089d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2099d9cf229Sdrh ){
2106a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2117d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21265a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2130b9f50d8Sdrh     AutoincInfo *pInfo;
2140b9f50d8Sdrh 
21565a7cd16Sdan     pInfo = pToplevel->pAinc;
2160b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2170b9f50d8Sdrh     if( pInfo==0 ){
2180b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2190b9f50d8Sdrh       if( pInfo==0 ) return 0;
22065a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22165a7cd16Sdan       pToplevel->pAinc = pInfo;
2220b9f50d8Sdrh       pInfo->pTab = pTab;
2230b9f50d8Sdrh       pInfo->iDb = iDb;
22465a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
22565a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
22665a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2270b9f50d8Sdrh     }
2280b9f50d8Sdrh     memId = pInfo->regCtr;
2299d9cf229Sdrh   }
2309d9cf229Sdrh   return memId;
2319d9cf229Sdrh }
2329d9cf229Sdrh 
2339d9cf229Sdrh /*
2340b9f50d8Sdrh ** This routine generates code that will initialize all of the
2350b9f50d8Sdrh ** register used by the autoincrement tracker.
2360b9f50d8Sdrh */
2370b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2380b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2390b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2400b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2410b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2420b9f50d8Sdrh   int addr;                  /* A VDBE address */
2430b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2440b9f50d8Sdrh 
245345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
246345ba7dbSdrh   ** only called from the top-level */
247345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
248345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
24976d462eeSdan 
2500b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2510b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2520b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2530b9f50d8Sdrh     memId = p->regCtr;
2542120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2550b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
256f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2570b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2580b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2590b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2600b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2610b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2620b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2630b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2640b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2650b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2660b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2670b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2680b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2690b9f50d8Sdrh   }
2700b9f50d8Sdrh }
2710b9f50d8Sdrh 
2720b9f50d8Sdrh /*
2739d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2749d9cf229Sdrh **
2759d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2769d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2779d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2789d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2799d9cf229Sdrh */
2806a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2819d9cf229Sdrh   if( memId>0 ){
2826a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2839d9cf229Sdrh   }
2849d9cf229Sdrh }
2859d9cf229Sdrh 
2869d9cf229Sdrh /*
2870b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2880b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2890b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2900b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2910b9f50d8Sdrh ** routine just before the "exit" code.
2929d9cf229Sdrh */
2930b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2940b9f50d8Sdrh   AutoincInfo *p;
2959d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2960b9f50d8Sdrh   sqlite3 *db = pParse->db;
2976a288a33Sdrh 
2989d9cf229Sdrh   assert( v );
2990b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3000b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3010b9f50d8Sdrh     int j1, j2, j3, j4, j5;
3020b9f50d8Sdrh     int iRec;
3030b9f50d8Sdrh     int memId = p->regCtr;
3040b9f50d8Sdrh 
3050b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3062120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3070b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
3086a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
3090b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
3100b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
3110b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3120b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3130b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3140b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3150b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3160b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3170b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3186a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3190b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
320a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3210b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
32235573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3230b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3240b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3259d9cf229Sdrh   }
3269d9cf229Sdrh }
3279d9cf229Sdrh #else
3289d9cf229Sdrh /*
3299d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3309d9cf229Sdrh ** above are all no-ops
3319d9cf229Sdrh */
3329d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
333287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3349d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3359d9cf229Sdrh 
3369d9cf229Sdrh 
3375f085269Sdrh /*
3385f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3395f085269Sdrh ** row at a time.
3405f085269Sdrh **
3415f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3425f085269Sdrh ** Information about the location of co-routine and the registers it will use
3435f085269Sdrh ** is returned by filling in the pDest object.
3445f085269Sdrh **
3455f085269Sdrh ** Registers are allocated as follows:
3465f085269Sdrh **
3475f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3485f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3495f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3505f085269Sdrh **
3515f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3525f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3535f085269Sdrh **                       generated a new result row, or 1 if the subquery
3545f085269Sdrh **                       has completed.  If the Yield is called again
3555f085269Sdrh **                       after this register becomes 1, then the VDBE will
3565f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3575f085269Sdrh **
3585f085269Sdrh **   pDest->iSdst        First result register.
3595f085269Sdrh **
3605f085269Sdrh **   pDest->nSdst        Number of result registers.
3615f085269Sdrh **
3625f085269Sdrh ** This routine handles all of the register allocation and fills in the
3635f085269Sdrh ** pDest structure appropriately.
3645f085269Sdrh **
3655f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3665f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3675f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3685f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3695f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3705f085269Sdrh **
3715f085269Sdrh **         X <- A
3725f085269Sdrh **         EOF <- 0
3735f085269Sdrh **         goto B
3745f085269Sdrh **      A: setup for the SELECT
3755f085269Sdrh **         loop rows in the SELECT
3765f085269Sdrh **           load results into registers R..S
3775f085269Sdrh **           yield X
3785f085269Sdrh **         end loop
3795f085269Sdrh **         cleanup after the SELECT
3805f085269Sdrh **         EOF <- 1
3815f085269Sdrh **         yield X
3825f085269Sdrh **         halt-error
3835f085269Sdrh **      B:
3845f085269Sdrh **
3855f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3865f085269Sdrh **
3875f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3885f085269Sdrh **      S: yield X
3895f085269Sdrh **         if EOF goto E
3905f085269Sdrh **         if skip this row, goto C
3915f085269Sdrh **         if terminate loop, goto E
3925f085269Sdrh **         deal with this row
3935f085269Sdrh **      C: goto S
3945f085269Sdrh **      E:
3955f085269Sdrh */
3965f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3975f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3985f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
3995f085269Sdrh   int addrTop;        /* Top of the co-routine */
4005f085269Sdrh   int j1;             /* Jump instruction */
4015f085269Sdrh   int rc;             /* Result code */
4025f085269Sdrh   Vdbe *v;            /* VDBE under construction */
4035f085269Sdrh 
4045f085269Sdrh   regYield = ++pParse->nMem;
4055f085269Sdrh   regEof = ++pParse->nMem;
4065f085269Sdrh   v = sqlite3GetVdbe(pParse);
4075f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
4085f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
4095f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
4105f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
4115f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4125f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4135f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4145f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4155f085269Sdrh   assert( pParse->nErr==0 || rc );
4165f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4175f085269Sdrh   if( rc ) return rc;
4185f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4195f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4205f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4215f085269Sdrh   VdbeComment((v, "End of coroutine"));
4225f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4235f085269Sdrh   return rc;
4245f085269Sdrh }
4255f085269Sdrh 
4265f085269Sdrh 
4275f085269Sdrh 
4289d9cf229Sdrh /* Forward declaration */
4299d9cf229Sdrh static int xferOptimization(
4309d9cf229Sdrh   Parse *pParse,        /* Parser context */
4319d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4329d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4339d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4349d9cf229Sdrh   int iDbDest           /* The database of pDest */
4359d9cf229Sdrh );
4369d9cf229Sdrh 
4373d1bfeaaSdanielk1977 /*
438d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
439cce7d176Sdrh **
440cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4411ccde15dSdrh **    insert into TABLE (IDLIST) select
442cce7d176Sdrh **
4431ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4441ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
445967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4461ccde15dSdrh **
4471ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4481ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4491ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4501ccde15dSdrh ** data for the insert.
451142e30dfSdrh **
4529d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
453d82b5021Sdrh ** insert with data coming from a VALUES clause, the code executes
454e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
455e00ee6ebSdrh ** the "1st template"):
456142e30dfSdrh **
457142e30dfSdrh **         open write cursor to <table> and its indices
458ec95c441Sdrh **         put VALUES clause expressions into registers
459142e30dfSdrh **         write the resulting record into <table>
460142e30dfSdrh **         cleanup
461142e30dfSdrh **
4629d9cf229Sdrh ** The three remaining templates assume the statement is of the form
463142e30dfSdrh **
464142e30dfSdrh **   INSERT INTO <table> SELECT ...
465142e30dfSdrh **
4669d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4679d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4689d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4699d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4709d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4719d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4729d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
473e00ee6ebSdrh ** template.  This is the 2nd template.
4749d9cf229Sdrh **
4759d9cf229Sdrh **         open a write cursor to <table>
4769d9cf229Sdrh **         open read cursor on <table2>
4779d9cf229Sdrh **         transfer all records in <table2> over to <table>
4789d9cf229Sdrh **         close cursors
4799d9cf229Sdrh **         foreach index on <table>
4809d9cf229Sdrh **           open a write cursor on the <table> index
4819d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4829d9cf229Sdrh **           transfer all records from the read to the write cursors
4839d9cf229Sdrh **           close cursors
4849d9cf229Sdrh **         end foreach
4859d9cf229Sdrh **
486e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4879d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4889d9cf229Sdrh ** The generated code follows this template:
489142e30dfSdrh **
490e00ee6ebSdrh **         EOF <- 0
491e00ee6ebSdrh **         X <- A
492142e30dfSdrh **         goto B
493142e30dfSdrh **      A: setup for the SELECT
4949d9cf229Sdrh **         loop over the rows in the SELECT
495e00ee6ebSdrh **           load values into registers R..R+n
496e00ee6ebSdrh **           yield X
497142e30dfSdrh **         end loop
498142e30dfSdrh **         cleanup after the SELECT
499e00ee6ebSdrh **         EOF <- 1
500e00ee6ebSdrh **         yield X
501142e30dfSdrh **         goto A
502e00ee6ebSdrh **      B: open write cursor to <table> and its indices
503e00ee6ebSdrh **      C: yield X
504e00ee6ebSdrh **         if EOF goto D
505e00ee6ebSdrh **         insert the select result into <table> from R..R+n
506e00ee6ebSdrh **         goto C
507142e30dfSdrh **      D: cleanup
508142e30dfSdrh **
509e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
510142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
511142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
512142e30dfSdrh ** we have to use a intermediate table to store the results of
513142e30dfSdrh ** the select.  The template is like this:
514142e30dfSdrh **
515e00ee6ebSdrh **         EOF <- 0
516e00ee6ebSdrh **         X <- A
517142e30dfSdrh **         goto B
518142e30dfSdrh **      A: setup for the SELECT
519142e30dfSdrh **         loop over the tables in the SELECT
520e00ee6ebSdrh **           load value into register R..R+n
521e00ee6ebSdrh **           yield X
522142e30dfSdrh **         end loop
523142e30dfSdrh **         cleanup after the SELECT
524e00ee6ebSdrh **         EOF <- 1
525e00ee6ebSdrh **         yield X
526e00ee6ebSdrh **         halt-error
527e00ee6ebSdrh **      B: open temp table
528e00ee6ebSdrh **      L: yield X
529e00ee6ebSdrh **         if EOF goto M
530e00ee6ebSdrh **         insert row from R..R+n into temp table
531e00ee6ebSdrh **         goto L
532e00ee6ebSdrh **      M: open write cursor to <table> and its indices
533e00ee6ebSdrh **         rewind temp table
534e00ee6ebSdrh **      C: loop over rows of intermediate table
535142e30dfSdrh **           transfer values form intermediate table into <table>
536e00ee6ebSdrh **         end loop
537e00ee6ebSdrh **      D: cleanup
538cce7d176Sdrh */
5394adee20fSdanielk1977 void sqlite3Insert(
540cce7d176Sdrh   Parse *pParse,        /* Parser context */
541113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
542cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5435974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5449cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5459cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
546cce7d176Sdrh ){
5476a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5486a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
549113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
550e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5515974a30fSdrh   int i, j, idx;        /* Loop counters */
5525974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5535974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
554967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5556a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
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 */
570cce7d176Sdrh 
5716a288a33Sdrh   /* Register allocations */
5721bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5736a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5746a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5756a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5766a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5776a288a33Sdrh   int regData;          /* register holding first column to insert */
5781bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
579aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5806a288a33Sdrh 
581798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
582798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5832f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5842f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
585798da52cSdrh #endif
586c3f9bad2Sdanielk1977 
58717435752Sdrh   db = pParse->db;
5881bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
58917435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5906f7adc8aSdrh     goto insert_cleanup;
5916f7adc8aSdrh   }
592daffd0e5Sdrh 
5931ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5941ccde15dSdrh   */
595113088ecSdrh   assert( pTabList->nSrc==1 );
596113088ecSdrh   zTab = pTabList->a[0].zName;
597098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5984adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
599c3f9bad2Sdanielk1977   if( pTab==0 ){
600c3f9bad2Sdanielk1977     goto insert_cleanup;
601c3f9bad2Sdanielk1977   }
602da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
603da184236Sdanielk1977   assert( iDb<db->nDb );
604da184236Sdanielk1977   pDb = &db->aDb[iDb];
6052958a4e6Sdrh   zDb = pDb->zName;
6064adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
6071962bda7Sdrh     goto insert_cleanup;
6081962bda7Sdrh   }
609ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
610c3f9bad2Sdanielk1977 
611b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
612b7f9164eSdrh   ** inserted into is a view
613b7f9164eSdrh   */
614b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6152f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
616b7f9164eSdrh   isView = pTab->pSelect!=0;
617b7f9164eSdrh #else
6182f886d1dSdanielk1977 # define pTrigger 0
6192f886d1dSdanielk1977 # define tmask 0
620b7f9164eSdrh # define isView 0
621b7f9164eSdrh #endif
622b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
623b7f9164eSdrh # undef isView
624b7f9164eSdrh # define isView 0
625b7f9164eSdrh #endif
6262f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
627b7f9164eSdrh 
628f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
629d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
630f573c99bSdrh   */
631b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
632f573c99bSdrh     goto insert_cleanup;
633f573c99bSdrh   }
634f573c99bSdrh 
635d82b5021Sdrh   /* Cannot insert into a read-only table.
636595a523aSdanielk1977   */
637595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
638595a523aSdanielk1977     goto insert_cleanup;
639595a523aSdanielk1977   }
640595a523aSdanielk1977 
6411ccde15dSdrh   /* Allocate a VDBE
6421ccde15dSdrh   */
6434adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6445974a30fSdrh   if( v==0 ) goto insert_cleanup;
6454794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6462f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6471ccde15dSdrh 
6489d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6499d9cf229Sdrh   /* If the statement is of the form
6509d9cf229Sdrh   **
6519d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6529d9cf229Sdrh   **
6539d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6549d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
655e00ee6ebSdrh   **
656e00ee6ebSdrh   ** This is the 2nd template.
6579d9cf229Sdrh   */
6589d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6592f886d1dSdanielk1977     assert( !pTrigger );
6609d9cf229Sdrh     assert( pList==0 );
6610b9f50d8Sdrh     goto insert_end;
6629d9cf229Sdrh   }
6639d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6649d9cf229Sdrh 
6652958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6666a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6672958a4e6Sdrh   */
6686a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6692958a4e6Sdrh 
6701ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
671e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
672e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
673e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6741ccde15dSdrh   */
6755974a30fSdrh   if( pSelect ){
676d82b5021Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
6775f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6785f085269Sdrh     if( rc ) goto insert_cleanup;
6791013c932Sdrh 
6805f085269Sdrh     regEof = dest.iSDParm + 1;
6812b596da8Sdrh     regFromSelect = dest.iSdst;
6825974a30fSdrh     assert( pSelect->pEList );
683967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6842b596da8Sdrh     assert( dest.nSdst==nColumn );
685142e30dfSdrh 
686142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
687e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
688d82b5021Sdrh     ** FALSE if each output row of the SELECT can be written directly into
689e00ee6ebSdrh     ** the destination table (template 3).
690048c530cSdrh     **
691048c530cSdrh     ** A temp table must be used if the table being updated is also one
692048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
693048c530cSdrh     ** temp table in the case of row triggers.
694142e30dfSdrh     */
695595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
696048c530cSdrh       useTempTable = 1;
697048c530cSdrh     }
698142e30dfSdrh 
699142e30dfSdrh     if( useTempTable ){
700e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
701e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
702e00ee6ebSdrh       ** here is from the 4th template:
703e00ee6ebSdrh       **
704e00ee6ebSdrh       **      B: open temp table
705e00ee6ebSdrh       **      L: yield X
706e00ee6ebSdrh       **         if EOF goto M
707e00ee6ebSdrh       **         insert row from R..R+n into temp table
708e00ee6ebSdrh       **         goto L
709e00ee6ebSdrh       **      M: ...
710142e30dfSdrh       */
711e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
712dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
713e00ee6ebSdrh       int addrTop;         /* Label "L" */
714e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
715b7654111Sdrh 
716142e30dfSdrh       srcTab = pParse->nTab++;
717b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
718dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
719e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7202b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
721e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7221db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
723dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
724dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
725e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
726e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
727b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
728dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
729142e30dfSdrh     }
730142e30dfSdrh   }else{
731142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
732142e30dfSdrh     ** clause
733142e30dfSdrh     */
734b3bce662Sdanielk1977     NameContext sNC;
735b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
736b3bce662Sdanielk1977     sNC.pParse = pParse;
7375974a30fSdrh     srcTab = -1;
73848d1178aSdrh     assert( useTempTable==0 );
739147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
740e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7417d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
742b04a5d87Sdrh         goto insert_cleanup;
743b04a5d87Sdrh       }
744e64e7b20Sdrh     }
7455974a30fSdrh   }
7461ccde15dSdrh 
7471ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7481ccde15dSdrh   ** of columns to be inserted into the table.
7491ccde15dSdrh   */
750034ca14fSdanielk1977   if( IsVirtual(pTab) ){
751034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
752034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
753034ca14fSdanielk1977     }
754034ca14fSdanielk1977   }
755034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7564adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
757da93d238Sdrh        "table %S has %d columns but %d values were supplied",
758d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
759cce7d176Sdrh     goto insert_cleanup;
760cce7d176Sdrh   }
761967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7624adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
763cce7d176Sdrh     goto insert_cleanup;
764cce7d176Sdrh   }
7651ccde15dSdrh 
7661ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7671ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7681ccde15dSdrh   ** remember the column indices.
769c8392586Sdrh   **
770c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
771d82b5021Sdrh   ** is named in the IDLIST, then record in the ipkColumn variable
772d82b5021Sdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
773c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
774d82b5021Sdrh   ** is appears in the original table.  (The index of the INTEGER
775d82b5021Sdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
7761ccde15dSdrh   */
777967e8b73Sdrh   if( pColumn ){
778967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
779967e8b73Sdrh       pColumn->a[i].idx = -1;
780cce7d176Sdrh     }
781967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
782cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7834adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
784967e8b73Sdrh           pColumn->a[i].idx = j;
7854a32431cSdrh           if( j==pTab->iPKey ){
786d82b5021Sdrh             ipkColumn = i;  assert( !withoutRowid );
7874a32431cSdrh           }
788cce7d176Sdrh           break;
789cce7d176Sdrh         }
790cce7d176Sdrh       }
791cce7d176Sdrh       if( j>=pTab->nCol ){
792ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
793d82b5021Sdrh           ipkColumn = i;
794a0217ba7Sdrh         }else{
7954adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
796da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
7971db95106Sdan           pParse->checkSchema = 1;
798cce7d176Sdrh           goto insert_cleanup;
799cce7d176Sdrh         }
800cce7d176Sdrh       }
801cce7d176Sdrh     }
802a0217ba7Sdrh   }
8031ccde15dSdrh 
804aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
805d82b5021Sdrh   ** key, the set the ipkColumn variable to the integer primary key
806d82b5021Sdrh   ** column index in the original table definition.
8074a32431cSdrh   */
808147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
809d82b5021Sdrh     ipkColumn = pTab->iPKey;
8104a32431cSdrh   }
8114a32431cSdrh 
812c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8131ccde15dSdrh   */
814142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8156a288a33Sdrh     regRowCount = ++pParse->nMem;
8166a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
817c3f9bad2Sdanielk1977   }
818c3f9bad2Sdanielk1977 
819e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
820e448dc4aSdanielk1977   if( !isView ){
821aa9b8963Sdrh     int nIdx;
82226198bb4Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1,
82326198bb4Sdrh                                       &iDataCur, &iIdxCur);
8245c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
825aa9b8963Sdrh     if( aRegIdx==0 ){
826aa9b8963Sdrh       goto insert_cleanup;
827aa9b8963Sdrh     }
828aa9b8963Sdrh     for(i=0; i<nIdx; i++){
829aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
830aa9b8963Sdrh     }
831feeb1394Sdrh   }
832feeb1394Sdrh 
833e00ee6ebSdrh   /* This is the top of the main insertion loop */
834142e30dfSdrh   if( useTempTable ){
835e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
836e00ee6ebSdrh     ** following pseudocode (template 4):
837e00ee6ebSdrh     **
838e00ee6ebSdrh     **         rewind temp table
839e00ee6ebSdrh     **      C: loop over rows of intermediate table
840e00ee6ebSdrh     **           transfer values form intermediate table into <table>
841e00ee6ebSdrh     **         end loop
842e00ee6ebSdrh     **      D: ...
843e00ee6ebSdrh     */
844e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
845e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
846142e30dfSdrh   }else if( pSelect ){
847e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
848e00ee6ebSdrh     ** following pseudocode (template 3):
849e00ee6ebSdrh     **
850e00ee6ebSdrh     **      C: yield X
851e00ee6ebSdrh     **         if EOF goto D
852e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
853e00ee6ebSdrh     **         goto C
854e00ee6ebSdrh     **      D: ...
855e00ee6ebSdrh     */
8562b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
857e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
858bed8690fSdrh   }
8591ccde15dSdrh 
8606a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8616a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8626a288a33Sdrh   */
8636a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8646a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8656a288a33Sdrh   if( IsVirtual(pTab) ){
8666a288a33Sdrh     regRowid++;
8676a288a33Sdrh     pParse->nMem++;
8686a288a33Sdrh   }
8696a288a33Sdrh   regData = regRowid+1;
8706a288a33Sdrh 
8715cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
87270ce3f0cSdrh   */
8734adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8742f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
87576d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
876c3f9bad2Sdanielk1977 
87770ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
87870ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
87970ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
88070ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
88170ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
88270ce3f0cSdrh     */
883d82b5021Sdrh     if( ipkColumn<0 ){
88476d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88570ce3f0cSdrh     }else{
8866a288a33Sdrh       int j1;
887ec95c441Sdrh       assert( !withoutRowid );
8887fe45908Sdrh       if( useTempTable ){
889d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
8907fe45908Sdrh       }else{
891d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
892d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
8937fe45908Sdrh       }
89476d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89576d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
8966a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
89776d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89870ce3f0cSdrh     }
89970ce3f0cSdrh 
900034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
901034ca14fSdanielk1977     ** this block would have to account for hidden column.
902034ca14fSdanielk1977     */
903034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
904034ca14fSdanielk1977 
90570ce3f0cSdrh     /* Create the new column data
90670ce3f0cSdrh     */
907c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
908c3f9bad2Sdanielk1977       if( pColumn==0 ){
909c3f9bad2Sdanielk1977         j = i;
910c3f9bad2Sdanielk1977       }else{
911c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
912c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
913c3f9bad2Sdanielk1977         }
914c3f9bad2Sdanielk1977       }
9157ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91676d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
917142e30dfSdrh       }else if( useTempTable ){
91876d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
919c3f9bad2Sdanielk1977       }else{
920d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
92176d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
922c3f9bad2Sdanielk1977       }
923c3f9bad2Sdanielk1977     }
924a37cdde0Sdanielk1977 
925a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
926a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
927a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
928a37cdde0Sdanielk1977     ** table column affinities.
929a37cdde0Sdanielk1977     */
930a37cdde0Sdanielk1977     if( !isView ){
93176d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
932a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
933a37cdde0Sdanielk1977     }
934c3f9bad2Sdanielk1977 
9355cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
936165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
93794d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
938165921a7Sdan 
93976d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
94070ce3f0cSdrh   }
941c3f9bad2Sdanielk1977 
942d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
943d82b5021Sdrh   ** registers beginning at regIns.
9441ccde15dSdrh   */
9455cf590c1Sdrh   if( !isView ){
9464cbdda9eSdrh     if( IsVirtual(pTab) ){
9474cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9486a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9494cbdda9eSdrh     }
950d82b5021Sdrh     if( ipkColumn>=0 ){
951142e30dfSdrh       if( useTempTable ){
952d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
953142e30dfSdrh       }else if( pSelect ){
954d82b5021Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid);
9554a32431cSdrh       }else{
956e4d90813Sdrh         VdbeOp *pOp;
957d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
95820411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9591b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
960e4d90813Sdrh           appendFlag = 1;
961e4d90813Sdrh           pOp->opcode = OP_NewRowid;
96226198bb4Sdrh           pOp->p1 = iDataCur;
9636a288a33Sdrh           pOp->p2 = regRowid;
9646a288a33Sdrh           pOp->p3 = regAutoinc;
965e4d90813Sdrh         }
96627a32783Sdrh       }
967f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
968e1e68f49Sdrh       ** to generate a unique primary key value.
969e1e68f49Sdrh       */
970e4d90813Sdrh       if( !appendFlag ){
9711db639ceSdrh         int j1;
972bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9731db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
97426198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
9751db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
976bb50e7adSdanielk1977         }else{
977bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
978bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
979bb50e7adSdanielk1977         }
9803c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
981e4d90813Sdrh       }
982ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9836a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9844a32431cSdrh     }else{
98526198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
986e4d90813Sdrh       appendFlag = 1;
9874a32431cSdrh     }
9886a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9894a32431cSdrh 
990d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
9914a32431cSdrh     ** with the first column.
9924a32431cSdrh     */
993034ca14fSdanielk1977     nHidden = 0;
994cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9956a288a33Sdrh       int iRegStore = regRowid+1+i;
9964a32431cSdrh       if( i==pTab->iPKey ){
9974a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
998d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
999d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
1000aacc543eSdrh         ** taking up data space with information that will never be used. */
10014c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
10024a32431cSdrh         continue;
10034a32431cSdrh       }
1004967e8b73Sdrh       if( pColumn==0 ){
1005034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1006034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1007034ca14fSdanielk1977           j = -1;
1008034ca14fSdanielk1977           nHidden++;
1009034ca14fSdanielk1977         }else{
1010034ca14fSdanielk1977           j = i - nHidden;
1011034ca14fSdanielk1977         }
1012cce7d176Sdrh       }else{
1013967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1014967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1015cce7d176Sdrh         }
1016cce7d176Sdrh       }
1017034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1018287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1019142e30dfSdrh       }else if( useTempTable ){
1020287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1021142e30dfSdrh       }else if( pSelect ){
1022b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1023cce7d176Sdrh       }else{
1024287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1025cce7d176Sdrh       }
1026cce7d176Sdrh     }
10271ccde15dSdrh 
10280ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10290ca3e24bSdrh     ** do the insertion.
10304a32431cSdrh     */
10314cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10324cbdda9eSdrh     if( IsVirtual(pTab) ){
1033595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10344f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1035595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1036b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1037e0af83acSdan       sqlite3MayAbort(pParse);
10384cbdda9eSdrh     }else
10394cbdda9eSdrh #endif
10404cbdda9eSdrh     {
1041de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1042f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1043f8ffb278Sdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
104404adf416Sdrh       );
10458ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
104626198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
104726198bb4Sdrh                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
10485cf590c1Sdrh     }
10494cbdda9eSdrh   }
10501bee3d7bSdrh 
1051feeb1394Sdrh   /* Update the count of rows that are inserted
10521bee3d7bSdrh   */
1053142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10546a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10551bee3d7bSdrh   }
1056c3f9bad2Sdanielk1977 
10572f886d1dSdanielk1977   if( pTrigger ){
1058c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1059165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
106094d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1061c3f9bad2Sdanielk1977   }
10621bee3d7bSdrh 
1063e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1064e00ee6ebSdrh   ** is a SELECT statement.
10651ccde15dSdrh   */
10664adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1067142e30dfSdrh   if( useTempTable ){
1068e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1069e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10702eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1071142e30dfSdrh   }else if( pSelect ){
1072e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1073e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10746b56344dSdrh   }
1075c3f9bad2Sdanielk1977 
1076e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1077c3f9bad2Sdanielk1977     /* Close all tables opened */
107826198bb4Sdrh     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
107926198bb4Sdrh     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
108026198bb4Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
1081cce7d176Sdrh     }
1082c3f9bad2Sdanielk1977   }
1083c3f9bad2Sdanielk1977 
10840b9f50d8Sdrh insert_end:
1085f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10860b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10870b9f50d8Sdrh   ** autoincrement tables.
10882958a4e6Sdrh   */
1089165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10900b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10910b9f50d8Sdrh   }
10922958a4e6Sdrh 
10931bee3d7bSdrh   /*
1094e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1095e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1096e7de6f25Sdanielk1977   ** invoke the callback function.
10971bee3d7bSdrh   */
1098165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
10996a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110022322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
110110fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
11021bee3d7bSdrh   }
1103cce7d176Sdrh 
1104cce7d176Sdrh insert_cleanup:
1105633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1106633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1107633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1108633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1109633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1110cce7d176Sdrh }
11119cfcf5d4Sdrh 
111275cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
111375cbd984Sdan ** thely may interfere with compilation of other functions in this file
111475cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
111575cbd984Sdan #ifdef isView
111675cbd984Sdan  #undef isView
111775cbd984Sdan #endif
111875cbd984Sdan #ifdef pTrigger
111975cbd984Sdan  #undef pTrigger
112075cbd984Sdan #endif
112175cbd984Sdan #ifdef tmask
112275cbd984Sdan  #undef tmask
112375cbd984Sdan #endif
112475cbd984Sdan 
112511e85273Sdrh /*
11266934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
11276934fc7bSdrh ** on table pTab.
11289cfcf5d4Sdrh **
11296934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
11306934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
11316934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
11326934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
11336934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
11346934fc7bSdrh ** contain the content of the first table column.  The third register will
11356934fc7bSdrh ** contain the content of the second table column.  And so forth.
11360ca3e24bSdrh **
1137f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1138f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1139f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1140f8ffb278Sdrh ** checking regOldData for zero.
11410ca3e24bSdrh **
1142f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1143f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1144f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1145f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1146f8ffb278Sdrh **
1147f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1148f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1149f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1150f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1151f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1152f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
11530ca3e24bSdrh **
11546934fc7bSdrh ** The code generated by this routine will store new index entries into
1155aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1156aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1157aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
11586934fc7bSdrh ** at pTab->pIndex.
11596934fc7bSdrh **
11606934fc7bSdrh ** The caller must have already opened writeable cursors on the main
11616934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
11626934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
11636934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
11646934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
11656934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
11666934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
11679cfcf5d4Sdrh **
11689cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11699cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11701c92853dSdrh ** then the appropriate action is performed.  There are five possible
11711c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11729cfcf5d4Sdrh **
11739cfcf5d4Sdrh **  Constraint type  Action       What Happens
11749cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11751c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
11766934fc7bSdrh **                                sqlite3_step() returns immediately with a
11779cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11789cfcf5d4Sdrh **
11791c92853dSdrh **  any              ABORT        Back out changes from the current command
11801c92853dSdrh **                                only (do not do a complete rollback) then
11816934fc7bSdrh **                                cause sqlite3_step() to return immediately
11821c92853dSdrh **                                with SQLITE_CONSTRAINT.
11831c92853dSdrh **
11846934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
11851c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11861c92853dSdrh **                                transaction is not rolled back and any
11876934fc7bSdrh **                                changes to prior rows are retained.
11881c92853dSdrh **
11896934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
11906934fc7bSdrh **                                row is skipped, without throwing an error.
11916934fc7bSdrh **                                Processing continues with the next row.
11926934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
11939cfcf5d4Sdrh **
11949cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11959cfcf5d4Sdrh **                                value for that column.  If the default value
11969cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11979cfcf5d4Sdrh **
11989cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
11999cfcf5d4Sdrh **                                being inserted is removed.
12009cfcf5d4Sdrh **
12019cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
12029cfcf5d4Sdrh **
12031c92853dSdrh ** Which action to take is determined by the overrideError parameter.
12041c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
12051c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
12061c92853dSdrh ** for the constraint is used.
12079cfcf5d4Sdrh */
12084adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
12099cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
12106934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1211f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
12126934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
121326198bb4Sdrh   int iIdxCur,         /* First index cursor */
12146934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1215f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1216f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1217f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1218de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1219de630353Sdanielk1977   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
12209cfcf5d4Sdrh ){
12211b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
12221b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
122311e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
12242938f924Sdrh   sqlite3 *db;         /* Database connection */
1225f8ffb278Sdrh   int i;               /* loop counter */
1226f8ffb278Sdrh   int ix;              /* Index loop counter */
1227f8ffb278Sdrh   int nCol;            /* Number of columns */
1228f8ffb278Sdrh   int onError;         /* Conflict resolution strategy */
1229f8ffb278Sdrh   int j1;              /* Addresss of jump instruction */
12301b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
12316fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1232f8ffb278Sdrh   u8 isUpdate;
12339cfcf5d4Sdrh 
1234f8ffb278Sdrh   isUpdate = regOldData!=0;
12352938f924Sdrh   db = pParse->db;
12364adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12379cfcf5d4Sdrh   assert( v!=0 );
1238417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12399cfcf5d4Sdrh   nCol = pTab->nCol;
1240aa9b8963Sdrh 
12416934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
12426934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
12436934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
12446934fc7bSdrh   ** number of fields in the true primary key of the table. */
124526198bb4Sdrh   if( HasRowid(pTab) ){
124626198bb4Sdrh     pPk = 0;
124726198bb4Sdrh     nPkField = 1;
124826198bb4Sdrh   }else{
124926198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
125026198bb4Sdrh     nPkField = pPk->nKeyCol;
125126198bb4Sdrh   }
12526fbe41acSdrh 
12536fbe41acSdrh   /* Record that this module has started */
12546fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
12556934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
125611e85273Sdrh 
12579cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12589cfcf5d4Sdrh   */
12599cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12600ca3e24bSdrh     if( i==pTab->iPKey ){
12610ca3e24bSdrh       continue;
12620ca3e24bSdrh     }
12639cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12640ca3e24bSdrh     if( onError==OE_None ) continue;
12659cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12669cfcf5d4Sdrh       onError = overrideError;
1267a996e477Sdrh     }else if( onError==OE_Default ){
1268a996e477Sdrh       onError = OE_Abort;
12699cfcf5d4Sdrh     }
12707977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12719cfcf5d4Sdrh       onError = OE_Abort;
12729cfcf5d4Sdrh     }
1273b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1274b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12759cfcf5d4Sdrh     switch( onError ){
12761c92853dSdrh       case OE_Abort:
1277e0af83acSdan         sqlite3MayAbort(pParse);
12780978d4ffSdrh         /* Fall through */
1279e0af83acSdan       case OE_Rollback:
12801c92853dSdrh       case OE_Fail: {
1281f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1282f9c8ce3cSdrh                                     pTab->aCol[i].zName);
1283f9c8ce3cSdrh         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1284f9c8ce3cSdrh                           regNewData+1+i, zMsg, P4_DYNAMIC);
1285f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
12869cfcf5d4Sdrh         break;
12879cfcf5d4Sdrh       }
12889cfcf5d4Sdrh       case OE_Ignore: {
12896934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
12909cfcf5d4Sdrh         break;
12919cfcf5d4Sdrh       }
1292098d1684Sdrh       default: {
1293098d1684Sdrh         assert( onError==OE_Replace );
12946934fc7bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
12956934fc7bSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
12965053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
12979cfcf5d4Sdrh         break;
12989cfcf5d4Sdrh       }
12999cfcf5d4Sdrh     }
13009cfcf5d4Sdrh   }
13019cfcf5d4Sdrh 
13029cfcf5d4Sdrh   /* Test all CHECK constraints
13039cfcf5d4Sdrh   */
1304ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
13052938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
13062938f924Sdrh     ExprList *pCheck = pTab->pCheck;
13076934fc7bSdrh     pParse->ckBase = regNewData+1;
1308aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
13092938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
13102938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
13112d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
13122e06c67cSdrh       if( onError==OE_Ignore ){
131366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1314aa01c7e2Sdrh       }else{
1315f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1316f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
13176dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1318d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1319f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1320f9c8ce3cSdrh                               P5_ConstraintCheck);
1321aa01c7e2Sdrh       }
1322ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1323c31c7c1cSdrh     }
13242938f924Sdrh   }
1325ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13269cfcf5d4Sdrh 
1327f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1328f8ffb278Sdrh   ** exist in the table.
13299cfcf5d4Sdrh   */
13306fbe41acSdrh   if( pkChng && pPk==0 ){
133111e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
133211e85273Sdrh 
1333f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
13340ca3e24bSdrh     onError = pTab->keyConf;
13350ca3e24bSdrh     if( overrideError!=OE_Default ){
13360ca3e24bSdrh       onError = overrideError;
1337a996e477Sdrh     }else if( onError==OE_Default ){
1338a996e477Sdrh       onError = OE_Abort;
13390ca3e24bSdrh     }
1340a0217ba7Sdrh 
134179b0c956Sdrh     if( isUpdate ){
1342f8ffb278Sdrh       /* pkChng!=0 does not mean that the rowid has change, only that
1343f8ffb278Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1344f8ffb278Sdrh       ** is unchanged. */
13456934fc7bSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
134679b0c956Sdrh     }
1347f8ffb278Sdrh 
1348f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1349f8ffb278Sdrh     ** the following conflict logic if it does not. */
13506934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1351f8ffb278Sdrh 
1352f8ffb278Sdrh     /* Generate code that deals with a rowid collision */
13530ca3e24bSdrh     switch( onError ){
1354a0217ba7Sdrh       default: {
1355a0217ba7Sdrh         onError = OE_Abort;
1356a0217ba7Sdrh         /* Fall thru into the next case */
1357a0217ba7Sdrh       }
13581c92853dSdrh       case OE_Rollback:
13591c92853dSdrh       case OE_Abort:
13601c92853dSdrh       case OE_Fail: {
1361f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
13620ca3e24bSdrh         break;
13630ca3e24bSdrh       }
13645383ae5cSdrh       case OE_Replace: {
13652283d46cSdan         /* If there are DELETE triggers on this table and the
13662283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1367d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13682283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13692283d46cSdan         **
13702283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1371da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1372da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1373da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1374da730f6eSdan         ** when it is inserted.
1375da730f6eSdan         **
1376da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1377da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1378da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1379da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1380da730f6eSdan         ** but being more selective here allows statements like:
1381da730f6eSdan         **
1382da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1383da730f6eSdan         **
1384da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1385da730f6eSdan         ** table.
1386da730f6eSdan         */
13872283d46cSdan         Trigger *pTrigger = 0;
13882938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
13892283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
13902283d46cSdan         }
1391e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1392da730f6eSdan           sqlite3MultiWrite(pParse);
139326198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
13946934fc7bSdrh                                    regNewData, 1, 0, OE_Replace);
1395da730f6eSdan         }else if( pTab->pIndex ){
1396da730f6eSdan           sqlite3MultiWrite(pParse);
139726198bb4Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
13982283d46cSdan         }
13995383ae5cSdrh         seenReplace = 1;
14005383ae5cSdrh         break;
14015383ae5cSdrh       }
14020ca3e24bSdrh       case OE_Ignore: {
14035383ae5cSdrh         assert( seenReplace==0 );
140466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14050ca3e24bSdrh         break;
14060ca3e24bSdrh       }
14070ca3e24bSdrh     }
140811e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
14090ca3e24bSdrh   }
14100bd1f4eaSdrh 
14110bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
14120bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
141311e85273Sdrh   ** Compute the revised record entries for indices as we go.
1414f8ffb278Sdrh   **
1415f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1416f8ffb278Sdrh   ** WITHOUT ROWID table.
14170bd1f4eaSdrh   */
141826198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
14196934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
14206934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
14216934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
14226934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
14232184fc75Sdrh 
142426198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
14256934fc7bSdrh     iThisCur = iIdxCur+ix;
14266934fc7bSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(v);
1427b2fe7d8cSdrh 
1428f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1429b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
143026198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
14316934fc7bSdrh       pParse->ckBase = regNewData+1;
143211e85273Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1433b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1434b2b9d3d7Sdrh       pParse->ckBase = 0;
1435b2b9d3d7Sdrh     }
1436b2b9d3d7Sdrh 
14376934fc7bSdrh     /* Create a record for this index entry as it should appear after
1438f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1439f8ffb278Sdrh     */
144011e85273Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
14419cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
14426934fc7bSdrh       int iField = pIdx->aiColumn[i];
1443f82b9afcSdrh       int x;
144426198bb4Sdrh       if( iField<0 || iField==pTab->iPKey ){
1445f82b9afcSdrh         x = regNewData;
14469cfcf5d4Sdrh       }else{
1447f82b9afcSdrh         x = iField + regNewData + 1;
14489cfcf5d4Sdrh       }
1449f82b9afcSdrh       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
1450f82b9afcSdrh       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
14519cfcf5d4Sdrh     }
145226198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
14538d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
145426198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
1455bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1456b2fe7d8cSdrh 
1457f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1458f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1459f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1460f8ffb278Sdrh     ** logic below can all be skipped. */
146100012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1462da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1463da475b8dSdrh       continue;
1464da475b8dSdrh     }
1465f8ffb278Sdrh 
14666934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
14679cfcf5d4Sdrh     onError = pIdx->onError;
1468de630353Sdanielk1977     if( onError==OE_None ){
146926198bb4Sdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
147011e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1471de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1472de630353Sdanielk1977     }
14739cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14749cfcf5d4Sdrh       onError = overrideError;
1475a996e477Sdrh     }else if( onError==OE_Default ){
1476a996e477Sdrh       onError = OE_Abort;
14779cfcf5d4Sdrh     }
14785383ae5cSdrh     if( seenReplace ){
14795383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
14805383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
14815383ae5cSdrh     }
14825383ae5cSdrh 
1483b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
14846fbe41acSdrh     regR = sqlite3GetTempRange(pParse, nPkField);
148526198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
14866f225d0dSdrh                          regIdx, pIdx->nKeyCol);
1487f8ffb278Sdrh 
1488f8ffb278Sdrh     /* Generate code to handle collisions */
148911e85273Sdrh     if( HasRowid(pTab) ){
14906934fc7bSdrh       sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
14910978d4ffSdrh       /* Conflict only if the rowid of the existing index entry
14920978d4ffSdrh       ** is different from old-rowid */
1493f8ffb278Sdrh       if( isUpdate ){
14946934fc7bSdrh         sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
1495f8ffb278Sdrh       }
149626198bb4Sdrh     }else{
1497ccc79f02Sdrh       int x;
149826198bb4Sdrh       /* Extract the PRIMARY KEY from the end of the index entry and
1499da475b8dSdrh       ** store it in registers regR..regR+nPk-1 */
1500da475b8dSdrh       if( isUpdate || onError==OE_Replace ){
150126198bb4Sdrh         for(i=0; i<pPk->nKeyCol; i++){
1502ccc79f02Sdrh           x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
150326198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
150426198bb4Sdrh           VdbeComment((v, "%s.%s", pTab->zName,
150526198bb4Sdrh                        pTab->aCol[pPk->aiColumn[i]].zName));
150626198bb4Sdrh         }
1507da475b8dSdrh       }
1508da475b8dSdrh       if( isUpdate ){
1509*e83267daSdan         /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1510*e83267daSdan         ** table, only conflict if the new PRIMARY KEY values are actually
1511*e83267daSdan         ** different from the old.
1512*e83267daSdan         **
1513*e83267daSdan         ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1514*e83267daSdan         ** of the matched index row are different from the original PRIMARY
1515*e83267daSdan         ** KEY values of this row before the update.  */
1516*e83267daSdan         char *p4;
1517*e83267daSdan         int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1518*e83267daSdan         int op = OP_Ne;
1519*e83267daSdan         int regCmp = (pIdx->autoIndex==2 ? regIdx : regR);
1520*e83267daSdan 
1521*e83267daSdan         for(i=0; i<pPk->nKeyCol; i++){
1522*e83267daSdan           char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1523ccc79f02Sdrh           x = pPk->aiColumn[i];
1524*e83267daSdan           if( i==(pPk->nKeyCol-1) ){
1525*e83267daSdan             addrJump = addrUniqueOk;
1526*e83267daSdan             op = OP_Eq;
152711e85273Sdrh           }
1528*e83267daSdan           sqlite3VdbeAddOp4(v, op,
1529*e83267daSdan               regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1530*e83267daSdan           );
1531da475b8dSdrh         }
153211e85273Sdrh       }
153326198bb4Sdrh     }
153411e85273Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1535b2fe7d8cSdrh 
1536b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1537b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1538b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
15399cfcf5d4Sdrh     switch( onError ){
15401c92853dSdrh       case OE_Rollback:
15411c92853dSdrh       case OE_Abort:
15421c92853dSdrh       case OE_Fail: {
1543f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
15449cfcf5d4Sdrh         break;
15459cfcf5d4Sdrh       }
15469cfcf5d4Sdrh       case OE_Ignore: {
15470ca3e24bSdrh         assert( seenReplace==0 );
154866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
15499cfcf5d4Sdrh         break;
15509cfcf5d4Sdrh       }
1551098d1684Sdrh       default: {
15522283d46cSdan         Trigger *pTrigger = 0;
1553098d1684Sdrh         assert( onError==OE_Replace );
15541bea559aSdan         sqlite3MultiWrite(pParse);
15552938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15562283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15572283d46cSdan         }
155826198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
15596fbe41acSdrh                                  regR, nPkField, 0, OE_Replace);
15600ca3e24bSdrh         seenReplace = 1;
15619cfcf5d4Sdrh         break;
15629cfcf5d4Sdrh       }
15639cfcf5d4Sdrh     }
156411e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
156526198bb4Sdrh     sqlite3ReleaseTempRange(pParse, regR, nPkField);
15669cfcf5d4Sdrh   }
1567de630353Sdanielk1977 
1568de630353Sdanielk1977   if( pbMayReplace ){
1569de630353Sdanielk1977     *pbMayReplace = seenReplace;
1570de630353Sdanielk1977   }
15716fbe41acSdrh   VdbeModuleComment((v, "END: GenCnstCks()"));
15729cfcf5d4Sdrh }
15730ca3e24bSdrh 
15740ca3e24bSdrh /*
15750ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
15764adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
15776934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
157804adf416Sdrh ** rowid and the content to be inserted.
15790ca3e24bSdrh **
1580b419a926Sdrh ** The arguments to this routine should be the same as the first six
15814adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
15820ca3e24bSdrh */
15834adee20fSdanielk1977 void sqlite3CompleteInsertion(
15840ca3e24bSdrh   Parse *pParse,      /* The parser context */
15850ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
158626198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
158726198bb4Sdrh   int iIdxCur,        /* First index cursor */
15886934fc7bSdrh   int regNewData,     /* Range of content */
1589aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
159070ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1591de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1592de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
15930ca3e24bSdrh ){
15946934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
15956934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
15966934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
15976934fc7bSdrh   int regData;        /* Content registers (after the rowid) */
15986934fc7bSdrh   int regRec;         /* Register holding assemblied record for the table */
15996934fc7bSdrh   int i;              /* Loop counter */
16000ca3e24bSdrh 
16014adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
16020ca3e24bSdrh   assert( v!=0 );
1603417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1604b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1605aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1606b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1607b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1608b2b9d3d7Sdrh     }
160926198bb4Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
16106546af14Sdrh     pik_flags = 0;
16116546af14Sdrh     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
16126546af14Sdrh     if( pIdx->autoIndex==2 && !HasRowid(pTab) && pParse->nested==0 ){
16136546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1614de630353Sdanielk1977     }
16156546af14Sdrh     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
16160ca3e24bSdrh   }
1617ec95c441Sdrh   if( !HasRowid(pTab) ) return;
16186934fc7bSdrh   regData = regNewData + 1;
1619b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
16201db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1621a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1622da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
16234794f735Sdrh   if( pParse->nested ){
16244794f735Sdrh     pik_flags = 0;
16254794f735Sdrh   }else{
162694eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
162794eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
16284794f735Sdrh   }
1629e4d90813Sdrh   if( appendBias ){
1630e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1631e4d90813Sdrh   }
1632de630353Sdanielk1977   if( useSeekResult ){
1633de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1634de630353Sdanielk1977   }
16356934fc7bSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
163694eb6a14Sdanielk1977   if( !pParse->nested ){
16378d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
163894eb6a14Sdanielk1977   }
1639b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
16400ca3e24bSdrh }
1641cd44690aSdrh 
1642cd44690aSdrh /*
164326198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
164426198bb4Sdrh ** code to open and initialized those cursors.
1645aa9b8963Sdrh **
164626198bb4Sdrh ** The cursor for the object that contains the complete data (normally
164726198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
164826198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
164926198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
165026198bb4Sdrh **
165126198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
165226198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
165326198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
165426198bb4Sdrh **
165526198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
165626198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
165726198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
165826198bb4Sdrh ** pTab->pIndex list.
1659cd44690aSdrh */
1660aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1661290c1948Sdrh   Parse *pParse,   /* Parsing context */
1662290c1948Sdrh   Table *pTab,     /* Table to be opened */
166326198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
166426198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
166526198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
166626198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
1667290c1948Sdrh ){
1668cd44690aSdrh   int i;
16694cbdda9eSdrh   int iDb;
1670cd44690aSdrh   Index *pIdx;
16714cbdda9eSdrh   Vdbe *v;
16724cbdda9eSdrh 
167326198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
167426198bb4Sdrh   if( IsVirtual(pTab) ){
167526198bb4Sdrh     *piDataCur = 0;
167626198bb4Sdrh     *piIdxCur = 1;
167726198bb4Sdrh     return 0;
167826198bb4Sdrh   }
16794cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
16804cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1681cd44690aSdrh   assert( v!=0 );
168226198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
168326198bb4Sdrh   if( HasRowid(pTab) ){
168426198bb4Sdrh     *piDataCur = iBase++;
168526198bb4Sdrh     sqlite3OpenTable(pParse, *piDataCur, iDb, pTab, op);
16866fbe41acSdrh   }else{
168726198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
16886fbe41acSdrh   }
168926198bb4Sdrh   *piIdxCur = iBase;
169026198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1691b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
169226198bb4Sdrh     int iIdxCur = iBase++;
1693da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
169426198bb4Sdrh     if( pIdx->autoIndex==2 && !HasRowid(pTab) ) *piDataCur = iIdxCur;
169526198bb4Sdrh     sqlite3VdbeAddOp4(v, op, iIdxCur, pIdx->tnum, iDb,
169666a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1697207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1698cd44690aSdrh   }
169926198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
170026198bb4Sdrh   return i;
1701cd44690aSdrh }
17029d9cf229Sdrh 
170391c58e23Sdrh 
170491c58e23Sdrh #ifdef SQLITE_TEST
170591c58e23Sdrh /*
170691c58e23Sdrh ** The following global variable is incremented whenever the
170791c58e23Sdrh ** transfer optimization is used.  This is used for testing
170891c58e23Sdrh ** purposes only - to make sure the transfer optimization really
170991c58e23Sdrh ** is happening when it is suppose to.
171091c58e23Sdrh */
171191c58e23Sdrh int sqlite3_xferopt_count;
171291c58e23Sdrh #endif /* SQLITE_TEST */
171391c58e23Sdrh 
171491c58e23Sdrh 
17159d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
17169d9cf229Sdrh /*
17179d9cf229Sdrh ** Check to collation names to see if they are compatible.
17189d9cf229Sdrh */
17199d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
17209d9cf229Sdrh   if( z1==0 ){
17219d9cf229Sdrh     return z2==0;
17229d9cf229Sdrh   }
17239d9cf229Sdrh   if( z2==0 ){
17249d9cf229Sdrh     return 0;
17259d9cf229Sdrh   }
17269d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
17279d9cf229Sdrh }
17289d9cf229Sdrh 
17299d9cf229Sdrh 
17309d9cf229Sdrh /*
17319d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
17329d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
17339d9cf229Sdrh ** for a compatible index:
17349d9cf229Sdrh **
17359d9cf229Sdrh **    *   The index is over the same set of columns
17369d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
17379d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
17389d9cf229Sdrh **    *   The same collating sequence on each column
1739b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
17409d9cf229Sdrh */
17419d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
17429d9cf229Sdrh   int i;
17439d9cf229Sdrh   assert( pDest && pSrc );
17449d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1745bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
17469d9cf229Sdrh     return 0;   /* Different number of columns */
17479d9cf229Sdrh   }
17489d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
17499d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
17509d9cf229Sdrh   }
1751bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
17529d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
17539d9cf229Sdrh       return 0;   /* Different columns indexed */
17549d9cf229Sdrh     }
17559d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
17569d9cf229Sdrh       return 0;   /* Different sort orders */
17579d9cf229Sdrh     }
17583f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
175960a713c6Sdrh       return 0;   /* Different collating sequences */
17609d9cf229Sdrh     }
17619d9cf229Sdrh   }
1762619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1763b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1764b2b9d3d7Sdrh   }
17659d9cf229Sdrh 
17669d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
17679d9cf229Sdrh   return 1;
17689d9cf229Sdrh }
17699d9cf229Sdrh 
17709d9cf229Sdrh /*
17719d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
17729d9cf229Sdrh **
17739d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
17749d9cf229Sdrh **
1775ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1776ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1777ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
17789d9cf229Sdrh **
1779ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1780ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1781ccdf1baeSdrh ** embedded in the code for details.
17829d9cf229Sdrh **
1783ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1784ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1785ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1786ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1787ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1788ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1789ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1790ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1791ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
17929d9cf229Sdrh **
1793ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
17949d9cf229Sdrh */
17959d9cf229Sdrh static int xferOptimization(
17969d9cf229Sdrh   Parse *pParse,        /* Parser context */
17979d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
17989d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
17999d9cf229Sdrh   int onError,          /* How to handle constraint errors */
18009d9cf229Sdrh   int iDbDest           /* The database of pDest */
18019d9cf229Sdrh ){
18029d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
18039d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
18049d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
18059d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
18069d9cf229Sdrh   int i;                           /* Loop counter */
18079d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
18089d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
18099d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
1810da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
1811da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
18129d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
18139d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
18146a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1815f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1816b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
18179d9cf229Sdrh 
18189d9cf229Sdrh   if( pSelect==0 ){
18199d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
18209d9cf229Sdrh   }
18212f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
18229d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
18239d9cf229Sdrh   }
18249d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18257d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
18269d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
18279d9cf229Sdrh   }
18289d9cf229Sdrh #endif
18299d9cf229Sdrh   if( onError==OE_Default ){
1830e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1831e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
18329d9cf229Sdrh   }
18335ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
18349d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
18359d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
18369d9cf229Sdrh   }
18379d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
18389d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
18399d9cf229Sdrh   }
18409d9cf229Sdrh   if( pSelect->pWhere ){
18419d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
18429d9cf229Sdrh   }
18439d9cf229Sdrh   if( pSelect->pOrderBy ){
18449d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
18459d9cf229Sdrh   }
18468103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
18478103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
18489d9cf229Sdrh   if( pSelect->pGroupBy ){
18499d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
18509d9cf229Sdrh   }
18519d9cf229Sdrh   if( pSelect->pLimit ){
18529d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
18539d9cf229Sdrh   }
18548103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
18559d9cf229Sdrh   if( pSelect->pPrior ){
18569d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
18579d9cf229Sdrh   }
18587d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
18599d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
18609d9cf229Sdrh   }
18619d9cf229Sdrh   pEList = pSelect->pEList;
18629d9cf229Sdrh   assert( pEList!=0 );
18639d9cf229Sdrh   if( pEList->nExpr!=1 ){
18649d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
18659d9cf229Sdrh   }
18669d9cf229Sdrh   assert( pEList->a[0].pExpr );
18679d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
18689d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
18699d9cf229Sdrh   }
18709d9cf229Sdrh 
18719d9cf229Sdrh   /* At this point we have established that the statement is of the
18729d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
18739d9cf229Sdrh   ** we have to check the semantics.
18749d9cf229Sdrh   */
18759d9cf229Sdrh   pItem = pSelect->pSrc->a;
187641fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
18779d9cf229Sdrh   if( pSrc==0 ){
18789d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
18799d9cf229Sdrh   }
18809d9cf229Sdrh   if( pSrc==pDest ){
18819d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
18829d9cf229Sdrh   }
188355548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
188455548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
188555548273Sdrh   }
18869d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18877d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
18889d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
18899d9cf229Sdrh   }
18909d9cf229Sdrh #endif
18919d9cf229Sdrh   if( pSrc->pSelect ){
18929d9cf229Sdrh     return 0;   /* tab2 may not be a view */
18939d9cf229Sdrh   }
18949d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
18959d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
18969d9cf229Sdrh   }
18979d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
18989d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
18999d9cf229Sdrh   }
190055548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
190155548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
190255548273Sdrh   }
19039d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
19049d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
19059d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
19069d9cf229Sdrh     }
19079d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
19089d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
19099d9cf229Sdrh     }
19109d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
19119d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
19129d9cf229Sdrh     }
19139d9cf229Sdrh   }
19149d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1915f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1916f33c9fadSdrh       destHasUniqueIdx = 1;
1917f33c9fadSdrh     }
19189d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
19199d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19209d9cf229Sdrh     }
19219d9cf229Sdrh     if( pSrcIdx==0 ){
19229d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
19239d9cf229Sdrh     }
19249d9cf229Sdrh   }
19257fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1926619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
19278103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
19288103b7d2Sdrh   }
19297fc2f41bSdrh #endif
1930713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1931713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1932713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1933713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1934713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1935713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1936713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1937713de341Sdrh   */
1938713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1939713de341Sdrh     return 0;
1940713de341Sdrh   }
1941713de341Sdrh #endif
19421696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1943ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
19441696124dSdan   }
19459d9cf229Sdrh 
1946ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1947ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1948ccdf1baeSdrh   ** table (tab1) is initially empty.
19499d9cf229Sdrh   */
1950dd73521bSdrh #ifdef SQLITE_TEST
1951dd73521bSdrh   sqlite3_xferopt_count++;
1952dd73521bSdrh #endif
19539d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
19549d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1955f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
19569d9cf229Sdrh   iSrc = pParse->nTab++;
19579d9cf229Sdrh   iDest = pParse->nTab++;
19586a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
195955548273Sdrh   regData = sqlite3GetTempReg(pParse);
196055548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
196155548273Sdrh   if( HasRowid(pSrc) ){
19629d9cf229Sdrh     sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1963ccdf1baeSdrh     if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1964ccdf1baeSdrh      || destHasUniqueIdx                              /* (2) */
1965ccdf1baeSdrh      || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1966ccdf1baeSdrh     ){
1967ccdf1baeSdrh       /* In some circumstances, we are able to run the xfer optimization
1968ccdf1baeSdrh       ** only if the destination table is initially empty.  This code makes
1969ccdf1baeSdrh       ** that determination.  Conditions under which the destination must
1970ccdf1baeSdrh       ** be empty:
1971f33c9fadSdrh       **
1972ccdf1baeSdrh       ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1973ccdf1baeSdrh       **     (If the destination is not initially empty, the rowid fields
1974ccdf1baeSdrh       **     of index entries might need to change.)
1975ccdf1baeSdrh       **
1976ccdf1baeSdrh       ** (2) The destination has a unique index.  (The xfer optimization
1977ccdf1baeSdrh       **     is unable to test uniqueness.)
1978ccdf1baeSdrh       **
1979ccdf1baeSdrh       ** (3) onError is something other than OE_Abort and OE_Rollback.
19809d9cf229Sdrh       */
198166a5167bSdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
198266a5167bSdrh       emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
19839d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr1);
19849d9cf229Sdrh     }else{
19859d9cf229Sdrh       emptyDestTest = 0;
19869d9cf229Sdrh     }
19879d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
198866a5167bSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
198942242dedSdrh     if( pDest->iPKey>=0 ){
1990b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1991b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1992f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
19939d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
1994b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
1995bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
1996b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
199795bad4c7Sdrh     }else{
1998b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
19997d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
200095bad4c7Sdrh     }
2001b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
2002b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
2003b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
20041f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
200566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
200655548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
200755548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2008da475b8dSdrh   }else{
2009da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2010da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
201155548273Sdrh   }
20129d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
20131b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
20149d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
20159d9cf229Sdrh     }
20169d9cf229Sdrh     assert( pSrcIdx );
20179d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
2018207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
2019207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
2020d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
20219d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
2022207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
202366a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
202459885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2025207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
202666a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
2027b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2028b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
202966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
20309d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
203155548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
203255548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20339d9cf229Sdrh   }
20349d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
2035b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2036b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
20379d9cf229Sdrh   if( emptyDestTest ){
203866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
20399d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
204066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20419d9cf229Sdrh     return 0;
20429d9cf229Sdrh   }else{
20439d9cf229Sdrh     return 1;
20449d9cf229Sdrh   }
20459d9cf229Sdrh }
20469d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2047