xref: /sqlite-3.40.0/src/insert.c (revision ec95c441)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17cce7d176Sdrh /*
18bbb5e4e0Sdrh ** Generate code that will open a table for reading.
19bbb5e4e0Sdrh */
20bbb5e4e0Sdrh void sqlite3OpenTable(
21bbb5e4e0Sdrh   Parse *p,       /* Generate code into this VDBE */
22bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
23bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
24bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
25bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
26bbb5e4e0Sdrh ){
27bbb5e4e0Sdrh   Vdbe *v;
285f53aac2Sdrh   assert( !IsVirtual(pTab) );
29bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
30bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
31bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
32*ec95c441Sdrh   if( HasRowid(pTab) ){
33bbb5e4e0Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
34bbb5e4e0Sdrh     sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
35bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
36bbb5e4e0Sdrh   }
37*ec95c441Sdrh }
38bbb5e4e0Sdrh 
39bbb5e4e0Sdrh /*
4069f8bb9cSdan ** Return a pointer to the column affinity string associated with index
4169f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
4269f8bb9cSdan ** the table, according to the affinity of the column:
433d1bfeaaSdanielk1977 **
443d1bfeaaSdanielk1977 **  Character      Column affinity
453d1bfeaaSdanielk1977 **  ------------------------------
463eda040bSdrh **  'a'            TEXT
473eda040bSdrh **  'b'            NONE
483eda040bSdrh **  'c'            NUMERIC
493eda040bSdrh **  'd'            INTEGER
503eda040bSdrh **  'e'            REAL
512d401ab8Sdrh **
520c733f67Sdan ** An extra 'd' is appended to the end of the string to cover the
532d401ab8Sdrh ** rowid that appears as the last column in every index.
5469f8bb9cSdan **
5569f8bb9cSdan ** Memory for the buffer containing the column index affinity string
5669f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
5769f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
583d1bfeaaSdanielk1977 */
5969f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
60a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
61e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
62a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
63e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
64a37cdde0Sdanielk1977     **
65a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
66e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
67a37cdde0Sdanielk1977     ** up.
68a37cdde0Sdanielk1977     */
69a37cdde0Sdanielk1977     int n;
70a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
71abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
72bbbdc83bSdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nKeyCol+2);
73a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
74633e6d57Sdrh       db->mallocFailed = 1;
7569f8bb9cSdan       return 0;
76a37cdde0Sdanielk1977     }
77bbbdc83bSdrh     for(n=0; n<pIdx->nKeyCol; n++){
78a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
79a37cdde0Sdanielk1977     }
800c733f67Sdan     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
812d401ab8Sdrh     pIdx->zColAff[n] = 0;
82a37cdde0Sdanielk1977   }
833d1bfeaaSdanielk1977 
8469f8bb9cSdan   return pIdx->zColAff;
85a37cdde0Sdanielk1977 }
86a37cdde0Sdanielk1977 
87a37cdde0Sdanielk1977 /*
8866a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
89a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
90a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
91a37cdde0Sdanielk1977 ** column:
92a37cdde0Sdanielk1977 **
93a37cdde0Sdanielk1977 **  Character      Column affinity
94a37cdde0Sdanielk1977 **  ------------------------------
953eda040bSdrh **  'a'            TEXT
963eda040bSdrh **  'b'            NONE
973eda040bSdrh **  'c'            NUMERIC
983eda040bSdrh **  'd'            INTEGER
993eda040bSdrh **  'e'            REAL
100a37cdde0Sdanielk1977 */
101a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1023d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
1033d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1043d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1053d1bfeaaSdanielk1977   **
1063d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1073d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1083d1bfeaaSdanielk1977   */
1093d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1103d1bfeaaSdanielk1977     char *zColAff;
1113d1bfeaaSdanielk1977     int i;
112abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1133d1bfeaaSdanielk1977 
114b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1153d1bfeaaSdanielk1977     if( !zColAff ){
116633e6d57Sdrh       db->mallocFailed = 1;
117a37cdde0Sdanielk1977       return;
1183d1bfeaaSdanielk1977     }
1193d1bfeaaSdanielk1977 
1203d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
121a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1223d1bfeaaSdanielk1977     }
1233d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1243d1bfeaaSdanielk1977 
1253d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1263d1bfeaaSdanielk1977   }
1273d1bfeaaSdanielk1977 
1288d129422Sdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
1293d1bfeaaSdanielk1977 }
1303d1bfeaaSdanielk1977 
1314d88778bSdanielk1977 /*
13248d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
13348d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
13448d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
13548d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
13648d1178aSdrh ** run without using temporary table for the results of the SELECT.
1374d88778bSdanielk1977 */
138595a523aSdanielk1977 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
139595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1404d88778bSdanielk1977   int i;
14148d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
142595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
143595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
144595a523aSdanielk1977 #endif
145595a523aSdanielk1977 
14648d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
14748d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
148ef0bea92Sdrh     assert( pOp!=0 );
149207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
15048d1178aSdrh       Index *pIndex;
151207872a4Sdanielk1977       int tnum = pOp->p2;
15248d1178aSdrh       if( tnum==pTab->tnum ){
15348d1178aSdrh         return 1;
15448d1178aSdrh       }
15548d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
15648d1178aSdrh         if( tnum==pIndex->tnum ){
15748d1178aSdrh           return 1;
15848d1178aSdrh         }
15948d1178aSdrh       }
16048d1178aSdrh     }
161543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
162595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1632dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
16466a5167bSdrh       assert( pOp->p4type==P4_VTAB );
16548d1178aSdrh       return 1;
1664d88778bSdanielk1977     }
167543165efSdrh #endif
1684d88778bSdanielk1977   }
1694d88778bSdanielk1977   return 0;
1704d88778bSdanielk1977 }
1713d1bfeaaSdanielk1977 
1729d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1739d9cf229Sdrh /*
1740b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1750b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1760b9f50d8Sdrh ** that holds the maximum rowid.
1779d9cf229Sdrh **
1780b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1790b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1800b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1810b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1820b9f50d8Sdrh ** AutoincInfo structure is used.
1839d9cf229Sdrh **
1840b9f50d8Sdrh ** Three memory locations are allocated:
1850b9f50d8Sdrh **
1860b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
1870b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
1880b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
1890b9f50d8Sdrh **
1900b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
1910b9f50d8Sdrh ** insert routine needs to know about.
1929d9cf229Sdrh */
1939d9cf229Sdrh static int autoIncBegin(
1949d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1959d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1969d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1979d9cf229Sdrh ){
1986a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
1997d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
20065a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2010b9f50d8Sdrh     AutoincInfo *pInfo;
2020b9f50d8Sdrh 
20365a7cd16Sdan     pInfo = pToplevel->pAinc;
2040b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2050b9f50d8Sdrh     if( pInfo==0 ){
2060b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2070b9f50d8Sdrh       if( pInfo==0 ) return 0;
20865a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
20965a7cd16Sdan       pToplevel->pAinc = pInfo;
2100b9f50d8Sdrh       pInfo->pTab = pTab;
2110b9f50d8Sdrh       pInfo->iDb = iDb;
21265a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
21365a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
21465a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2150b9f50d8Sdrh     }
2160b9f50d8Sdrh     memId = pInfo->regCtr;
2179d9cf229Sdrh   }
2189d9cf229Sdrh   return memId;
2199d9cf229Sdrh }
2209d9cf229Sdrh 
2219d9cf229Sdrh /*
2220b9f50d8Sdrh ** This routine generates code that will initialize all of the
2230b9f50d8Sdrh ** register used by the autoincrement tracker.
2240b9f50d8Sdrh */
2250b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2260b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2270b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2280b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2290b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2300b9f50d8Sdrh   int addr;                  /* A VDBE address */
2310b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2320b9f50d8Sdrh 
233345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
234345ba7dbSdrh   ** only called from the top-level */
235345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
236345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
23776d462eeSdan 
2380b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2390b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2400b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2410b9f50d8Sdrh     memId = p->regCtr;
2422120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2430b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
244f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2450b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2460b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
2470b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
2480b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
2490b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
2500b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2510b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2520b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2530b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2540b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
2550b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2560b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2570b9f50d8Sdrh   }
2580b9f50d8Sdrh }
2590b9f50d8Sdrh 
2600b9f50d8Sdrh /*
2619d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2629d9cf229Sdrh **
2639d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2649d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2659d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2669d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2679d9cf229Sdrh */
2686a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2699d9cf229Sdrh   if( memId>0 ){
2706a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2719d9cf229Sdrh   }
2729d9cf229Sdrh }
2739d9cf229Sdrh 
2749d9cf229Sdrh /*
2750b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2760b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2770b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2780b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2790b9f50d8Sdrh ** routine just before the "exit" code.
2809d9cf229Sdrh */
2810b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2820b9f50d8Sdrh   AutoincInfo *p;
2839d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
2840b9f50d8Sdrh   sqlite3 *db = pParse->db;
2856a288a33Sdrh 
2869d9cf229Sdrh   assert( v );
2870b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2880b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
2890b9f50d8Sdrh     int j1, j2, j3, j4, j5;
2900b9f50d8Sdrh     int iRec;
2910b9f50d8Sdrh     int memId = p->regCtr;
2920b9f50d8Sdrh 
2930b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
2942120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2950b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2966a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
2970b9f50d8Sdrh     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
2980b9f50d8Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
2990b9f50d8Sdrh     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
3000b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
3010b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j2);
3020b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3030b9f50d8Sdrh     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
3040b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j4);
3050b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
3066a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
3070b9f50d8Sdrh     sqlite3VdbeJumpHere(v, j5);
308a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3090b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
31035573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3110b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3120b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3139d9cf229Sdrh   }
3149d9cf229Sdrh }
3159d9cf229Sdrh #else
3169d9cf229Sdrh /*
3179d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3189d9cf229Sdrh ** above are all no-ops
3199d9cf229Sdrh */
3209d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
321287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3229d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3239d9cf229Sdrh 
3249d9cf229Sdrh 
3255f085269Sdrh /*
3265f085269Sdrh ** Generate code for a co-routine that will evaluate a subquery one
3275f085269Sdrh ** row at a time.
3285f085269Sdrh **
3295f085269Sdrh ** The pSelect parameter is the subquery that the co-routine will evaluation.
3305f085269Sdrh ** Information about the location of co-routine and the registers it will use
3315f085269Sdrh ** is returned by filling in the pDest object.
3325f085269Sdrh **
3335f085269Sdrh ** Registers are allocated as follows:
3345f085269Sdrh **
3355f085269Sdrh **   pDest->iSDParm      The register holding the next entry-point of the
3365f085269Sdrh **                       co-routine.  Run the co-routine to its next breakpoint
3375f085269Sdrh **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
3385f085269Sdrh **
3395f085269Sdrh **   pDest->iSDParm+1    The register holding the "completed" flag for the
3405f085269Sdrh **                       co-routine. This register is 0 if the previous Yield
3415f085269Sdrh **                       generated a new result row, or 1 if the subquery
3425f085269Sdrh **                       has completed.  If the Yield is called again
3435f085269Sdrh **                       after this register becomes 1, then the VDBE will
3445f085269Sdrh **                       halt with an SQLITE_INTERNAL error.
3455f085269Sdrh **
3465f085269Sdrh **   pDest->iSdst        First result register.
3475f085269Sdrh **
3485f085269Sdrh **   pDest->nSdst        Number of result registers.
3495f085269Sdrh **
3505f085269Sdrh ** This routine handles all of the register allocation and fills in the
3515f085269Sdrh ** pDest structure appropriately.
3525f085269Sdrh **
3535f085269Sdrh ** Here is a schematic of the generated code assuming that X is the
3545f085269Sdrh ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
3555f085269Sdrh ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
3565f085269Sdrh ** registers that hold the result set, reg[pDest->iSdst] through
3575f085269Sdrh ** reg[pDest->iSdst+pDest->nSdst-1]:
3585f085269Sdrh **
3595f085269Sdrh **         X <- A
3605f085269Sdrh **         EOF <- 0
3615f085269Sdrh **         goto B
3625f085269Sdrh **      A: setup for the SELECT
3635f085269Sdrh **         loop rows in the SELECT
3645f085269Sdrh **           load results into registers R..S
3655f085269Sdrh **           yield X
3665f085269Sdrh **         end loop
3675f085269Sdrh **         cleanup after the SELECT
3685f085269Sdrh **         EOF <- 1
3695f085269Sdrh **         yield X
3705f085269Sdrh **         halt-error
3715f085269Sdrh **      B:
3725f085269Sdrh **
3735f085269Sdrh ** To use this subroutine, the caller generates code as follows:
3745f085269Sdrh **
3755f085269Sdrh **         [ Co-routine generated by this subroutine, shown above ]
3765f085269Sdrh **      S: yield X
3775f085269Sdrh **         if EOF goto E
3785f085269Sdrh **         if skip this row, goto C
3795f085269Sdrh **         if terminate loop, goto E
3805f085269Sdrh **         deal with this row
3815f085269Sdrh **      C: goto S
3825f085269Sdrh **      E:
3835f085269Sdrh */
3845f085269Sdrh int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
3855f085269Sdrh   int regYield;       /* Register holding co-routine entry-point */
3865f085269Sdrh   int regEof;         /* Register holding co-routine completion flag */
3875f085269Sdrh   int addrTop;        /* Top of the co-routine */
3885f085269Sdrh   int j1;             /* Jump instruction */
3895f085269Sdrh   int rc;             /* Result code */
3905f085269Sdrh   Vdbe *v;            /* VDBE under construction */
3915f085269Sdrh 
3925f085269Sdrh   regYield = ++pParse->nMem;
3935f085269Sdrh   regEof = ++pParse->nMem;
3945f085269Sdrh   v = sqlite3GetVdbe(pParse);
3955f085269Sdrh   addrTop = sqlite3VdbeCurrentAddr(v);
3965f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
3975f085269Sdrh   VdbeComment((v, "Co-routine entry point"));
3985f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
3995f085269Sdrh   VdbeComment((v, "Co-routine completion flag"));
4005f085269Sdrh   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
4015f085269Sdrh   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4025f085269Sdrh   rc = sqlite3Select(pParse, pSelect, pDest);
4035f085269Sdrh   assert( pParse->nErr==0 || rc );
4045f085269Sdrh   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
4055f085269Sdrh   if( rc ) return rc;
4065f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
4075f085269Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
4085f085269Sdrh   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
4095f085269Sdrh   VdbeComment((v, "End of coroutine"));
4105f085269Sdrh   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
4115f085269Sdrh   return rc;
4125f085269Sdrh }
4135f085269Sdrh 
4145f085269Sdrh 
4155f085269Sdrh 
4169d9cf229Sdrh /* Forward declaration */
4179d9cf229Sdrh static int xferOptimization(
4189d9cf229Sdrh   Parse *pParse,        /* Parser context */
4199d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
4209d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4219d9cf229Sdrh   int onError,          /* How to handle constraint errors */
4229d9cf229Sdrh   int iDbDest           /* The database of pDest */
4239d9cf229Sdrh );
4249d9cf229Sdrh 
4253d1bfeaaSdanielk1977 /*
4261ccde15dSdrh ** This routine is call to handle SQL of the following forms:
427cce7d176Sdrh **
428cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
4291ccde15dSdrh **    insert into TABLE (IDLIST) select
430cce7d176Sdrh **
4311ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
4321ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
433967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
4341ccde15dSdrh **
4351ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
4361ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
4371ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
4381ccde15dSdrh ** data for the insert.
439142e30dfSdrh **
4409d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
441142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
442e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
443e00ee6ebSdrh ** the "1st template"):
444142e30dfSdrh **
445142e30dfSdrh **         open write cursor to <table> and its indices
446*ec95c441Sdrh **         put VALUES clause expressions into registers
447142e30dfSdrh **         write the resulting record into <table>
448142e30dfSdrh **         cleanup
449142e30dfSdrh **
4509d9cf229Sdrh ** The three remaining templates assume the statement is of the form
451142e30dfSdrh **
452142e30dfSdrh **   INSERT INTO <table> SELECT ...
453142e30dfSdrh **
4549d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
4559d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
4569d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
4579d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
4589d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
4599d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
4609d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
461e00ee6ebSdrh ** template.  This is the 2nd template.
4629d9cf229Sdrh **
4639d9cf229Sdrh **         open a write cursor to <table>
4649d9cf229Sdrh **         open read cursor on <table2>
4659d9cf229Sdrh **         transfer all records in <table2> over to <table>
4669d9cf229Sdrh **         close cursors
4679d9cf229Sdrh **         foreach index on <table>
4689d9cf229Sdrh **           open a write cursor on the <table> index
4699d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
4709d9cf229Sdrh **           transfer all records from the read to the write cursors
4719d9cf229Sdrh **           close cursors
4729d9cf229Sdrh **         end foreach
4739d9cf229Sdrh **
474e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
4759d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
4769d9cf229Sdrh ** The generated code follows this template:
477142e30dfSdrh **
478e00ee6ebSdrh **         EOF <- 0
479e00ee6ebSdrh **         X <- A
480142e30dfSdrh **         goto B
481142e30dfSdrh **      A: setup for the SELECT
4829d9cf229Sdrh **         loop over the rows in the SELECT
483e00ee6ebSdrh **           load values into registers R..R+n
484e00ee6ebSdrh **           yield X
485142e30dfSdrh **         end loop
486142e30dfSdrh **         cleanup after the SELECT
487e00ee6ebSdrh **         EOF <- 1
488e00ee6ebSdrh **         yield X
489142e30dfSdrh **         goto A
490e00ee6ebSdrh **      B: open write cursor to <table> and its indices
491e00ee6ebSdrh **      C: yield X
492e00ee6ebSdrh **         if EOF goto D
493e00ee6ebSdrh **         insert the select result into <table> from R..R+n
494e00ee6ebSdrh **         goto C
495142e30dfSdrh **      D: cleanup
496142e30dfSdrh **
497e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
498142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
499142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
500142e30dfSdrh ** we have to use a intermediate table to store the results of
501142e30dfSdrh ** the select.  The template is like this:
502142e30dfSdrh **
503e00ee6ebSdrh **         EOF <- 0
504e00ee6ebSdrh **         X <- A
505142e30dfSdrh **         goto B
506142e30dfSdrh **      A: setup for the SELECT
507142e30dfSdrh **         loop over the tables in the SELECT
508e00ee6ebSdrh **           load value into register R..R+n
509e00ee6ebSdrh **           yield X
510142e30dfSdrh **         end loop
511142e30dfSdrh **         cleanup after the SELECT
512e00ee6ebSdrh **         EOF <- 1
513e00ee6ebSdrh **         yield X
514e00ee6ebSdrh **         halt-error
515e00ee6ebSdrh **      B: open temp table
516e00ee6ebSdrh **      L: yield X
517e00ee6ebSdrh **         if EOF goto M
518e00ee6ebSdrh **         insert row from R..R+n into temp table
519e00ee6ebSdrh **         goto L
520e00ee6ebSdrh **      M: open write cursor to <table> and its indices
521e00ee6ebSdrh **         rewind temp table
522e00ee6ebSdrh **      C: loop over rows of intermediate table
523142e30dfSdrh **           transfer values form intermediate table into <table>
524e00ee6ebSdrh **         end loop
525e00ee6ebSdrh **      D: cleanup
526cce7d176Sdrh */
5274adee20fSdanielk1977 void sqlite3Insert(
528cce7d176Sdrh   Parse *pParse,        /* Parser context */
529113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
530cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
5315974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
5329cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
5339cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
534cce7d176Sdrh ){
5356a288a33Sdrh   sqlite3 *db;          /* The main database structure */
5366a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
537113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
538e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
5395974a30fSdrh   int i, j, idx;        /* Loop counters */
5405974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
5415974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
542967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
5436a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
54404adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
5454a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
5460ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
5474d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
548cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
549e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
550e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
551e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
5522eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
5536a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
5542958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
555e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
556*ec95c441Sdrh   int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
557cce7d176Sdrh 
5586a288a33Sdrh   /* Register allocations */
5591bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
5606a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
5616a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
5626a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
5636a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
5646a288a33Sdrh   int regData;          /* register holding first column to insert */
5651bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
566aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
5676a288a33Sdrh 
568798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
569798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
5702f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
5712f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
572798da52cSdrh #endif
573c3f9bad2Sdanielk1977 
57417435752Sdrh   db = pParse->db;
5751bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
57617435752Sdrh   if( pParse->nErr || db->mallocFailed ){
5776f7adc8aSdrh     goto insert_cleanup;
5786f7adc8aSdrh   }
579daffd0e5Sdrh 
5801ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5811ccde15dSdrh   */
582113088ecSdrh   assert( pTabList->nSrc==1 );
583113088ecSdrh   zTab = pTabList->a[0].zName;
584098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5854adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
586c3f9bad2Sdanielk1977   if( pTab==0 ){
587c3f9bad2Sdanielk1977     goto insert_cleanup;
588c3f9bad2Sdanielk1977   }
589da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
590da184236Sdanielk1977   assert( iDb<db->nDb );
591da184236Sdanielk1977   pDb = &db->aDb[iDb];
5922958a4e6Sdrh   zDb = pDb->zName;
5934adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
5941962bda7Sdrh     goto insert_cleanup;
5951962bda7Sdrh   }
596*ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
597c3f9bad2Sdanielk1977 
598b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
599b7f9164eSdrh   ** inserted into is a view
600b7f9164eSdrh   */
601b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
6022f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
603b7f9164eSdrh   isView = pTab->pSelect!=0;
604b7f9164eSdrh #else
6052f886d1dSdanielk1977 # define pTrigger 0
6062f886d1dSdanielk1977 # define tmask 0
607b7f9164eSdrh # define isView 0
608b7f9164eSdrh #endif
609b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
610b7f9164eSdrh # undef isView
611b7f9164eSdrh # define isView 0
612b7f9164eSdrh #endif
6132f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
614b7f9164eSdrh 
615f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
616b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
617b3d24bf8Sdanielk1977   ** module table).
618f573c99bSdrh   */
619b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
620f573c99bSdrh     goto insert_cleanup;
621f573c99bSdrh   }
622f573c99bSdrh 
623595a523aSdanielk1977   /* Ensure that:
624595a523aSdanielk1977   *  (a) the table is not read-only,
625595a523aSdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
626595a523aSdanielk1977   */
627595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
628595a523aSdanielk1977     goto insert_cleanup;
629595a523aSdanielk1977   }
630595a523aSdanielk1977 
6311ccde15dSdrh   /* Allocate a VDBE
6321ccde15dSdrh   */
6334adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
6345974a30fSdrh   if( v==0 ) goto insert_cleanup;
6354794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
6362f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
6371ccde15dSdrh 
6389d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
6399d9cf229Sdrh   /* If the statement is of the form
6409d9cf229Sdrh   **
6419d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
6429d9cf229Sdrh   **
6439d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
6449d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
645e00ee6ebSdrh   **
646e00ee6ebSdrh   ** This is the 2nd template.
6479d9cf229Sdrh   */
6489d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
6492f886d1dSdanielk1977     assert( !pTrigger );
6509d9cf229Sdrh     assert( pList==0 );
6510b9f50d8Sdrh     goto insert_end;
6529d9cf229Sdrh   }
6539d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
6549d9cf229Sdrh 
6552958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
6566a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
6572958a4e6Sdrh   */
6586a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
6592958a4e6Sdrh 
6601ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
661e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
662e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
663e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6641ccde15dSdrh   */
6655974a30fSdrh   if( pSelect ){
6665f085269Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run that
6675f085269Sdrh     ** SELECT. */
6685f085269Sdrh     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
6695f085269Sdrh     if( rc ) goto insert_cleanup;
6701013c932Sdrh 
6715f085269Sdrh     regEof = dest.iSDParm + 1;
6722b596da8Sdrh     regFromSelect = dest.iSdst;
6735974a30fSdrh     assert( pSelect->pEList );
674967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
6752b596da8Sdrh     assert( dest.nSdst==nColumn );
676142e30dfSdrh 
677142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
678e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
679e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
680e00ee6ebSdrh     ** the destination table (template 3).
681048c530cSdrh     **
682048c530cSdrh     ** A temp table must be used if the table being updated is also one
683048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
684048c530cSdrh     ** temp table in the case of row triggers.
685142e30dfSdrh     */
686595a523aSdanielk1977     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
687048c530cSdrh       useTempTable = 1;
688048c530cSdrh     }
689142e30dfSdrh 
690142e30dfSdrh     if( useTempTable ){
691e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
692e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
693e00ee6ebSdrh       ** here is from the 4th template:
694e00ee6ebSdrh       **
695e00ee6ebSdrh       **      B: open temp table
696e00ee6ebSdrh       **      L: yield X
697e00ee6ebSdrh       **         if EOF goto M
698e00ee6ebSdrh       **         insert row from R..R+n into temp table
699e00ee6ebSdrh       **         goto L
700e00ee6ebSdrh       **      M: ...
701142e30dfSdrh       */
702e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
703dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
704e00ee6ebSdrh       int addrTop;         /* Label "L" */
705e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
706b7654111Sdrh 
707142e30dfSdrh       srcTab = pParse->nTab++;
708b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
709dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
710e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
7112b596da8Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
712e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
7131db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
714dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
715dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
716e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
717e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
718b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
719dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
720142e30dfSdrh     }
721142e30dfSdrh   }else{
722142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
723142e30dfSdrh     ** clause
724142e30dfSdrh     */
725b3bce662Sdanielk1977     NameContext sNC;
726b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
727b3bce662Sdanielk1977     sNC.pParse = pParse;
7285974a30fSdrh     srcTab = -1;
72948d1178aSdrh     assert( useTempTable==0 );
730147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
731e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7327d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
733b04a5d87Sdrh         goto insert_cleanup;
734b04a5d87Sdrh       }
735e64e7b20Sdrh     }
7365974a30fSdrh   }
7371ccde15dSdrh 
7381ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7391ccde15dSdrh   ** of columns to be inserted into the table.
7401ccde15dSdrh   */
741034ca14fSdanielk1977   if( IsVirtual(pTab) ){
742034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
743034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
744034ca14fSdanielk1977     }
745034ca14fSdanielk1977   }
746034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7474adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
748da93d238Sdrh        "table %S has %d columns but %d values were supplied",
749d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
750cce7d176Sdrh     goto insert_cleanup;
751cce7d176Sdrh   }
752967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7534adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
754cce7d176Sdrh     goto insert_cleanup;
755cce7d176Sdrh   }
7561ccde15dSdrh 
7571ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
7581ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
7591ccde15dSdrh   ** remember the column indices.
760c8392586Sdrh   **
761c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
762c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
763c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
764c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
765c8392586Sdrh   ** is appears in the original table.  (The index of the primary
766c8392586Sdrh   ** key in the original table is pTab->iPKey.)
7671ccde15dSdrh   */
768967e8b73Sdrh   if( pColumn ){
769967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
770967e8b73Sdrh       pColumn->a[i].idx = -1;
771cce7d176Sdrh     }
772967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
773cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
7744adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
775967e8b73Sdrh           pColumn->a[i].idx = j;
7764a32431cSdrh           if( j==pTab->iPKey ){
777*ec95c441Sdrh             keyColumn = i;  assert( !withoutRowid );
7784a32431cSdrh           }
779cce7d176Sdrh           break;
780cce7d176Sdrh         }
781cce7d176Sdrh       }
782cce7d176Sdrh       if( j>=pTab->nCol ){
783*ec95c441Sdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
784a0217ba7Sdrh           keyColumn = i;
785a0217ba7Sdrh         }else{
7864adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
787da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
7881db95106Sdan           pParse->checkSchema = 1;
789cce7d176Sdrh           goto insert_cleanup;
790cce7d176Sdrh         }
791cce7d176Sdrh       }
792cce7d176Sdrh     }
793a0217ba7Sdrh   }
7941ccde15dSdrh 
795aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
796c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
797c8392586Sdrh   ** in the original table definition.
7984a32431cSdrh   */
799147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
8004a32431cSdrh     keyColumn = pTab->iPKey;
8014a32431cSdrh   }
8024a32431cSdrh 
803c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
8041ccde15dSdrh   */
805142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
8066a288a33Sdrh     regRowCount = ++pParse->nMem;
8076a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
808c3f9bad2Sdanielk1977   }
809c3f9bad2Sdanielk1977 
810e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
811e448dc4aSdanielk1977   if( !isView ){
812aa9b8963Sdrh     int nIdx;
813aa9b8963Sdrh 
814*ec95c441Sdrh     baseCur = pParse->nTab - withoutRowid;
81504adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
8165c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
817aa9b8963Sdrh     if( aRegIdx==0 ){
818aa9b8963Sdrh       goto insert_cleanup;
819aa9b8963Sdrh     }
820aa9b8963Sdrh     for(i=0; i<nIdx; i++){
821aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
822aa9b8963Sdrh     }
823feeb1394Sdrh   }
824feeb1394Sdrh 
825e00ee6ebSdrh   /* This is the top of the main insertion loop */
826142e30dfSdrh   if( useTempTable ){
827e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
828e00ee6ebSdrh     ** following pseudocode (template 4):
829e00ee6ebSdrh     **
830e00ee6ebSdrh     **         rewind temp table
831e00ee6ebSdrh     **      C: loop over rows of intermediate table
832e00ee6ebSdrh     **           transfer values form intermediate table into <table>
833e00ee6ebSdrh     **         end loop
834e00ee6ebSdrh     **      D: ...
835e00ee6ebSdrh     */
836e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
837e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
838142e30dfSdrh   }else if( pSelect ){
839e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
840e00ee6ebSdrh     ** following pseudocode (template 3):
841e00ee6ebSdrh     **
842e00ee6ebSdrh     **      C: yield X
843e00ee6ebSdrh     **         if EOF goto D
844e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
845e00ee6ebSdrh     **         goto C
846e00ee6ebSdrh     **      D: ...
847e00ee6ebSdrh     */
8482b596da8Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
849e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
850bed8690fSdrh   }
8511ccde15dSdrh 
8526a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
8536a288a33Sdrh   ** the content of the new row, and the assemblied row record.
8546a288a33Sdrh   */
8556a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
8566a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
8576a288a33Sdrh   if( IsVirtual(pTab) ){
8586a288a33Sdrh     regRowid++;
8596a288a33Sdrh     pParse->nMem++;
8606a288a33Sdrh   }
8616a288a33Sdrh   regData = regRowid+1;
8626a288a33Sdrh 
8635cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
86470ce3f0cSdrh   */
8654adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
8662f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
86776d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
868c3f9bad2Sdanielk1977 
86970ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
87070ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
87170ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
87270ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
87370ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
87470ce3f0cSdrh     */
87570ce3f0cSdrh     if( keyColumn<0 ){
87676d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
87770ce3f0cSdrh     }else{
8786a288a33Sdrh       int j1;
879*ec95c441Sdrh       assert( !withoutRowid );
8807fe45908Sdrh       if( useTempTable ){
88176d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
8827fe45908Sdrh       }else{
883d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
88476d462eeSdan         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
8857fe45908Sdrh       }
88676d462eeSdan       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
88776d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
8886a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
88976d462eeSdan       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89070ce3f0cSdrh     }
89170ce3f0cSdrh 
892034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
893034ca14fSdanielk1977     ** this block would have to account for hidden column.
894034ca14fSdanielk1977     */
895034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
896034ca14fSdanielk1977 
89770ce3f0cSdrh     /* Create the new column data
89870ce3f0cSdrh     */
899c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
900c3f9bad2Sdanielk1977       if( pColumn==0 ){
901c3f9bad2Sdanielk1977         j = i;
902c3f9bad2Sdanielk1977       }else{
903c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
904c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
905c3f9bad2Sdanielk1977         }
906c3f9bad2Sdanielk1977       }
9077ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
90876d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
909142e30dfSdrh       }else if( useTempTable ){
91076d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
911c3f9bad2Sdanielk1977       }else{
912d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
91376d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
914c3f9bad2Sdanielk1977       }
915c3f9bad2Sdanielk1977     }
916a37cdde0Sdanielk1977 
917a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
918a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
919a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
920a37cdde0Sdanielk1977     ** table column affinities.
921a37cdde0Sdanielk1977     */
922a37cdde0Sdanielk1977     if( !isView ){
92376d462eeSdan       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
924a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
925a37cdde0Sdanielk1977     }
926c3f9bad2Sdanielk1977 
9275cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
928165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
92994d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
930165921a7Sdan 
93176d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
93270ce3f0cSdrh   }
933c3f9bad2Sdanielk1977 
9344a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
935f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
9364a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
937b419a926Sdrh   ** case the record number is the same as that column.
9381ccde15dSdrh   */
9395cf590c1Sdrh   if( !isView ){
9404cbdda9eSdrh     if( IsVirtual(pTab) ){
9414cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
9426a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
9434cbdda9eSdrh     }
9444a32431cSdrh     if( keyColumn>=0 ){
945142e30dfSdrh       if( useTempTable ){
9466a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
947142e30dfSdrh       }else if( pSelect ){
948b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
9494a32431cSdrh       }else{
950e4d90813Sdrh         VdbeOp *pOp;
9511db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
95220411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
9531b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
954e4d90813Sdrh           appendFlag = 1;
955e4d90813Sdrh           pOp->opcode = OP_NewRowid;
95604adf416Sdrh           pOp->p1 = baseCur;
9576a288a33Sdrh           pOp->p2 = regRowid;
9586a288a33Sdrh           pOp->p3 = regAutoinc;
959e4d90813Sdrh         }
96027a32783Sdrh       }
961f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
962e1e68f49Sdrh       ** to generate a unique primary key value.
963e1e68f49Sdrh       */
964e4d90813Sdrh       if( !appendFlag ){
9651db639ceSdrh         int j1;
966bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
9671db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
96804adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
9691db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
970bb50e7adSdanielk1977         }else{
971bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
972bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
973bb50e7adSdanielk1977         }
9743c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
975e4d90813Sdrh       }
976*ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
9776a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
9784a32431cSdrh     }else{
97904adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
980e4d90813Sdrh       appendFlag = 1;
9814a32431cSdrh     }
9826a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9834a32431cSdrh 
984aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
9854a32431cSdrh     ** with the first column.
9864a32431cSdrh     */
987034ca14fSdanielk1977     nHidden = 0;
988cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9896a288a33Sdrh       int iRegStore = regRowid+1+i;
9904a32431cSdrh       if( i==pTab->iPKey ){
9914a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
992aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
993aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
994aacc543eSdrh         ** taking up data space with information that will never be used. */
9954c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
9964a32431cSdrh         continue;
9974a32431cSdrh       }
998967e8b73Sdrh       if( pColumn==0 ){
999034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
1000034ca14fSdanielk1977           assert( IsVirtual(pTab) );
1001034ca14fSdanielk1977           j = -1;
1002034ca14fSdanielk1977           nHidden++;
1003034ca14fSdanielk1977         }else{
1004034ca14fSdanielk1977           j = i - nHidden;
1005034ca14fSdanielk1977         }
1006cce7d176Sdrh       }else{
1007967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
1008967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
1009cce7d176Sdrh         }
1010cce7d176Sdrh       }
1011034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1012287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
1013142e30dfSdrh       }else if( useTempTable ){
1014287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1015142e30dfSdrh       }else if( pSelect ){
1016b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1017cce7d176Sdrh       }else{
1018287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1019cce7d176Sdrh       }
1020cce7d176Sdrh     }
10211ccde15dSdrh 
10220ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
10230ca3e24bSdrh     ** do the insertion.
10244a32431cSdrh     */
10254cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
10264cbdda9eSdrh     if( IsVirtual(pTab) ){
1027595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
10284f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
1029595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1030b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1031e0af83acSdan       sqlite3MayAbort(pParse);
10324cbdda9eSdrh     }else
10334cbdda9eSdrh #endif
10344cbdda9eSdrh     {
1035de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
1036de630353Sdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
1037de630353Sdanielk1977           keyColumn>=0, 0, onError, endOfLoop, &isReplace
103804adf416Sdrh       );
10398ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
104004adf416Sdrh       sqlite3CompleteInsertion(
10412832ad42Sdan           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
104204adf416Sdrh       );
10435cf590c1Sdrh     }
10444cbdda9eSdrh   }
10451bee3d7bSdrh 
1046feeb1394Sdrh   /* Update the count of rows that are inserted
10471bee3d7bSdrh   */
1048142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
10496a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
10501bee3d7bSdrh   }
1051c3f9bad2Sdanielk1977 
10522f886d1dSdanielk1977   if( pTrigger ){
1053c3f9bad2Sdanielk1977     /* Code AFTER triggers */
1054165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
105594d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
1056c3f9bad2Sdanielk1977   }
10571bee3d7bSdrh 
1058e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
1059e00ee6ebSdrh   ** is a SELECT statement.
10601ccde15dSdrh   */
10614adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
1062142e30dfSdrh   if( useTempTable ){
1063e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1064e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10652eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1066142e30dfSdrh   }else if( pSelect ){
1067e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1068e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
10696b56344dSdrh   }
1070c3f9bad2Sdanielk1977 
1071e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
1072c3f9bad2Sdanielk1977     /* Close all tables opened */
1073*ec95c441Sdrh     if( !withoutRowid ) sqlite3VdbeAddOp1(v, OP_Close, baseCur);
10746b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
10752eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
1076cce7d176Sdrh     }
1077c3f9bad2Sdanielk1977   }
1078c3f9bad2Sdanielk1977 
10790b9f50d8Sdrh insert_end:
1080f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10810b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10820b9f50d8Sdrh   ** autoincrement tables.
10832958a4e6Sdrh   */
1084165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10850b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10860b9f50d8Sdrh   }
10872958a4e6Sdrh 
10881bee3d7bSdrh   /*
1089e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1090e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1091e7de6f25Sdanielk1977   ** invoke the callback function.
10921bee3d7bSdrh   */
1093165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
10946a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
109522322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
109610fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
10971bee3d7bSdrh   }
1098cce7d176Sdrh 
1099cce7d176Sdrh insert_cleanup:
1100633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1101633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1102633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1103633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1104633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1105cce7d176Sdrh }
11069cfcf5d4Sdrh 
110775cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
110875cbd984Sdan ** thely may interfere with compilation of other functions in this file
110975cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
111075cbd984Sdan #ifdef isView
111175cbd984Sdan  #undef isView
111275cbd984Sdan #endif
111375cbd984Sdan #ifdef pTrigger
111475cbd984Sdan  #undef pTrigger
111575cbd984Sdan #endif
111675cbd984Sdan #ifdef tmask
111775cbd984Sdan  #undef tmask
111875cbd984Sdan #endif
111975cbd984Sdan 
112075cbd984Sdan 
11219cfcf5d4Sdrh /*
11226a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
11239cfcf5d4Sdrh **
112404adf416Sdrh ** The input is a range of consecutive registers as follows:
11250ca3e24bSdrh **
112665a7cd16Sdan **    1.  The rowid of the row after the update.
11270ca3e24bSdrh **
112865a7cd16Sdan **    2.  The data in the first column of the entry after the update.
11290ca3e24bSdrh **
11300ca3e24bSdrh **    i.  Data from middle columns...
11310ca3e24bSdrh **
11320ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
11330ca3e24bSdrh **
113465a7cd16Sdan ** The regRowid parameter is the index of the register containing (1).
113504adf416Sdrh **
113665a7cd16Sdan ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
113765a7cd16Sdan ** the address of a register containing the rowid before the update takes
113865a7cd16Sdan ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
113965a7cd16Sdan ** is false, indicating an INSERT statement, then a non-zero rowidChng
114065a7cd16Sdan ** indicates that the rowid was explicitly specified as part of the
114165a7cd16Sdan ** INSERT statement. If rowidChng is false, it means that  the rowid is
114265a7cd16Sdan ** computed automatically in an insert or that the rowid value is not
114365a7cd16Sdan ** modified by an update.
11440ca3e24bSdrh **
1145aa9b8963Sdrh ** The code generated by this routine store new index entries into
1146aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1147aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1148aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1149aa9b8963Sdrh ** attached to the table.
11509cfcf5d4Sdrh **
11519cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
11529cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
11531c92853dSdrh ** then the appropriate action is performed.  There are five possible
11541c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
11559cfcf5d4Sdrh **
11569cfcf5d4Sdrh **  Constraint type  Action       What Happens
11579cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
11581c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
115924b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
11609cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
11619cfcf5d4Sdrh **
11621c92853dSdrh **  any              ABORT        Back out changes from the current command
11631c92853dSdrh **                                only (do not do a complete rollback) then
116424b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
11651c92853dSdrh **                                with SQLITE_CONSTRAINT.
11661c92853dSdrh **
1167e4c88c0cSdrh **  any              FAIL         Sqlite3_exec() returns immediately with a
11681c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11691c92853dSdrh **                                transaction is not rolled back and any
11701c92853dSdrh **                                prior changes are retained.
11711c92853dSdrh **
11729cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
11739cfcf5d4Sdrh **                                the stack and there is an immediate jump
11749cfcf5d4Sdrh **                                to label ignoreDest.
11759cfcf5d4Sdrh **
11769cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11779cfcf5d4Sdrh **                                value for that column.  If the default value
11789cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11799cfcf5d4Sdrh **
11809cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
11819cfcf5d4Sdrh **                                being inserted is removed.
11829cfcf5d4Sdrh **
11839cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
11849cfcf5d4Sdrh **
11851c92853dSdrh ** Which action to take is determined by the overrideError parameter.
11861c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
11871c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
11881c92853dSdrh ** for the constraint is used.
11899cfcf5d4Sdrh **
1190aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
119104adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
119204adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
11939cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1194aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
11959cfcf5d4Sdrh */
11964adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
11979cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
11989cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
119904adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
120004adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1201aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1202a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1203b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
12049cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1205de630353Sdanielk1977   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
1206de630353Sdanielk1977   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
12079cfcf5d4Sdrh ){
12081b7ecbb4Sdrh   int i;              /* loop counter */
12091b7ecbb4Sdrh   Vdbe *v;            /* VDBE under constrution */
12101b7ecbb4Sdrh   int nCol;           /* Number of columns */
12111b7ecbb4Sdrh   int onError;        /* Conflict resolution strategy */
12121bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
12131bd10f8aSdrh   int j2 = 0, j3;     /* Addresses of jump instructions */
121404adf416Sdrh   int regData;        /* Register containing first data column */
12151b7ecbb4Sdrh   int iCur;           /* Table cursor number */
12161b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
12172938f924Sdrh   sqlite3 *db;         /* Database connection */
12181b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
121965a7cd16Sdan   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
12209cfcf5d4Sdrh 
12212938f924Sdrh   db = pParse->db;
12224adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12239cfcf5d4Sdrh   assert( v!=0 );
1224417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12259cfcf5d4Sdrh   nCol = pTab->nCol;
1226aa9b8963Sdrh   regData = regRowid + 1;
1227aa9b8963Sdrh 
12289cfcf5d4Sdrh   /* Test all NOT NULL constraints.
12299cfcf5d4Sdrh   */
12309cfcf5d4Sdrh   for(i=0; i<nCol; i++){
12310ca3e24bSdrh     if( i==pTab->iPKey ){
12320ca3e24bSdrh       continue;
12330ca3e24bSdrh     }
12349cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
12350ca3e24bSdrh     if( onError==OE_None ) continue;
12369cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12379cfcf5d4Sdrh       onError = overrideError;
1238a996e477Sdrh     }else if( onError==OE_Default ){
1239a996e477Sdrh       onError = OE_Abort;
12409cfcf5d4Sdrh     }
12417977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
12429cfcf5d4Sdrh       onError = OE_Abort;
12439cfcf5d4Sdrh     }
1244b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1245b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12469cfcf5d4Sdrh     switch( onError ){
12471c92853dSdrh       case OE_Abort:
1248e0af83acSdan         sqlite3MayAbort(pParse);
1249e0af83acSdan       case OE_Rollback:
12501c92853dSdrh       case OE_Fail: {
1251f089aa45Sdrh         char *zMsg;
1252c126e63eSdrh         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1253d91c1a17Sdrh                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
12542938f924Sdrh         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
1255f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
125666a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
12579cfcf5d4Sdrh         break;
12589cfcf5d4Sdrh       }
12599cfcf5d4Sdrh       case OE_Ignore: {
12605053a79bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
12619cfcf5d4Sdrh         break;
12629cfcf5d4Sdrh       }
1263098d1684Sdrh       default: {
1264098d1684Sdrh         assert( onError==OE_Replace );
12655053a79bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
126604adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
12675053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
12689cfcf5d4Sdrh         break;
12699cfcf5d4Sdrh       }
12709cfcf5d4Sdrh     }
12719cfcf5d4Sdrh   }
12729cfcf5d4Sdrh 
12739cfcf5d4Sdrh   /* Test all CHECK constraints
12749cfcf5d4Sdrh   */
1275ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
12762938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
12772938f924Sdrh     ExprList *pCheck = pTab->pCheck;
1278aa9b8963Sdrh     pParse->ckBase = regData;
1279aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
12802938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
12812938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
12822d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
12832e06c67cSdrh       if( onError==OE_Ignore ){
128466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1285aa01c7e2Sdrh       }else{
12862938f924Sdrh         char *zConsName = pCheck->a[i].zName;
12876dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
12882938f924Sdrh         if( zConsName ){
12892938f924Sdrh           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
12902938f924Sdrh         }else{
1291f68686aeSdrh           zConsName = 0;
12922938f924Sdrh         }
1293d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1294d91c1a17Sdrh                               onError, zConsName, P4_DYNAMIC);
1295aa01c7e2Sdrh       }
1296ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1297c31c7c1cSdrh     }
12982938f924Sdrh   }
1299ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
13009cfcf5d4Sdrh 
13010bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
13020bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
13030bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
13049cfcf5d4Sdrh   */
1305f0863fe5Sdrh   if( rowidChng ){
13060ca3e24bSdrh     onError = pTab->keyConf;
13070ca3e24bSdrh     if( overrideError!=OE_Default ){
13080ca3e24bSdrh       onError = overrideError;
1309a996e477Sdrh     }else if( onError==OE_Default ){
1310a996e477Sdrh       onError = OE_Abort;
13110ca3e24bSdrh     }
1312a0217ba7Sdrh 
131379b0c956Sdrh     if( isUpdate ){
131476d462eeSdan       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
131579b0c956Sdrh     }
131604adf416Sdrh     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
13170ca3e24bSdrh     switch( onError ){
1318a0217ba7Sdrh       default: {
1319a0217ba7Sdrh         onError = OE_Abort;
1320a0217ba7Sdrh         /* Fall thru into the next case */
1321a0217ba7Sdrh       }
13221c92853dSdrh       case OE_Rollback:
13231c92853dSdrh       case OE_Abort:
13241c92853dSdrh       case OE_Fail: {
1325d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1326d91c1a17Sdrh            onError, "PRIMARY KEY must be unique", P4_STATIC);
13270ca3e24bSdrh         break;
13280ca3e24bSdrh       }
13295383ae5cSdrh       case OE_Replace: {
13302283d46cSdan         /* If there are DELETE triggers on this table and the
13312283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1332d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13332283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13342283d46cSdan         **
13352283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1336da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1337da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1338da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1339da730f6eSdan         ** when it is inserted.
1340da730f6eSdan         **
1341da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1342da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1343da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1344da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1345da730f6eSdan         ** but being more selective here allows statements like:
1346da730f6eSdan         **
1347da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1348da730f6eSdan         **
1349da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1350da730f6eSdan         ** table.
1351da730f6eSdan         */
13522283d46cSdan         Trigger *pTrigger = 0;
13532938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
13542283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
13552283d46cSdan         }
1356e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1357da730f6eSdan           sqlite3MultiWrite(pParse);
13582283d46cSdan           sqlite3GenerateRowDelete(
13592283d46cSdan               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
13602283d46cSdan           );
1361da730f6eSdan         }else if( pTab->pIndex ){
1362da730f6eSdan           sqlite3MultiWrite(pParse);
13632d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
13642283d46cSdan         }
13655383ae5cSdrh         seenReplace = 1;
13665383ae5cSdrh         break;
13675383ae5cSdrh       }
13680ca3e24bSdrh       case OE_Ignore: {
13695383ae5cSdrh         assert( seenReplace==0 );
137066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13710ca3e24bSdrh         break;
13720ca3e24bSdrh       }
13730ca3e24bSdrh     }
1374aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j3);
1375f5905aa7Sdrh     if( isUpdate ){
1376aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j2);
1377a05a722fSdrh     }
13780ca3e24bSdrh   }
13790bd1f4eaSdrh 
13800bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
13810bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
13820bd1f4eaSdrh   ** Add the new records to the indices as we go.
13830bd1f4eaSdrh   */
1384b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
13852d401ab8Sdrh     int regIdx;
13862d401ab8Sdrh     int regR;
1387b2b9d3d7Sdrh     int addrSkipRow = 0;
13882184fc75Sdrh 
1389aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1390b2fe7d8cSdrh 
1391b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1392b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
1393b2b9d3d7Sdrh       addrSkipRow = sqlite3VdbeMakeLabel(v);
1394b2b9d3d7Sdrh       pParse->ckBase = regData;
1395b2b9d3d7Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
1396b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1397b2b9d3d7Sdrh       pParse->ckBase = 0;
1398b2b9d3d7Sdrh     }
1399b2b9d3d7Sdrh 
1400b2fe7d8cSdrh     /* Create a key for accessing the index entry */
1401bbbdc83bSdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nKeyCol+1);
14029cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
1403bbbdc83bSdrh       i16 idx = pIdx->aiColumn[i];
1404bbbdc83bSdrh       if( idx<0 || idx==pTab->iPKey ){
14052d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
14069cfcf5d4Sdrh       }else{
14072d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
14089cfcf5d4Sdrh       }
14099cfcf5d4Sdrh     }
1410bbbdc83bSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[iCur]);
14118d129422Sdrh     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
1412bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1413b2fe7d8cSdrh 
1414b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
14159cfcf5d4Sdrh     onError = pIdx->onError;
1416de630353Sdanielk1977     if( onError==OE_None ){
1417bbbdc83bSdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
14188a9789b6Sdrh       sqlite3VdbeResolveLabel(v, addrSkipRow);
1419de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1420de630353Sdanielk1977     }
14219cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14229cfcf5d4Sdrh       onError = overrideError;
1423a996e477Sdrh     }else if( onError==OE_Default ){
1424a996e477Sdrh       onError = OE_Abort;
14259cfcf5d4Sdrh     }
14265383ae5cSdrh     if( seenReplace ){
14275383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
14285383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
14295383ae5cSdrh     }
14305383ae5cSdrh 
1431b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
14322d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
143365a7cd16Sdan     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
14342d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1435de630353Sdanielk1977                            regR, SQLITE_INT_TO_PTR(regIdx),
1436a9e852b6Smlcreech                            P4_INT32);
1437bbbdc83bSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nKeyCol+1);
1438b2fe7d8cSdrh 
1439b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1440b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1441b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
14429cfcf5d4Sdrh     switch( onError ){
14431c92853dSdrh       case OE_Rollback:
14441c92853dSdrh       case OE_Abort:
14451c92853dSdrh       case OE_Fail: {
1446098d1684Sdrh         int j;
1447098d1684Sdrh         StrAccum errMsg;
1448098d1684Sdrh         const char *zSep;
1449098d1684Sdrh         char *zErr;
1450098d1684Sdrh 
1451098d1684Sdrh         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
14522938f924Sdrh         errMsg.db = db;
1453bbbdc83bSdrh         zSep = pIdx->nKeyCol>1 ? "columns " : "column ";
1454bbbdc83bSdrh         for(j=0; j<pIdx->nKeyCol; j++){
145537ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1456098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zSep, -1);
1457098d1684Sdrh           zSep = ", ";
1458098d1684Sdrh           sqlite3StrAccumAppend(&errMsg, zCol, -1);
145937ed48edSdrh         }
1460098d1684Sdrh         sqlite3StrAccumAppend(&errMsg,
1461bbbdc83bSdrh             pIdx->nKeyCol>1 ? " are not unique" : " is not unique", -1);
1462098d1684Sdrh         zErr = sqlite3StrAccumFinish(&errMsg);
1463d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
1464d91c1a17Sdrh                               onError, zErr, 0);
1465098d1684Sdrh         sqlite3DbFree(errMsg.db, zErr);
14669cfcf5d4Sdrh         break;
14679cfcf5d4Sdrh       }
14689cfcf5d4Sdrh       case OE_Ignore: {
14690ca3e24bSdrh         assert( seenReplace==0 );
147066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14719cfcf5d4Sdrh         break;
14729cfcf5d4Sdrh       }
1473098d1684Sdrh       default: {
14742283d46cSdan         Trigger *pTrigger = 0;
1475098d1684Sdrh         assert( onError==OE_Replace );
14761bea559aSdan         sqlite3MultiWrite(pParse);
14772938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
14782283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
14792283d46cSdan         }
14802283d46cSdan         sqlite3GenerateRowDelete(
14812283d46cSdan             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
14822283d46cSdan         );
14830ca3e24bSdrh         seenReplace = 1;
14849cfcf5d4Sdrh         break;
14859cfcf5d4Sdrh       }
14869cfcf5d4Sdrh     }
14872d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
1488b2b9d3d7Sdrh     sqlite3VdbeResolveLabel(v, addrSkipRow);
14892d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
14909cfcf5d4Sdrh   }
1491de630353Sdanielk1977 
1492de630353Sdanielk1977   if( pbMayReplace ){
1493de630353Sdanielk1977     *pbMayReplace = seenReplace;
1494de630353Sdanielk1977   }
14959cfcf5d4Sdrh }
14960ca3e24bSdrh 
14970ca3e24bSdrh /*
14980ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
14994adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
150004adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
150104adf416Sdrh ** rowid and the content to be inserted.
15020ca3e24bSdrh **
1503b419a926Sdrh ** The arguments to this routine should be the same as the first six
15044adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
15050ca3e24bSdrh */
15064adee20fSdanielk1977 void sqlite3CompleteInsertion(
15070ca3e24bSdrh   Parse *pParse,      /* The parser context */
15080ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
150904adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
151004adf416Sdrh   int regRowid,       /* Range of content */
1511aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
151270ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1513de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1514de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
15150ca3e24bSdrh ){
15160ca3e24bSdrh   int i;
15170ca3e24bSdrh   Vdbe *v;
15180ca3e24bSdrh   Index *pIdx;
15191bd10f8aSdrh   u8 pik_flags;
152004adf416Sdrh   int regData;
1521b7654111Sdrh   int regRec;
15220ca3e24bSdrh 
15234adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
15240ca3e24bSdrh   assert( v!=0 );
1525417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1526b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1527aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
1528b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1529b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1530b2b9d3d7Sdrh     }
153104adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1532de630353Sdanielk1977     if( useSeekResult ){
1533de630353Sdanielk1977       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1534de630353Sdanielk1977     }
15350ca3e24bSdrh   }
1536*ec95c441Sdrh   if( !HasRowid(pTab) ) return;
153704adf416Sdrh   regData = regRowid + 1;
1538b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
15391db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1540a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1541da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
15424794f735Sdrh   if( pParse->nested ){
15434794f735Sdrh     pik_flags = 0;
15444794f735Sdrh   }else{
154594eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
154694eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
15474794f735Sdrh   }
1548e4d90813Sdrh   if( appendBias ){
1549e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1550e4d90813Sdrh   }
1551de630353Sdanielk1977   if( useSeekResult ){
1552de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1553de630353Sdanielk1977   }
1554b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
155594eb6a14Sdanielk1977   if( !pParse->nested ){
15568d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
155794eb6a14Sdanielk1977   }
1558b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
15590ca3e24bSdrh }
1560cd44690aSdrh 
1561cd44690aSdrh /*
1562290c1948Sdrh ** Generate code that will open cursors for a table and for all
156304adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1564cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1565aa9b8963Sdrh **
1566aa9b8963Sdrh ** Return the number of indices on the table.
1567cd44690aSdrh */
1568aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1569290c1948Sdrh   Parse *pParse,   /* Parsing context */
1570290c1948Sdrh   Table *pTab,     /* Table to be opened */
157104adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1572290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1573290c1948Sdrh ){
1574cd44690aSdrh   int i;
15754cbdda9eSdrh   int iDb;
1576cd44690aSdrh   Index *pIdx;
15774cbdda9eSdrh   Vdbe *v;
15784cbdda9eSdrh 
1579aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
15804cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
15814cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1582cd44690aSdrh   assert( v!=0 );
158304adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1584cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1585b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1586da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
158704adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
158866a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1589207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1590cd44690aSdrh   }
15911b7ecbb4Sdrh   if( pParse->nTab<baseCur+i ){
159204adf416Sdrh     pParse->nTab = baseCur+i;
1593290c1948Sdrh   }
1594aa9b8963Sdrh   return i-1;
1595cd44690aSdrh }
15969d9cf229Sdrh 
159791c58e23Sdrh 
159891c58e23Sdrh #ifdef SQLITE_TEST
159991c58e23Sdrh /*
160091c58e23Sdrh ** The following global variable is incremented whenever the
160191c58e23Sdrh ** transfer optimization is used.  This is used for testing
160291c58e23Sdrh ** purposes only - to make sure the transfer optimization really
160391c58e23Sdrh ** is happening when it is suppose to.
160491c58e23Sdrh */
160591c58e23Sdrh int sqlite3_xferopt_count;
160691c58e23Sdrh #endif /* SQLITE_TEST */
160791c58e23Sdrh 
160891c58e23Sdrh 
16099d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
16109d9cf229Sdrh /*
16119d9cf229Sdrh ** Check to collation names to see if they are compatible.
16129d9cf229Sdrh */
16139d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
16149d9cf229Sdrh   if( z1==0 ){
16159d9cf229Sdrh     return z2==0;
16169d9cf229Sdrh   }
16179d9cf229Sdrh   if( z2==0 ){
16189d9cf229Sdrh     return 0;
16199d9cf229Sdrh   }
16209d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
16219d9cf229Sdrh }
16229d9cf229Sdrh 
16239d9cf229Sdrh 
16249d9cf229Sdrh /*
16259d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
16269d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
16279d9cf229Sdrh ** for a compatible index:
16289d9cf229Sdrh **
16299d9cf229Sdrh **    *   The index is over the same set of columns
16309d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
16319d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
16329d9cf229Sdrh **    *   The same collating sequence on each column
1633b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
16349d9cf229Sdrh */
16359d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
16369d9cf229Sdrh   int i;
16379d9cf229Sdrh   assert( pDest && pSrc );
16389d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1639bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
16409d9cf229Sdrh     return 0;   /* Different number of columns */
16419d9cf229Sdrh   }
16429d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
16439d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
16449d9cf229Sdrh   }
1645bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
16469d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
16479d9cf229Sdrh       return 0;   /* Different columns indexed */
16489d9cf229Sdrh     }
16499d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
16509d9cf229Sdrh       return 0;   /* Different sort orders */
16519d9cf229Sdrh     }
16523f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
165360a713c6Sdrh       return 0;   /* Different collating sequences */
16549d9cf229Sdrh     }
16559d9cf229Sdrh   }
1656619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1657b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1658b2b9d3d7Sdrh   }
16599d9cf229Sdrh 
16609d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
16619d9cf229Sdrh   return 1;
16629d9cf229Sdrh }
16639d9cf229Sdrh 
16649d9cf229Sdrh /*
16659d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
16669d9cf229Sdrh **
16679d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
16689d9cf229Sdrh **
1669ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
1670ccdf1baeSdrh ** Columns are not decoded and reassemblied, which greatly improves
1671ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
16729d9cf229Sdrh **
1673ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1674ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1675ccdf1baeSdrh ** embedded in the code for details.
16769d9cf229Sdrh **
1677ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1678ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1679ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1680ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1681ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1682ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1683ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1684ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1685ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
16869d9cf229Sdrh **
1687ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
16889d9cf229Sdrh */
16899d9cf229Sdrh static int xferOptimization(
16909d9cf229Sdrh   Parse *pParse,        /* Parser context */
16919d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
16929d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
16939d9cf229Sdrh   int onError,          /* How to handle constraint errors */
16949d9cf229Sdrh   int iDbDest           /* The database of pDest */
16959d9cf229Sdrh ){
16969d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
16979d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
16989d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
16999d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
17009d9cf229Sdrh   int i;                           /* Loop counter */
17019d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
17029d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
17039d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
17049d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
17059d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
17069d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
17079d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
17086a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1709f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1710b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
17119d9cf229Sdrh 
17129d9cf229Sdrh   if( pSelect==0 ){
17139d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
17149d9cf229Sdrh   }
17152f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
17169d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
17179d9cf229Sdrh   }
17189d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17197d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
17209d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
17219d9cf229Sdrh   }
17229d9cf229Sdrh #endif
17239d9cf229Sdrh   if( onError==OE_Default ){
1724e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1725e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
17269d9cf229Sdrh   }
17275ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
17289d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
17299d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
17309d9cf229Sdrh   }
17319d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
17329d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
17339d9cf229Sdrh   }
17349d9cf229Sdrh   if( pSelect->pWhere ){
17359d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
17369d9cf229Sdrh   }
17379d9cf229Sdrh   if( pSelect->pOrderBy ){
17389d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
17399d9cf229Sdrh   }
17408103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
17418103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
17429d9cf229Sdrh   if( pSelect->pGroupBy ){
17439d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
17449d9cf229Sdrh   }
17459d9cf229Sdrh   if( pSelect->pLimit ){
17469d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
17479d9cf229Sdrh   }
17488103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
17499d9cf229Sdrh   if( pSelect->pPrior ){
17509d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
17519d9cf229Sdrh   }
17527d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
17539d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
17549d9cf229Sdrh   }
17559d9cf229Sdrh   pEList = pSelect->pEList;
17569d9cf229Sdrh   assert( pEList!=0 );
17579d9cf229Sdrh   if( pEList->nExpr!=1 ){
17589d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
17599d9cf229Sdrh   }
17609d9cf229Sdrh   assert( pEList->a[0].pExpr );
17619d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
17629d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
17639d9cf229Sdrh   }
17649d9cf229Sdrh 
17659d9cf229Sdrh   /* At this point we have established that the statement is of the
17669d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
17679d9cf229Sdrh   ** we have to check the semantics.
17689d9cf229Sdrh   */
17699d9cf229Sdrh   pItem = pSelect->pSrc->a;
177041fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
17719d9cf229Sdrh   if( pSrc==0 ){
17729d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
17739d9cf229Sdrh   }
17749d9cf229Sdrh   if( pSrc==pDest ){
17759d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
17769d9cf229Sdrh   }
17779d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17787d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
17799d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
17809d9cf229Sdrh   }
17819d9cf229Sdrh #endif
17829d9cf229Sdrh   if( pSrc->pSelect ){
17839d9cf229Sdrh     return 0;   /* tab2 may not be a view */
17849d9cf229Sdrh   }
17859d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
17869d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
17879d9cf229Sdrh   }
17889d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
17899d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
17909d9cf229Sdrh   }
17919d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
17929d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
17939d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
17949d9cf229Sdrh     }
17959d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
17969d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
17979d9cf229Sdrh     }
17989d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
17999d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
18009d9cf229Sdrh     }
18019d9cf229Sdrh   }
18029d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1803f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1804f33c9fadSdrh       destHasUniqueIdx = 1;
1805f33c9fadSdrh     }
18069d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
18079d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18089d9cf229Sdrh     }
18099d9cf229Sdrh     if( pSrcIdx==0 ){
18109d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
18119d9cf229Sdrh     }
18129d9cf229Sdrh   }
18137fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1814619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
18158103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
18168103b7d2Sdrh   }
18177fc2f41bSdrh #endif
1818713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1819713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1820713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1821713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1822713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1823713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1824713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1825713de341Sdrh   */
1826713de341Sdrh   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1827713de341Sdrh     return 0;
1828713de341Sdrh   }
1829713de341Sdrh #endif
18301696124dSdan   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1831ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
18321696124dSdan   }
18339d9cf229Sdrh 
1834ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1835ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1836ccdf1baeSdrh   ** table (tab1) is initially empty.
18379d9cf229Sdrh   */
1838dd73521bSdrh #ifdef SQLITE_TEST
1839dd73521bSdrh   sqlite3_xferopt_count++;
1840dd73521bSdrh #endif
18419d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
18429d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1843f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
18449d9cf229Sdrh   iSrc = pParse->nTab++;
18459d9cf229Sdrh   iDest = pParse->nTab++;
18466a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
18479d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1848ccdf1baeSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1849ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
1850ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1851ccdf1baeSdrh   ){
1852ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
1853ccdf1baeSdrh     ** only if the destination table is initially empty.  This code makes
1854ccdf1baeSdrh     ** that determination.  Conditions under which the destination must
1855ccdf1baeSdrh     ** be empty:
1856f33c9fadSdrh     **
1857ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1858ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
1859ccdf1baeSdrh     **     of index entries might need to change.)
1860ccdf1baeSdrh     **
1861ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
1862ccdf1baeSdrh     **     is unable to test uniqueness.)
1863ccdf1baeSdrh     **
1864ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
18659d9cf229Sdrh     */
186666a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
186766a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
18689d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
18699d9cf229Sdrh   }else{
18709d9cf229Sdrh     emptyDestTest = 0;
18719d9cf229Sdrh   }
18729d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
187366a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1874b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1875b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
187642242dedSdrh   if( pDest->iPKey>=0 ){
1877b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1878b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1879d91c1a17Sdrh     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1880d91c1a17Sdrh         onError, "PRIMARY KEY must be unique", P4_STATIC);
18819d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1882b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1883bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1884b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
188595bad4c7Sdrh   }else{
1886b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
18877d10d5a6Sdrh     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
188895bad4c7Sdrh   }
1889b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1890b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1891b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
18921f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
189366a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
18949d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
18951b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
18969d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18979d9cf229Sdrh     }
18989d9cf229Sdrh     assert( pSrcIdx );
189966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
190066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19019d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1902207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1903207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1904d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
19059d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1906207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
190766a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
190859885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
1909207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
191066a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1911b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1912b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
191366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
19149d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
19159d9cf229Sdrh   }
19169d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1917b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1918b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
191966a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
192066a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19219d9cf229Sdrh   if( emptyDestTest ){
192266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
19239d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
192466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
19259d9cf229Sdrh     return 0;
19269d9cf229Sdrh   }else{
19279d9cf229Sdrh     return 1;
19289d9cf229Sdrh   }
19299d9cf229Sdrh }
19309d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1931