blob: e94af09855bf4c455fee4a2fde6946d83b52cb02 [file] [log] [blame]
drhcce7d172000-05-31 15:34:51 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drhcce7d172000-05-31 15:34:51 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drhcce7d172000-05-31 15:34:51 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drhcce7d172000-05-31 15:34:51 +000010**
11*************************************************************************
12** This file contains C code routines that are called by the parser
drhb19a2bc2001-09-16 00:13:26 +000013** to handle INSERT statements in SQLite.
drhcce7d172000-05-31 15:34:51 +000014*/
15#include "sqliteInt.h"
16
17/*
drh26198bb2013-10-31 11:15:09 +000018** Generate code that will
drhdd9930e2013-10-23 23:37:02 +000019**
drh26198bb2013-10-31 11:15:09 +000020** (1) acquire a lock for table pTab then
21** (2) open pTab as cursor iCur.
22**
23** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
24** for that table that is actually opened.
drhbbb5e4e2009-04-30 00:11:09 +000025*/
26void sqlite3OpenTable(
drh2ec2fb22013-11-06 19:59:23 +000027 Parse *pParse, /* Generate code into this VDBE */
drhbbb5e4e2009-04-30 00:11:09 +000028 int iCur, /* The cursor number of the table */
29 int iDb, /* The database index in sqlite3.aDb[] */
30 Table *pTab, /* The table to be opened */
31 int opcode /* OP_OpenRead or OP_OpenWrite */
32){
33 Vdbe *v;
drh5f53aac2012-12-03 19:42:39 +000034 assert( !IsVirtual(pTab) );
drh2ec2fb22013-11-06 19:59:23 +000035 v = sqlite3GetVdbe(pParse);
drhbbb5e4e2009-04-30 00:11:09 +000036 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
drh2ec2fb22013-11-06 19:59:23 +000037 sqlite3TableLock(pParse, iDb, pTab->tnum,
38 (opcode==OP_OpenWrite)?1:0, pTab->zName);
drhec95c442013-10-23 01:57:32 +000039 if( HasRowid(pTab) ){
drh261c02d2013-10-25 14:46:15 +000040 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
drhdd9930e2013-10-23 23:37:02 +000041 VdbeComment((v, "%s", pTab->zName));
drh26198bb2013-10-31 11:15:09 +000042 }else{
drhdd9930e2013-10-23 23:37:02 +000043 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
44 assert( pPk!=0 );
drhafe028a2015-05-22 13:09:50 +000045 assert( pPk->tnum==pTab->tnum );
drh2ec2fb22013-11-06 19:59:23 +000046 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
47 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
drhec95c442013-10-23 01:57:32 +000048 VdbeComment((v, "%s", pTab->zName));
49 }
drhbbb5e4e2009-04-30 00:11:09 +000050}
51
52/*
dan69f8bb92009-08-13 19:21:16 +000053** Return a pointer to the column affinity string associated with index
54** pIdx. A column affinity string has one character for each column in
55** the table, according to the affinity of the column:
danielk19773d1bfea2004-05-14 11:00:53 +000056**
57** Character Column affinity
58** ------------------------------
drh05883a32015-06-02 15:32:08 +000059** 'A' BLOB
drh4583c372014-09-19 20:13:25 +000060** 'B' TEXT
61** 'C' NUMERIC
62** 'D' INTEGER
63** 'F' REAL
drh2d401ab2008-01-10 23:50:11 +000064**
drh4583c372014-09-19 20:13:25 +000065** An extra 'D' is appended to the end of the string to cover the
drh2d401ab2008-01-10 23:50:11 +000066** rowid that appears as the last column in every index.
dan69f8bb92009-08-13 19:21:16 +000067**
68** Memory for the buffer containing the column index affinity string
69** is managed along with the rest of the Index structure. It will be
70** released when sqlite3DeleteIndex() is called.
danielk19773d1bfea2004-05-14 11:00:53 +000071*/
drhe9107692015-08-25 19:20:04 +000072const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
danielk1977a37cdde2004-05-16 11:15:36 +000073 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000074 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000075 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000076 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000077 **
78 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000079 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000080 ** up.
81 */
82 int n;
83 Table *pTab = pIdx->pTable;
drhad124322013-10-23 13:30:58 +000084 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
danielk1977a37cdde2004-05-16 11:15:36 +000085 if( !pIdx->zColAff ){
drh633e6d52008-07-28 19:34:53 +000086 db->mallocFailed = 1;
dan69f8bb92009-08-13 19:21:16 +000087 return 0;
danielk1977a37cdde2004-05-16 11:15:36 +000088 }
drhad124322013-10-23 13:30:58 +000089 for(n=0; n<pIdx->nColumn; n++){
90 i16 x = pIdx->aiColumn[n];
91 pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
danielk1977a37cdde2004-05-16 11:15:36 +000092 }
drh2d401ab2008-01-10 23:50:11 +000093 pIdx->zColAff[n] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +000094 }
danielk19773d1bfea2004-05-14 11:00:53 +000095
dan69f8bb92009-08-13 19:21:16 +000096 return pIdx->zColAff;
danielk1977a37cdde2004-05-16 11:15:36 +000097}
98
99/*
drhe9107692015-08-25 19:20:04 +0000100** Return the affinity for a single column of an index.
101*/
102char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
103 if( !pIdx->zColAff ){
104 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
105 }
106 return pIdx->zColAff[iCol];
107}
108
109/*
drh57bf4a82014-02-17 14:59:22 +0000110** Compute the affinity string for table pTab, if it has not already been
drh05883a32015-06-02 15:32:08 +0000111** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
drh57bf4a82014-02-17 14:59:22 +0000112**
drh05883a32015-06-02 15:32:08 +0000113** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
drh57bf4a82014-02-17 14:59:22 +0000114** if iReg>0 then code an OP_Affinity opcode that will set the affinities
115** for register iReg and following. Or if affinities exists and iReg==0,
116** then just set the P4 operand of the previous opcode (which should be
117** an OP_MakeRecord) to the affinity string.
118**
drhb6e8fd12014-03-06 01:56:33 +0000119** A column affinity string has one character per column:
danielk1977a37cdde2004-05-16 11:15:36 +0000120**
121** Character Column affinity
122** ------------------------------
drh05883a32015-06-02 15:32:08 +0000123** 'A' BLOB
drh4583c372014-09-19 20:13:25 +0000124** 'B' TEXT
125** 'C' NUMERIC
126** 'D' INTEGER
127** 'E' REAL
danielk1977a37cdde2004-05-16 11:15:36 +0000128*/
drh57bf4a82014-02-17 14:59:22 +0000129void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
130 int i;
131 char *zColAff = pTab->zColAff;
132 if( zColAff==0 ){
drhabb6fca2007-08-16 12:24:01 +0000133 sqlite3 *db = sqlite3VdbeDb(v);
drhb9755982010-07-24 16:34:37 +0000134 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +0000135 if( !zColAff ){
drh633e6d52008-07-28 19:34:53 +0000136 db->mallocFailed = 1;
danielk1977a37cdde2004-05-16 11:15:36 +0000137 return;
danielk19773d1bfea2004-05-14 11:00:53 +0000138 }
139
140 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +0000141 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +0000142 }
drh57bf4a82014-02-17 14:59:22 +0000143 do{
144 zColAff[i--] = 0;
drh05883a32015-06-02 15:32:08 +0000145 }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
danielk19773d1bfea2004-05-14 11:00:53 +0000146 pTab->zColAff = zColAff;
147 }
drh57bf4a82014-02-17 14:59:22 +0000148 i = sqlite3Strlen30(zColAff);
149 if( i ){
150 if( iReg ){
151 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
152 }else{
153 sqlite3VdbeChangeP4(v, -1, zColAff, i);
154 }
155 }
danielk19773d1bfea2004-05-14 11:00:53 +0000156}
157
danielk19774d887782005-02-08 08:42:27 +0000158/*
drh48d11782007-11-23 15:02:19 +0000159** Return non-zero if the table pTab in database iDb or any of its indices
drhb6e8fd12014-03-06 01:56:33 +0000160** have been opened at any point in the VDBE program. This is used to see if
drh48d11782007-11-23 15:02:19 +0000161** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
drhb6e8fd12014-03-06 01:56:33 +0000162** run without using a temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000163*/
drh05a86c52014-02-16 01:55:49 +0000164static int readsTable(Parse *p, int iDb, Table *pTab){
danielk1977595a5232009-07-24 17:58:53 +0000165 Vdbe *v = sqlite3GetVdbe(p);
danielk19774d887782005-02-08 08:42:27 +0000166 int i;
drh48d11782007-11-23 15:02:19 +0000167 int iEnd = sqlite3VdbeCurrentAddr(v);
danielk1977595a5232009-07-24 17:58:53 +0000168#ifndef SQLITE_OMIT_VIRTUALTABLE
169 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
170#endif
171
drh05a86c52014-02-16 01:55:49 +0000172 for(i=1; i<iEnd; i++){
drh48d11782007-11-23 15:02:19 +0000173 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000174 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000175 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
176 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000177 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000178 if( tnum==pTab->tnum ){
179 return 1;
180 }
181 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
182 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000183 return 1;
184 }
drh48d11782007-11-23 15:02:19 +0000185 }
186 }
drh543165e2007-11-27 14:46:41 +0000187#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53 +0000188 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
danielk19772dca4ac2008-01-03 11:50:29 +0000189 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000190 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000191 return 1;
danielk19774d887782005-02-08 08:42:27 +0000192 }
drh543165e2007-11-27 14:46:41 +0000193#endif
danielk19774d887782005-02-08 08:42:27 +0000194 }
195 return 0;
196}
danielk19773d1bfea2004-05-14 11:00:53 +0000197
drh9d9cf222007-02-13 15:01:11 +0000198#ifndef SQLITE_OMIT_AUTOINCREMENT
199/*
drh0b9f50d2009-06-23 20:28:53 +0000200** Locate or create an AutoincInfo structure associated with table pTab
201** which is in database iDb. Return the register number for the register
202** that holds the maximum rowid.
drh9d9cf222007-02-13 15:01:11 +0000203**
drh0b9f50d2009-06-23 20:28:53 +0000204** There is at most one AutoincInfo structure per table even if the
205** same table is autoincremented multiple times due to inserts within
206** triggers. A new AutoincInfo structure is created if this is the
207** first use of table pTab. On 2nd and subsequent uses, the original
208** AutoincInfo structure is used.
drh9d9cf222007-02-13 15:01:11 +0000209**
drh0b9f50d2009-06-23 20:28:53 +0000210** Three memory locations are allocated:
211**
212** (1) Register to hold the name of the pTab table.
213** (2) Register to hold the maximum ROWID of pTab.
214** (3) Register to hold the rowid in sqlite_sequence of pTab
215**
216** The 2nd register is the one that is returned. That is all the
217** insert routine needs to know about.
drh9d9cf222007-02-13 15:01:11 +0000218*/
219static int autoIncBegin(
220 Parse *pParse, /* Parsing context */
221 int iDb, /* Index of the database holding pTab */
222 Table *pTab /* The table we are writing to */
223){
drh6a288a32008-01-07 19:20:24 +0000224 int memId = 0; /* Register holding maximum rowid */
drh7d10d5a2008-08-20 16:35:10 +0000225 if( pTab->tabFlags & TF_Autoincrement ){
dan65a7cd12009-09-01 12:16:01 +0000226 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000227 AutoincInfo *pInfo;
228
dan65a7cd12009-09-01 12:16:01 +0000229 pInfo = pToplevel->pAinc;
drh0b9f50d2009-06-23 20:28:53 +0000230 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
231 if( pInfo==0 ){
232 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
233 if( pInfo==0 ) return 0;
dan65a7cd12009-09-01 12:16:01 +0000234 pInfo->pNext = pToplevel->pAinc;
235 pToplevel->pAinc = pInfo;
drh0b9f50d2009-06-23 20:28:53 +0000236 pInfo->pTab = pTab;
237 pInfo->iDb = iDb;
dan65a7cd12009-09-01 12:16:01 +0000238 pToplevel->nMem++; /* Register to hold name of table */
239 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
240 pToplevel->nMem++; /* Rowid in sqlite_sequence */
drh0b9f50d2009-06-23 20:28:53 +0000241 }
242 memId = pInfo->regCtr;
drh9d9cf222007-02-13 15:01:11 +0000243 }
244 return memId;
245}
246
247/*
drh0b9f50d2009-06-23 20:28:53 +0000248** This routine generates code that will initialize all of the
249** register used by the autoincrement tracker.
250*/
251void sqlite3AutoincrementBegin(Parse *pParse){
252 AutoincInfo *p; /* Information about an AUTOINCREMENT */
253 sqlite3 *db = pParse->db; /* The database connection */
254 Db *pDb; /* Database only autoinc table */
255 int memId; /* Register holding max rowid */
256 int addr; /* A VDBE address */
257 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
258
drh345ba7d2009-09-08 13:40:16 +0000259 /* This routine is never called during trigger-generation. It is
260 ** only called from the top-level */
261 assert( pParse->pTriggerTab==0 );
262 assert( pParse==sqlite3ParseToplevel(pParse) );
dan76d462e2009-08-30 11:42:51 +0000263
drh0b9f50d2009-06-23 20:28:53 +0000264 assert( v ); /* We failed long ago if this is not so */
265 for(p = pParse->pAinc; p; p = p->pNext){
266 pDb = &db->aDb[p->iDb];
267 memId = p->regCtr;
drh21206082011-04-04 18:22:02 +0000268 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drh0b9f50d2009-06-23 20:28:53 +0000269 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drhf4d31bc2011-12-09 16:59:19 +0000270 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
drh0b9f50d2009-06-23 20:28:53 +0000271 addr = sqlite3VdbeCurrentAddr(v);
272 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
drh688852a2014-02-17 22:40:43 +0000273 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
drh0b9f50d2009-06-23 20:28:53 +0000274 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
drh688852a2014-02-17 22:40:43 +0000275 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
drh0b9f50d2009-06-23 20:28:53 +0000276 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
277 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
278 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
279 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
drh688852a2014-02-17 22:40:43 +0000280 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
drh0b9f50d2009-06-23 20:28:53 +0000281 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
282 sqlite3VdbeAddOp0(v, OP_Close);
283 }
284}
285
286/*
drh9d9cf222007-02-13 15:01:11 +0000287** Update the maximum rowid for an autoincrement calculation.
288**
289** This routine should be called when the top of the stack holds a
290** new rowid that is about to be inserted. If that new rowid is
291** larger than the maximum rowid in the memId memory cell, then the
292** memory cell is updated. The stack is unchanged.
293*/
drh6a288a32008-01-07 19:20:24 +0000294static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000295 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000296 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000297 }
298}
299
300/*
drh0b9f50d2009-06-23 20:28:53 +0000301** This routine generates the code needed to write autoincrement
302** maximum rowid values back into the sqlite_sequence register.
303** Every statement that might do an INSERT into an autoincrement
304** table (either directly or through triggers) needs to call this
305** routine just before the "exit" code.
drh9d9cf222007-02-13 15:01:11 +0000306*/
drh0b9f50d2009-06-23 20:28:53 +0000307void sqlite3AutoincrementEnd(Parse *pParse){
308 AutoincInfo *p;
309 Vdbe *v = pParse->pVdbe;
310 sqlite3 *db = pParse->db;
drh6a288a32008-01-07 19:20:24 +0000311
drh0b9f50d2009-06-23 20:28:53 +0000312 assert( v );
313 for(p = pParse->pAinc; p; p = p->pNext){
314 Db *pDb = &db->aDb[p->iDb];
drh3d77dee2014-02-19 14:20:49 +0000315 int j1;
drh0b9f50d2009-06-23 20:28:53 +0000316 int iRec;
317 int memId = p->regCtr;
318
319 iRec = sqlite3GetTempReg(pParse);
drh21206082011-04-04 18:22:02 +0000320 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drh0b9f50d2009-06-23 20:28:53 +0000321 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh688852a2014-02-17 22:40:43 +0000322 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
drh0b9f50d2009-06-23 20:28:53 +0000323 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
drh6a288a32008-01-07 19:20:24 +0000324 sqlite3VdbeJumpHere(v, j1);
danielk1977a7a8e142008-02-13 18:25:27 +0000325 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
drh0b9f50d2009-06-23 20:28:53 +0000326 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
drh35573352008-01-08 23:54:25 +0000327 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh0b9f50d2009-06-23 20:28:53 +0000328 sqlite3VdbeAddOp0(v, OP_Close);
329 sqlite3ReleaseTempReg(pParse, iRec);
drh9d9cf222007-02-13 15:01:11 +0000330 }
331}
332#else
333/*
334** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
335** above are all no-ops
336*/
337# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000338# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000339#endif /* SQLITE_OMIT_AUTOINCREMENT */
340
341
342/* Forward declaration */
343static int xferOptimization(
344 Parse *pParse, /* Parser context */
345 Table *pDest, /* The table we are inserting into */
346 Select *pSelect, /* A SELECT statement to use as the data source */
347 int onError, /* How to handle constraint errors */
348 int iDbDest /* The database of pDest */
349);
350
danielk19773d1bfea2004-05-14 11:00:53 +0000351/*
drhd82b5022013-10-26 00:58:34 +0000352** This routine is called to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000353**
drha21f78b2015-04-19 18:32:43 +0000354** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
drh1ccde152000-06-17 13:12:39 +0000355** insert into TABLE (IDLIST) select
drha21f78b2015-04-19 18:32:43 +0000356** insert into TABLE (IDLIST) default values
drhcce7d172000-05-31 15:34:51 +0000357**
drh1ccde152000-06-17 13:12:39 +0000358** The IDLIST following the table name is always optional. If omitted,
drha21f78b2015-04-19 18:32:43 +0000359** then a list of all (non-hidden) columns for the table is substituted.
360** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
361** is omitted.
drh1ccde152000-06-17 13:12:39 +0000362**
drha21f78b2015-04-19 18:32:43 +0000363** For the pSelect parameter holds the values to be inserted for the
364** first two forms shown above. A VALUES clause is really just short-hand
365** for a SELECT statement that omits the FROM clause and everything else
366** that follows. If the pSelect parameter is NULL, that means that the
367** DEFAULT VALUES form of the INSERT statement is intended.
drh142e30d2002-08-28 03:00:58 +0000368**
drh9d9cf222007-02-13 15:01:11 +0000369** The code generated follows one of four templates. For a simple
drha21f78b2015-04-19 18:32:43 +0000370** insert with data coming from a single-row VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01 +0000371** once straight down through. Pseudo-code follows (we call this
372** the "1st template"):
drh142e30d2002-08-28 03:00:58 +0000373**
374** open write cursor to <table> and its indices
drhec95c442013-10-23 01:57:32 +0000375** put VALUES clause expressions into registers
drh142e30d2002-08-28 03:00:58 +0000376** write the resulting record into <table>
377** cleanup
378**
drh9d9cf222007-02-13 15:01:11 +0000379** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000380**
381** INSERT INTO <table> SELECT ...
382**
drh9d9cf222007-02-13 15:01:11 +0000383** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
384** in other words if the SELECT pulls all columns from a single table
385** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
386** if <table2> and <table1> are distinct tables but have identical
387** schemas, including all the same indices, then a special optimization
388** is invoked that copies raw records from <table2> over to <table1>.
389** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01 +0000390** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000391**
392** open a write cursor to <table>
393** open read cursor on <table2>
394** transfer all records in <table2> over to <table>
395** close cursors
396** foreach index on <table>
397** open a write cursor on the <table> index
398** open a read cursor on the corresponding <table2> index
399** transfer all records from the read to the write cursors
400** close cursors
401** end foreach
402**
drhe00ee6e2008-06-20 15:24:01 +0000403** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11 +0000404** and the SELECT clause does not read from <table> at any time.
405** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000406**
drhe00ee6e2008-06-20 15:24:01 +0000407** X <- A
drh142e30d2002-08-28 03:00:58 +0000408** goto B
409** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000410** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000411** load values into registers R..R+n
412** yield X
drh142e30d2002-08-28 03:00:58 +0000413** end loop
414** cleanup after the SELECT
drh81cf13e2014-02-07 18:27:53 +0000415** end-coroutine X
drhe00ee6e2008-06-20 15:24:01 +0000416** B: open write cursor to <table> and its indices
drh81cf13e2014-02-07 18:27:53 +0000417** C: yield X, at EOF goto D
drhe00ee6e2008-06-20 15:24:01 +0000418** insert the select result into <table> from R..R+n
419** goto C
drh142e30d2002-08-28 03:00:58 +0000420** D: cleanup
421**
drhe00ee6e2008-06-20 15:24:01 +0000422** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000423** values from a SELECT but the data is being inserted into a table
424** that is also read as part of the SELECT. In the third form,
peter.d.reid60ec9142014-09-06 16:39:46 +0000425** we have to use an intermediate table to store the results of
drh142e30d2002-08-28 03:00:58 +0000426** the select. The template is like this:
427**
drhe00ee6e2008-06-20 15:24:01 +0000428** X <- A
drh142e30d2002-08-28 03:00:58 +0000429** goto B
430** A: setup for the SELECT
431** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000432** load value into register R..R+n
433** yield X
drh142e30d2002-08-28 03:00:58 +0000434** end loop
435** cleanup after the SELECT
drh81cf13e2014-02-07 18:27:53 +0000436** end co-routine R
drhe00ee6e2008-06-20 15:24:01 +0000437** B: open temp table
drh81cf13e2014-02-07 18:27:53 +0000438** L: yield X, at EOF goto M
drhe00ee6e2008-06-20 15:24:01 +0000439** insert row from R..R+n into temp table
440** goto L
441** M: open write cursor to <table> and its indices
442** rewind temp table
443** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58 +0000444** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01 +0000445** end loop
446** D: cleanup
drhcce7d172000-05-31 15:34:51 +0000447*/
danielk19774adee202004-05-08 08:23:19 +0000448void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000449 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000450 SrcList *pTabList, /* Name of table into which we are inserting */
drh5974a302000-06-07 14:42:26 +0000451 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000452 IdList *pColumn, /* Column names corresponding to IDLIST. */
453 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000454){
drh6a288a32008-01-07 19:20:24 +0000455 sqlite3 *db; /* The main database structure */
456 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000457 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000458 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000459 int i, j, idx; /* Loop counters */
460 Vdbe *v; /* Generate code into this virtual machine */
461 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000462 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000463 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh26198bb2013-10-31 11:15:09 +0000464 int iDataCur = 0; /* VDBE cursor that is the main data repository */
465 int iIdxCur = 0; /* First index cursor */
drhd82b5022013-10-26 00:58:34 +0000466 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000467 int endOfLoop; /* Label for the end of the insertion loop */
danielk1977cfe9a692004-06-16 12:00:29 +0000468 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01 +0000469 int addrInsTop = 0; /* Jump to label "D" */
470 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
drh2eb95372008-06-06 15:04:36 +0000471 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24 +0000472 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000473 Db *pDb; /* The database containing table being inserted into */
drh05a86c52014-02-16 01:55:49 +0000474 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
475 u8 appendFlag = 0; /* True if the insert is likely to be an append */
476 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
drha21f78b2015-04-19 18:32:43 +0000477 u8 bIdListInOrder; /* True if IDLIST is in table order */
drh75593d92014-01-10 20:46:55 +0000478 ExprList *pList = 0; /* List of VALUES() to be inserted */
drhcce7d172000-05-31 15:34:51 +0000479
drh6a288a32008-01-07 19:20:24 +0000480 /* Register allocations */
drh1bd10f82008-12-10 21:19:56 +0000481 int regFromSelect = 0;/* Base register for data coming from SELECT */
drh6a288a32008-01-07 19:20:24 +0000482 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
483 int regRowCount = 0; /* Memory cell used for the row counter */
484 int regIns; /* Block of regs holding rowid+data being inserted */
485 int regRowid; /* registers holding insert rowid */
486 int regData; /* register holding first column to insert */
drhaa9b8962008-01-08 02:57:55 +0000487 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000488
drh798da522004-11-04 04:42:28 +0000489#ifndef SQLITE_OMIT_TRIGGER
490 int isView; /* True if attempting to insert into a view */
danielk19772f886d12009-02-28 10:47:41 +0000491 Trigger *pTrigger; /* List of triggers on pTab, if required */
492 int tmask; /* Mask of trigger times */
drh798da522004-11-04 04:42:28 +0000493#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000494
drh17435752007-08-16 04:30:38 +0000495 db = pParse->db;
drh1bd10f82008-12-10 21:19:56 +0000496 memset(&dest, 0, sizeof(dest));
drh17435752007-08-16 04:30:38 +0000497 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000498 goto insert_cleanup;
499 }
drhdaffd0e2001-04-11 14:28:42 +0000500
drh75593d92014-01-10 20:46:55 +0000501 /* If the Select object is really just a simple VALUES() list with a
drha21f78b2015-04-19 18:32:43 +0000502 ** single row (the common case) then keep that one row of values
503 ** and discard the other (unused) parts of the pSelect object
drh75593d92014-01-10 20:46:55 +0000504 */
505 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
506 pList = pSelect->pEList;
507 pSelect->pEList = 0;
508 sqlite3SelectDelete(db, pSelect);
509 pSelect = 0;
510 }
511
drh1ccde152000-06-17 13:12:39 +0000512 /* Locate the table into which we will be inserting new information.
513 */
drh113088e2003-03-20 01:16:58 +0000514 assert( pTabList->nSrc==1 );
515 zTab = pTabList->a[0].zName;
drh098d1682009-05-02 15:46:46 +0000516 if( NEVER(zTab==0) ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000517 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000518 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000519 goto insert_cleanup;
520 }
danielk1977da184232006-01-05 11:34:32 +0000521 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
522 assert( iDb<db->nDb );
523 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000524 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000525 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000526 goto insert_cleanup;
527 }
drhec95c442013-10-23 01:57:32 +0000528 withoutRowid = !HasRowid(pTab);
danielk1977c3f9bad2002-05-15 08:30:12 +0000529
drhb7f91642004-10-31 02:22:47 +0000530 /* Figure out if we have any triggers and if the table being
531 ** inserted into is a view
532 */
533#ifndef SQLITE_OMIT_TRIGGER
danielk19772f886d12009-02-28 10:47:41 +0000534 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
drhb7f91642004-10-31 02:22:47 +0000535 isView = pTab->pSelect!=0;
536#else
danielk19772f886d12009-02-28 10:47:41 +0000537# define pTrigger 0
538# define tmask 0
drhb7f91642004-10-31 02:22:47 +0000539# define isView 0
540#endif
541#ifdef SQLITE_OMIT_VIEW
542# undef isView
543# define isView 0
544#endif
danielk19772f886d12009-02-28 10:47:41 +0000545 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
drhb7f91642004-10-31 02:22:47 +0000546
drhf573c992002-07-31 00:32:50 +0000547 /* If pTab is really a view, make sure it has been initialized.
drhd82b5022013-10-26 00:58:34 +0000548 ** ViewGetColumnNames() is a no-op if pTab is not a view.
drhf573c992002-07-31 00:32:50 +0000549 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000550 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000551 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000552 }
553
drhd82b5022013-10-26 00:58:34 +0000554 /* Cannot insert into a read-only table.
danielk1977595a5232009-07-24 17:58:53 +0000555 */
556 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
557 goto insert_cleanup;
558 }
559
drh1ccde152000-06-17 13:12:39 +0000560 /* Allocate a VDBE
561 */
danielk19774adee202004-05-08 08:23:19 +0000562 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000563 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000564 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk19772f886d12009-02-28 10:47:41 +0000565 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
drh1ccde152000-06-17 13:12:39 +0000566
drh9d9cf222007-02-13 15:01:11 +0000567#ifndef SQLITE_OMIT_XFER_OPT
568 /* If the statement is of the form
569 **
570 ** INSERT INTO <table1> SELECT * FROM <table2>;
571 **
572 ** Then special optimizations can be applied that make the transfer
573 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000574 **
575 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000576 */
danebbf08a2014-01-18 08:27:02 +0000577 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
danielk19772f886d12009-02-28 10:47:41 +0000578 assert( !pTrigger );
drh9d9cf222007-02-13 15:01:11 +0000579 assert( pList==0 );
drh0b9f50d2009-06-23 20:28:53 +0000580 goto insert_end;
drh9d9cf222007-02-13 15:01:11 +0000581 }
582#endif /* SQLITE_OMIT_XFER_OPT */
583
drh2958a4e2004-11-12 03:56:15 +0000584 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000585 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000586 */
drh6a288a32008-01-07 19:20:24 +0000587 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000588
drh05a86c52014-02-16 01:55:49 +0000589 /* Allocate registers for holding the rowid of the new row,
peter.d.reid60ec9142014-09-06 16:39:46 +0000590 ** the content of the new row, and the assembled row record.
drh05a86c52014-02-16 01:55:49 +0000591 */
592 regRowid = regIns = pParse->nMem+1;
593 pParse->nMem += pTab->nCol + 1;
594 if( IsVirtual(pTab) ){
595 regRowid++;
596 pParse->nMem++;
597 }
598 regData = regRowid+1;
599
600 /* If the INSERT statement included an IDLIST term, then make sure
601 ** all elements of the IDLIST really are columns of the table and
602 ** remember the column indices.
603 **
604 ** If the table has an INTEGER PRIMARY KEY column and that column
605 ** is named in the IDLIST, then record in the ipkColumn variable
606 ** the index into IDLIST of the primary key column. ipkColumn is
607 ** the index of the primary key as it appears in IDLIST, not as
608 ** is appears in the original table. (The index of the INTEGER
609 ** PRIMARY KEY in the original table is pTab->iPKey.)
610 */
drha21f78b2015-04-19 18:32:43 +0000611 bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
drh05a86c52014-02-16 01:55:49 +0000612 if( pColumn ){
613 for(i=0; i<pColumn->nId; i++){
614 pColumn->a[i].idx = -1;
615 }
616 for(i=0; i<pColumn->nId; i++){
617 for(j=0; j<pTab->nCol; j++){
618 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
619 pColumn->a[i].idx = j;
620 if( i!=j ) bIdListInOrder = 0;
621 if( j==pTab->iPKey ){
622 ipkColumn = i; assert( !withoutRowid );
623 }
624 break;
625 }
626 }
627 if( j>=pTab->nCol ){
628 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
629 ipkColumn = i;
drhe48ae712014-05-23 11:48:57 +0000630 bIdListInOrder = 0;
drh05a86c52014-02-16 01:55:49 +0000631 }else{
632 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
633 pTabList, 0, pColumn->a[i].zName);
634 pParse->checkSchema = 1;
635 goto insert_cleanup;
636 }
637 }
638 }
639 }
640
drh1ccde152000-06-17 13:12:39 +0000641 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000642 ** is coming from a SELECT statement, then generate a co-routine that
643 ** produces a single row of the SELECT on each invocation. The
644 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000645 */
drh5974a302000-06-07 14:42:26 +0000646 if( pSelect ){
drha21f78b2015-04-19 18:32:43 +0000647 /* Data is coming from a SELECT or from a multi-row VALUES clause.
648 ** Generate a co-routine to run the SELECT. */
drh05a86c52014-02-16 01:55:49 +0000649 int regYield; /* Register holding co-routine entry-point */
650 int addrTop; /* Top of the co-routine */
651 int rc; /* Result code */
drh1013c932008-01-06 00:25:21 +0000652
drh05a86c52014-02-16 01:55:49 +0000653 regYield = ++pParse->nMem;
654 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
655 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
656 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
657 dest.iSdst = bIdListInOrder ? regData : 0;
658 dest.nSdst = pTab->nCol;
659 rc = sqlite3Select(pParse, pSelect, &dest);
drh2b596da2012-07-23 21:43:19 +0000660 regFromSelect = dest.iSdst;
drh992590b2015-04-19 22:41:22 +0000661 if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
drh05a86c52014-02-16 01:55:49 +0000662 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
663 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
drh5974a302000-06-07 14:42:26 +0000664 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000665 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000666
667 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000668 ** should be written into a temporary table (template 4). Set to
drhd82b5022013-10-26 00:58:34 +0000669 ** FALSE if each output row of the SELECT can be written directly into
drhe00ee6e2008-06-20 15:24:01 +0000670 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000671 **
672 ** A temp table must be used if the table being updated is also one
673 ** of the tables being read by the SELECT statement. Also use a
674 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000675 */
drh05a86c52014-02-16 01:55:49 +0000676 if( pTrigger || readsTable(pParse, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000677 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000678 }
drh142e30d2002-08-28 03:00:58 +0000679
680 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000681 /* Invoke the coroutine to extract information from the SELECT
682 ** and add it to a transient table srcTab. The code generated
683 ** here is from the 4th template:
684 **
685 ** B: open temp table
drh81cf13e2014-02-07 18:27:53 +0000686 ** L: yield X, goto M at EOF
drhe00ee6e2008-06-20 15:24:01 +0000687 ** insert row from R..R+n into temp table
688 ** goto L
689 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000690 */
drhdc5ea5c2008-12-10 17:19:59 +0000691 int regRec; /* Register to hold packed record */
692 int regTempRowid; /* Register to hold temp table ROWID */
drh06280ee2014-02-20 19:32:38 +0000693 int addrL; /* Label "L" */
drhb7654112008-01-12 12:48:07 +0000694
drh142e30d2002-08-28 03:00:58 +0000695 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000696 regRec = sqlite3GetTempReg(pParse);
drhdc5ea5c2008-12-10 17:19:59 +0000697 regTempRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000698 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh06280ee2014-02-20 19:32:38 +0000699 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
drh1db639c2008-01-17 02:36:28 +0000700 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000701 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
702 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drh06280ee2014-02-20 19:32:38 +0000703 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
704 sqlite3VdbeJumpHere(v, addrL);
drhb7654112008-01-12 12:48:07 +0000705 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000706 sqlite3ReleaseTempReg(pParse, regTempRowid);
drh142e30d2002-08-28 03:00:58 +0000707 }
drh5974a302000-06-07 14:42:26 +0000708 }else{
drha21f78b2015-04-19 18:32:43 +0000709 /* This is the case if the data for the INSERT is coming from a
710 ** single-row VALUES clause
drh142e30d2002-08-28 03:00:58 +0000711 */
danielk1977b3bce662005-01-29 08:32:43 +0000712 NameContext sNC;
713 memset(&sNC, 0, sizeof(sNC));
714 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000715 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000716 assert( useTempTable==0 );
drhfea870b2015-08-24 20:54:06 +0000717 if( pList ){
718 nColumn = pList->nExpr;
719 if( sqlite3ResolveExprListNames(&sNC, pList) ){
drhb04a5d82002-04-12 03:55:15 +0000720 goto insert_cleanup;
721 }
drhfea870b2015-08-24 20:54:06 +0000722 }else{
723 nColumn = 0;
drhe64e7b22002-02-18 13:56:36 +0000724 }
drh5974a302000-06-07 14:42:26 +0000725 }
drh1ccde152000-06-17 13:12:39 +0000726
drh05a86c52014-02-16 01:55:49 +0000727 /* If there is no IDLIST term but the table has an integer primary
728 ** key, the set the ipkColumn variable to the integer primary key
729 ** column index in the original table definition.
730 */
731 if( pColumn==0 && nColumn>0 ){
732 ipkColumn = pTab->iPKey;
733 }
734
drh1ccde152000-06-17 13:12:39 +0000735 /* Make sure the number of columns in the source data matches the number
736 ** of columns to be inserted into the table.
737 */
danielk1977034ca142007-06-26 10:38:54 +0000738 if( IsVirtual(pTab) ){
739 for(i=0; i<pTab->nCol; i++){
740 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
741 }
742 }
743 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000744 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000745 "table %S has %d columns but %d values were supplied",
drhd51397a2009-05-01 15:17:48 +0000746 pTabList, 0, pTab->nCol-nHidden, nColumn);
drhcce7d172000-05-31 15:34:51 +0000747 goto insert_cleanup;
748 }
drh967e8b72000-06-21 13:59:10 +0000749 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000750 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000751 goto insert_cleanup;
752 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000753
drhfeeb1392002-04-09 03:28:01 +0000754 /* Initialize the count of rows to be inserted
755 */
drh142e30d2002-08-28 03:00:58 +0000756 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000757 regRowCount = ++pParse->nMem;
758 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000759 }
760
danielk1977e448dc42008-01-02 11:50:51 +0000761 /* If this is not a view, open the table and and all indices */
762 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000763 int nIdx;
drh6a534992013-11-16 20:13:39 +0000764 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
drh26198bb2013-10-31 11:15:09 +0000765 &iDataCur, &iIdxCur);
drh5c070532008-04-11 15:36:03 +0000766 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000767 if( aRegIdx==0 ){
768 goto insert_cleanup;
769 }
770 for(i=0; i<nIdx; i++){
771 aRegIdx[i] = ++pParse->nMem;
772 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000773 }
774
drhe00ee6e2008-06-20 15:24:01 +0000775 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000776 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000777 /* This block codes the top of loop only. The complete loop is the
778 ** following pseudocode (template 4):
779 **
drh81cf13e2014-02-07 18:27:53 +0000780 ** rewind temp table, if empty goto D
drhe00ee6e2008-06-20 15:24:01 +0000781 ** C: loop over rows of intermediate table
782 ** transfer values form intermediate table into <table>
783 ** end loop
784 ** D: ...
785 */
drh688852a2014-02-17 22:40:43 +0000786 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
drhe00ee6e2008-06-20 15:24:01 +0000787 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000788 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000789 /* This block codes the top of loop only. The complete loop is the
790 ** following pseudocode (template 3):
791 **
drh81cf13e2014-02-07 18:27:53 +0000792 ** C: yield X, at EOF goto D
drhe00ee6e2008-06-20 15:24:01 +0000793 ** insert the select result into <table> from R..R+n
794 ** goto C
795 ** D: ...
796 */
drh81cf13e2014-02-07 18:27:53 +0000797 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
drh688852a2014-02-17 22:40:43 +0000798 VdbeCoverage(v);
drh5974a302000-06-07 14:42:26 +0000799 }
drh1ccde152000-06-17 13:12:39 +0000800
drh5cf590c2003-04-24 01:45:04 +0000801 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000802 */
danielk19774adee202004-05-08 08:23:19 +0000803 endOfLoop = sqlite3VdbeMakeLabel(v);
danielk19772f886d12009-02-28 10:47:41 +0000804 if( tmask & TRIGGER_BEFORE ){
dan76d462e2009-08-30 11:42:51 +0000805 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000806
drh70ce3f02003-04-15 19:22:22 +0000807 /* build the NEW.* reference row. Note that if there is an INTEGER
808 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
809 ** translated into a unique ID for the row. But on a BEFORE trigger,
810 ** we do not know what the unique ID will be (because the insert has
811 ** not happened yet) so we substitute a rowid of -1
812 */
drhd82b5022013-10-26 00:58:34 +0000813 if( ipkColumn<0 ){
dan76d462e2009-08-30 11:42:51 +0000814 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh70ce3f02003-04-15 19:22:22 +0000815 }else{
drh6a288a32008-01-07 19:20:24 +0000816 int j1;
drhec95c442013-10-23 01:57:32 +0000817 assert( !withoutRowid );
drh7fe45902009-05-01 02:08:04 +0000818 if( useTempTable ){
drhd82b5022013-10-26 00:58:34 +0000819 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
drh7fe45902009-05-01 02:08:04 +0000820 }else{
821 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drhd82b5022013-10-26 00:58:34 +0000822 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
drh7fe45902009-05-01 02:08:04 +0000823 }
drh688852a2014-02-17 22:40:43 +0000824 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
dan76d462e2009-08-30 11:42:51 +0000825 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh6a288a32008-01-07 19:20:24 +0000826 sqlite3VdbeJumpHere(v, j1);
drh688852a2014-02-17 22:40:43 +0000827 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
drh70ce3f02003-04-15 19:22:22 +0000828 }
829
danielk1977034ca142007-06-26 10:38:54 +0000830 /* Cannot have triggers on a virtual table. If it were possible,
831 ** this block would have to account for hidden column.
832 */
dan165921a2009-08-28 18:53:45 +0000833 assert( !IsVirtual(pTab) );
danielk1977034ca142007-06-26 10:38:54 +0000834
drh70ce3f02003-04-15 19:22:22 +0000835 /* Create the new column data
836 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000837 for(i=0; i<pTab->nCol; i++){
838 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000839 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000840 }else{
drh9adf9ac2002-05-15 11:44:13 +0000841 for(j=0; j<pColumn->nId; j++){
842 if( pColumn->a[j].idx==i ) break;
843 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000844 }
dan7ba45972010-03-30 12:40:32 +0000845 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
dan76d462e2009-08-30 11:42:51 +0000846 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
drh142e30d2002-08-28 03:00:58 +0000847 }else if( useTempTable ){
dan76d462e2009-08-30 11:42:51 +0000848 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000849 }else{
drhd6fe9612005-01-14 01:22:00 +0000850 assert( pSelect==0 ); /* Otherwise useTempTable is true */
dan76d462e2009-08-30 11:42:51 +0000851 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000852 }
853 }
danielk1977a37cdde2004-05-16 11:15:36 +0000854
855 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
856 ** do not attempt any conversions before assembling the record.
857 ** If this is a real table, attempt conversions as required by the
858 ** table column affinities.
859 */
860 if( !isView ){
drh57bf4a82014-02-17 14:59:22 +0000861 sqlite3TableAffinity(v, pTab, regCols+1);
danielk1977a37cdde2004-05-16 11:15:36 +0000862 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000863
drh5cf590c2003-04-24 01:45:04 +0000864 /* Fire BEFORE or INSTEAD OF triggers */
dan165921a2009-08-28 18:53:45 +0000865 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
dan94d7f502009-09-24 09:05:49 +0000866 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
dan165921a2009-08-28 18:53:45 +0000867
dan76d462e2009-08-30 11:42:51 +0000868 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
drh70ce3f02003-04-15 19:22:22 +0000869 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000870
drhd82b5022013-10-26 00:58:34 +0000871 /* Compute the content of the next row to insert into a range of
872 ** registers beginning at regIns.
drh1ccde152000-06-17 13:12:39 +0000873 */
drh5cf590c2003-04-24 01:45:04 +0000874 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000875 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000876 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000877 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000878 }
drhd82b5022013-10-26 00:58:34 +0000879 if( ipkColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000880 if( useTempTable ){
drhd82b5022013-10-26 00:58:34 +0000881 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000882 }else if( pSelect ){
drh05a86c52014-02-16 01:55:49 +0000883 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000884 }else{
drhe4d90812007-03-29 05:51:49 +0000885 VdbeOp *pOp;
drhd82b5022013-10-26 00:58:34 +0000886 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
drh20411ea2009-05-29 19:00:12 +0000887 pOp = sqlite3VdbeGetOp(v, -1);
drh1b7ecbb2009-05-03 01:00:59 +0000888 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000889 appendFlag = 1;
890 pOp->opcode = OP_NewRowid;
drh26198bb2013-10-31 11:15:09 +0000891 pOp->p1 = iDataCur;
drh6a288a32008-01-07 19:20:24 +0000892 pOp->p2 = regRowid;
893 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000894 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000895 }
drhf0863fe2005-06-12 21:35:51 +0000896 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000897 ** to generate a unique primary key value.
898 */
drhe4d90812007-03-29 05:51:49 +0000899 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000900 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000901 if( !IsVirtual(pTab) ){
drh688852a2014-02-17 22:40:43 +0000902 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
drh26198bb2013-10-31 11:15:09 +0000903 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
danielk1977bb50e7a2008-07-04 10:56:07 +0000904 sqlite3VdbeJumpHere(v, j1);
905 }else{
906 j1 = sqlite3VdbeCurrentAddr(v);
drh688852a2014-02-17 22:40:43 +0000907 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
danielk1977bb50e7a2008-07-04 10:56:07 +0000908 }
drh688852a2014-02-17 22:40:43 +0000909 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
drhe4d90812007-03-29 05:51:49 +0000910 }
drhec95c442013-10-23 01:57:32 +0000911 }else if( IsVirtual(pTab) || withoutRowid ){
drh6a288a32008-01-07 19:20:24 +0000912 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000913 }else{
drh26198bb2013-10-31 11:15:09 +0000914 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000915 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000916 }
drh6a288a32008-01-07 19:20:24 +0000917 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000918
drhd82b5022013-10-26 00:58:34 +0000919 /* Compute data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000920 ** with the first column.
921 */
danielk1977034ca142007-06-26 10:38:54 +0000922 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000923 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000924 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000925 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000926 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
drhd82b5022013-10-26 00:58:34 +0000927 ** Whenever this column is read, the rowid will be substituted
928 ** in its place. Hence, fill this column with a NULL to avoid
drh05a86c52014-02-16 01:55:49 +0000929 ** taking up data space with information that will never be used.
930 ** As there may be shallow copies of this value, make it a soft-NULL */
931 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000932 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000933 }
934 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000935 if( IsHiddenColumn(&pTab->aCol[i]) ){
936 assert( IsVirtual(pTab) );
937 j = -1;
938 nHidden++;
939 }else{
940 j = i - nHidden;
941 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000942 }else{
drh9adf9ac2002-05-15 11:44:13 +0000943 for(j=0; j<pColumn->nId; j++){
944 if( pColumn->a[j].idx==i ) break;
945 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000946 }
danielk1977034ca142007-06-26 10:38:54 +0000947 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
drh05a86c52014-02-16 01:55:49 +0000948 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000949 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000950 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000951 }else if( pSelect ){
drh05a86c52014-02-16 01:55:49 +0000952 if( regFromSelect!=regData ){
953 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
954 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000955 }else{
danielk1977287fb612008-01-04 19:10:28 +0000956 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000957 }
drhbed86902000-06-02 13:27:59 +0000958 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000959
960 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000961 ** do the insertion.
962 */
drh4cbdda92006-06-14 19:00:20 +0000963#ifndef SQLITE_OMIT_VIRTUALTABLE
964 if( IsVirtual(pTab) ){
danielk1977595a5232009-07-24 17:58:53 +0000965 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
drh4f3dd152008-04-28 18:46:43 +0000966 sqlite3VtabMakeWritable(pParse, pTab);
danielk1977595a5232009-07-24 17:58:53 +0000967 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
danb061d052011-04-25 18:49:57 +0000968 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
dane0af83a2009-09-08 19:15:01 +0000969 sqlite3MayAbort(pParse);
drh4cbdda92006-06-14 19:00:20 +0000970 }else
971#endif
972 {
danielk1977de630352009-05-04 11:42:29 +0000973 int isReplace; /* Set to true if constraints may cause a replace */
drhf8ffb272013-11-01 17:08:56 +0000974 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
975 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
drh04adf412008-01-08 18:57:50 +0000976 );
dan8ff2d952013-09-05 18:40:29 +0000977 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
drh26198bb2013-10-31 11:15:09 +0000978 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
979 regIns, aRegIdx, 0, appendFlag, isReplace==0);
drh4cbdda92006-06-14 19:00:20 +0000980 }
drh5cf590c2003-04-24 01:45:04 +0000981 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000982
drh5cf590c2003-04-24 01:45:04 +0000983 /* Update the count of rows that are inserted
984 */
985 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000986 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000987 }
drh1ccde152000-06-17 13:12:39 +0000988
danielk19772f886d12009-02-28 10:47:41 +0000989 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000990 /* Code AFTER triggers */
dan165921a2009-08-28 18:53:45 +0000991 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
dan94d7f502009-09-24 09:05:49 +0000992 pTab, regData-2-pTab->nCol, onError, endOfLoop);
drh1bee3d72001-10-15 00:44:35 +0000993 }
994
drhe00ee6e2008-06-20 15:24:01 +0000995 /* The bottom of the main insertion loop, if the data source
996 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:12 +0000997 */
danielk19774adee202004-05-08 08:23:19 +0000998 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000999 if( useTempTable ){
drh688852a2014-02-17 22:40:43 +00001000 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
drhe00ee6e2008-06-20 15:24:01 +00001001 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:36 +00001002 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:58 +00001003 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +00001004 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1005 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:26 +00001006 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001007
danielk1977e448dc42008-01-02 11:50:51 +00001008 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +00001009 /* Close all tables opened */
drh26198bb2013-10-31 11:15:09 +00001010 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
1011 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
1012 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
danielk1977c3f9bad2002-05-15 08:30:12 +00001013 }
drhcce7d172000-05-31 15:34:51 +00001014 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001015
drh0b9f50d2009-06-23 20:28:53 +00001016insert_end:
drhf3388142004-11-13 03:48:06 +00001017 /* Update the sqlite_sequence table by storing the content of the
drh0b9f50d2009-06-23 20:28:53 +00001018 ** maximum rowid counter values recorded while inserting into
1019 ** autoincrement tables.
drh2958a4e2004-11-12 03:56:15 +00001020 */
dan165921a2009-08-28 18:53:45 +00001021 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
drh0b9f50d2009-06-23 20:28:53 +00001022 sqlite3AutoincrementEnd(pParse);
1023 }
drh2958a4e2004-11-12 03:56:15 +00001024
drh1bee3d72001-10-15 00:44:35 +00001025 /*
danielk1977e7de6f22004-11-05 06:02:06 +00001026 ** Return the number of rows inserted. If this routine is
1027 ** generating code because of a call to sqlite3NestedParse(), do not
1028 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +00001029 */
dan165921a2009-08-28 18:53:45 +00001030 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
drh6a288a32008-01-07 19:20:24 +00001031 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +00001032 sqlite3VdbeSetNumCols(v, 1);
danielk197710fb7492008-10-31 10:53:22 +00001033 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
drh1bee3d72001-10-15 00:44:35 +00001034 }
drhcce7d172000-05-31 15:34:51 +00001035
1036insert_cleanup:
drh633e6d52008-07-28 19:34:53 +00001037 sqlite3SrcListDelete(db, pTabList);
1038 sqlite3ExprListDelete(db, pList);
1039 sqlite3SelectDelete(db, pSelect);
1040 sqlite3IdListDelete(db, pColumn);
1041 sqlite3DbFree(db, aRegIdx);
drhcce7d172000-05-31 15:34:51 +00001042}
drh9cfcf5d2002-01-29 18:41:24 +00001043
dan75cbd982009-09-21 16:06:03 +00001044/* Make sure "isView" and other macros defined above are undefined. Otherwise
peter.d.reid60ec9142014-09-06 16:39:46 +00001045** they may interfere with compilation of other functions in this file
dan75cbd982009-09-21 16:06:03 +00001046** (or in another file, if this file becomes part of the amalgamation). */
1047#ifdef isView
1048 #undef isView
1049#endif
1050#ifdef pTrigger
1051 #undef pTrigger
1052#endif
1053#ifdef tmask
1054 #undef tmask
1055#endif
1056
drh11e85272013-10-26 15:40:48 +00001057/*
drh6934fc72013-10-31 15:37:49 +00001058** Generate code to do constraint checks prior to an INSERT or an UPDATE
1059** on table pTab.
drh9cfcf5d2002-01-29 18:41:24 +00001060**
drh6934fc72013-10-31 15:37:49 +00001061** The regNewData parameter is the first register in a range that contains
1062** the data to be inserted or the data after the update. There will be
1063** pTab->nCol+1 registers in this range. The first register (the one
1064** that regNewData points to) will contain the new rowid, or NULL in the
1065** case of a WITHOUT ROWID table. The second register in the range will
1066** contain the content of the first table column. The third register will
1067** contain the content of the second table column. And so forth.
drh0ca3e242002-01-29 23:07:02 +00001068**
drhf8ffb272013-11-01 17:08:56 +00001069** The regOldData parameter is similar to regNewData except that it contains
1070** the data prior to an UPDATE rather than afterwards. regOldData is zero
1071** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1072** checking regOldData for zero.
drh0ca3e242002-01-29 23:07:02 +00001073**
drhf8ffb272013-11-01 17:08:56 +00001074** For an UPDATE, the pkChng boolean is true if the true primary key (the
1075** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1076** might be modified by the UPDATE. If pkChng is false, then the key of
1077** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1078**
1079** For an INSERT, the pkChng boolean indicates whether or not the rowid
1080** was explicitly specified as part of the INSERT statement. If pkChng
1081** is zero, it means that the either rowid is computed automatically or
1082** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1083** pkChng will only be true if the INSERT statement provides an integer
1084** value for either the rowid column or its INTEGER PRIMARY KEY alias.
drh0ca3e242002-01-29 23:07:02 +00001085**
drh6934fc72013-10-31 15:37:49 +00001086** The code generated by this routine will store new index entries into
drhaa9b8962008-01-08 02:57:55 +00001087** registers identified by aRegIdx[]. No index entry is created for
1088** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1089** the same as the order of indices on the linked list of indices
drh6934fc72013-10-31 15:37:49 +00001090** at pTab->pIndex.
1091**
1092** The caller must have already opened writeable cursors on the main
1093** table and all applicable indices (that is to say, all indices for which
1094** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1095** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1096** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1097** for the first index in the pTab->pIndex list. Cursors for other indices
1098** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
drh9cfcf5d2002-01-29 18:41:24 +00001099**
1100** This routine also generates code to check constraints. NOT NULL,
1101** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +00001102** then the appropriate action is performed. There are five possible
1103** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +00001104**
1105** Constraint type Action What Happens
1106** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +00001107** any ROLLBACK The current transaction is rolled back and
drh6934fc72013-10-31 15:37:49 +00001108** sqlite3_step() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +00001109** return code of SQLITE_CONSTRAINT.
1110**
drh1c928532002-01-31 15:54:21 +00001111** any ABORT Back out changes from the current command
1112** only (do not do a complete rollback) then
drh6934fc72013-10-31 15:37:49 +00001113** cause sqlite3_step() to return immediately
drh1c928532002-01-31 15:54:21 +00001114** with SQLITE_CONSTRAINT.
1115**
drh6934fc72013-10-31 15:37:49 +00001116** any FAIL Sqlite3_step() returns immediately with a
drh1c928532002-01-31 15:54:21 +00001117** return code of SQLITE_CONSTRAINT. The
1118** transaction is not rolled back and any
drh6934fc72013-10-31 15:37:49 +00001119** changes to prior rows are retained.
drh1c928532002-01-31 15:54:21 +00001120**
drh6934fc72013-10-31 15:37:49 +00001121** any IGNORE The attempt in insert or update the current
1122** row is skipped, without throwing an error.
1123** Processing continues with the next row.
1124** (There is an immediate jump to ignoreDest.)
drh9cfcf5d2002-01-29 18:41:24 +00001125**
1126** NOT NULL REPLACE The NULL value is replace by the default
1127** value for that column. If the default value
1128** is NULL, the action is the same as ABORT.
1129**
1130** UNIQUE REPLACE The other row that conflicts with the row
1131** being inserted is removed.
1132**
1133** CHECK REPLACE Illegal. The results in an exception.
1134**
drh1c928532002-01-31 15:54:21 +00001135** Which action to take is determined by the overrideError parameter.
1136** Or if overrideError==OE_Default, then the pParse->onError parameter
1137** is used. Or if pParse->onError==OE_Default then the onError value
1138** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001139*/
danielk19774adee202004-05-08 08:23:19 +00001140void sqlite3GenerateConstraintChecks(
drh6934fc72013-10-31 15:37:49 +00001141 Parse *pParse, /* The parser context */
1142 Table *pTab, /* The table being inserted or updated */
drhf8ffb272013-11-01 17:08:56 +00001143 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
drh6934fc72013-10-31 15:37:49 +00001144 int iDataCur, /* Canonical data cursor (main table or PK index) */
1145 int iIdxCur, /* First index cursor */
1146 int regNewData, /* First register in a range holding values to insert */
drhf8ffb272013-11-01 17:08:56 +00001147 int regOldData, /* Previous content. 0 for INSERTs */
1148 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1149 u8 overrideError, /* Override onError to this if not OE_Default */
drh6934fc72013-10-31 15:37:49 +00001150 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1151 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
drh9cfcf5d2002-01-29 18:41:24 +00001152){
drh6934fc72013-10-31 15:37:49 +00001153 Vdbe *v; /* VDBE under constrution */
drh1b7ecbb2009-05-03 01:00:59 +00001154 Index *pIdx; /* Pointer to one of the indices */
drh11e85272013-10-26 15:40:48 +00001155 Index *pPk = 0; /* The PRIMARY KEY index */
drh2938f922012-03-07 19:13:29 +00001156 sqlite3 *db; /* Database connection */
drhf8ffb272013-11-01 17:08:56 +00001157 int i; /* loop counter */
1158 int ix; /* Index loop counter */
1159 int nCol; /* Number of columns */
1160 int onError; /* Conflict resolution strategy */
peter.d.reid60ec9142014-09-06 16:39:46 +00001161 int j1; /* Address of jump instruction */
drh1b7ecbb2009-05-03 01:00:59 +00001162 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
drh6fbe41a2013-10-30 20:22:55 +00001163 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
drh8d1b82e2013-11-05 19:41:32 +00001164 int ipkTop = 0; /* Top of the rowid change constraint check */
1165 int ipkBottom = 0; /* Bottom of the rowid change constraint check */
1166 u8 isUpdate; /* True if this is an UPDATE operation */
drh57bf4a82014-02-17 14:59:22 +00001167 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
drh5426d802014-01-03 16:03:43 +00001168 int regRowid = -1; /* Register holding ROWID value */
drh9cfcf5d2002-01-29 18:41:24 +00001169
drhf8ffb272013-11-01 17:08:56 +00001170 isUpdate = regOldData!=0;
drh2938f922012-03-07 19:13:29 +00001171 db = pParse->db;
danielk19774adee202004-05-08 08:23:19 +00001172 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001173 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001174 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001175 nCol = pTab->nCol;
drh6934fc72013-10-31 15:37:49 +00001176
1177 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1178 ** normal rowid tables. nPkField is the number of key fields in the
1179 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1180 ** number of fields in the true primary key of the table. */
drh26198bb2013-10-31 11:15:09 +00001181 if( HasRowid(pTab) ){
1182 pPk = 0;
1183 nPkField = 1;
1184 }else{
1185 pPk = sqlite3PrimaryKeyIndex(pTab);
1186 nPkField = pPk->nKeyCol;
1187 }
drh6fbe41a2013-10-30 20:22:55 +00001188
1189 /* Record that this module has started */
1190 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
drh6934fc72013-10-31 15:37:49 +00001191 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
drh11e85272013-10-26 15:40:48 +00001192
drh9cfcf5d2002-01-29 18:41:24 +00001193 /* Test all NOT NULL constraints.
1194 */
1195 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001196 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001197 continue;
1198 }
drh9cfcf5d2002-01-29 18:41:24 +00001199 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001200 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001201 if( overrideError!=OE_Default ){
1202 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001203 }else if( onError==OE_Default ){
1204 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001205 }
danielk19777977a172004-11-09 12:44:37 +00001206 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001207 onError = OE_Abort;
1208 }
danielk1977b84f96f2005-01-20 11:32:23 +00001209 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1210 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001211 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001212 case OE_Abort:
dane0af83a2009-09-08 19:15:01 +00001213 sqlite3MayAbort(pParse);
drh0978d4f2013-10-29 16:14:35 +00001214 /* Fall through */
dane0af83a2009-09-08 19:15:01 +00001215 case OE_Rollback:
drh1c928532002-01-31 15:54:21 +00001216 case OE_Fail: {
drhf9c8ce32013-11-05 13:33:55 +00001217 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1218 pTab->aCol[i].zName);
1219 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1220 regNewData+1+i, zMsg, P4_DYNAMIC);
1221 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
drh688852a2014-02-17 22:40:43 +00001222 VdbeCoverage(v);
drh9cfcf5d2002-01-29 18:41:24 +00001223 break;
1224 }
1225 case OE_Ignore: {
drh6934fc72013-10-31 15:37:49 +00001226 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
drh688852a2014-02-17 22:40:43 +00001227 VdbeCoverage(v);
drh9cfcf5d2002-01-29 18:41:24 +00001228 break;
1229 }
drh098d1682009-05-02 15:46:46 +00001230 default: {
1231 assert( onError==OE_Replace );
drh688852a2014-02-17 22:40:43 +00001232 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
drh6934fc72013-10-31 15:37:49 +00001233 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
drh5053a792009-02-20 03:02:23 +00001234 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001235 break;
1236 }
drh9cfcf5d2002-01-29 18:41:24 +00001237 }
1238 }
1239
1240 /* Test all CHECK constraints
1241 */
drhffe07b22005-11-03 00:41:17 +00001242#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +00001243 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1244 ExprList *pCheck = pTab->pCheck;
drh6934fc72013-10-31 15:37:49 +00001245 pParse->ckBase = regNewData+1;
drhaa01c7e2006-03-15 16:26:10 +00001246 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2938f922012-03-07 19:13:29 +00001247 for(i=0; i<pCheck->nExpr; i++){
1248 int allOk = sqlite3VdbeMakeLabel(v);
drh2d8e9202012-12-08 04:10:44 +00001249 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
1250 if( onError==OE_Ignore ){
1251 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1252 }else{
drhf9c8ce32013-11-05 13:33:55 +00001253 char *zName = pCheck->a[i].zName;
1254 if( zName==0 ) zName = pTab->zName;
drh2d8e9202012-12-08 04:10:44 +00001255 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
drhd91c1a12013-02-09 13:58:25 +00001256 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
drhf9c8ce32013-11-05 13:33:55 +00001257 onError, zName, P4_TRANSIENT,
1258 P5_ConstraintCheck);
drh2938f922012-03-07 19:13:29 +00001259 }
drh2d8e9202012-12-08 04:10:44 +00001260 sqlite3VdbeResolveLabel(v, allOk);
drhaa01c7e2006-03-15 16:26:10 +00001261 }
drhffe07b22005-11-03 00:41:17 +00001262 }
1263#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001264
drhf8ffb272013-11-01 17:08:56 +00001265 /* If rowid is changing, make sure the new rowid does not previously
1266 ** exist in the table.
drh9cfcf5d2002-01-29 18:41:24 +00001267 */
drh6fbe41a2013-10-30 20:22:55 +00001268 if( pkChng && pPk==0 ){
drh11e85272013-10-26 15:40:48 +00001269 int addrRowidOk = sqlite3VdbeMakeLabel(v);
1270
drhf8ffb272013-11-01 17:08:56 +00001271 /* Figure out what action to take in case of a rowid collision */
drh0ca3e242002-01-29 23:07:02 +00001272 onError = pTab->keyConf;
1273 if( overrideError!=OE_Default ){
1274 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001275 }else if( onError==OE_Default ){
1276 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001277 }
drh11e85272013-10-26 15:40:48 +00001278
dane1e2ae22009-09-24 16:52:28 +00001279 if( isUpdate ){
drhf8ffb272013-11-01 17:08:56 +00001280 /* pkChng!=0 does not mean that the rowid has change, only that
1281 ** it might have changed. Skip the conflict logic below if the rowid
1282 ** is unchanged. */
drh6934fc72013-10-31 15:37:49 +00001283 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
drh3d77dee2014-02-19 14:20:49 +00001284 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
drh688852a2014-02-17 22:40:43 +00001285 VdbeCoverage(v);
dane1e2ae22009-09-24 16:52:28 +00001286 }
drhf8ffb272013-11-01 17:08:56 +00001287
drh8d1b82e2013-11-05 19:41:32 +00001288 /* If the response to a rowid conflict is REPLACE but the response
1289 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
1290 ** to defer the running of the rowid conflict checking until after
1291 ** the UNIQUE constraints have run.
1292 */
1293 if( onError==OE_Replace && overrideError!=OE_Replace ){
1294 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1295 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
1296 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
1297 break;
1298 }
1299 }
1300 }
1301
drhf8ffb272013-11-01 17:08:56 +00001302 /* Check to see if the new rowid already exists in the table. Skip
1303 ** the following conflict logic if it does not. */
drh6934fc72013-10-31 15:37:49 +00001304 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
drh688852a2014-02-17 22:40:43 +00001305 VdbeCoverage(v);
drhf8ffb272013-11-01 17:08:56 +00001306
1307 /* Generate code that deals with a rowid collision */
dane1e2ae22009-09-24 16:52:28 +00001308 switch( onError ){
1309 default: {
1310 onError = OE_Abort;
1311 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001312 }
dane1e2ae22009-09-24 16:52:28 +00001313 case OE_Rollback:
1314 case OE_Abort:
1315 case OE_Fail: {
drhf9c8ce32013-11-05 13:33:55 +00001316 sqlite3RowidConstraint(pParse, onError, pTab);
dane1e2ae22009-09-24 16:52:28 +00001317 break;
drh0ca3e242002-01-29 23:07:02 +00001318 }
dane1e2ae22009-09-24 16:52:28 +00001319 case OE_Replace: {
1320 /* If there are DELETE triggers on this table and the
1321 ** recursive-triggers flag is set, call GenerateRowDelete() to
mistachkind5578432012-08-25 10:01:29 +00001322 ** remove the conflicting row from the table. This will fire
dane1e2ae22009-09-24 16:52:28 +00001323 ** the triggers and remove both the table and index b-tree entries.
1324 **
1325 ** Otherwise, if there are no triggers or the recursive-triggers
danda730f62010-02-18 08:19:19 +00001326 ** flag is not set, but the table has one or more indexes, call
1327 ** GenerateRowIndexDelete(). This removes the index b-tree entries
1328 ** only. The table b-tree entry will be replaced by the new entry
1329 ** when it is inserted.
1330 **
1331 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1332 ** also invoke MultiWrite() to indicate that this VDBE may require
1333 ** statement rollback (if the statement is aborted after the delete
1334 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1335 ** but being more selective here allows statements like:
1336 **
1337 ** REPLACE INTO t(rowid) VALUES($newrowid)
1338 **
1339 ** to run without a statement journal if there are no indexes on the
1340 ** table.
1341 */
dane1e2ae22009-09-24 16:52:28 +00001342 Trigger *pTrigger = 0;
drh2938f922012-03-07 19:13:29 +00001343 if( db->flags&SQLITE_RecTriggers ){
dane1e2ae22009-09-24 16:52:28 +00001344 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1345 }
dane7a94d82009-10-01 16:09:04 +00001346 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
danda730f62010-02-18 08:19:19 +00001347 sqlite3MultiWrite(pParse);
drh26198bb2013-10-31 11:15:09 +00001348 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
drh392ee212013-11-08 16:54:56 +00001349 regNewData, 1, 0, OE_Replace, 1);
danda730f62010-02-18 08:19:19 +00001350 }else if( pTab->pIndex ){
1351 sqlite3MultiWrite(pParse);
drh26198bb2013-10-31 11:15:09 +00001352 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
dane1e2ae22009-09-24 16:52:28 +00001353 }
1354 seenReplace = 1;
1355 break;
drh5383ae52003-06-04 12:23:30 +00001356 }
dane1e2ae22009-09-24 16:52:28 +00001357 case OE_Ignore: {
drh8d1b82e2013-11-05 19:41:32 +00001358 /*assert( seenReplace==0 );*/
dane1e2ae22009-09-24 16:52:28 +00001359 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1360 break;
1361 }
1362 }
drh11e85272013-10-26 15:40:48 +00001363 sqlite3VdbeResolveLabel(v, addrRowidOk);
drh8d1b82e2013-11-05 19:41:32 +00001364 if( ipkTop ){
1365 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
1366 sqlite3VdbeJumpHere(v, ipkTop);
1367 }
drh0ca3e242002-01-29 23:07:02 +00001368 }
drh0bd1f4e2002-06-06 18:54:39 +00001369
1370 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1371 ** index and making sure that duplicate entries do not already exist.
drh11e85272013-10-26 15:40:48 +00001372 ** Compute the revised record entries for indices as we go.
drhf8ffb272013-11-01 17:08:56 +00001373 **
1374 ** This loop also handles the case of the PRIMARY KEY index for a
1375 ** WITHOUT ROWID table.
drh0bd1f4e2002-06-06 18:54:39 +00001376 */
drh26198bb2013-10-31 11:15:09 +00001377 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
drh6934fc72013-10-31 15:37:49 +00001378 int regIdx; /* Range of registers hold conent for pIdx */
1379 int regR; /* Range of registers holding conflicting PK */
1380 int iThisCur; /* Cursor for this UNIQUE index */
1381 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
drh2184fc72011-04-09 03:04:13 +00001382
drh26198bb2013-10-31 11:15:09 +00001383 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
drh57bf4a82014-02-17 14:59:22 +00001384 if( bAffinityDone==0 ){
1385 sqlite3TableAffinity(v, pTab, regNewData+1);
1386 bAffinityDone = 1;
1387 }
drh6934fc72013-10-31 15:37:49 +00001388 iThisCur = iIdxCur+ix;
1389 addrUniqueOk = sqlite3VdbeMakeLabel(v);
drhb2fe7d82003-04-20 17:29:23 +00001390
drhf8ffb272013-11-01 17:08:56 +00001391 /* Skip partial indices for which the WHERE clause is not true */
drhb2b9d3d2013-08-01 01:14:43 +00001392 if( pIdx->pPartIdxWhere ){
drh26198bb2013-10-31 11:15:09 +00001393 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
drh6934fc72013-10-31 15:37:49 +00001394 pParse->ckBase = regNewData+1;
drh72bc8202015-06-11 13:58:35 +00001395 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1396 SQLITE_JUMPIFNULL);
drhb2b9d3d2013-08-01 01:14:43 +00001397 pParse->ckBase = 0;
1398 }
1399
drh6934fc72013-10-31 15:37:49 +00001400 /* Create a record for this index entry as it should appear after
drhf8ffb272013-11-01 17:08:56 +00001401 ** the insert or update. Store that record in the aRegIdx[ix] register
1402 */
drh11e85272013-10-26 15:40:48 +00001403 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
drh9cfcf5d2002-01-29 18:41:24 +00001404 for(i=0; i<pIdx->nColumn; i++){
drh6934fc72013-10-31 15:37:49 +00001405 int iField = pIdx->aiColumn[i];
drhf82b9af2013-11-01 14:03:20 +00001406 int x;
drh26198bb2013-10-31 11:15:09 +00001407 if( iField<0 || iField==pTab->iPKey ){
drh5426d802014-01-03 16:03:43 +00001408 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
drhf82b9af2013-11-01 14:03:20 +00001409 x = regNewData;
drh5426d802014-01-03 16:03:43 +00001410 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
drh9cfcf5d2002-01-29 18:41:24 +00001411 }else{
drhf82b9af2013-11-01 14:03:20 +00001412 x = iField + regNewData + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001413 }
drhf82b9af2013-11-01 14:03:20 +00001414 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
1415 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
drh9cfcf5d2002-01-29 18:41:24 +00001416 }
drh26198bb2013-10-31 11:15:09 +00001417 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
drh26198bb2013-10-31 11:15:09 +00001418 VdbeComment((v, "for %s", pIdx->zName));
drhbbbdc832013-10-22 18:01:40 +00001419 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
drhb2fe7d82003-04-20 17:29:23 +00001420
drhf8ffb272013-11-01 17:08:56 +00001421 /* In an UPDATE operation, if this index is the PRIMARY KEY index
1422 ** of a WITHOUT ROWID table and there has been no change the
1423 ** primary key, then no collision is possible. The collision detection
1424 ** logic below can all be skipped. */
drh00012df2013-11-05 01:59:07 +00001425 if( isUpdate && pPk==pIdx && pkChng==0 ){
drhda475b82013-11-04 21:44:54 +00001426 sqlite3VdbeResolveLabel(v, addrUniqueOk);
1427 continue;
1428 }
drhf8ffb272013-11-01 17:08:56 +00001429
drh6934fc72013-10-31 15:37:49 +00001430 /* Find out what action to take in case there is a uniqueness conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001431 onError = pIdx->onError;
danielk1977de630352009-05-04 11:42:29 +00001432 if( onError==OE_None ){
drh26198bb2013-10-31 11:15:09 +00001433 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
drh11e85272013-10-26 15:40:48 +00001434 sqlite3VdbeResolveLabel(v, addrUniqueOk);
danielk1977de630352009-05-04 11:42:29 +00001435 continue; /* pIdx is not a UNIQUE index */
1436 }
drh9cfcf5d2002-01-29 18:41:24 +00001437 if( overrideError!=OE_Default ){
1438 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001439 }else if( onError==OE_Default ){
1440 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001441 }
drh5383ae52003-06-04 12:23:30 +00001442
drhb2fe7d82003-04-20 17:29:23 +00001443 /* Check to see if the new index entry will be unique */
drh26198bb2013-10-31 11:15:09 +00001444 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
drh688852a2014-02-17 22:40:43 +00001445 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
drhf8ffb272013-11-01 17:08:56 +00001446
1447 /* Generate code to handle collisions */
drh392ee212013-11-08 16:54:56 +00001448 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
drh46d03fc2013-12-19 02:23:45 +00001449 if( isUpdate || onError==OE_Replace ){
1450 if( HasRowid(pTab) ){
1451 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
1452 /* Conflict only if the rowid of the existing index entry
1453 ** is different from old-rowid */
1454 if( isUpdate ){
1455 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
drh3d77dee2014-02-19 14:20:49 +00001456 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
drh688852a2014-02-17 22:40:43 +00001457 VdbeCoverage(v);
drhda475b82013-11-04 21:44:54 +00001458 }
drh46d03fc2013-12-19 02:23:45 +00001459 }else{
1460 int x;
1461 /* Extract the PRIMARY KEY from the end of the index entry and
1462 ** store it in registers regR..regR+nPk-1 */
drha021f122013-12-19 14:34:34 +00001463 if( pIdx!=pPk ){
drh46d03fc2013-12-19 02:23:45 +00001464 for(i=0; i<pPk->nKeyCol; i++){
1465 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
1466 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
1467 VdbeComment((v, "%s.%s", pTab->zName,
1468 pTab->aCol[pPk->aiColumn[i]].zName));
drhda475b82013-11-04 21:44:54 +00001469 }
drh46d03fc2013-12-19 02:23:45 +00001470 }
1471 if( isUpdate ){
1472 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1473 ** table, only conflict if the new PRIMARY KEY values are actually
1474 ** different from the old.
1475 **
1476 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1477 ** of the matched index row are different from the original PRIMARY
1478 ** KEY values of this row before the update. */
1479 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1480 int op = OP_Ne;
drh48dd1d82014-05-27 18:18:58 +00001481 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
drh46d03fc2013-12-19 02:23:45 +00001482
1483 for(i=0; i<pPk->nKeyCol; i++){
1484 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1485 x = pPk->aiColumn[i];
1486 if( i==(pPk->nKeyCol-1) ){
1487 addrJump = addrUniqueOk;
1488 op = OP_Eq;
1489 }
1490 sqlite3VdbeAddOp4(v, op,
1491 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
drh3d77dee2014-02-19 14:20:49 +00001492 );
1493 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1494 VdbeCoverageIf(v, op==OP_Eq);
1495 VdbeCoverageIf(v, op==OP_Ne);
drh46d03fc2013-12-19 02:23:45 +00001496 }
drh26198bb2013-10-31 11:15:09 +00001497 }
drh26198bb2013-10-31 11:15:09 +00001498 }
drh11e85272013-10-26 15:40:48 +00001499 }
drhb2fe7d82003-04-20 17:29:23 +00001500
1501 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001502 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1503 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001504 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001505 case OE_Rollback:
1506 case OE_Abort:
1507 case OE_Fail: {
drhf9c8ce32013-11-05 13:33:55 +00001508 sqlite3UniqueConstraint(pParse, onError, pIdx);
drh9cfcf5d2002-01-29 18:41:24 +00001509 break;
1510 }
1511 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001512 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001513 break;
1514 }
drh098d1682009-05-02 15:46:46 +00001515 default: {
dan2283d462009-09-08 15:55:15 +00001516 Trigger *pTrigger = 0;
drh098d1682009-05-02 15:46:46 +00001517 assert( onError==OE_Replace );
dan1bea5592009-09-24 11:31:21 +00001518 sqlite3MultiWrite(pParse);
drh2938f922012-03-07 19:13:29 +00001519 if( db->flags&SQLITE_RecTriggers ){
dan2283d462009-09-08 15:55:15 +00001520 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1521 }
drh26198bb2013-10-31 11:15:09 +00001522 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
drh392ee212013-11-08 16:54:56 +00001523 regR, nPkField, 0, OE_Replace, pIdx==pPk);
drh0ca3e242002-01-29 23:07:02 +00001524 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001525 break;
1526 }
drh9cfcf5d2002-01-29 18:41:24 +00001527 }
drh11e85272013-10-26 15:40:48 +00001528 sqlite3VdbeResolveLabel(v, addrUniqueOk);
drh392ee212013-11-08 16:54:56 +00001529 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
1530 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
drh9cfcf5d2002-01-29 18:41:24 +00001531 }
drh8d1b82e2013-11-05 19:41:32 +00001532 if( ipkTop ){
1533 sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
1534 sqlite3VdbeJumpHere(v, ipkBottom);
1535 }
dan1da40a32009-09-19 17:00:31 +00001536
drh4308e342013-11-11 16:55:52 +00001537 *pbMayReplace = seenReplace;
drhce60aa42013-11-08 01:09:15 +00001538 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
drh9cfcf5d2002-01-29 18:41:24 +00001539}
drh0ca3e242002-01-29 23:07:02 +00001540
1541/*
1542** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001543** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh6934fc72013-10-31 15:37:49 +00001544** A consecutive range of registers starting at regNewData contains the
drh04adf412008-01-08 18:57:50 +00001545** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001546**
drhb419a922002-01-30 16:17:23 +00001547** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001548** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001549*/
danielk19774adee202004-05-08 08:23:19 +00001550void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001551 Parse *pParse, /* The parser context */
1552 Table *pTab, /* the table into which we are inserting */
drh26198bb2013-10-31 11:15:09 +00001553 int iDataCur, /* Cursor of the canonical data source */
1554 int iIdxCur, /* First index cursor */
drh6934fc72013-10-31 15:37:49 +00001555 int regNewData, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001556 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh70ce3f02003-04-15 19:22:22 +00001557 int isUpdate, /* True for UPDATE, False for INSERT */
danielk1977de630352009-05-04 11:42:29 +00001558 int appendBias, /* True if this is likely to be an append */
1559 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
drh0ca3e242002-01-29 23:07:02 +00001560){
drh6934fc72013-10-31 15:37:49 +00001561 Vdbe *v; /* Prepared statements under construction */
1562 Index *pIdx; /* An index being inserted or updated */
1563 u8 pik_flags; /* flag values passed to the btree insert */
1564 int regData; /* Content registers (after the rowid) */
peter.d.reid60ec9142014-09-06 16:39:46 +00001565 int regRec; /* Register holding assembled record for the table */
drh6934fc72013-10-31 15:37:49 +00001566 int i; /* Loop counter */
drh57bf4a82014-02-17 14:59:22 +00001567 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
drh0ca3e242002-01-29 23:07:02 +00001568
danielk19774adee202004-05-08 08:23:19 +00001569 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001570 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001571 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drhb2b9d3d2013-08-01 01:14:43 +00001572 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
drhaa9b8962008-01-08 02:57:55 +00001573 if( aRegIdx[i]==0 ) continue;
drh57bf4a82014-02-17 14:59:22 +00001574 bAffinityDone = 1;
drhb2b9d3d2013-08-01 01:14:43 +00001575 if( pIdx->pPartIdxWhere ){
1576 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00001577 VdbeCoverage(v);
drhb2b9d3d2013-08-01 01:14:43 +00001578 }
drh26198bb2013-10-31 11:15:09 +00001579 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
drh6546af12013-11-04 15:23:25 +00001580 pik_flags = 0;
1581 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
drh48dd1d82014-05-27 18:18:58 +00001582 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
drh4308e342013-11-11 16:55:52 +00001583 assert( pParse->nested==0 );
drh6546af12013-11-04 15:23:25 +00001584 pik_flags |= OPFLAG_NCHANGE;
danielk1977de630352009-05-04 11:42:29 +00001585 }
drh6546af12013-11-04 15:23:25 +00001586 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001587 }
drhec95c442013-10-23 01:57:32 +00001588 if( !HasRowid(pTab) ) return;
drh6934fc72013-10-31 15:37:49 +00001589 regData = regNewData + 1;
drhb7654112008-01-12 12:48:07 +00001590 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001591 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
drh57bf4a82014-02-17 14:59:22 +00001592 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
drhda250ea2008-04-01 05:07:14 +00001593 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
drh4794f732004-11-05 17:17:50 +00001594 if( pParse->nested ){
1595 pik_flags = 0;
1596 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001597 pik_flags = OPFLAG_NCHANGE;
1598 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001599 }
drhe4d90812007-03-29 05:51:49 +00001600 if( appendBias ){
1601 pik_flags |= OPFLAG_APPEND;
1602 }
danielk1977de630352009-05-04 11:42:29 +00001603 if( useSeekResult ){
1604 pik_flags |= OPFLAG_USESEEKRESULT;
1605 }
drh6934fc72013-10-31 15:37:49 +00001606 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
danielk197794eb6a12005-12-15 15:22:08 +00001607 if( !pParse->nested ){
drh8d129422011-04-05 12:25:19 +00001608 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
danielk197794eb6a12005-12-15 15:22:08 +00001609 }
drhb7654112008-01-12 12:48:07 +00001610 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001611}
drhcd446902004-02-24 01:05:31 +00001612
1613/*
drh26198bb2013-10-31 11:15:09 +00001614** Allocate cursors for the pTab table and all its indices and generate
1615** code to open and initialized those cursors.
drhaa9b8962008-01-08 02:57:55 +00001616**
drh26198bb2013-10-31 11:15:09 +00001617** The cursor for the object that contains the complete data (normally
1618** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
1619** ROWID table) is returned in *piDataCur. The first index cursor is
1620** returned in *piIdxCur. The number of indices is returned.
1621**
1622** Use iBase as the first cursor (either the *piDataCur for rowid tables
1623** or the first index for WITHOUT ROWID tables) if it is non-negative.
1624** If iBase is negative, then allocate the next available cursor.
1625**
1626** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
1627** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
1628** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
1629** pTab->pIndex list.
drhb6b4b792014-08-21 14:10:23 +00001630**
1631** If pTab is a virtual table, then this routine is a no-op and the
1632** *piDataCur and *piIdxCur values are left uninitialized.
drhcd446902004-02-24 01:05:31 +00001633*/
drhaa9b8962008-01-08 02:57:55 +00001634int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001635 Parse *pParse, /* Parsing context */
1636 Table *pTab, /* Table to be opened */
drh26198bb2013-10-31 11:15:09 +00001637 int op, /* OP_OpenRead or OP_OpenWrite */
1638 int iBase, /* Use this for the table cursor, if there is one */
drh6a534992013-11-16 20:13:39 +00001639 u8 *aToOpen, /* If not NULL: boolean for each table and index */
drh26198bb2013-10-31 11:15:09 +00001640 int *piDataCur, /* Write the database source cursor number here */
1641 int *piIdxCur /* Write the first index cursor number here */
drh290c1942004-08-21 17:54:45 +00001642){
drhcd446902004-02-24 01:05:31 +00001643 int i;
drh4cbdda92006-06-14 19:00:20 +00001644 int iDb;
drh6a534992013-11-16 20:13:39 +00001645 int iDataCur;
drhcd446902004-02-24 01:05:31 +00001646 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001647 Vdbe *v;
1648
drh26198bb2013-10-31 11:15:09 +00001649 assert( op==OP_OpenRead || op==OP_OpenWrite );
1650 if( IsVirtual(pTab) ){
drhb6b4b792014-08-21 14:10:23 +00001651 /* This routine is a no-op for virtual tables. Leave the output
1652 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
1653 ** can detect if they are used by mistake in the caller. */
drh26198bb2013-10-31 11:15:09 +00001654 return 0;
1655 }
drh4cbdda92006-06-14 19:00:20 +00001656 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1657 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001658 assert( v!=0 );
drh26198bb2013-10-31 11:15:09 +00001659 if( iBase<0 ) iBase = pParse->nTab;
drh6a534992013-11-16 20:13:39 +00001660 iDataCur = iBase++;
1661 if( piDataCur ) *piDataCur = iDataCur;
1662 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
1663 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
drh6fbe41a2013-10-30 20:22:55 +00001664 }else{
drh26198bb2013-10-31 11:15:09 +00001665 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
drh6fbe41a2013-10-30 20:22:55 +00001666 }
drh6a534992013-11-16 20:13:39 +00001667 if( piIdxCur ) *piIdxCur = iBase;
drh26198bb2013-10-31 11:15:09 +00001668 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
drh26198bb2013-10-31 11:15:09 +00001669 int iIdxCur = iBase++;
danielk1977da184232006-01-05 11:34:32 +00001670 assert( pIdx->pSchema==pTab->pSchema );
drh48dd1d82014-05-27 18:18:58 +00001671 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
drh6a534992013-11-16 20:13:39 +00001672 *piDataCur = iIdxCur;
1673 }
1674 if( aToOpen==0 || aToOpen[i+1] ){
1675 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
1676 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1677 VdbeComment((v, "%s", pIdx->zName));
1678 }
drhcd446902004-02-24 01:05:31 +00001679 }
drh26198bb2013-10-31 11:15:09 +00001680 if( iBase>pParse->nTab ) pParse->nTab = iBase;
1681 return i;
drhcd446902004-02-24 01:05:31 +00001682}
drh9d9cf222007-02-13 15:01:11 +00001683
drh91c58e22007-03-27 12:04:04 +00001684
1685#ifdef SQLITE_TEST
1686/*
1687** The following global variable is incremented whenever the
1688** transfer optimization is used. This is used for testing
1689** purposes only - to make sure the transfer optimization really
peter.d.reid60ec9142014-09-06 16:39:46 +00001690** is happening when it is supposed to.
drh91c58e22007-03-27 12:04:04 +00001691*/
1692int sqlite3_xferopt_count;
1693#endif /* SQLITE_TEST */
1694
1695
drh9d9cf222007-02-13 15:01:11 +00001696#ifndef SQLITE_OMIT_XFER_OPT
1697/*
1698** Check to collation names to see if they are compatible.
1699*/
1700static int xferCompatibleCollation(const char *z1, const char *z2){
1701 if( z1==0 ){
1702 return z2==0;
1703 }
1704 if( z2==0 ){
1705 return 0;
1706 }
1707 return sqlite3StrICmp(z1, z2)==0;
1708}
1709
1710
1711/*
1712** Check to see if index pSrc is compatible as a source of data
1713** for index pDest in an insert transfer optimization. The rules
1714** for a compatible index:
1715**
1716** * The index is over the same set of columns
1717** * The same DESC and ASC markings occurs on all columns
1718** * The same onError processing (OE_Abort, OE_Ignore, etc)
1719** * The same collating sequence on each column
drhb2b9d3d2013-08-01 01:14:43 +00001720** * The index has the exact same WHERE clause
drh9d9cf222007-02-13 15:01:11 +00001721*/
1722static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1723 int i;
1724 assert( pDest && pSrc );
1725 assert( pDest->pTable!=pSrc->pTable );
drhbbbdc832013-10-22 18:01:40 +00001726 if( pDest->nKeyCol!=pSrc->nKeyCol ){
drh9d9cf222007-02-13 15:01:11 +00001727 return 0; /* Different number of columns */
1728 }
1729 if( pDest->onError!=pSrc->onError ){
1730 return 0; /* Different conflict resolution strategies */
1731 }
drhbbbdc832013-10-22 18:01:40 +00001732 for(i=0; i<pSrc->nKeyCol; i++){
drh9d9cf222007-02-13 15:01:11 +00001733 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1734 return 0; /* Different columns indexed */
1735 }
1736 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1737 return 0; /* Different sort orders */
1738 }
drh3f6e7812009-05-02 00:28:19 +00001739 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
drh60a713c2008-01-21 16:22:45 +00001740 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001741 }
1742 }
drh619a1302013-08-01 13:04:46 +00001743 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
drhb2b9d3d2013-08-01 01:14:43 +00001744 return 0; /* Different WHERE clauses */
1745 }
drh9d9cf222007-02-13 15:01:11 +00001746
1747 /* If no test above fails then the indices must be compatible */
1748 return 1;
1749}
1750
1751/*
1752** Attempt the transfer optimization on INSERTs of the form
1753**
1754** INSERT INTO tab1 SELECT * FROM tab2;
1755**
drhccdf1ba2011-11-04 14:36:02 +00001756** The xfer optimization transfers raw records from tab2 over to tab1.
peter.d.reid60ec9142014-09-06 16:39:46 +00001757** Columns are not decoded and reassembled, which greatly improves
drhccdf1ba2011-11-04 14:36:02 +00001758** performance. Raw index records are transferred in the same way.
drh9d9cf222007-02-13 15:01:11 +00001759**
drhccdf1ba2011-11-04 14:36:02 +00001760** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1761** There are lots of rules for determining compatibility - see comments
1762** embedded in the code for details.
drh9d9cf222007-02-13 15:01:11 +00001763**
drhccdf1ba2011-11-04 14:36:02 +00001764** This routine returns TRUE if the optimization is guaranteed to be used.
1765** Sometimes the xfer optimization will only work if the destination table
1766** is empty - a factor that can only be determined at run-time. In that
1767** case, this routine generates code for the xfer optimization but also
1768** does a test to see if the destination table is empty and jumps over the
1769** xfer optimization code if the test fails. In that case, this routine
1770** returns FALSE so that the caller will know to go ahead and generate
1771** an unoptimized transfer. This routine also returns FALSE if there
1772** is no chance that the xfer optimization can be applied.
drh9d9cf222007-02-13 15:01:11 +00001773**
drhccdf1ba2011-11-04 14:36:02 +00001774** This optimization is particularly useful at making VACUUM run faster.
drh9d9cf222007-02-13 15:01:11 +00001775*/
1776static int xferOptimization(
1777 Parse *pParse, /* Parser context */
1778 Table *pDest, /* The table we are inserting into */
1779 Select *pSelect, /* A SELECT statement to use as the data source */
1780 int onError, /* How to handle constraint errors */
1781 int iDbDest /* The database of pDest */
1782){
dane34162b2015-04-01 18:20:25 +00001783 sqlite3 *db = pParse->db;
drh9d9cf222007-02-13 15:01:11 +00001784 ExprList *pEList; /* The result set of the SELECT */
1785 Table *pSrc; /* The table in the FROM clause of SELECT */
1786 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1787 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1788 int i; /* Loop counter */
1789 int iDbSrc; /* The database of pSrc */
1790 int iSrc, iDest; /* Cursors from source and destination */
1791 int addr1, addr2; /* Loop addresses */
drhda475b82013-11-04 21:44:54 +00001792 int emptyDestTest = 0; /* Address of test for empty pDest */
1793 int emptySrcTest = 0; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001794 Vdbe *v; /* The VDBE we are building */
drh6a288a32008-01-07 19:20:24 +00001795 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001796 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001797 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001798
1799 if( pSelect==0 ){
1800 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1801 }
danebbf08a2014-01-18 08:27:02 +00001802 if( pParse->pWith || pSelect->pWith ){
1803 /* Do not attempt to process this query if there are an WITH clauses
1804 ** attached to it. Proceeding may generate a false "no such table: xxx"
1805 ** error if pSelect reads from a CTE named "xxx". */
1806 return 0;
1807 }
danielk19772f886d12009-02-28 10:47:41 +00001808 if( sqlite3TriggerList(pParse, pDest) ){
drh9d9cf222007-02-13 15:01:11 +00001809 return 0; /* tab1 must not have triggers */
1810 }
1811#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001812 if( pDest->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001813 return 0; /* tab1 must not be a virtual table */
1814 }
1815#endif
1816 if( onError==OE_Default ){
drhe7224a02011-11-04 00:23:53 +00001817 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1818 if( onError==OE_Default ) onError = OE_Abort;
drh9d9cf222007-02-13 15:01:11 +00001819 }
danielk19775ce240a2007-09-03 17:30:06 +00001820 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001821 if( pSelect->pSrc->nSrc!=1 ){
1822 return 0; /* FROM clause must have exactly one term */
1823 }
1824 if( pSelect->pSrc->a[0].pSelect ){
1825 return 0; /* FROM clause cannot contain a subquery */
1826 }
1827 if( pSelect->pWhere ){
1828 return 0; /* SELECT may not have a WHERE clause */
1829 }
1830 if( pSelect->pOrderBy ){
1831 return 0; /* SELECT may not have an ORDER BY clause */
1832 }
drh8103b7d2007-02-24 13:23:51 +00001833 /* Do not need to test for a HAVING clause. If HAVING is present but
1834 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001835 if( pSelect->pGroupBy ){
1836 return 0; /* SELECT may not have a GROUP BY clause */
1837 }
1838 if( pSelect->pLimit ){
1839 return 0; /* SELECT may not have a LIMIT clause */
1840 }
drh8103b7d2007-02-24 13:23:51 +00001841 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001842 if( pSelect->pPrior ){
1843 return 0; /* SELECT may not be a compound query */
1844 }
drh7d10d5a2008-08-20 16:35:10 +00001845 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:11 +00001846 return 0; /* SELECT may not be DISTINCT */
1847 }
1848 pEList = pSelect->pEList;
1849 assert( pEList!=0 );
1850 if( pEList->nExpr!=1 ){
1851 return 0; /* The result set must have exactly one column */
1852 }
1853 assert( pEList->a[0].pExpr );
1854 if( pEList->a[0].pExpr->op!=TK_ALL ){
1855 return 0; /* The result set must be the special operator "*" */
1856 }
1857
1858 /* At this point we have established that the statement is of the
1859 ** correct syntactic form to participate in this optimization. Now
1860 ** we have to check the semantics.
1861 */
1862 pItem = pSelect->pSrc->a;
dan41fb5cd2012-10-04 19:33:00 +00001863 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
drh9d9cf222007-02-13 15:01:11 +00001864 if( pSrc==0 ){
1865 return 0; /* FROM clause does not contain a real table */
1866 }
1867 if( pSrc==pDest ){
1868 return 0; /* tab1 and tab2 may not be the same table */
1869 }
drh55548272013-10-23 16:03:07 +00001870 if( HasRowid(pDest)!=HasRowid(pSrc) ){
1871 return 0; /* source and destination must both be WITHOUT ROWID or not */
1872 }
drh9d9cf222007-02-13 15:01:11 +00001873#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001874 if( pSrc->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001875 return 0; /* tab2 must not be a virtual table */
1876 }
1877#endif
1878 if( pSrc->pSelect ){
1879 return 0; /* tab2 may not be a view */
1880 }
1881 if( pDest->nCol!=pSrc->nCol ){
1882 return 0; /* Number of columns must be the same in tab1 and tab2 */
1883 }
1884 if( pDest->iPKey!=pSrc->iPKey ){
1885 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1886 }
1887 for(i=0; i<pDest->nCol; i++){
dan9940e2a2014-04-26 14:07:57 +00001888 Column *pDestCol = &pDest->aCol[i];
1889 Column *pSrcCol = &pSrc->aCol[i];
1890 if( pDestCol->affinity!=pSrcCol->affinity ){
drh9d9cf222007-02-13 15:01:11 +00001891 return 0; /* Affinity must be the same on all columns */
1892 }
dan9940e2a2014-04-26 14:07:57 +00001893 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
drh9d9cf222007-02-13 15:01:11 +00001894 return 0; /* Collating sequence must be the same on all columns */
1895 }
dan9940e2a2014-04-26 14:07:57 +00001896 if( pDestCol->notNull && !pSrcCol->notNull ){
drh9d9cf222007-02-13 15:01:11 +00001897 return 0; /* tab2 must be NOT NULL if tab1 is */
1898 }
drh453e0262014-04-26 17:52:08 +00001899 /* Default values for second and subsequent columns need to match. */
1900 if( i>0
1901 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
1902 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
dan9940e2a2014-04-26 14:07:57 +00001903 ){
1904 return 0; /* Default values must be the same for all columns */
1905 }
drh9d9cf222007-02-13 15:01:11 +00001906 }
1907 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh5f1d1d92014-07-31 22:59:04 +00001908 if( IsUniqueIndex(pDestIdx) ){
drhf33c9fa2007-04-10 18:17:55 +00001909 destHasUniqueIdx = 1;
1910 }
drh9d9cf222007-02-13 15:01:11 +00001911 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1912 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1913 }
1914 if( pSrcIdx==0 ){
1915 return 0; /* pDestIdx has no corresponding index in pSrc */
1916 }
1917 }
drh7fc2f412007-03-29 00:08:24 +00001918#ifndef SQLITE_OMIT_CHECK
drh619a1302013-08-01 13:04:46 +00001919 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
drh8103b7d2007-02-24 13:23:51 +00001920 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1921 }
drh7fc2f412007-03-29 00:08:24 +00001922#endif
drh713de342011-04-24 22:56:07 +00001923#ifndef SQLITE_OMIT_FOREIGN_KEY
1924 /* Disallow the transfer optimization if the destination table constains
1925 ** any foreign key constraints. This is more restrictive than necessary.
1926 ** But the main beneficiary of the transfer optimization is the VACUUM
1927 ** command, and the VACUUM command disables foreign key constraints. So
1928 ** the extra complication to make this rule less restrictive is probably
1929 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1930 */
dane34162b2015-04-01 18:20:25 +00001931 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
drh713de342011-04-24 22:56:07 +00001932 return 0;
1933 }
1934#endif
dane34162b2015-04-01 18:20:25 +00001935 if( (db->flags & SQLITE_CountRows)!=0 ){
drhccdf1ba2011-11-04 14:36:02 +00001936 return 0; /* xfer opt does not play well with PRAGMA count_changes */
dan16961242011-09-30 12:01:01 +00001937 }
drh9d9cf222007-02-13 15:01:11 +00001938
drhccdf1ba2011-11-04 14:36:02 +00001939 /* If we get this far, it means that the xfer optimization is at
1940 ** least a possibility, though it might only work if the destination
1941 ** table (tab1) is initially empty.
drh9d9cf222007-02-13 15:01:11 +00001942 */
drhdd735212007-02-24 13:53:05 +00001943#ifdef SQLITE_TEST
1944 sqlite3_xferopt_count++;
1945#endif
dane34162b2015-04-01 18:20:25 +00001946 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
drh9d9cf222007-02-13 15:01:11 +00001947 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001948 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001949 iSrc = pParse->nTab++;
1950 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001951 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drhb7654112008-01-12 12:48:07 +00001952 regData = sqlite3GetTempReg(pParse);
1953 regRowid = sqlite3GetTempReg(pParse);
dan427ebba2013-11-05 16:39:31 +00001954 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1955 assert( HasRowid(pDest) || destHasUniqueIdx );
dane34162b2015-04-01 18:20:25 +00001956 if( (db->flags & SQLITE_Vacuum)==0 && (
1957 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
dan427ebba2013-11-05 16:39:31 +00001958 || destHasUniqueIdx /* (2) */
1959 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
dane34162b2015-04-01 18:20:25 +00001960 )){
dan427ebba2013-11-05 16:39:31 +00001961 /* In some circumstances, we are able to run the xfer optimization
dane34162b2015-04-01 18:20:25 +00001962 ** only if the destination table is initially empty. Unless the
1963 ** SQLITE_Vacuum flag is set, this block generates code to make
1964 ** that determination. If SQLITE_Vacuum is set, then the destination
1965 ** table is always empty.
1966 **
1967 ** Conditions under which the destination must be empty:
dan427ebba2013-11-05 16:39:31 +00001968 **
1969 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1970 ** (If the destination is not initially empty, the rowid fields
1971 ** of index entries might need to change.)
1972 **
1973 ** (2) The destination has a unique index. (The xfer optimization
1974 ** is unable to test uniqueness.)
1975 **
1976 ** (3) onError is something other than OE_Abort and OE_Rollback.
1977 */
drh688852a2014-02-17 22:40:43 +00001978 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
dan427ebba2013-11-05 16:39:31 +00001979 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
1980 sqlite3VdbeJumpHere(v, addr1);
1981 }
drh55548272013-10-23 16:03:07 +00001982 if( HasRowid(pSrc) ){
drh55548272013-10-23 16:03:07 +00001983 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00001984 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
drh55548272013-10-23 16:03:07 +00001985 if( pDest->iPKey>=0 ){
1986 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1987 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
drh688852a2014-02-17 22:40:43 +00001988 VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00001989 sqlite3RowidConstraint(pParse, onError, pDest);
drh55548272013-10-23 16:03:07 +00001990 sqlite3VdbeJumpHere(v, addr2);
1991 autoIncStep(pParse, regAutoinc, regRowid);
1992 }else if( pDest->pIndex==0 ){
1993 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
1994 }else{
1995 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1996 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
1997 }
1998 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1999 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
2000 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
2001 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh688852a2014-02-17 22:40:43 +00002002 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
drh55548272013-10-23 16:03:07 +00002003 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2004 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drhda475b82013-11-04 21:44:54 +00002005 }else{
2006 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2007 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
drh95bad4c2007-03-28 18:04:10 +00002008 }
drh9d9cf222007-02-13 15:01:11 +00002009 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh41b9ca22015-07-28 18:53:37 +00002010 u8 idxInsFlags = 0;
drh1b7ecbb2009-05-03 01:00:59 +00002011 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
drh9d9cf222007-02-13 15:01:11 +00002012 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2013 }
2014 assert( pSrcIdx );
drh2ec2fb22013-11-06 19:59:23 +00002015 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
2016 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
drhd4e70eb2008-01-02 00:34:36 +00002017 VdbeComment((v, "%s", pSrcIdx->zName));
drh2ec2fb22013-11-06 19:59:23 +00002018 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
2019 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
dan59885722013-10-04 18:17:18 +00002020 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
danielk1977207872a2008-01-03 07:54:23 +00002021 VdbeComment((v, "%s", pDestIdx->zName));
drh688852a2014-02-17 22:40:43 +00002022 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
drhb7654112008-01-12 12:48:07 +00002023 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
dane34162b2015-04-01 18:20:25 +00002024 if( db->flags & SQLITE_Vacuum ){
2025 /* This INSERT command is part of a VACUUM operation, which guarantees
2026 ** that the destination table is empty. If all indexed columns use
2027 ** collation sequence BINARY, then it can also be assumed that the
2028 ** index will be populated by inserting keys in strictly sorted
2029 ** order. In this case, instead of seeking within the b-tree as part
2030 ** of every OP_IdxInsert opcode, an OP_Last is added before the
2031 ** OP_IdxInsert to seek to the point within the b-tree where each key
2032 ** should be inserted. This is faster.
2033 **
2034 ** If any of the indexed columns use a collation sequence other than
2035 ** BINARY, this optimization is disabled. This is because the user
2036 ** might change the definition of a collation sequence and then run
2037 ** a VACUUM command. In that case keys may not be written in strictly
2038 ** sorted order. */
dane34162b2015-04-01 18:20:25 +00002039 for(i=0; i<pSrcIdx->nColumn; i++){
2040 char *zColl = pSrcIdx->azColl[i];
drhab06b0e2015-04-13 14:03:54 +00002041 assert( zColl!=0 );
2042 if( sqlite3_stricmp("BINARY", zColl) ) break;
dane34162b2015-04-01 18:20:25 +00002043 }
2044 if( i==pSrcIdx->nColumn ){
drh41b9ca22015-07-28 18:53:37 +00002045 idxInsFlags = OPFLAG_USESEEKRESULT;
dane34162b2015-04-01 18:20:25 +00002046 sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
2047 }
2048 }
drh41b9ca22015-07-28 18:53:37 +00002049 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
2050 idxInsFlags |= OPFLAG_NCHANGE;
2051 }
drhb7654112008-01-12 12:48:07 +00002052 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh41b9ca22015-07-28 18:53:37 +00002053 sqlite3VdbeChangeP5(v, idxInsFlags);
drh688852a2014-02-17 22:40:43 +00002054 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
drh9d9cf222007-02-13 15:01:11 +00002055 sqlite3VdbeJumpHere(v, addr1);
drh55548272013-10-23 16:03:07 +00002056 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2057 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00002058 }
drhaceb31b2014-02-08 01:40:27 +00002059 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00002060 sqlite3ReleaseTempReg(pParse, regRowid);
2061 sqlite3ReleaseTempReg(pParse, regData);
drh9d9cf222007-02-13 15:01:11 +00002062 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00002063 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00002064 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00002065 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00002066 return 0;
2067 }else{
2068 return 1;
2069 }
2070}
2071#endif /* SQLITE_OMIT_XFER_OPT */