xref: /sqlite-3.40.0/src/insert.c (revision ab06b0e5)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17cce7d176Sdrh /*
1826198bb4Sdrh ** Generate code that will
19dd9930efSdrh **
2026198bb4Sdrh **   (1) acquire a lock for table pTab then
2126198bb4Sdrh **   (2) open pTab as cursor iCur.
2226198bb4Sdrh **
2326198bb4Sdrh ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
2426198bb4Sdrh ** for that table that is actually opened.
25bbb5e4e0Sdrh */
26bbb5e4e0Sdrh void sqlite3OpenTable(
272ec2fb22Sdrh   Parse *pParse,  /* Generate code into this VDBE */
28bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
29bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
30bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
31bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
32bbb5e4e0Sdrh ){
33bbb5e4e0Sdrh   Vdbe *v;
345f53aac2Sdrh   assert( !IsVirtual(pTab) );
352ec2fb22Sdrh   v = sqlite3GetVdbe(pParse);
36bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
372ec2fb22Sdrh   sqlite3TableLock(pParse, iDb, pTab->tnum,
382ec2fb22Sdrh                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
39ec95c441Sdrh   if( HasRowid(pTab) ){
40261c02d9Sdrh     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
41dd9930efSdrh     VdbeComment((v, "%s", pTab->zName));
4226198bb4Sdrh   }else{
43dd9930efSdrh     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44dd9930efSdrh     assert( pPk!=0 );
45dd9930efSdrh     assert( pPk->tnum=pTab->tnum );
462ec2fb22Sdrh     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
472ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
48bbb5e4e0Sdrh     VdbeComment((v, "%s", pTab->zName));
49bbb5e4e0Sdrh   }
50ec95c441Sdrh }
51bbb5e4e0Sdrh 
52bbb5e4e0Sdrh /*
5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index
5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in
5569f8bb9cSdan ** the table, according to the affinity of the column:
563d1bfeaaSdanielk1977 **
573d1bfeaaSdanielk1977 **  Character      Column affinity
583d1bfeaaSdanielk1977 **  ------------------------------
594583c37cSdrh **  'A'            NONE
604583c37cSdrh **  'B'            TEXT
614583c37cSdrh **  'C'            NUMERIC
624583c37cSdrh **  'D'            INTEGER
634583c37cSdrh **  'F'            REAL
642d401ab8Sdrh **
654583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the
662d401ab8Sdrh ** rowid that appears as the last column in every index.
6769f8bb9cSdan **
6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string
6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be
7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called.
713d1bfeaaSdanielk1977 */
7269f8bb9cSdan const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
73a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
74e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
75a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
76e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
77a37cdde0Sdanielk1977     **
78a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
79e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80a37cdde0Sdanielk1977     ** up.
81a37cdde0Sdanielk1977     */
82a37cdde0Sdanielk1977     int n;
83a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
84abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
85ad124329Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
86a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
87633e6d57Sdrh       db->mallocFailed = 1;
8869f8bb9cSdan       return 0;
89a37cdde0Sdanielk1977     }
90ad124329Sdrh     for(n=0; n<pIdx->nColumn; n++){
91ad124329Sdrh       i16 x = pIdx->aiColumn[n];
92ad124329Sdrh       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
93a37cdde0Sdanielk1977     }
942d401ab8Sdrh     pIdx->zColAff[n] = 0;
95a37cdde0Sdanielk1977   }
963d1bfeaaSdanielk1977 
9769f8bb9cSdan   return pIdx->zColAff;
98a37cdde0Sdanielk1977 }
99a37cdde0Sdanielk1977 
100a37cdde0Sdanielk1977 /*
10157bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been
10257bf4a8eSdrh ** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
10357bf4a8eSdrh **
104b6e8fd10Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
10557bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
10657bf4a8eSdrh ** for register iReg and following.  Or if affinities exists and iReg==0,
10757bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should  be
10857bf4a8eSdrh ** an OP_MakeRecord) to the affinity string.
10957bf4a8eSdrh **
110b6e8fd10Sdrh ** A column affinity string has one character per column:
111a37cdde0Sdanielk1977 **
112a37cdde0Sdanielk1977 **  Character      Column affinity
113a37cdde0Sdanielk1977 **  ------------------------------
1144583c37cSdrh **  'A'            NONE
1154583c37cSdrh **  'B'            TEXT
1164583c37cSdrh **  'C'            NUMERIC
1174583c37cSdrh **  'D'            INTEGER
1184583c37cSdrh **  'E'            REAL
119a37cdde0Sdanielk1977 */
12057bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
1213d1bfeaaSdanielk1977   int i;
12257bf4a8eSdrh   char *zColAff = pTab->zColAff;
12357bf4a8eSdrh   if( zColAff==0 ){
124abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
125b975598eSdrh     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
1263d1bfeaaSdanielk1977     if( !zColAff ){
127633e6d57Sdrh       db->mallocFailed = 1;
128a37cdde0Sdanielk1977       return;
1293d1bfeaaSdanielk1977     }
1303d1bfeaaSdanielk1977 
1313d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
132a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1333d1bfeaaSdanielk1977     }
13457bf4a8eSdrh     do{
13557bf4a8eSdrh       zColAff[i--] = 0;
13657bf4a8eSdrh     }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
1373d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1383d1bfeaaSdanielk1977   }
13957bf4a8eSdrh   i = sqlite3Strlen30(zColAff);
14057bf4a8eSdrh   if( i ){
14157bf4a8eSdrh     if( iReg ){
14257bf4a8eSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
14357bf4a8eSdrh     }else{
14457bf4a8eSdrh       sqlite3VdbeChangeP4(v, -1, zColAff, i);
14557bf4a8eSdrh     }
14657bf4a8eSdrh   }
1473d1bfeaaSdanielk1977 }
1483d1bfeaaSdanielk1977 
1494d88778bSdanielk1977 /*
15048d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
151b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if
15248d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
153b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT.
1544d88778bSdanielk1977 */
15505a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){
156595a523aSdanielk1977   Vdbe *v = sqlite3GetVdbe(p);
1574d88778bSdanielk1977   int i;
15848d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
159595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
160595a523aSdanielk1977   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
161595a523aSdanielk1977 #endif
162595a523aSdanielk1977 
16305a86c5cSdrh   for(i=1; i<iEnd; i++){
16448d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
165ef0bea92Sdrh     assert( pOp!=0 );
166207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
16748d1178aSdrh       Index *pIndex;
168207872a4Sdanielk1977       int tnum = pOp->p2;
16948d1178aSdrh       if( tnum==pTab->tnum ){
17048d1178aSdrh         return 1;
17148d1178aSdrh       }
17248d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
17348d1178aSdrh         if( tnum==pIndex->tnum ){
17448d1178aSdrh           return 1;
17548d1178aSdrh         }
17648d1178aSdrh       }
17748d1178aSdrh     }
178543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
179595a523aSdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
1802dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
18166a5167bSdrh       assert( pOp->p4type==P4_VTAB );
18248d1178aSdrh       return 1;
1834d88778bSdanielk1977     }
184543165efSdrh #endif
1854d88778bSdanielk1977   }
1864d88778bSdanielk1977   return 0;
1874d88778bSdanielk1977 }
1883d1bfeaaSdanielk1977 
1899d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1909d9cf229Sdrh /*
1910b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab
1920b9f50d8Sdrh ** which is in database iDb.  Return the register number for the register
1930b9f50d8Sdrh ** that holds the maximum rowid.
1949d9cf229Sdrh **
1950b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the
1960b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within
1970b9f50d8Sdrh ** triggers.  A new AutoincInfo structure is created if this is the
1980b9f50d8Sdrh ** first use of table pTab.  On 2nd and subsequent uses, the original
1990b9f50d8Sdrh ** AutoincInfo structure is used.
2009d9cf229Sdrh **
2010b9f50d8Sdrh ** Three memory locations are allocated:
2020b9f50d8Sdrh **
2030b9f50d8Sdrh **   (1)  Register to hold the name of the pTab table.
2040b9f50d8Sdrh **   (2)  Register to hold the maximum ROWID of pTab.
2050b9f50d8Sdrh **   (3)  Register to hold the rowid in sqlite_sequence of pTab
2060b9f50d8Sdrh **
2070b9f50d8Sdrh ** The 2nd register is the one that is returned.  That is all the
2080b9f50d8Sdrh ** insert routine needs to know about.
2099d9cf229Sdrh */
2109d9cf229Sdrh static int autoIncBegin(
2119d9cf229Sdrh   Parse *pParse,      /* Parsing context */
2129d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
2139d9cf229Sdrh   Table *pTab         /* The table we are writing to */
2149d9cf229Sdrh ){
2156a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
2167d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
21765a7cd16Sdan     Parse *pToplevel = sqlite3ParseToplevel(pParse);
2180b9f50d8Sdrh     AutoincInfo *pInfo;
2190b9f50d8Sdrh 
22065a7cd16Sdan     pInfo = pToplevel->pAinc;
2210b9f50d8Sdrh     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
2220b9f50d8Sdrh     if( pInfo==0 ){
2230b9f50d8Sdrh       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
2240b9f50d8Sdrh       if( pInfo==0 ) return 0;
22565a7cd16Sdan       pInfo->pNext = pToplevel->pAinc;
22665a7cd16Sdan       pToplevel->pAinc = pInfo;
2270b9f50d8Sdrh       pInfo->pTab = pTab;
2280b9f50d8Sdrh       pInfo->iDb = iDb;
22965a7cd16Sdan       pToplevel->nMem++;                  /* Register to hold name of table */
23065a7cd16Sdan       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
23165a7cd16Sdan       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
2320b9f50d8Sdrh     }
2330b9f50d8Sdrh     memId = pInfo->regCtr;
2349d9cf229Sdrh   }
2359d9cf229Sdrh   return memId;
2369d9cf229Sdrh }
2379d9cf229Sdrh 
2389d9cf229Sdrh /*
2390b9f50d8Sdrh ** This routine generates code that will initialize all of the
2400b9f50d8Sdrh ** register used by the autoincrement tracker.
2410b9f50d8Sdrh */
2420b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){
2430b9f50d8Sdrh   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
2440b9f50d8Sdrh   sqlite3 *db = pParse->db;  /* The database connection */
2450b9f50d8Sdrh   Db *pDb;                   /* Database only autoinc table */
2460b9f50d8Sdrh   int memId;                 /* Register holding max rowid */
2470b9f50d8Sdrh   int addr;                  /* A VDBE address */
2480b9f50d8Sdrh   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
2490b9f50d8Sdrh 
250345ba7dbSdrh   /* This routine is never called during trigger-generation.  It is
251345ba7dbSdrh   ** only called from the top-level */
252345ba7dbSdrh   assert( pParse->pTriggerTab==0 );
253345ba7dbSdrh   assert( pParse==sqlite3ParseToplevel(pParse) );
25476d462eeSdan 
2550b9f50d8Sdrh   assert( v );   /* We failed long ago if this is not so */
2560b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
2570b9f50d8Sdrh     pDb = &db->aDb[p->iDb];
2580b9f50d8Sdrh     memId = p->regCtr;
2592120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
2600b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
261f4d31bcbSdrh     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
2620b9f50d8Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2630b9f50d8Sdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
264688852abSdrh     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
2650b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
266688852abSdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
2670b9f50d8Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2680b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
2690b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
2700b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
271688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
2720b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
2730b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
2740b9f50d8Sdrh   }
2750b9f50d8Sdrh }
2760b9f50d8Sdrh 
2770b9f50d8Sdrh /*
2789d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2799d9cf229Sdrh **
2809d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2819d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2829d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2839d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2849d9cf229Sdrh */
2856a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2869d9cf229Sdrh   if( memId>0 ){
2876a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2889d9cf229Sdrh   }
2899d9cf229Sdrh }
2909d9cf229Sdrh 
2919d9cf229Sdrh /*
2920b9f50d8Sdrh ** This routine generates the code needed to write autoincrement
2930b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register.
2940b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement
2950b9f50d8Sdrh ** table (either directly or through triggers) needs to call this
2960b9f50d8Sdrh ** routine just before the "exit" code.
2979d9cf229Sdrh */
2980b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){
2990b9f50d8Sdrh   AutoincInfo *p;
3009d9cf229Sdrh   Vdbe *v = pParse->pVdbe;
3010b9f50d8Sdrh   sqlite3 *db = pParse->db;
3026a288a33Sdrh 
3039d9cf229Sdrh   assert( v );
3040b9f50d8Sdrh   for(p = pParse->pAinc; p; p = p->pNext){
3050b9f50d8Sdrh     Db *pDb = &db->aDb[p->iDb];
3063d77dee9Sdrh     int j1;
3070b9f50d8Sdrh     int iRec;
3080b9f50d8Sdrh     int memId = p->regCtr;
3090b9f50d8Sdrh 
3100b9f50d8Sdrh     iRec = sqlite3GetTempReg(pParse);
3112120608eSdrh     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
3120b9f50d8Sdrh     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
313688852abSdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
3140b9f50d8Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
3156a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
316a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
3170b9f50d8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
31835573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3190b9f50d8Sdrh     sqlite3VdbeAddOp0(v, OP_Close);
3200b9f50d8Sdrh     sqlite3ReleaseTempReg(pParse, iRec);
3219d9cf229Sdrh   }
3229d9cf229Sdrh }
3239d9cf229Sdrh #else
3249d9cf229Sdrh /*
3259d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
3269d9cf229Sdrh ** above are all no-ops
3279d9cf229Sdrh */
3289d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
329287fb61cSdanielk1977 # define autoIncStep(A,B,C)
3309d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3319d9cf229Sdrh 
3329d9cf229Sdrh 
3339d9cf229Sdrh /* Forward declaration */
3349d9cf229Sdrh static int xferOptimization(
3359d9cf229Sdrh   Parse *pParse,        /* Parser context */
3369d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
3379d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3389d9cf229Sdrh   int onError,          /* How to handle constraint errors */
3399d9cf229Sdrh   int iDbDest           /* The database of pDest */
3409d9cf229Sdrh );
3419d9cf229Sdrh 
3423d1bfeaaSdanielk1977 /*
343d82b5021Sdrh ** This routine is called to handle SQL of the following forms:
344cce7d176Sdrh **
345cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
3461ccde15dSdrh **    insert into TABLE (IDLIST) select
347cce7d176Sdrh **
3481ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
3491ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
350967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
3511ccde15dSdrh **
3521ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
3531ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
3541ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
3551ccde15dSdrh ** data for the insert.
356142e30dfSdrh **
3579d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
358d82b5021Sdrh ** insert with data coming from a VALUES clause, the code executes
359e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
360e00ee6ebSdrh ** the "1st template"):
361142e30dfSdrh **
362142e30dfSdrh **         open write cursor to <table> and its indices
363ec95c441Sdrh **         put VALUES clause expressions into registers
364142e30dfSdrh **         write the resulting record into <table>
365142e30dfSdrh **         cleanup
366142e30dfSdrh **
3679d9cf229Sdrh ** The three remaining templates assume the statement is of the form
368142e30dfSdrh **
369142e30dfSdrh **   INSERT INTO <table> SELECT ...
370142e30dfSdrh **
3719d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
3729d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
3739d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
3749d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
3759d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
3769d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
3779d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
378e00ee6ebSdrh ** template.  This is the 2nd template.
3799d9cf229Sdrh **
3809d9cf229Sdrh **         open a write cursor to <table>
3819d9cf229Sdrh **         open read cursor on <table2>
3829d9cf229Sdrh **         transfer all records in <table2> over to <table>
3839d9cf229Sdrh **         close cursors
3849d9cf229Sdrh **         foreach index on <table>
3859d9cf229Sdrh **           open a write cursor on the <table> index
3869d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
3879d9cf229Sdrh **           transfer all records from the read to the write cursors
3889d9cf229Sdrh **           close cursors
3899d9cf229Sdrh **         end foreach
3909d9cf229Sdrh **
391e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
3929d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
3939d9cf229Sdrh ** The generated code follows this template:
394142e30dfSdrh **
395e00ee6ebSdrh **         X <- A
396142e30dfSdrh **         goto B
397142e30dfSdrh **      A: setup for the SELECT
3989d9cf229Sdrh **         loop over the rows in the SELECT
399e00ee6ebSdrh **           load values into registers R..R+n
400e00ee6ebSdrh **           yield X
401142e30dfSdrh **         end loop
402142e30dfSdrh **         cleanup after the SELECT
40381cf13ecSdrh **         end-coroutine X
404e00ee6ebSdrh **      B: open write cursor to <table> and its indices
40581cf13ecSdrh **      C: yield X, at EOF goto D
406e00ee6ebSdrh **         insert the select result into <table> from R..R+n
407e00ee6ebSdrh **         goto C
408142e30dfSdrh **      D: cleanup
409142e30dfSdrh **
410e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
411142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
412142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
41360ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of
414142e30dfSdrh ** the select.  The template is like this:
415142e30dfSdrh **
416e00ee6ebSdrh **         X <- A
417142e30dfSdrh **         goto B
418142e30dfSdrh **      A: setup for the SELECT
419142e30dfSdrh **         loop over the tables in the SELECT
420e00ee6ebSdrh **           load value into register R..R+n
421e00ee6ebSdrh **           yield X
422142e30dfSdrh **         end loop
423142e30dfSdrh **         cleanup after the SELECT
42481cf13ecSdrh **         end co-routine R
425e00ee6ebSdrh **      B: open temp table
42681cf13ecSdrh **      L: yield X, at EOF goto M
427e00ee6ebSdrh **         insert row from R..R+n into temp table
428e00ee6ebSdrh **         goto L
429e00ee6ebSdrh **      M: open write cursor to <table> and its indices
430e00ee6ebSdrh **         rewind temp table
431e00ee6ebSdrh **      C: loop over rows of intermediate table
432142e30dfSdrh **           transfer values form intermediate table into <table>
433e00ee6ebSdrh **         end loop
434e00ee6ebSdrh **      D: cleanup
435cce7d176Sdrh */
4364adee20fSdanielk1977 void sqlite3Insert(
437cce7d176Sdrh   Parse *pParse,        /* Parser context */
438113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
4395974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
4409cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
4419cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
442cce7d176Sdrh ){
4436a288a33Sdrh   sqlite3 *db;          /* The main database structure */
4446a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
445113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
446e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
4475974a30fSdrh   int i, j, idx;        /* Loop counters */
4485974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
4495974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
450967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
4516a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
45226198bb4Sdrh   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
45326198bb4Sdrh   int iIdxCur = 0;      /* First index cursor */
454d82b5021Sdrh   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
4550ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
456cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
457e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
458e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
4592eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
4606a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
4612958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
46205a86c5cSdrh   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
46305a86c5cSdrh   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
46405a86c5cSdrh   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
46505a86c5cSdrh   u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
46675593d96Sdrh   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
467cce7d176Sdrh 
4686a288a33Sdrh   /* Register allocations */
4691bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
4706a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
4716a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
4726a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
4736a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
4746a288a33Sdrh   int regData;          /* register holding first column to insert */
475aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
4766a288a33Sdrh 
477798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
478798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
4792f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
4802f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
481798da52cSdrh #endif
482c3f9bad2Sdanielk1977 
48317435752Sdrh   db = pParse->db;
4841bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
48517435752Sdrh   if( pParse->nErr || db->mallocFailed ){
4866f7adc8aSdrh     goto insert_cleanup;
4876f7adc8aSdrh   }
488daffd0e5Sdrh 
48975593d96Sdrh   /* If the Select object is really just a simple VALUES() list with a
49075593d96Sdrh   ** single row values (the common case) then keep that one row of values
49175593d96Sdrh   ** and go ahead and discard the Select object
49275593d96Sdrh   */
49375593d96Sdrh   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
49475593d96Sdrh     pList = pSelect->pEList;
49575593d96Sdrh     pSelect->pEList = 0;
49675593d96Sdrh     sqlite3SelectDelete(db, pSelect);
49775593d96Sdrh     pSelect = 0;
49875593d96Sdrh   }
49975593d96Sdrh 
5001ccde15dSdrh   /* Locate the table into which we will be inserting new information.
5011ccde15dSdrh   */
502113088ecSdrh   assert( pTabList->nSrc==1 );
503113088ecSdrh   zTab = pTabList->a[0].zName;
504098d1684Sdrh   if( NEVER(zTab==0) ) goto insert_cleanup;
5054adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
506c3f9bad2Sdanielk1977   if( pTab==0 ){
507c3f9bad2Sdanielk1977     goto insert_cleanup;
508c3f9bad2Sdanielk1977   }
509da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
510da184236Sdanielk1977   assert( iDb<db->nDb );
511da184236Sdanielk1977   pDb = &db->aDb[iDb];
5122958a4e6Sdrh   zDb = pDb->zName;
5134adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
5141962bda7Sdrh     goto insert_cleanup;
5151962bda7Sdrh   }
516ec95c441Sdrh   withoutRowid = !HasRowid(pTab);
517c3f9bad2Sdanielk1977 
518b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
519b7f9164eSdrh   ** inserted into is a view
520b7f9164eSdrh   */
521b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
5222f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
523b7f9164eSdrh   isView = pTab->pSelect!=0;
524b7f9164eSdrh #else
5252f886d1dSdanielk1977 # define pTrigger 0
5262f886d1dSdanielk1977 # define tmask 0
527b7f9164eSdrh # define isView 0
528b7f9164eSdrh #endif
529b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
530b7f9164eSdrh # undef isView
531b7f9164eSdrh # define isView 0
532b7f9164eSdrh #endif
5332f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
534b7f9164eSdrh 
535f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
536d82b5021Sdrh   ** ViewGetColumnNames() is a no-op if pTab is not a view.
537f573c99bSdrh   */
538b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
539f573c99bSdrh     goto insert_cleanup;
540f573c99bSdrh   }
541f573c99bSdrh 
542d82b5021Sdrh   /* Cannot insert into a read-only table.
543595a523aSdanielk1977   */
544595a523aSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
545595a523aSdanielk1977     goto insert_cleanup;
546595a523aSdanielk1977   }
547595a523aSdanielk1977 
5481ccde15dSdrh   /* Allocate a VDBE
5491ccde15dSdrh   */
5504adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
5515974a30fSdrh   if( v==0 ) goto insert_cleanup;
5524794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
5532f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
5541ccde15dSdrh 
5559d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
5569d9cf229Sdrh   /* If the statement is of the form
5579d9cf229Sdrh   **
5589d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
5599d9cf229Sdrh   **
5609d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
5619d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
562e00ee6ebSdrh   **
563e00ee6ebSdrh   ** This is the 2nd template.
5649d9cf229Sdrh   */
565ebbf08a0Sdan   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
5662f886d1dSdanielk1977     assert( !pTrigger );
5679d9cf229Sdrh     assert( pList==0 );
5680b9f50d8Sdrh     goto insert_end;
5699d9cf229Sdrh   }
5709d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
5719d9cf229Sdrh 
5722958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
5736a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
5742958a4e6Sdrh   */
5756a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
5762958a4e6Sdrh 
57705a86c5cSdrh   /* Allocate registers for holding the rowid of the new row,
57860ec914cSpeter.d.reid   ** the content of the new row, and the assembled row record.
57905a86c5cSdrh   */
58005a86c5cSdrh   regRowid = regIns = pParse->nMem+1;
58105a86c5cSdrh   pParse->nMem += pTab->nCol + 1;
58205a86c5cSdrh   if( IsVirtual(pTab) ){
58305a86c5cSdrh     regRowid++;
58405a86c5cSdrh     pParse->nMem++;
58505a86c5cSdrh   }
58605a86c5cSdrh   regData = regRowid+1;
58705a86c5cSdrh 
58805a86c5cSdrh   /* If the INSERT statement included an IDLIST term, then make sure
58905a86c5cSdrh   ** all elements of the IDLIST really are columns of the table and
59005a86c5cSdrh   ** remember the column indices.
59105a86c5cSdrh   **
59205a86c5cSdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
59305a86c5cSdrh   ** is named in the IDLIST, then record in the ipkColumn variable
59405a86c5cSdrh   ** the index into IDLIST of the primary key column.  ipkColumn is
59505a86c5cSdrh   ** the index of the primary key as it appears in IDLIST, not as
59605a86c5cSdrh   ** is appears in the original table.  (The index of the INTEGER
59705a86c5cSdrh   ** PRIMARY KEY in the original table is pTab->iPKey.)
59805a86c5cSdrh   */
59905a86c5cSdrh   if( pColumn ){
60005a86c5cSdrh     for(i=0; i<pColumn->nId; i++){
60105a86c5cSdrh       pColumn->a[i].idx = -1;
60205a86c5cSdrh     }
60305a86c5cSdrh     for(i=0; i<pColumn->nId; i++){
60405a86c5cSdrh       for(j=0; j<pTab->nCol; j++){
60505a86c5cSdrh         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
60605a86c5cSdrh           pColumn->a[i].idx = j;
60705a86c5cSdrh           if( i!=j ) bIdListInOrder = 0;
60805a86c5cSdrh           if( j==pTab->iPKey ){
60905a86c5cSdrh             ipkColumn = i;  assert( !withoutRowid );
61005a86c5cSdrh           }
61105a86c5cSdrh           break;
61205a86c5cSdrh         }
61305a86c5cSdrh       }
61405a86c5cSdrh       if( j>=pTab->nCol ){
61505a86c5cSdrh         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
61605a86c5cSdrh           ipkColumn = i;
617e48ae715Sdrh           bIdListInOrder = 0;
61805a86c5cSdrh         }else{
61905a86c5cSdrh           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
62005a86c5cSdrh               pTabList, 0, pColumn->a[i].zName);
62105a86c5cSdrh           pParse->checkSchema = 1;
62205a86c5cSdrh           goto insert_cleanup;
62305a86c5cSdrh         }
62405a86c5cSdrh       }
62505a86c5cSdrh     }
62605a86c5cSdrh   }
62705a86c5cSdrh 
6281ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
629e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
630e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
631e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
6321ccde15dSdrh   */
6335974a30fSdrh   if( pSelect ){
634d82b5021Sdrh     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
63505a86c5cSdrh     int regYield;       /* Register holding co-routine entry-point */
63605a86c5cSdrh     int addrTop;        /* Top of the co-routine */
63705a86c5cSdrh     int rc;             /* Result code */
6381013c932Sdrh 
63905a86c5cSdrh     regYield = ++pParse->nMem;
64005a86c5cSdrh     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
64105a86c5cSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
64205a86c5cSdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
64305a86c5cSdrh     dest.iSdst = bIdListInOrder ? regData : 0;
64405a86c5cSdrh     dest.nSdst = pTab->nCol;
64505a86c5cSdrh     rc = sqlite3Select(pParse, pSelect, &dest);
6462b596da8Sdrh     regFromSelect = dest.iSdst;
64705a86c5cSdrh     assert( pParse->nErr==0 || rc );
64805a86c5cSdrh     if( rc || db->mallocFailed ) goto insert_cleanup;
64905a86c5cSdrh     sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
65005a86c5cSdrh     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
6515974a30fSdrh     assert( pSelect->pEList );
652967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
653142e30dfSdrh 
654142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
655e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
656d82b5021Sdrh     ** FALSE if each output row of the SELECT can be written directly into
657e00ee6ebSdrh     ** the destination table (template 3).
658048c530cSdrh     **
659048c530cSdrh     ** A temp table must be used if the table being updated is also one
660048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
661048c530cSdrh     ** temp table in the case of row triggers.
662142e30dfSdrh     */
66305a86c5cSdrh     if( pTrigger || readsTable(pParse, iDb, pTab) ){
664048c530cSdrh       useTempTable = 1;
665048c530cSdrh     }
666142e30dfSdrh 
667142e30dfSdrh     if( useTempTable ){
668e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
669e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
670e00ee6ebSdrh       ** here is from the 4th template:
671e00ee6ebSdrh       **
672e00ee6ebSdrh       **      B: open temp table
67381cf13ecSdrh       **      L: yield X, goto M at EOF
674e00ee6ebSdrh       **         insert row from R..R+n into temp table
675e00ee6ebSdrh       **         goto L
676e00ee6ebSdrh       **      M: ...
677142e30dfSdrh       */
678e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
679dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
68006280ee5Sdrh       int addrL;           /* Label "L" */
681b7654111Sdrh 
682142e30dfSdrh       srcTab = pParse->nTab++;
683b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
684dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
685e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
68606280ee5Sdrh       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
6871db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
688dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
689dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
69006280ee5Sdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
69106280ee5Sdrh       sqlite3VdbeJumpHere(v, addrL);
692b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
693dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
694142e30dfSdrh     }
695142e30dfSdrh   }else{
696142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
697142e30dfSdrh     ** clause
698142e30dfSdrh     */
699b3bce662Sdanielk1977     NameContext sNC;
700b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
701b3bce662Sdanielk1977     sNC.pParse = pParse;
7025974a30fSdrh     srcTab = -1;
70348d1178aSdrh     assert( useTempTable==0 );
704147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
705e64e7b20Sdrh     for(i=0; i<nColumn; i++){
7067d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
707b04a5d87Sdrh         goto insert_cleanup;
708b04a5d87Sdrh       }
709e64e7b20Sdrh     }
7105974a30fSdrh   }
7111ccde15dSdrh 
71205a86c5cSdrh   /* If there is no IDLIST term but the table has an integer primary
71305a86c5cSdrh   ** key, the set the ipkColumn variable to the integer primary key
71405a86c5cSdrh   ** column index in the original table definition.
71505a86c5cSdrh   */
71605a86c5cSdrh   if( pColumn==0 && nColumn>0 ){
71705a86c5cSdrh     ipkColumn = pTab->iPKey;
71805a86c5cSdrh   }
71905a86c5cSdrh 
7201ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
7211ccde15dSdrh   ** of columns to be inserted into the table.
7221ccde15dSdrh   */
723034ca14fSdanielk1977   if( IsVirtual(pTab) ){
724034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
725034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
726034ca14fSdanielk1977     }
727034ca14fSdanielk1977   }
728034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
7294adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
730da93d238Sdrh        "table %S has %d columns but %d values were supplied",
731d51397a6Sdrh        pTabList, 0, pTab->nCol-nHidden, nColumn);
732cce7d176Sdrh     goto insert_cleanup;
733cce7d176Sdrh   }
734967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
7354adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
736cce7d176Sdrh     goto insert_cleanup;
737cce7d176Sdrh   }
7381ccde15dSdrh 
739c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
7401ccde15dSdrh   */
741142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
7426a288a33Sdrh     regRowCount = ++pParse->nMem;
7436a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
744c3f9bad2Sdanielk1977   }
745c3f9bad2Sdanielk1977 
746e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
747e448dc4aSdanielk1977   if( !isView ){
748aa9b8963Sdrh     int nIdx;
7496a53499aSdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
75026198bb4Sdrh                                       &iDataCur, &iIdxCur);
7515c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
752aa9b8963Sdrh     if( aRegIdx==0 ){
753aa9b8963Sdrh       goto insert_cleanup;
754aa9b8963Sdrh     }
755aa9b8963Sdrh     for(i=0; i<nIdx; i++){
756aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
757aa9b8963Sdrh     }
758feeb1394Sdrh   }
759feeb1394Sdrh 
760e00ee6ebSdrh   /* This is the top of the main insertion loop */
761142e30dfSdrh   if( useTempTable ){
762e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
763e00ee6ebSdrh     ** following pseudocode (template 4):
764e00ee6ebSdrh     **
76581cf13ecSdrh     **         rewind temp table, if empty goto D
766e00ee6ebSdrh     **      C: loop over rows of intermediate table
767e00ee6ebSdrh     **           transfer values form intermediate table into <table>
768e00ee6ebSdrh     **         end loop
769e00ee6ebSdrh     **      D: ...
770e00ee6ebSdrh     */
771688852abSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
772e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
773142e30dfSdrh   }else if( pSelect ){
774e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
775e00ee6ebSdrh     ** following pseudocode (template 3):
776e00ee6ebSdrh     **
77781cf13ecSdrh     **      C: yield X, at EOF goto D
778e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
779e00ee6ebSdrh     **         goto C
780e00ee6ebSdrh     **      D: ...
781e00ee6ebSdrh     */
78281cf13ecSdrh     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
783688852abSdrh     VdbeCoverage(v);
784bed8690fSdrh   }
7851ccde15dSdrh 
7865cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
78770ce3f0cSdrh   */
7884adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
7892f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
79076d462eeSdan     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
791c3f9bad2Sdanielk1977 
79270ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
79370ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
79470ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
79570ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
79670ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
79770ce3f0cSdrh     */
798d82b5021Sdrh     if( ipkColumn<0 ){
79976d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
80070ce3f0cSdrh     }else{
8016a288a33Sdrh       int j1;
802ec95c441Sdrh       assert( !withoutRowid );
8037fe45908Sdrh       if( useTempTable ){
804d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
8057fe45908Sdrh       }else{
806d6fe961eSdrh         assert( pSelect==0 );  /* Otherwise useTempTable is true */
807d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
8087fe45908Sdrh       }
809688852abSdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
81076d462eeSdan       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
8116a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
812688852abSdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
81370ce3f0cSdrh     }
81470ce3f0cSdrh 
815034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
816034ca14fSdanielk1977     ** this block would have to account for hidden column.
817034ca14fSdanielk1977     */
818034ca14fSdanielk1977     assert( !IsVirtual(pTab) );
819034ca14fSdanielk1977 
82070ce3f0cSdrh     /* Create the new column data
82170ce3f0cSdrh     */
822c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
823c3f9bad2Sdanielk1977       if( pColumn==0 ){
824c3f9bad2Sdanielk1977         j = i;
825c3f9bad2Sdanielk1977       }else{
826c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
827c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
828c3f9bad2Sdanielk1977         }
829c3f9bad2Sdanielk1977       }
8307ba45971Sdan       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
83176d462eeSdan         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
832142e30dfSdrh       }else if( useTempTable ){
83376d462eeSdan         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
834c3f9bad2Sdanielk1977       }else{
835d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
83676d462eeSdan         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
837c3f9bad2Sdanielk1977       }
838c3f9bad2Sdanielk1977     }
839a37cdde0Sdanielk1977 
840a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
841a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
842a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
843a37cdde0Sdanielk1977     ** table column affinities.
844a37cdde0Sdanielk1977     */
845a37cdde0Sdanielk1977     if( !isView ){
84657bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regCols+1);
847a37cdde0Sdanielk1977     }
848c3f9bad2Sdanielk1977 
8495cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
850165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
85194d7f50aSdan         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
852165921a7Sdan 
85376d462eeSdan     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85470ce3f0cSdrh   }
855c3f9bad2Sdanielk1977 
856d82b5021Sdrh   /* Compute the content of the next row to insert into a range of
857d82b5021Sdrh   ** registers beginning at regIns.
8581ccde15dSdrh   */
8595cf590c1Sdrh   if( !isView ){
8604cbdda9eSdrh     if( IsVirtual(pTab) ){
8614cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
8626a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
8634cbdda9eSdrh     }
864d82b5021Sdrh     if( ipkColumn>=0 ){
865142e30dfSdrh       if( useTempTable ){
866d82b5021Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
867142e30dfSdrh       }else if( pSelect ){
86805a86c5cSdrh         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
8694a32431cSdrh       }else{
870e4d90813Sdrh         VdbeOp *pOp;
871d82b5021Sdrh         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
87220411ea7Sdrh         pOp = sqlite3VdbeGetOp(v, -1);
8731b7ecbb4Sdrh         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
874e4d90813Sdrh           appendFlag = 1;
875e4d90813Sdrh           pOp->opcode = OP_NewRowid;
87626198bb4Sdrh           pOp->p1 = iDataCur;
8776a288a33Sdrh           pOp->p2 = regRowid;
8786a288a33Sdrh           pOp->p3 = regAutoinc;
879e4d90813Sdrh         }
88027a32783Sdrh       }
881f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
882e1e68f49Sdrh       ** to generate a unique primary key value.
883e1e68f49Sdrh       */
884e4d90813Sdrh       if( !appendFlag ){
8851db639ceSdrh         int j1;
886bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
887688852abSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
88826198bb4Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
8891db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
890bb50e7adSdanielk1977         }else{
891bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
892688852abSdrh           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
893bb50e7adSdanielk1977         }
894688852abSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
895e4d90813Sdrh       }
896ec95c441Sdrh     }else if( IsVirtual(pTab) || withoutRowid ){
8976a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
8984a32431cSdrh     }else{
89926198bb4Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
900e4d90813Sdrh       appendFlag = 1;
9014a32431cSdrh     }
9026a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
9034a32431cSdrh 
904d82b5021Sdrh     /* Compute data for all columns of the new entry, beginning
9054a32431cSdrh     ** with the first column.
9064a32431cSdrh     */
907034ca14fSdanielk1977     nHidden = 0;
908cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
9096a288a33Sdrh       int iRegStore = regRowid+1+i;
9104a32431cSdrh       if( i==pTab->iPKey ){
9114a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
912d82b5021Sdrh         ** Whenever this column is read, the rowid will be substituted
913d82b5021Sdrh         ** in its place.  Hence, fill this column with a NULL to avoid
91405a86c5cSdrh         ** taking up data space with information that will never be used.
91505a86c5cSdrh         ** As there may be shallow copies of this value, make it a soft-NULL */
91605a86c5cSdrh         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
9174a32431cSdrh         continue;
9184a32431cSdrh       }
919967e8b73Sdrh       if( pColumn==0 ){
920034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
921034ca14fSdanielk1977           assert( IsVirtual(pTab) );
922034ca14fSdanielk1977           j = -1;
923034ca14fSdanielk1977           nHidden++;
924034ca14fSdanielk1977         }else{
925034ca14fSdanielk1977           j = i - nHidden;
926034ca14fSdanielk1977         }
927cce7d176Sdrh       }else{
928967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
929967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
930cce7d176Sdrh         }
931cce7d176Sdrh       }
932034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
93305a86c5cSdrh         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
934142e30dfSdrh       }else if( useTempTable ){
935287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
936142e30dfSdrh       }else if( pSelect ){
93705a86c5cSdrh         if( regFromSelect!=regData ){
938b7654111Sdrh           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
93905a86c5cSdrh         }
940cce7d176Sdrh       }else{
941287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
942cce7d176Sdrh       }
943cce7d176Sdrh     }
9441ccde15dSdrh 
9450ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
9460ca3e24bSdrh     ** do the insertion.
9474a32431cSdrh     */
9484cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
9494cbdda9eSdrh     if( IsVirtual(pTab) ){
950595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
9514f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
952595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
953b061d058Sdan       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
954e0af83acSdan       sqlite3MayAbort(pParse);
9554cbdda9eSdrh     }else
9564cbdda9eSdrh #endif
9574cbdda9eSdrh     {
958de630353Sdanielk1977       int isReplace;    /* Set to true if constraints may cause a replace */
959f8ffb278Sdrh       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
960f8ffb278Sdrh           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
96104adf416Sdrh       );
9628ff2d956Sdan       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
96326198bb4Sdrh       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
96426198bb4Sdrh                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
9655cf590c1Sdrh     }
9664cbdda9eSdrh   }
9671bee3d7bSdrh 
968feeb1394Sdrh   /* Update the count of rows that are inserted
9691bee3d7bSdrh   */
970142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
9716a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
9721bee3d7bSdrh   }
973c3f9bad2Sdanielk1977 
9742f886d1dSdanielk1977   if( pTrigger ){
975c3f9bad2Sdanielk1977     /* Code AFTER triggers */
976165921a7Sdan     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
97794d7f50aSdan         pTab, regData-2-pTab->nCol, onError, endOfLoop);
978c3f9bad2Sdanielk1977   }
9791bee3d7bSdrh 
980e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
981e00ee6ebSdrh   ** is a SELECT statement.
9821ccde15dSdrh   */
9834adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
984142e30dfSdrh   if( useTempTable ){
985688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
986e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9872eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
988142e30dfSdrh   }else if( pSelect ){
989e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
990e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9916b56344dSdrh   }
992c3f9bad2Sdanielk1977 
993e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
994c3f9bad2Sdanielk1977     /* Close all tables opened */
99526198bb4Sdrh     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
99626198bb4Sdrh     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
99726198bb4Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
998cce7d176Sdrh     }
999c3f9bad2Sdanielk1977   }
1000c3f9bad2Sdanielk1977 
10010b9f50d8Sdrh insert_end:
1002f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10030b9f50d8Sdrh   ** maximum rowid counter values recorded while inserting into
10040b9f50d8Sdrh   ** autoincrement tables.
10052958a4e6Sdrh   */
1006165921a7Sdan   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
10070b9f50d8Sdrh     sqlite3AutoincrementEnd(pParse);
10080b9f50d8Sdrh   }
10092958a4e6Sdrh 
10101bee3d7bSdrh   /*
1011e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1012e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1013e7de6f25Sdanielk1977   ** invoke the callback function.
10141bee3d7bSdrh   */
1015165921a7Sdan   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
10166a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
101722322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
101810fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
10191bee3d7bSdrh   }
1020cce7d176Sdrh 
1021cce7d176Sdrh insert_cleanup:
1022633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1023633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1024633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1025633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1026633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1027cce7d176Sdrh }
10289cfcf5d4Sdrh 
102975cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise
103060ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file
103175cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation).  */
103275cbd984Sdan #ifdef isView
103375cbd984Sdan  #undef isView
103475cbd984Sdan #endif
103575cbd984Sdan #ifdef pTrigger
103675cbd984Sdan  #undef pTrigger
103775cbd984Sdan #endif
103875cbd984Sdan #ifdef tmask
103975cbd984Sdan  #undef tmask
104075cbd984Sdan #endif
104175cbd984Sdan 
104211e85273Sdrh /*
10436934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE
10446934fc7bSdrh ** on table pTab.
10459cfcf5d4Sdrh **
10466934fc7bSdrh ** The regNewData parameter is the first register in a range that contains
10476934fc7bSdrh ** the data to be inserted or the data after the update.  There will be
10486934fc7bSdrh ** pTab->nCol+1 registers in this range.  The first register (the one
10496934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the
10506934fc7bSdrh ** case of a WITHOUT ROWID table.  The second register in the range will
10516934fc7bSdrh ** contain the content of the first table column.  The third register will
10526934fc7bSdrh ** contain the content of the second table column.  And so forth.
10530ca3e24bSdrh **
1054f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains
1055f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
1056f8ffb278Sdrh ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
1057f8ffb278Sdrh ** checking regOldData for zero.
10580ca3e24bSdrh **
1059f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1060f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1061f8ffb278Sdrh ** might be modified by the UPDATE.  If pkChng is false, then the key of
1062f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1063f8ffb278Sdrh **
1064f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1065f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement.  If pkChng
1066f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or
1067f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
1068f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer
1069f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
10700ca3e24bSdrh **
10716934fc7bSdrh ** The code generated by this routine will store new index entries into
1072aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1073aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1074aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
10756934fc7bSdrh ** at pTab->pIndex.
10766934fc7bSdrh **
10776934fc7bSdrh ** The caller must have already opened writeable cursors on the main
10786934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which
10796934fc7bSdrh ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
10806934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
10816934fc7bSdrh ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
10826934fc7bSdrh ** for the first index in the pTab->pIndex list.  Cursors for other indices
10836934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
10849cfcf5d4Sdrh **
10859cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
10869cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
10871c92853dSdrh ** then the appropriate action is performed.  There are five possible
10881c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
10899cfcf5d4Sdrh **
10909cfcf5d4Sdrh **  Constraint type  Action       What Happens
10919cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
10921c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
10936934fc7bSdrh **                                sqlite3_step() returns immediately with a
10949cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
10959cfcf5d4Sdrh **
10961c92853dSdrh **  any              ABORT        Back out changes from the current command
10971c92853dSdrh **                                only (do not do a complete rollback) then
10986934fc7bSdrh **                                cause sqlite3_step() to return immediately
10991c92853dSdrh **                                with SQLITE_CONSTRAINT.
11001c92853dSdrh **
11016934fc7bSdrh **  any              FAIL         Sqlite3_step() returns immediately with a
11021c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
11031c92853dSdrh **                                transaction is not rolled back and any
11046934fc7bSdrh **                                changes to prior rows are retained.
11051c92853dSdrh **
11066934fc7bSdrh **  any              IGNORE       The attempt in insert or update the current
11076934fc7bSdrh **                                row is skipped, without throwing an error.
11086934fc7bSdrh **                                Processing continues with the next row.
11096934fc7bSdrh **                                (There is an immediate jump to ignoreDest.)
11109cfcf5d4Sdrh **
11119cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
11129cfcf5d4Sdrh **                                value for that column.  If the default value
11139cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
11149cfcf5d4Sdrh **
11159cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
11169cfcf5d4Sdrh **                                being inserted is removed.
11179cfcf5d4Sdrh **
11189cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
11199cfcf5d4Sdrh **
11201c92853dSdrh ** Which action to take is determined by the overrideError parameter.
11211c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
11221c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
11231c92853dSdrh ** for the constraint is used.
11249cfcf5d4Sdrh */
11254adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
11269cfcf5d4Sdrh   Parse *pParse,       /* The parser context */
11276934fc7bSdrh   Table *pTab,         /* The table being inserted or updated */
1128f8ffb278Sdrh   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
11296934fc7bSdrh   int iDataCur,        /* Canonical data cursor (main table or PK index) */
113026198bb4Sdrh   int iIdxCur,         /* First index cursor */
11316934fc7bSdrh   int regNewData,      /* First register in a range holding values to insert */
1132f8ffb278Sdrh   int regOldData,      /* Previous content.  0 for INSERTs */
1133f8ffb278Sdrh   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
1134f8ffb278Sdrh   u8 overrideError,    /* Override onError to this if not OE_Default */
1135de630353Sdanielk1977   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
1136de630353Sdanielk1977   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
11379cfcf5d4Sdrh ){
11381b7ecbb4Sdrh   Vdbe *v;             /* VDBE under constrution */
11391b7ecbb4Sdrh   Index *pIdx;         /* Pointer to one of the indices */
114011e85273Sdrh   Index *pPk = 0;      /* The PRIMARY KEY index */
11412938f924Sdrh   sqlite3 *db;         /* Database connection */
1142f8ffb278Sdrh   int i;               /* loop counter */
1143f8ffb278Sdrh   int ix;              /* Index loop counter */
1144f8ffb278Sdrh   int nCol;            /* Number of columns */
1145f8ffb278Sdrh   int onError;         /* Conflict resolution strategy */
114660ec914cSpeter.d.reid   int j1;              /* Address of jump instruction */
11471b7ecbb4Sdrh   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
11486fbe41acSdrh   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
11498d1b82e4Sdrh   int ipkTop = 0;      /* Top of the rowid change constraint check */
11508d1b82e4Sdrh   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
11518d1b82e4Sdrh   u8 isUpdate;         /* True if this is an UPDATE operation */
115257bf4a8eSdrh   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
11535426d809Sdrh   int regRowid = -1;   /* Register holding ROWID value */
11549cfcf5d4Sdrh 
1155f8ffb278Sdrh   isUpdate = regOldData!=0;
11562938f924Sdrh   db = pParse->db;
11574adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
11589cfcf5d4Sdrh   assert( v!=0 );
1159417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
11609cfcf5d4Sdrh   nCol = pTab->nCol;
1161aa9b8963Sdrh 
11626934fc7bSdrh   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
11636934fc7bSdrh   ** normal rowid tables.  nPkField is the number of key fields in the
11646934fc7bSdrh   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
11656934fc7bSdrh   ** number of fields in the true primary key of the table. */
116626198bb4Sdrh   if( HasRowid(pTab) ){
116726198bb4Sdrh     pPk = 0;
116826198bb4Sdrh     nPkField = 1;
116926198bb4Sdrh   }else{
117026198bb4Sdrh     pPk = sqlite3PrimaryKeyIndex(pTab);
117126198bb4Sdrh     nPkField = pPk->nKeyCol;
117226198bb4Sdrh   }
11736fbe41acSdrh 
11746fbe41acSdrh   /* Record that this module has started */
11756fbe41acSdrh   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
11766934fc7bSdrh                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
117711e85273Sdrh 
11789cfcf5d4Sdrh   /* Test all NOT NULL constraints.
11799cfcf5d4Sdrh   */
11809cfcf5d4Sdrh   for(i=0; i<nCol; i++){
11810ca3e24bSdrh     if( i==pTab->iPKey ){
11820ca3e24bSdrh       continue;
11830ca3e24bSdrh     }
11849cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
11850ca3e24bSdrh     if( onError==OE_None ) continue;
11869cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11879cfcf5d4Sdrh       onError = overrideError;
1188a996e477Sdrh     }else if( onError==OE_Default ){
1189a996e477Sdrh       onError = OE_Abort;
11909cfcf5d4Sdrh     }
11917977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
11929cfcf5d4Sdrh       onError = OE_Abort;
11939cfcf5d4Sdrh     }
1194b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1195b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11969cfcf5d4Sdrh     switch( onError ){
11971c92853dSdrh       case OE_Abort:
1198e0af83acSdan         sqlite3MayAbort(pParse);
11990978d4ffSdrh         /* Fall through */
1200e0af83acSdan       case OE_Rollback:
12011c92853dSdrh       case OE_Fail: {
1202f9c8ce3cSdrh         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1203f9c8ce3cSdrh                                     pTab->aCol[i].zName);
1204f9c8ce3cSdrh         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1205f9c8ce3cSdrh                           regNewData+1+i, zMsg, P4_DYNAMIC);
1206f9c8ce3cSdrh         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1207688852abSdrh         VdbeCoverage(v);
12089cfcf5d4Sdrh         break;
12099cfcf5d4Sdrh       }
12109cfcf5d4Sdrh       case OE_Ignore: {
12116934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
1212688852abSdrh         VdbeCoverage(v);
12139cfcf5d4Sdrh         break;
12149cfcf5d4Sdrh       }
1215098d1684Sdrh       default: {
1216098d1684Sdrh         assert( onError==OE_Replace );
1217688852abSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
12186934fc7bSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
12195053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
12209cfcf5d4Sdrh         break;
12219cfcf5d4Sdrh       }
12229cfcf5d4Sdrh     }
12239cfcf5d4Sdrh   }
12249cfcf5d4Sdrh 
12259cfcf5d4Sdrh   /* Test all CHECK constraints
12269cfcf5d4Sdrh   */
1227ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
12282938f924Sdrh   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
12292938f924Sdrh     ExprList *pCheck = pTab->pCheck;
12306934fc7bSdrh     pParse->ckBase = regNewData+1;
1231aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
12322938f924Sdrh     for(i=0; i<pCheck->nExpr; i++){
12332938f924Sdrh       int allOk = sqlite3VdbeMakeLabel(v);
12342d8e9203Sdrh       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
12352e06c67cSdrh       if( onError==OE_Ignore ){
123666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1237aa01c7e2Sdrh       }else{
1238f9c8ce3cSdrh         char *zName = pCheck->a[i].zName;
1239f9c8ce3cSdrh         if( zName==0 ) zName = pTab->zName;
12406dc84902Sdrh         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1241d91c1a17Sdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1242f9c8ce3cSdrh                               onError, zName, P4_TRANSIENT,
1243f9c8ce3cSdrh                               P5_ConstraintCheck);
1244aa01c7e2Sdrh       }
1245ffe07b2dSdrh       sqlite3VdbeResolveLabel(v, allOk);
1246c31c7c1cSdrh     }
12472938f924Sdrh   }
1248ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
12499cfcf5d4Sdrh 
1250f8ffb278Sdrh   /* If rowid is changing, make sure the new rowid does not previously
1251f8ffb278Sdrh   ** exist in the table.
12529cfcf5d4Sdrh   */
12536fbe41acSdrh   if( pkChng && pPk==0 ){
125411e85273Sdrh     int addrRowidOk = sqlite3VdbeMakeLabel(v);
125511e85273Sdrh 
1256f8ffb278Sdrh     /* Figure out what action to take in case of a rowid collision */
12570ca3e24bSdrh     onError = pTab->keyConf;
12580ca3e24bSdrh     if( overrideError!=OE_Default ){
12590ca3e24bSdrh       onError = overrideError;
1260a996e477Sdrh     }else if( onError==OE_Default ){
1261a996e477Sdrh       onError = OE_Abort;
12620ca3e24bSdrh     }
1263a0217ba7Sdrh 
126479b0c956Sdrh     if( isUpdate ){
1265f8ffb278Sdrh       /* pkChng!=0 does not mean that the rowid has change, only that
1266f8ffb278Sdrh       ** it might have changed.  Skip the conflict logic below if the rowid
1267f8ffb278Sdrh       ** is unchanged. */
12686934fc7bSdrh       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
12693d77dee9Sdrh       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1270688852abSdrh       VdbeCoverage(v);
127179b0c956Sdrh     }
1272f8ffb278Sdrh 
12738d1b82e4Sdrh     /* If the response to a rowid conflict is REPLACE but the response
12748d1b82e4Sdrh     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
12758d1b82e4Sdrh     ** to defer the running of the rowid conflict checking until after
12768d1b82e4Sdrh     ** the UNIQUE constraints have run.
12778d1b82e4Sdrh     */
12788d1b82e4Sdrh     if( onError==OE_Replace && overrideError!=OE_Replace ){
12798d1b82e4Sdrh       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
12808d1b82e4Sdrh         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
12818d1b82e4Sdrh           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
12828d1b82e4Sdrh           break;
12838d1b82e4Sdrh         }
12848d1b82e4Sdrh       }
12858d1b82e4Sdrh     }
12868d1b82e4Sdrh 
1287f8ffb278Sdrh     /* Check to see if the new rowid already exists in the table.  Skip
1288f8ffb278Sdrh     ** the following conflict logic if it does not. */
12896934fc7bSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1290688852abSdrh     VdbeCoverage(v);
1291f8ffb278Sdrh 
1292f8ffb278Sdrh     /* Generate code that deals with a rowid collision */
12930ca3e24bSdrh     switch( onError ){
1294a0217ba7Sdrh       default: {
1295a0217ba7Sdrh         onError = OE_Abort;
1296a0217ba7Sdrh         /* Fall thru into the next case */
1297a0217ba7Sdrh       }
12981c92853dSdrh       case OE_Rollback:
12991c92853dSdrh       case OE_Abort:
13001c92853dSdrh       case OE_Fail: {
1301f9c8ce3cSdrh         sqlite3RowidConstraint(pParse, onError, pTab);
13020ca3e24bSdrh         break;
13030ca3e24bSdrh       }
13045383ae5cSdrh       case OE_Replace: {
13052283d46cSdan         /* If there are DELETE triggers on this table and the
13062283d46cSdan         ** recursive-triggers flag is set, call GenerateRowDelete() to
1307d5578433Smistachkin         ** remove the conflicting row from the table. This will fire
13082283d46cSdan         ** the triggers and remove both the table and index b-tree entries.
13092283d46cSdan         **
13102283d46cSdan         ** Otherwise, if there are no triggers or the recursive-triggers
1311da730f6eSdan         ** flag is not set, but the table has one or more indexes, call
1312da730f6eSdan         ** GenerateRowIndexDelete(). This removes the index b-tree entries
1313da730f6eSdan         ** only. The table b-tree entry will be replaced by the new entry
1314da730f6eSdan         ** when it is inserted.
1315da730f6eSdan         **
1316da730f6eSdan         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1317da730f6eSdan         ** also invoke MultiWrite() to indicate that this VDBE may require
1318da730f6eSdan         ** statement rollback (if the statement is aborted after the delete
1319da730f6eSdan         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1320da730f6eSdan         ** but being more selective here allows statements like:
1321da730f6eSdan         **
1322da730f6eSdan         **   REPLACE INTO t(rowid) VALUES($newrowid)
1323da730f6eSdan         **
1324da730f6eSdan         ** to run without a statement journal if there are no indexes on the
1325da730f6eSdan         ** table.
1326da730f6eSdan         */
13272283d46cSdan         Trigger *pTrigger = 0;
13282938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
13292283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
13302283d46cSdan         }
1331e7a94d81Sdan         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1332da730f6eSdan           sqlite3MultiWrite(pParse);
133326198bb4Sdrh           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1334392ee21dSdrh                                    regNewData, 1, 0, OE_Replace, 1);
1335da730f6eSdan         }else if( pTab->pIndex ){
1336da730f6eSdan           sqlite3MultiWrite(pParse);
133726198bb4Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
13382283d46cSdan         }
13395383ae5cSdrh         seenReplace = 1;
13405383ae5cSdrh         break;
13415383ae5cSdrh       }
13420ca3e24bSdrh       case OE_Ignore: {
13438d1b82e4Sdrh         /*assert( seenReplace==0 );*/
134466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13450ca3e24bSdrh         break;
13460ca3e24bSdrh       }
13470ca3e24bSdrh     }
134811e85273Sdrh     sqlite3VdbeResolveLabel(v, addrRowidOk);
13498d1b82e4Sdrh     if( ipkTop ){
13508d1b82e4Sdrh       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
13518d1b82e4Sdrh       sqlite3VdbeJumpHere(v, ipkTop);
13528d1b82e4Sdrh     }
13530ca3e24bSdrh   }
13540bd1f4eaSdrh 
13550bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
13560bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
135711e85273Sdrh   ** Compute the revised record entries for indices as we go.
1358f8ffb278Sdrh   **
1359f8ffb278Sdrh   ** This loop also handles the case of the PRIMARY KEY index for a
1360f8ffb278Sdrh   ** WITHOUT ROWID table.
13610bd1f4eaSdrh   */
136226198bb4Sdrh   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
13636934fc7bSdrh     int regIdx;          /* Range of registers hold conent for pIdx */
13646934fc7bSdrh     int regR;            /* Range of registers holding conflicting PK */
13656934fc7bSdrh     int iThisCur;        /* Cursor for this UNIQUE index */
13666934fc7bSdrh     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
13672184fc75Sdrh 
136826198bb4Sdrh     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
136957bf4a8eSdrh     if( bAffinityDone==0 ){
137057bf4a8eSdrh       sqlite3TableAffinity(v, pTab, regNewData+1);
137157bf4a8eSdrh       bAffinityDone = 1;
137257bf4a8eSdrh     }
13736934fc7bSdrh     iThisCur = iIdxCur+ix;
13746934fc7bSdrh     addrUniqueOk = sqlite3VdbeMakeLabel(v);
1375b2fe7d8cSdrh 
1376f8ffb278Sdrh     /* Skip partial indices for which the WHERE clause is not true */
1377b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
137826198bb4Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
13796934fc7bSdrh       pParse->ckBase = regNewData+1;
138011e85273Sdrh       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1381b2b9d3d7Sdrh                          SQLITE_JUMPIFNULL);
1382b2b9d3d7Sdrh       pParse->ckBase = 0;
1383b2b9d3d7Sdrh     }
1384b2b9d3d7Sdrh 
13856934fc7bSdrh     /* Create a record for this index entry as it should appear after
1386f8ffb278Sdrh     ** the insert or update.  Store that record in the aRegIdx[ix] register
1387f8ffb278Sdrh     */
138811e85273Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
13899cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
13906934fc7bSdrh       int iField = pIdx->aiColumn[i];
1391f82b9afcSdrh       int x;
139226198bb4Sdrh       if( iField<0 || iField==pTab->iPKey ){
13935426d809Sdrh         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
1394f82b9afcSdrh         x = regNewData;
13955426d809Sdrh         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
13969cfcf5d4Sdrh       }else{
1397f82b9afcSdrh         x = iField + regNewData + 1;
13989cfcf5d4Sdrh       }
1399f82b9afcSdrh       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
1400f82b9afcSdrh       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
14019cfcf5d4Sdrh     }
140226198bb4Sdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
140326198bb4Sdrh     VdbeComment((v, "for %s", pIdx->zName));
1404bbbdc83bSdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
1405b2fe7d8cSdrh 
1406f8ffb278Sdrh     /* In an UPDATE operation, if this index is the PRIMARY KEY index
1407f8ffb278Sdrh     ** of a WITHOUT ROWID table and there has been no change the
1408f8ffb278Sdrh     ** primary key, then no collision is possible.  The collision detection
1409f8ffb278Sdrh     ** logic below can all be skipped. */
141000012df4Sdrh     if( isUpdate && pPk==pIdx && pkChng==0 ){
1411da475b8dSdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1412da475b8dSdrh       continue;
1413da475b8dSdrh     }
1414f8ffb278Sdrh 
14156934fc7bSdrh     /* Find out what action to take in case there is a uniqueness conflict */
14169cfcf5d4Sdrh     onError = pIdx->onError;
1417de630353Sdanielk1977     if( onError==OE_None ){
141826198bb4Sdrh       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
141911e85273Sdrh       sqlite3VdbeResolveLabel(v, addrUniqueOk);
1420de630353Sdanielk1977       continue;  /* pIdx is not a UNIQUE index */
1421de630353Sdanielk1977     }
14229cfcf5d4Sdrh     if( overrideError!=OE_Default ){
14239cfcf5d4Sdrh       onError = overrideError;
1424a996e477Sdrh     }else if( onError==OE_Default ){
1425a996e477Sdrh       onError = OE_Abort;
14269cfcf5d4Sdrh     }
14275383ae5cSdrh 
1428b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
142926198bb4Sdrh     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
1430688852abSdrh                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
1431f8ffb278Sdrh 
1432f8ffb278Sdrh     /* Generate code to handle collisions */
1433392ee21dSdrh     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
143446d03fcbSdrh     if( isUpdate || onError==OE_Replace ){
143511e85273Sdrh       if( HasRowid(pTab) ){
14366934fc7bSdrh         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
14370978d4ffSdrh         /* Conflict only if the rowid of the existing index entry
14380978d4ffSdrh         ** is different from old-rowid */
1439f8ffb278Sdrh         if( isUpdate ){
14406934fc7bSdrh           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
14413d77dee9Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1442688852abSdrh           VdbeCoverage(v);
1443f8ffb278Sdrh         }
144426198bb4Sdrh       }else{
1445ccc79f02Sdrh         int x;
144626198bb4Sdrh         /* Extract the PRIMARY KEY from the end of the index entry and
1447da475b8dSdrh         ** store it in registers regR..regR+nPk-1 */
1448a021f121Sdrh         if( pIdx!=pPk ){
144926198bb4Sdrh           for(i=0; i<pPk->nKeyCol; i++){
1450ccc79f02Sdrh             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
145126198bb4Sdrh             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
145226198bb4Sdrh             VdbeComment((v, "%s.%s", pTab->zName,
145326198bb4Sdrh                          pTab->aCol[pPk->aiColumn[i]].zName));
145426198bb4Sdrh           }
1455da475b8dSdrh         }
1456da475b8dSdrh         if( isUpdate ){
1457e83267daSdan           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1458e83267daSdan           ** table, only conflict if the new PRIMARY KEY values are actually
1459e83267daSdan           ** different from the old.
1460e83267daSdan           **
1461e83267daSdan           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1462e83267daSdan           ** of the matched index row are different from the original PRIMARY
1463e83267daSdan           ** KEY values of this row before the update.  */
1464e83267daSdan           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1465e83267daSdan           int op = OP_Ne;
146648dd1d8eSdrh           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
1467e83267daSdan 
1468e83267daSdan           for(i=0; i<pPk->nKeyCol; i++){
1469e83267daSdan             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1470ccc79f02Sdrh             x = pPk->aiColumn[i];
1471e83267daSdan             if( i==(pPk->nKeyCol-1) ){
1472e83267daSdan               addrJump = addrUniqueOk;
1473e83267daSdan               op = OP_Eq;
147411e85273Sdrh             }
1475e83267daSdan             sqlite3VdbeAddOp4(v, op,
1476e83267daSdan                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
14773d77dee9Sdrh             );
14783d77dee9Sdrh             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
14793d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Eq);
14803d77dee9Sdrh             VdbeCoverageIf(v, op==OP_Ne);
1481da475b8dSdrh           }
148211e85273Sdrh         }
148326198bb4Sdrh       }
148446d03fcbSdrh     }
1485b2fe7d8cSdrh 
1486b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1487b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1488b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
14899cfcf5d4Sdrh     switch( onError ){
14901c92853dSdrh       case OE_Rollback:
14911c92853dSdrh       case OE_Abort:
14921c92853dSdrh       case OE_Fail: {
1493f9c8ce3cSdrh         sqlite3UniqueConstraint(pParse, onError, pIdx);
14949cfcf5d4Sdrh         break;
14959cfcf5d4Sdrh       }
14969cfcf5d4Sdrh       case OE_Ignore: {
149766a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
14989cfcf5d4Sdrh         break;
14999cfcf5d4Sdrh       }
1500098d1684Sdrh       default: {
15012283d46cSdan         Trigger *pTrigger = 0;
1502098d1684Sdrh         assert( onError==OE_Replace );
15031bea559aSdan         sqlite3MultiWrite(pParse);
15042938f924Sdrh         if( db->flags&SQLITE_RecTriggers ){
15052283d46cSdan           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
15062283d46cSdan         }
150726198bb4Sdrh         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1508392ee21dSdrh                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
15090ca3e24bSdrh         seenReplace = 1;
15109cfcf5d4Sdrh         break;
15119cfcf5d4Sdrh       }
15129cfcf5d4Sdrh     }
151311e85273Sdrh     sqlite3VdbeResolveLabel(v, addrUniqueOk);
1514392ee21dSdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1515392ee21dSdrh     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
15169cfcf5d4Sdrh   }
15178d1b82e4Sdrh   if( ipkTop ){
15188d1b82e4Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
15198d1b82e4Sdrh     sqlite3VdbeJumpHere(v, ipkBottom);
15208d1b82e4Sdrh   }
1521de630353Sdanielk1977 
1522de630353Sdanielk1977   *pbMayReplace = seenReplace;
1523ce60aa46Sdrh   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
15249cfcf5d4Sdrh }
15250ca3e24bSdrh 
15260ca3e24bSdrh /*
15270ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
15284adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
15296934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the
153004adf416Sdrh ** rowid and the content to be inserted.
15310ca3e24bSdrh **
1532b419a926Sdrh ** The arguments to this routine should be the same as the first six
15334adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
15340ca3e24bSdrh */
15354adee20fSdanielk1977 void sqlite3CompleteInsertion(
15360ca3e24bSdrh   Parse *pParse,      /* The parser context */
15370ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
153826198bb4Sdrh   int iDataCur,       /* Cursor of the canonical data source */
153926198bb4Sdrh   int iIdxCur,        /* First index cursor */
15406934fc7bSdrh   int regNewData,     /* Range of content */
1541aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
154270ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1543de630353Sdanielk1977   int appendBias,     /* True if this is likely to be an append */
1544de630353Sdanielk1977   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
15450ca3e24bSdrh ){
15466934fc7bSdrh   Vdbe *v;            /* Prepared statements under construction */
15476934fc7bSdrh   Index *pIdx;        /* An index being inserted or updated */
15486934fc7bSdrh   u8 pik_flags;       /* flag values passed to the btree insert */
15496934fc7bSdrh   int regData;        /* Content registers (after the rowid) */
155060ec914cSpeter.d.reid   int regRec;         /* Register holding assembled record for the table */
15516934fc7bSdrh   int i;              /* Loop counter */
155257bf4a8eSdrh   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
15530ca3e24bSdrh 
15544adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
15550ca3e24bSdrh   assert( v!=0 );
1556417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1557b2b9d3d7Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1558aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
155957bf4a8eSdrh     bAffinityDone = 1;
1560b2b9d3d7Sdrh     if( pIdx->pPartIdxWhere ){
1561b2b9d3d7Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1562688852abSdrh       VdbeCoverage(v);
1563b2b9d3d7Sdrh     }
156426198bb4Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
15656546af14Sdrh     pik_flags = 0;
15666546af14Sdrh     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
156748dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
15684308e348Sdrh       assert( pParse->nested==0 );
15696546af14Sdrh       pik_flags |= OPFLAG_NCHANGE;
1570de630353Sdanielk1977     }
15716546af14Sdrh     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
15720ca3e24bSdrh   }
1573ec95c441Sdrh   if( !HasRowid(pTab) ) return;
15746934fc7bSdrh   regData = regNewData + 1;
1575b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
15761db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
157757bf4a8eSdrh   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
1578da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
15794794f735Sdrh   if( pParse->nested ){
15804794f735Sdrh     pik_flags = 0;
15814794f735Sdrh   }else{
158294eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
158394eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
15844794f735Sdrh   }
1585e4d90813Sdrh   if( appendBias ){
1586e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1587e4d90813Sdrh   }
1588de630353Sdanielk1977   if( useSeekResult ){
1589de630353Sdanielk1977     pik_flags |= OPFLAG_USESEEKRESULT;
1590de630353Sdanielk1977   }
15916934fc7bSdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
159294eb6a14Sdanielk1977   if( !pParse->nested ){
15938d129422Sdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
159494eb6a14Sdanielk1977   }
1595b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
15960ca3e24bSdrh }
1597cd44690aSdrh 
1598cd44690aSdrh /*
159926198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate
160026198bb4Sdrh ** code to open and initialized those cursors.
1601aa9b8963Sdrh **
160226198bb4Sdrh ** The cursor for the object that contains the complete data (normally
160326198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
160426198bb4Sdrh ** ROWID table) is returned in *piDataCur.  The first index cursor is
160526198bb4Sdrh ** returned in *piIdxCur.  The number of indices is returned.
160626198bb4Sdrh **
160726198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables
160826198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative.
160926198bb4Sdrh ** If iBase is negative, then allocate the next available cursor.
161026198bb4Sdrh **
161126198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
161226198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
161326198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
161426198bb4Sdrh ** pTab->pIndex list.
1615b6b4b79fSdrh **
1616b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the
1617b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized.
1618cd44690aSdrh */
1619aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1620290c1948Sdrh   Parse *pParse,   /* Parsing context */
1621290c1948Sdrh   Table *pTab,     /* Table to be opened */
162226198bb4Sdrh   int op,          /* OP_OpenRead or OP_OpenWrite */
162326198bb4Sdrh   int iBase,       /* Use this for the table cursor, if there is one */
16246a53499aSdrh   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
162526198bb4Sdrh   int *piDataCur,  /* Write the database source cursor number here */
162626198bb4Sdrh   int *piIdxCur    /* Write the first index cursor number here */
1627290c1948Sdrh ){
1628cd44690aSdrh   int i;
16294cbdda9eSdrh   int iDb;
16306a53499aSdrh   int iDataCur;
1631cd44690aSdrh   Index *pIdx;
16324cbdda9eSdrh   Vdbe *v;
16334cbdda9eSdrh 
163426198bb4Sdrh   assert( op==OP_OpenRead || op==OP_OpenWrite );
163526198bb4Sdrh   if( IsVirtual(pTab) ){
1636b6b4b79fSdrh     /* This routine is a no-op for virtual tables. Leave the output
1637b6b4b79fSdrh     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
1638b6b4b79fSdrh     ** can detect if they are used by mistake in the caller. */
163926198bb4Sdrh     return 0;
164026198bb4Sdrh   }
16414cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
16424cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1643cd44690aSdrh   assert( v!=0 );
164426198bb4Sdrh   if( iBase<0 ) iBase = pParse->nTab;
16456a53499aSdrh   iDataCur = iBase++;
16466a53499aSdrh   if( piDataCur ) *piDataCur = iDataCur;
16476a53499aSdrh   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
16486a53499aSdrh     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
16496fbe41acSdrh   }else{
165026198bb4Sdrh     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
16516fbe41acSdrh   }
16526a53499aSdrh   if( piIdxCur ) *piIdxCur = iBase;
165326198bb4Sdrh   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
165426198bb4Sdrh     int iIdxCur = iBase++;
1655da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
165648dd1d8eSdrh     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
16576a53499aSdrh       *piDataCur = iIdxCur;
16586a53499aSdrh     }
16596a53499aSdrh     if( aToOpen==0 || aToOpen[i+1] ){
16602ec2fb22Sdrh       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
16612ec2fb22Sdrh       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1662207872a4Sdanielk1977       VdbeComment((v, "%s", pIdx->zName));
1663cd44690aSdrh     }
16646a53499aSdrh   }
166526198bb4Sdrh   if( iBase>pParse->nTab ) pParse->nTab = iBase;
166626198bb4Sdrh   return i;
1667cd44690aSdrh }
16689d9cf229Sdrh 
166991c58e23Sdrh 
167091c58e23Sdrh #ifdef SQLITE_TEST
167191c58e23Sdrh /*
167291c58e23Sdrh ** The following global variable is incremented whenever the
167391c58e23Sdrh ** transfer optimization is used.  This is used for testing
167491c58e23Sdrh ** purposes only - to make sure the transfer optimization really
167560ec914cSpeter.d.reid ** is happening when it is supposed to.
167691c58e23Sdrh */
167791c58e23Sdrh int sqlite3_xferopt_count;
167891c58e23Sdrh #endif /* SQLITE_TEST */
167991c58e23Sdrh 
168091c58e23Sdrh 
16819d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
16829d9cf229Sdrh /*
16839d9cf229Sdrh ** Check to collation names to see if they are compatible.
16849d9cf229Sdrh */
16859d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
16869d9cf229Sdrh   if( z1==0 ){
16879d9cf229Sdrh     return z2==0;
16889d9cf229Sdrh   }
16899d9cf229Sdrh   if( z2==0 ){
16909d9cf229Sdrh     return 0;
16919d9cf229Sdrh   }
16929d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
16939d9cf229Sdrh }
16949d9cf229Sdrh 
16959d9cf229Sdrh 
16969d9cf229Sdrh /*
16979d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
16989d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
16999d9cf229Sdrh ** for a compatible index:
17009d9cf229Sdrh **
17019d9cf229Sdrh **    *   The index is over the same set of columns
17029d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
17039d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
17049d9cf229Sdrh **    *   The same collating sequence on each column
1705b2b9d3d7Sdrh **    *   The index has the exact same WHERE clause
17069d9cf229Sdrh */
17079d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
17089d9cf229Sdrh   int i;
17099d9cf229Sdrh   assert( pDest && pSrc );
17109d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
1711bbbdc83bSdrh   if( pDest->nKeyCol!=pSrc->nKeyCol ){
17129d9cf229Sdrh     return 0;   /* Different number of columns */
17139d9cf229Sdrh   }
17149d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
17159d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
17169d9cf229Sdrh   }
1717bbbdc83bSdrh   for(i=0; i<pSrc->nKeyCol; i++){
17189d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
17199d9cf229Sdrh       return 0;   /* Different columns indexed */
17209d9cf229Sdrh     }
17219d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
17229d9cf229Sdrh       return 0;   /* Different sort orders */
17239d9cf229Sdrh     }
17243f6e781dSdrh     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
172560a713c6Sdrh       return 0;   /* Different collating sequences */
17269d9cf229Sdrh     }
17279d9cf229Sdrh   }
1728619a1305Sdrh   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
1729b2b9d3d7Sdrh     return 0;     /* Different WHERE clauses */
1730b2b9d3d7Sdrh   }
17319d9cf229Sdrh 
17329d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
17339d9cf229Sdrh   return 1;
17349d9cf229Sdrh }
17359d9cf229Sdrh 
17369d9cf229Sdrh /*
17379d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
17389d9cf229Sdrh **
17399d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
17409d9cf229Sdrh **
1741ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1.
174260ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves
1743ccdf1baeSdrh ** performance.  Raw index records are transferred in the same way.
17449d9cf229Sdrh **
1745ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1746ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments
1747ccdf1baeSdrh ** embedded in the code for details.
17489d9cf229Sdrh **
1749ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used.
1750ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table
1751ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time.  In that
1752ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also
1753ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the
1754ccdf1baeSdrh ** xfer optimization code if the test fails.  In that case, this routine
1755ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate
1756ccdf1baeSdrh ** an unoptimized transfer.  This routine also returns FALSE if there
1757ccdf1baeSdrh ** is no chance that the xfer optimization can be applied.
17589d9cf229Sdrh **
1759ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster.
17609d9cf229Sdrh */
17619d9cf229Sdrh static int xferOptimization(
17629d9cf229Sdrh   Parse *pParse,        /* Parser context */
17639d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
17649d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
17659d9cf229Sdrh   int onError,          /* How to handle constraint errors */
17669d9cf229Sdrh   int iDbDest           /* The database of pDest */
17679d9cf229Sdrh ){
1768e34162b1Sdan   sqlite3 *db = pParse->db;
17699d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
17709d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
17719d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
17729d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
17739d9cf229Sdrh   int i;                           /* Loop counter */
17749d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
17759d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
17769d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
1777da475b8dSdrh   int emptyDestTest = 0;           /* Address of test for empty pDest */
1778da475b8dSdrh   int emptySrcTest = 0;            /* Address of test for empty pSrc */
17799d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
17806a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1781f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1782b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
17839d9cf229Sdrh 
17849d9cf229Sdrh   if( pSelect==0 ){
17859d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
17869d9cf229Sdrh   }
1787ebbf08a0Sdan   if( pParse->pWith || pSelect->pWith ){
1788ebbf08a0Sdan     /* Do not attempt to process this query if there are an WITH clauses
1789ebbf08a0Sdan     ** attached to it. Proceeding may generate a false "no such table: xxx"
1790ebbf08a0Sdan     ** error if pSelect reads from a CTE named "xxx".  */
1791ebbf08a0Sdan     return 0;
1792ebbf08a0Sdan   }
17932f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
17949d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
17959d9cf229Sdrh   }
17969d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
17977d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
17989d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
17999d9cf229Sdrh   }
18009d9cf229Sdrh #endif
18019d9cf229Sdrh   if( onError==OE_Default ){
1802e7224a01Sdrh     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1803e7224a01Sdrh     if( onError==OE_Default ) onError = OE_Abort;
18049d9cf229Sdrh   }
18055ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
18069d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
18079d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
18089d9cf229Sdrh   }
18099d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
18109d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
18119d9cf229Sdrh   }
18129d9cf229Sdrh   if( pSelect->pWhere ){
18139d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
18149d9cf229Sdrh   }
18159d9cf229Sdrh   if( pSelect->pOrderBy ){
18169d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
18179d9cf229Sdrh   }
18188103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
18198103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
18209d9cf229Sdrh   if( pSelect->pGroupBy ){
18219d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
18229d9cf229Sdrh   }
18239d9cf229Sdrh   if( pSelect->pLimit ){
18249d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
18259d9cf229Sdrh   }
18268103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
18279d9cf229Sdrh   if( pSelect->pPrior ){
18289d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
18299d9cf229Sdrh   }
18307d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
18319d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
18329d9cf229Sdrh   }
18339d9cf229Sdrh   pEList = pSelect->pEList;
18349d9cf229Sdrh   assert( pEList!=0 );
18359d9cf229Sdrh   if( pEList->nExpr!=1 ){
18369d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
18379d9cf229Sdrh   }
18389d9cf229Sdrh   assert( pEList->a[0].pExpr );
18399d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
18409d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
18419d9cf229Sdrh   }
18429d9cf229Sdrh 
18439d9cf229Sdrh   /* At this point we have established that the statement is of the
18449d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
18459d9cf229Sdrh   ** we have to check the semantics.
18469d9cf229Sdrh   */
18479d9cf229Sdrh   pItem = pSelect->pSrc->a;
184841fb5cd1Sdan   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
18499d9cf229Sdrh   if( pSrc==0 ){
18509d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
18519d9cf229Sdrh   }
18529d9cf229Sdrh   if( pSrc==pDest ){
18539d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
18549d9cf229Sdrh   }
185555548273Sdrh   if( HasRowid(pDest)!=HasRowid(pSrc) ){
185655548273Sdrh     return 0;   /* source and destination must both be WITHOUT ROWID or not */
185755548273Sdrh   }
18589d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
18597d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
18609d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
18619d9cf229Sdrh   }
18629d9cf229Sdrh #endif
18639d9cf229Sdrh   if( pSrc->pSelect ){
18649d9cf229Sdrh     return 0;   /* tab2 may not be a view */
18659d9cf229Sdrh   }
18669d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
18679d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
18689d9cf229Sdrh   }
18699d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
18709d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
18719d9cf229Sdrh   }
18729d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
18739940e2aaSdan     Column *pDestCol = &pDest->aCol[i];
18749940e2aaSdan     Column *pSrcCol = &pSrc->aCol[i];
18759940e2aaSdan     if( pDestCol->affinity!=pSrcCol->affinity ){
18769d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
18779d9cf229Sdrh     }
18789940e2aaSdan     if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
18799d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
18809d9cf229Sdrh     }
18819940e2aaSdan     if( pDestCol->notNull && !pSrcCol->notNull ){
18829d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
18839d9cf229Sdrh     }
1884453e0261Sdrh     /* Default values for second and subsequent columns need to match. */
1885453e0261Sdrh     if( i>0
1886453e0261Sdrh      && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
1887453e0261Sdrh          || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
18889940e2aaSdan     ){
18899940e2aaSdan       return 0;    /* Default values must be the same for all columns */
18909940e2aaSdan     }
18919d9cf229Sdrh   }
18929d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
18935f1d1d9cSdrh     if( IsUniqueIndex(pDestIdx) ){
1894f33c9fadSdrh       destHasUniqueIdx = 1;
1895f33c9fadSdrh     }
18969d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
18979d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
18989d9cf229Sdrh     }
18999d9cf229Sdrh     if( pSrcIdx==0 ){
19009d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
19019d9cf229Sdrh     }
19029d9cf229Sdrh   }
19037fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1904619a1305Sdrh   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
19058103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
19068103b7d2Sdrh   }
19077fc2f41bSdrh #endif
1908713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY
1909713de341Sdrh   /* Disallow the transfer optimization if the destination table constains
1910713de341Sdrh   ** any foreign key constraints.  This is more restrictive than necessary.
1911713de341Sdrh   ** But the main beneficiary of the transfer optimization is the VACUUM
1912713de341Sdrh   ** command, and the VACUUM command disables foreign key constraints.  So
1913713de341Sdrh   ** the extra complication to make this rule less restrictive is probably
1914713de341Sdrh   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1915713de341Sdrh   */
1916e34162b1Sdan   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1917713de341Sdrh     return 0;
1918713de341Sdrh   }
1919713de341Sdrh #endif
1920e34162b1Sdan   if( (db->flags & SQLITE_CountRows)!=0 ){
1921ccdf1baeSdrh     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
19221696124dSdan   }
19239d9cf229Sdrh 
1924ccdf1baeSdrh   /* If we get this far, it means that the xfer optimization is at
1925ccdf1baeSdrh   ** least a possibility, though it might only work if the destination
1926ccdf1baeSdrh   ** table (tab1) is initially empty.
19279d9cf229Sdrh   */
1928dd73521bSdrh #ifdef SQLITE_TEST
1929dd73521bSdrh   sqlite3_xferopt_count++;
1930dd73521bSdrh #endif
1931e34162b1Sdan   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
19329d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1933f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
19349d9cf229Sdrh   iSrc = pParse->nTab++;
19359d9cf229Sdrh   iDest = pParse->nTab++;
19366a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
193755548273Sdrh   regData = sqlite3GetTempReg(pParse);
193855548273Sdrh   regRowid = sqlite3GetTempReg(pParse);
19399d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1940427ebba1Sdan   assert( HasRowid(pDest) || destHasUniqueIdx );
1941e34162b1Sdan   if( (db->flags & SQLITE_Vacuum)==0 && (
1942e34162b1Sdan       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
1943ccdf1baeSdrh    || destHasUniqueIdx                              /* (2) */
1944ccdf1baeSdrh    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
1945e34162b1Sdan   )){
1946ccdf1baeSdrh     /* In some circumstances, we are able to run the xfer optimization
1947e34162b1Sdan     ** only if the destination table is initially empty. Unless the
1948e34162b1Sdan     ** SQLITE_Vacuum flag is set, this block generates code to make
1949e34162b1Sdan     ** that determination. If SQLITE_Vacuum is set, then the destination
1950e34162b1Sdan     ** table is always empty.
1951e34162b1Sdan     **
1952e34162b1Sdan     ** Conditions under which the destination must be empty:
1953f33c9fadSdrh     **
1954ccdf1baeSdrh     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1955ccdf1baeSdrh     **     (If the destination is not initially empty, the rowid fields
1956ccdf1baeSdrh     **     of index entries might need to change.)
1957ccdf1baeSdrh     **
1958ccdf1baeSdrh     ** (2) The destination has a unique index.  (The xfer optimization
1959ccdf1baeSdrh     **     is unable to test uniqueness.)
1960ccdf1baeSdrh     **
1961ccdf1baeSdrh     ** (3) onError is something other than OE_Abort and OE_Rollback.
19629d9cf229Sdrh     */
1963688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
196466a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
19659d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
19669d9cf229Sdrh   }
1967427ebba1Sdan   if( HasRowid(pSrc) ){
19689d9cf229Sdrh     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1969688852abSdrh     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
197042242dedSdrh     if( pDest->iPKey>=0 ){
1971b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1972b7654111Sdrh       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1973688852abSdrh       VdbeCoverage(v);
1974f9c8ce3cSdrh       sqlite3RowidConstraint(pParse, onError, pDest);
19759d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
1976b7654111Sdrh       autoIncStep(pParse, regAutoinc, regRowid);
1977bd36ba69Sdrh     }else if( pDest->pIndex==0 ){
1978b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
197995bad4c7Sdrh     }else{
1980b7654111Sdrh       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
19817d10d5a6Sdrh       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
198295bad4c7Sdrh     }
1983b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1984b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1985b7654111Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
19861f4aa337Sdanielk1977     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
1987688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
198855548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
198955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1990da475b8dSdrh   }else{
1991da475b8dSdrh     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
1992da475b8dSdrh     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
199355548273Sdrh   }
19949d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1995e34162b1Sdan     u8 useSeekResult = 0;
19961b7ecbb4Sdrh     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
19979d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
19989d9cf229Sdrh     }
19999d9cf229Sdrh     assert( pSrcIdx );
20002ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
20012ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2002d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
20032ec2fb22Sdrh     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
20042ec2fb22Sdrh     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
200559885728Sdan     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2006207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
2007688852abSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2008b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
2009e34162b1Sdan     if( db->flags & SQLITE_Vacuum ){
2010e34162b1Sdan       /* This INSERT command is part of a VACUUM operation, which guarantees
2011e34162b1Sdan       ** that the destination table is empty. If all indexed columns use
2012e34162b1Sdan       ** collation sequence BINARY, then it can also be assumed that the
2013e34162b1Sdan       ** index will be populated by inserting keys in strictly sorted
2014e34162b1Sdan       ** order. In this case, instead of seeking within the b-tree as part
2015e34162b1Sdan       ** of every OP_IdxInsert opcode, an OP_Last is added before the
2016e34162b1Sdan       ** OP_IdxInsert to seek to the point within the b-tree where each key
2017e34162b1Sdan       ** should be inserted. This is faster.
2018e34162b1Sdan       **
2019e34162b1Sdan       ** If any of the indexed columns use a collation sequence other than
2020e34162b1Sdan       ** BINARY, this optimization is disabled. This is because the user
2021e34162b1Sdan       ** might change the definition of a collation sequence and then run
2022e34162b1Sdan       ** a VACUUM command. In that case keys may not be written in strictly
2023e34162b1Sdan       ** sorted order.  */
2024e34162b1Sdan       int i;
2025e34162b1Sdan       for(i=0; i<pSrcIdx->nColumn; i++){
2026e34162b1Sdan         char *zColl = pSrcIdx->azColl[i];
2027*ab06b0e5Sdrh         assert( zColl!=0 );
2028*ab06b0e5Sdrh         if( sqlite3_stricmp("BINARY", zColl) ) break;
2029e34162b1Sdan       }
2030e34162b1Sdan       if( i==pSrcIdx->nColumn ){
2031e34162b1Sdan         useSeekResult = OPFLAG_USESEEKRESULT;
2032e34162b1Sdan         sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
2033e34162b1Sdan       }
2034e34162b1Sdan     }
2035b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
2036e34162b1Sdan     sqlite3VdbeChangeP5(v, useSeekResult);
2037688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
20389d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
203955548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
204055548273Sdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20419d9cf229Sdrh   }
2042aceb31b1Sdrh   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2043b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
2044b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
20459d9cf229Sdrh   if( emptyDestTest ){
204666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
20479d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
204866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
20499d9cf229Sdrh     return 0;
20509d9cf229Sdrh   }else{
20519d9cf229Sdrh     return 1;
20529d9cf229Sdrh   }
20539d9cf229Sdrh }
20549d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
2055