blob: 1c2cabb938b56a16ffbbc8a821180af5a4173a36 [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/*
drhbbb5e4e2009-04-30 00:11:09 +000018** Generate code that will open a table for reading.
19*/
20void sqlite3OpenTable(
21 Parse *p, /* Generate code into this VDBE */
22 int iCur, /* The cursor number of the table */
23 int iDb, /* The database index in sqlite3.aDb[] */
24 Table *pTab, /* The table to be opened */
25 int opcode /* OP_OpenRead or OP_OpenWrite */
26){
27 Vdbe *v;
drh5f53aac2012-12-03 19:42:39 +000028 assert( !IsVirtual(pTab) );
drhbbb5e4e2009-04-30 00:11:09 +000029 v = sqlite3GetVdbe(p);
30 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
31 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
32 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
33 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
34 VdbeComment((v, "%s", pTab->zName));
35}
36
37/*
dan69f8bb92009-08-13 19:21:16 +000038** Return a pointer to the column affinity string associated with index
39** pIdx. A column affinity string has one character for each column in
40** the table, according to the affinity of the column:
danielk19773d1bfea2004-05-14 11:00:53 +000041**
42** Character Column affinity
43** ------------------------------
drh3eda0402005-11-24 13:15:32 +000044** 'a' TEXT
45** 'b' NONE
46** 'c' NUMERIC
47** 'd' INTEGER
48** 'e' REAL
drh2d401ab2008-01-10 23:50:11 +000049**
dan0c733f62011-11-16 15:27:09 +000050** An extra 'd' is appended to the end of the string to cover the
drh2d401ab2008-01-10 23:50:11 +000051** rowid that appears as the last column in every index.
dan69f8bb92009-08-13 19:21:16 +000052**
53** Memory for the buffer containing the column index affinity string
54** is managed along with the rest of the Index structure. It will be
55** released when sqlite3DeleteIndex() is called.
danielk19773d1bfea2004-05-14 11:00:53 +000056*/
dan69f8bb92009-08-13 19:21:16 +000057const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
danielk1977a37cdde2004-05-16 11:15:36 +000058 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000059 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000060 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000061 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000062 **
63 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000064 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000065 ** up.
66 */
67 int n;
68 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000069 sqlite3 *db = sqlite3VdbeDb(v);
drhb9755982010-07-24 16:34:37 +000070 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
danielk1977a37cdde2004-05-16 11:15:36 +000071 if( !pIdx->zColAff ){
drh633e6d52008-07-28 19:34:53 +000072 db->mallocFailed = 1;
dan69f8bb92009-08-13 19:21:16 +000073 return 0;
danielk1977a37cdde2004-05-16 11:15:36 +000074 }
75 for(n=0; n<pIdx->nColumn; n++){
76 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
77 }
dan0c733f62011-11-16 15:27:09 +000078 pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
drh2d401ab2008-01-10 23:50:11 +000079 pIdx->zColAff[n] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +000080 }
danielk19773d1bfea2004-05-14 11:00:53 +000081
dan69f8bb92009-08-13 19:21:16 +000082 return pIdx->zColAff;
danielk1977a37cdde2004-05-16 11:15:36 +000083}
84
85/*
drh66a51672008-01-03 00:01:23 +000086** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000087** string for table pTab. A column affinity string has one character
88** for each column indexed by the index, according to the affinity of the
89** column:
90**
91** Character Column affinity
92** ------------------------------
drh3eda0402005-11-24 13:15:32 +000093** 'a' TEXT
94** 'b' NONE
95** 'c' NUMERIC
96** 'd' INTEGER
97** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000098*/
99void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +0000100 /* The first time a column affinity string for a particular table
101 ** is required, it is allocated and populated here. It is then
102 ** stored as a member of the Table structure for subsequent use.
103 **
104 ** The column affinity string will eventually be deleted by
105 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
106 */
107 if( !pTab->zColAff ){
108 char *zColAff;
109 int i;
drhabb6fca2007-08-16 12:24:01 +0000110 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +0000111
drhb9755982010-07-24 16:34:37 +0000112 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +0000113 if( !zColAff ){
drh633e6d52008-07-28 19:34:53 +0000114 db->mallocFailed = 1;
danielk1977a37cdde2004-05-16 11:15:36 +0000115 return;
danielk19773d1bfea2004-05-14 11:00:53 +0000116 }
117
118 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +0000119 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +0000120 }
121 zColAff[pTab->nCol] = '\0';
122
123 pTab->zColAff = zColAff;
124 }
125
drh8d129422011-04-05 12:25:19 +0000126 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
danielk19773d1bfea2004-05-14 11:00:53 +0000127}
128
danielk19774d887782005-02-08 08:42:27 +0000129/*
drh48d11782007-11-23 15:02:19 +0000130** Return non-zero if the table pTab in database iDb or any of its indices
131** have been opened at any point in the VDBE program beginning at location
132** iStartAddr throught the end of the program. This is used to see if
133** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
134** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000135*/
danielk1977595a5232009-07-24 17:58:53 +0000136static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
137 Vdbe *v = sqlite3GetVdbe(p);
danielk19774d887782005-02-08 08:42:27 +0000138 int i;
drh48d11782007-11-23 15:02:19 +0000139 int iEnd = sqlite3VdbeCurrentAddr(v);
danielk1977595a5232009-07-24 17:58:53 +0000140#ifndef SQLITE_OMIT_VIRTUALTABLE
141 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
142#endif
143
drh48d11782007-11-23 15:02:19 +0000144 for(i=iStartAddr; i<iEnd; i++){
145 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000146 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000147 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
148 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000149 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000150 if( tnum==pTab->tnum ){
151 return 1;
152 }
153 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
154 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000155 return 1;
156 }
drh48d11782007-11-23 15:02:19 +0000157 }
158 }
drh543165e2007-11-27 14:46:41 +0000159#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53 +0000160 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
danielk19772dca4ac2008-01-03 11:50:29 +0000161 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000162 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000163 return 1;
danielk19774d887782005-02-08 08:42:27 +0000164 }
drh543165e2007-11-27 14:46:41 +0000165#endif
danielk19774d887782005-02-08 08:42:27 +0000166 }
167 return 0;
168}
danielk19773d1bfea2004-05-14 11:00:53 +0000169
drh9d9cf222007-02-13 15:01:11 +0000170#ifndef SQLITE_OMIT_AUTOINCREMENT
171/*
drh0b9f50d2009-06-23 20:28:53 +0000172** Locate or create an AutoincInfo structure associated with table pTab
173** which is in database iDb. Return the register number for the register
174** that holds the maximum rowid.
drh9d9cf222007-02-13 15:01:11 +0000175**
drh0b9f50d2009-06-23 20:28:53 +0000176** There is at most one AutoincInfo structure per table even if the
177** same table is autoincremented multiple times due to inserts within
178** triggers. A new AutoincInfo structure is created if this is the
179** first use of table pTab. On 2nd and subsequent uses, the original
180** AutoincInfo structure is used.
drh9d9cf222007-02-13 15:01:11 +0000181**
drh0b9f50d2009-06-23 20:28:53 +0000182** Three memory locations are allocated:
183**
184** (1) Register to hold the name of the pTab table.
185** (2) Register to hold the maximum ROWID of pTab.
186** (3) Register to hold the rowid in sqlite_sequence of pTab
187**
188** The 2nd register is the one that is returned. That is all the
189** insert routine needs to know about.
drh9d9cf222007-02-13 15:01:11 +0000190*/
191static int autoIncBegin(
192 Parse *pParse, /* Parsing context */
193 int iDb, /* Index of the database holding pTab */
194 Table *pTab /* The table we are writing to */
195){
drh6a288a32008-01-07 19:20:24 +0000196 int memId = 0; /* Register holding maximum rowid */
drh7d10d5a2008-08-20 16:35:10 +0000197 if( pTab->tabFlags & TF_Autoincrement ){
dan65a7cd12009-09-01 12:16:01 +0000198 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000199 AutoincInfo *pInfo;
200
dan65a7cd12009-09-01 12:16:01 +0000201 pInfo = pToplevel->pAinc;
drh0b9f50d2009-06-23 20:28:53 +0000202 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
203 if( pInfo==0 ){
204 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
205 if( pInfo==0 ) return 0;
dan65a7cd12009-09-01 12:16:01 +0000206 pInfo->pNext = pToplevel->pAinc;
207 pToplevel->pAinc = pInfo;
drh0b9f50d2009-06-23 20:28:53 +0000208 pInfo->pTab = pTab;
209 pInfo->iDb = iDb;
dan65a7cd12009-09-01 12:16:01 +0000210 pToplevel->nMem++; /* Register to hold name of table */
211 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
212 pToplevel->nMem++; /* Rowid in sqlite_sequence */
drh0b9f50d2009-06-23 20:28:53 +0000213 }
214 memId = pInfo->regCtr;
drh9d9cf222007-02-13 15:01:11 +0000215 }
216 return memId;
217}
218
219/*
drh0b9f50d2009-06-23 20:28:53 +0000220** This routine generates code that will initialize all of the
221** register used by the autoincrement tracker.
222*/
223void sqlite3AutoincrementBegin(Parse *pParse){
224 AutoincInfo *p; /* Information about an AUTOINCREMENT */
225 sqlite3 *db = pParse->db; /* The database connection */
226 Db *pDb; /* Database only autoinc table */
227 int memId; /* Register holding max rowid */
228 int addr; /* A VDBE address */
229 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
230
drh345ba7d2009-09-08 13:40:16 +0000231 /* This routine is never called during trigger-generation. It is
232 ** only called from the top-level */
233 assert( pParse->pTriggerTab==0 );
234 assert( pParse==sqlite3ParseToplevel(pParse) );
dan76d462e2009-08-30 11:42:51 +0000235
drh0b9f50d2009-06-23 20:28:53 +0000236 assert( v ); /* We failed long ago if this is not so */
237 for(p = pParse->pAinc; p; p = p->pNext){
238 pDb = &db->aDb[p->iDb];
239 memId = p->regCtr;
drh21206082011-04-04 18:22:02 +0000240 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drh0b9f50d2009-06-23 20:28:53 +0000241 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drhf4d31bc2011-12-09 16:59:19 +0000242 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
drh0b9f50d2009-06-23 20:28:53 +0000243 addr = sqlite3VdbeCurrentAddr(v);
244 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
245 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
246 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
247 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
248 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
249 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
250 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
251 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
252 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
253 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
254 sqlite3VdbeAddOp0(v, OP_Close);
255 }
256}
257
258/*
drh9d9cf222007-02-13 15:01:11 +0000259** Update the maximum rowid for an autoincrement calculation.
260**
261** This routine should be called when the top of the stack holds a
262** new rowid that is about to be inserted. If that new rowid is
263** larger than the maximum rowid in the memId memory cell, then the
264** memory cell is updated. The stack is unchanged.
265*/
drh6a288a32008-01-07 19:20:24 +0000266static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000267 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000268 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000269 }
270}
271
272/*
drh0b9f50d2009-06-23 20:28:53 +0000273** This routine generates the code needed to write autoincrement
274** maximum rowid values back into the sqlite_sequence register.
275** Every statement that might do an INSERT into an autoincrement
276** table (either directly or through triggers) needs to call this
277** routine just before the "exit" code.
drh9d9cf222007-02-13 15:01:11 +0000278*/
drh0b9f50d2009-06-23 20:28:53 +0000279void sqlite3AutoincrementEnd(Parse *pParse){
280 AutoincInfo *p;
281 Vdbe *v = pParse->pVdbe;
282 sqlite3 *db = pParse->db;
drh6a288a32008-01-07 19:20:24 +0000283
drh0b9f50d2009-06-23 20:28:53 +0000284 assert( v );
285 for(p = pParse->pAinc; p; p = p->pNext){
286 Db *pDb = &db->aDb[p->iDb];
287 int j1, j2, j3, j4, j5;
288 int iRec;
289 int memId = p->regCtr;
290
291 iRec = sqlite3GetTempReg(pParse);
drh21206082011-04-04 18:22:02 +0000292 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drh0b9f50d2009-06-23 20:28:53 +0000293 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000294 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
drh0b9f50d2009-06-23 20:28:53 +0000295 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
296 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
297 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
298 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
299 sqlite3VdbeJumpHere(v, j2);
300 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
301 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
302 sqlite3VdbeJumpHere(v, j4);
303 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
drh6a288a32008-01-07 19:20:24 +0000304 sqlite3VdbeJumpHere(v, j1);
drh0b9f50d2009-06-23 20:28:53 +0000305 sqlite3VdbeJumpHere(v, j5);
danielk1977a7a8e142008-02-13 18:25:27 +0000306 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
drh0b9f50d2009-06-23 20:28:53 +0000307 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
drh35573352008-01-08 23:54:25 +0000308 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh0b9f50d2009-06-23 20:28:53 +0000309 sqlite3VdbeAddOp0(v, OP_Close);
310 sqlite3ReleaseTempReg(pParse, iRec);
drh9d9cf222007-02-13 15:01:11 +0000311 }
312}
313#else
314/*
315** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
316** above are all no-ops
317*/
318# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000319# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000320#endif /* SQLITE_OMIT_AUTOINCREMENT */
321
322
drh5f085262012-09-15 13:29:23 +0000323/*
324** Generate code for a co-routine that will evaluate a subquery one
325** row at a time.
326**
327** The pSelect parameter is the subquery that the co-routine will evaluation.
328** Information about the location of co-routine and the registers it will use
329** is returned by filling in the pDest object.
330**
331** Registers are allocated as follows:
332**
333** pDest->iSDParm The register holding the next entry-point of the
334** co-routine. Run the co-routine to its next breakpoint
335** by calling "OP_Yield $X" where $X is pDest->iSDParm.
336**
337** pDest->iSDParm+1 The register holding the "completed" flag for the
338** co-routine. This register is 0 if the previous Yield
339** generated a new result row, or 1 if the subquery
340** has completed. If the Yield is called again
341** after this register becomes 1, then the VDBE will
342** halt with an SQLITE_INTERNAL error.
343**
344** pDest->iSdst First result register.
345**
346** pDest->nSdst Number of result registers.
347**
348** This routine handles all of the register allocation and fills in the
349** pDest structure appropriately.
350**
351** Here is a schematic of the generated code assuming that X is the
352** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
353** completed flag reg[pDest->iSDParm+1], and R and S are the range of
354** registers that hold the result set, reg[pDest->iSdst] through
355** reg[pDest->iSdst+pDest->nSdst-1]:
356**
357** X <- A
358** EOF <- 0
359** goto B
360** A: setup for the SELECT
361** loop rows in the SELECT
362** load results into registers R..S
363** yield X
364** end loop
365** cleanup after the SELECT
366** EOF <- 1
367** yield X
368** halt-error
369** B:
370**
371** To use this subroutine, the caller generates code as follows:
372**
373** [ Co-routine generated by this subroutine, shown above ]
374** S: yield X
375** if EOF goto E
376** if skip this row, goto C
377** if terminate loop, goto E
378** deal with this row
379** C: goto S
380** E:
381*/
382int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
383 int regYield; /* Register holding co-routine entry-point */
384 int regEof; /* Register holding co-routine completion flag */
385 int addrTop; /* Top of the co-routine */
386 int j1; /* Jump instruction */
387 int rc; /* Result code */
388 Vdbe *v; /* VDBE under construction */
389
390 regYield = ++pParse->nMem;
391 regEof = ++pParse->nMem;
392 v = sqlite3GetVdbe(pParse);
393 addrTop = sqlite3VdbeCurrentAddr(v);
394 sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
395 VdbeComment((v, "Co-routine entry point"));
396 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
397 VdbeComment((v, "Co-routine completion flag"));
398 sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
399 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
400 rc = sqlite3Select(pParse, pSelect, pDest);
401 assert( pParse->nErr==0 || rc );
402 if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
403 if( rc ) return rc;
404 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
405 sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
406 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
407 VdbeComment((v, "End of coroutine"));
408 sqlite3VdbeJumpHere(v, j1); /* label B: */
409 return rc;
410}
411
412
413
drh9d9cf222007-02-13 15:01:11 +0000414/* Forward declaration */
415static int xferOptimization(
416 Parse *pParse, /* Parser context */
417 Table *pDest, /* The table we are inserting into */
418 Select *pSelect, /* A SELECT statement to use as the data source */
419 int onError, /* How to handle constraint errors */
420 int iDbDest /* The database of pDest */
421);
422
danielk19773d1bfea2004-05-14 11:00:53 +0000423/*
drh1ccde152000-06-17 13:12:39 +0000424** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000425**
426** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000427** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000428**
drh1ccde152000-06-17 13:12:39 +0000429** The IDLIST following the table name is always optional. If omitted,
430** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000431** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000432**
433** The pList parameter holds EXPRLIST in the first form of the INSERT
434** statement above, and pSelect is NULL. For the second form, pList is
435** NULL and pSelect is a pointer to the select statement used to generate
436** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000437**
drh9d9cf222007-02-13 15:01:11 +0000438** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000439** select with data coming from a VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01 +0000440** once straight down through. Pseudo-code follows (we call this
441** the "1st template"):
drh142e30d2002-08-28 03:00:58 +0000442**
443** open write cursor to <table> and its indices
444** puts VALUES clause expressions onto the stack
445** write the resulting record into <table>
446** cleanup
447**
drh9d9cf222007-02-13 15:01:11 +0000448** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000449**
450** INSERT INTO <table> SELECT ...
451**
drh9d9cf222007-02-13 15:01:11 +0000452** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
453** in other words if the SELECT pulls all columns from a single table
454** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
455** if <table2> and <table1> are distinct tables but have identical
456** schemas, including all the same indices, then a special optimization
457** is invoked that copies raw records from <table2> over to <table1>.
458** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01 +0000459** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000460**
461** open a write cursor to <table>
462** open read cursor on <table2>
463** transfer all records in <table2> over to <table>
464** close cursors
465** foreach index on <table>
466** open a write cursor on the <table> index
467** open a read cursor on the corresponding <table2> index
468** transfer all records from the read to the write cursors
469** close cursors
470** end foreach
471**
drhe00ee6e2008-06-20 15:24:01 +0000472** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11 +0000473** and the SELECT clause does not read from <table> at any time.
474** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000475**
drhe00ee6e2008-06-20 15:24:01 +0000476** EOF <- 0
477** X <- A
drh142e30d2002-08-28 03:00:58 +0000478** goto B
479** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000480** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000481** load values into registers R..R+n
482** yield X
drh142e30d2002-08-28 03:00:58 +0000483** end loop
484** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000485** EOF <- 1
486** yield X
drh142e30d2002-08-28 03:00:58 +0000487** goto A
drhe00ee6e2008-06-20 15:24:01 +0000488** B: open write cursor to <table> and its indices
489** C: yield X
490** if EOF goto D
491** insert the select result into <table> from R..R+n
492** goto C
drh142e30d2002-08-28 03:00:58 +0000493** D: cleanup
494**
drhe00ee6e2008-06-20 15:24:01 +0000495** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000496** values from a SELECT but the data is being inserted into a table
497** that is also read as part of the SELECT. In the third form,
498** we have to use a intermediate table to store the results of
499** the select. The template is like this:
500**
drhe00ee6e2008-06-20 15:24:01 +0000501** EOF <- 0
502** X <- A
drh142e30d2002-08-28 03:00:58 +0000503** goto B
504** A: setup for the SELECT
505** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000506** load value into register R..R+n
507** yield X
drh142e30d2002-08-28 03:00:58 +0000508** end loop
509** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000510** EOF <- 1
511** yield X
512** halt-error
513** B: open temp table
514** L: yield X
515** if EOF goto M
516** insert row from R..R+n into temp table
517** goto L
518** M: open write cursor to <table> and its indices
519** rewind temp table
520** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58 +0000521** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01 +0000522** end loop
523** D: cleanup
drhcce7d172000-05-31 15:34:51 +0000524*/
danielk19774adee202004-05-08 08:23:19 +0000525void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000526 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000527 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000528 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000529 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000530 IdList *pColumn, /* Column names corresponding to IDLIST. */
531 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000532){
drh6a288a32008-01-07 19:20:24 +0000533 sqlite3 *db; /* The main database structure */
534 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000535 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000536 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000537 int i, j, idx; /* Loop counters */
538 Vdbe *v; /* Generate code into this virtual machine */
539 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000540 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000541 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000542 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000543 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000544 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000545 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000546 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01 +0000547 int addrInsTop = 0; /* Jump to label "D" */
548 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
549 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
drh2eb95372008-06-06 15:04:36 +0000550 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24 +0000551 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000552 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000553 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000554
drh6a288a32008-01-07 19:20:24 +0000555 /* Register allocations */
drh1bd10f82008-12-10 21:19:56 +0000556 int regFromSelect = 0;/* Base register for data coming from SELECT */
drh6a288a32008-01-07 19:20:24 +0000557 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
558 int regRowCount = 0; /* Memory cell used for the row counter */
559 int regIns; /* Block of regs holding rowid+data being inserted */
560 int regRowid; /* registers holding insert rowid */
561 int regData; /* register holding first column to insert */
drh1bd10f82008-12-10 21:19:56 +0000562 int regEof = 0; /* Register recording end of SELECT data */
drhaa9b8962008-01-08 02:57:55 +0000563 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000564
drh798da522004-11-04 04:42:28 +0000565#ifndef SQLITE_OMIT_TRIGGER
566 int isView; /* True if attempting to insert into a view */
danielk19772f886d12009-02-28 10:47:41 +0000567 Trigger *pTrigger; /* List of triggers on pTab, if required */
568 int tmask; /* Mask of trigger times */
drh798da522004-11-04 04:42:28 +0000569#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000570
drh17435752007-08-16 04:30:38 +0000571 db = pParse->db;
drh1bd10f82008-12-10 21:19:56 +0000572 memset(&dest, 0, sizeof(dest));
drh17435752007-08-16 04:30:38 +0000573 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000574 goto insert_cleanup;
575 }
drhdaffd0e2001-04-11 14:28:42 +0000576
drh1ccde152000-06-17 13:12:39 +0000577 /* Locate the table into which we will be inserting new information.
578 */
drh113088e2003-03-20 01:16:58 +0000579 assert( pTabList->nSrc==1 );
580 zTab = pTabList->a[0].zName;
drh098d1682009-05-02 15:46:46 +0000581 if( NEVER(zTab==0) ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000582 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000583 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000584 goto insert_cleanup;
585 }
danielk1977da184232006-01-05 11:34:32 +0000586 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
587 assert( iDb<db->nDb );
588 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000589 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000590 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000591 goto insert_cleanup;
592 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000593
drhb7f91642004-10-31 02:22:47 +0000594 /* Figure out if we have any triggers and if the table being
595 ** inserted into is a view
596 */
597#ifndef SQLITE_OMIT_TRIGGER
danielk19772f886d12009-02-28 10:47:41 +0000598 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
drhb7f91642004-10-31 02:22:47 +0000599 isView = pTab->pSelect!=0;
600#else
danielk19772f886d12009-02-28 10:47:41 +0000601# define pTrigger 0
602# define tmask 0
drhb7f91642004-10-31 02:22:47 +0000603# define isView 0
604#endif
605#ifdef SQLITE_OMIT_VIEW
606# undef isView
607# define isView 0
608#endif
danielk19772f886d12009-02-28 10:47:41 +0000609 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
drhb7f91642004-10-31 02:22:47 +0000610
drhf573c992002-07-31 00:32:50 +0000611 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000612 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
613 ** module table).
drhf573c992002-07-31 00:32:50 +0000614 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000615 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000616 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000617 }
618
danielk1977595a5232009-07-24 17:58:53 +0000619 /* Ensure that:
620 * (a) the table is not read-only,
621 * (b) that if it is a view then ON INSERT triggers exist
622 */
623 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
624 goto insert_cleanup;
625 }
626
drh1ccde152000-06-17 13:12:39 +0000627 /* Allocate a VDBE
628 */
danielk19774adee202004-05-08 08:23:19 +0000629 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000630 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000631 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk19772f886d12009-02-28 10:47:41 +0000632 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
drh1ccde152000-06-17 13:12:39 +0000633
drh9d9cf222007-02-13 15:01:11 +0000634#ifndef SQLITE_OMIT_XFER_OPT
635 /* If the statement is of the form
636 **
637 ** INSERT INTO <table1> SELECT * FROM <table2>;
638 **
639 ** Then special optimizations can be applied that make the transfer
640 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000641 **
642 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000643 */
644 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
danielk19772f886d12009-02-28 10:47:41 +0000645 assert( !pTrigger );
drh9d9cf222007-02-13 15:01:11 +0000646 assert( pList==0 );
drh0b9f50d2009-06-23 20:28:53 +0000647 goto insert_end;
drh9d9cf222007-02-13 15:01:11 +0000648 }
649#endif /* SQLITE_OMIT_XFER_OPT */
650
drh2958a4e2004-11-12 03:56:15 +0000651 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000652 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000653 */
drh6a288a32008-01-07 19:20:24 +0000654 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000655
drh1ccde152000-06-17 13:12:39 +0000656 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000657 ** is coming from a SELECT statement, then generate a co-routine that
658 ** produces a single row of the SELECT on each invocation. The
659 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000660 */
drh5974a302000-06-07 14:42:26 +0000661 if( pSelect ){
drh5f085262012-09-15 13:29:23 +0000662 /* Data is coming from a SELECT. Generate a co-routine to run that
663 ** SELECT. */
664 int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
665 if( rc ) goto insert_cleanup;
drh1013c932008-01-06 00:25:21 +0000666
drh5f085262012-09-15 13:29:23 +0000667 regEof = dest.iSDParm + 1;
drh2b596da2012-07-23 21:43:19 +0000668 regFromSelect = dest.iSdst;
drh5974a302000-06-07 14:42:26 +0000669 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000670 nColumn = pSelect->pEList->nExpr;
drh2b596da2012-07-23 21:43:19 +0000671 assert( dest.nSdst==nColumn );
drh142e30d2002-08-28 03:00:58 +0000672
673 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000674 ** should be written into a temporary table (template 4). Set to
675 ** FALSE if each* row of the SELECT can be written directly into
676 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000677 **
678 ** A temp table must be used if the table being updated is also one
679 ** of the tables being read by the SELECT statement. Also use a
680 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000681 */
danielk1977595a5232009-07-24 17:58:53 +0000682 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000683 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000684 }
drh142e30d2002-08-28 03:00:58 +0000685
686 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000687 /* Invoke the coroutine to extract information from the SELECT
688 ** and add it to a transient table srcTab. The code generated
689 ** here is from the 4th template:
690 **
691 ** B: open temp table
692 ** L: yield X
693 ** if EOF goto M
694 ** insert row from R..R+n into temp table
695 ** goto L
696 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000697 */
drhdc5ea5c2008-12-10 17:19:59 +0000698 int regRec; /* Register to hold packed record */
699 int regTempRowid; /* Register to hold temp table ROWID */
700 int addrTop; /* Label "L" */
701 int addrIf; /* Address of jump to M */
drhb7654112008-01-12 12:48:07 +0000702
drh142e30d2002-08-28 03:00:58 +0000703 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000704 regRec = sqlite3GetTempReg(pParse);
drhdc5ea5c2008-12-10 17:19:59 +0000705 regTempRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000706 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh2b596da2012-07-23 21:43:19 +0000707 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
drhe00ee6e2008-06-20 15:24:01 +0000708 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh1db639c2008-01-17 02:36:28 +0000709 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000710 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
711 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drhe00ee6e2008-06-20 15:24:01 +0000712 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
713 sqlite3VdbeJumpHere(v, addrIf);
drhb7654112008-01-12 12:48:07 +0000714 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000715 sqlite3ReleaseTempReg(pParse, regTempRowid);
drh142e30d2002-08-28 03:00:58 +0000716 }
drh5974a302000-06-07 14:42:26 +0000717 }else{
drh142e30d2002-08-28 03:00:58 +0000718 /* This is the case if the data for the INSERT is coming from a VALUES
719 ** clause
720 */
danielk1977b3bce662005-01-29 08:32:43 +0000721 NameContext sNC;
722 memset(&sNC, 0, sizeof(sNC));
723 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000724 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000725 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000726 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000727 for(i=0; i<nColumn; i++){
drh7d10d5a2008-08-20 16:35:10 +0000728 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000729 goto insert_cleanup;
730 }
drhe64e7b22002-02-18 13:56:36 +0000731 }
drh5974a302000-06-07 14:42:26 +0000732 }
drh1ccde152000-06-17 13:12:39 +0000733
734 /* Make sure the number of columns in the source data matches the number
735 ** of columns to be inserted into the table.
736 */
danielk1977034ca142007-06-26 10:38:54 +0000737 if( IsVirtual(pTab) ){
738 for(i=0; i<pTab->nCol; i++){
739 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
740 }
741 }
742 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000743 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000744 "table %S has %d columns but %d values were supplied",
drhd51397a2009-05-01 15:17:48 +0000745 pTabList, 0, pTab->nCol-nHidden, nColumn);
drhcce7d172000-05-31 15:34:51 +0000746 goto insert_cleanup;
747 }
drh967e8b72000-06-21 13:59:10 +0000748 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000749 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000750 goto insert_cleanup;
751 }
drh1ccde152000-06-17 13:12:39 +0000752
753 /* If the INSERT statement included an IDLIST term, then make sure
754 ** all elements of the IDLIST really are columns of the table and
755 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000756 **
757 ** If the table has an INTEGER PRIMARY KEY column and that column
758 ** is named in the IDLIST, then record in the keyColumn variable
759 ** the index into IDLIST of the primary key column. keyColumn is
760 ** the index of the primary key as it appears in IDLIST, not as
761 ** is appears in the original table. (The index of the primary
762 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000763 */
drh967e8b72000-06-21 13:59:10 +0000764 if( pColumn ){
765 for(i=0; i<pColumn->nId; i++){
766 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000767 }
drh967e8b72000-06-21 13:59:10 +0000768 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000769 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000770 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000771 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000772 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000773 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000774 }
drhcce7d172000-05-31 15:34:51 +0000775 break;
776 }
777 }
778 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000779 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000780 keyColumn = i;
781 }else{
danielk19774adee202004-05-08 08:23:19 +0000782 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000783 pTabList, 0, pColumn->a[i].zName);
dan1db95102010-06-28 10:15:19 +0000784 pParse->checkSchema = 1;
drha0217ba2003-06-01 01:10:33 +0000785 goto insert_cleanup;
786 }
drhcce7d172000-05-31 15:34:51 +0000787 }
788 }
789 }
drh1ccde152000-06-17 13:12:39 +0000790
drhaacc5432002-01-06 17:07:40 +0000791 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000792 ** key, the set the keyColumn variable to the primary key column index
793 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000794 */
drh147d0cc2006-08-25 23:42:53 +0000795 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000796 keyColumn = pTab->iPKey;
797 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000798
drhfeeb1392002-04-09 03:28:01 +0000799 /* Initialize the count of rows to be inserted
800 */
drh142e30d2002-08-28 03:00:58 +0000801 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000802 regRowCount = ++pParse->nMem;
803 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000804 }
805
danielk1977e448dc42008-01-02 11:50:51 +0000806 /* If this is not a view, open the table and and all indices */
807 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000808 int nIdx;
drhaa9b8962008-01-08 02:57:55 +0000809
drh04adf412008-01-08 18:57:50 +0000810 baseCur = pParse->nTab;
811 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drh5c070532008-04-11 15:36:03 +0000812 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000813 if( aRegIdx==0 ){
814 goto insert_cleanup;
815 }
816 for(i=0; i<nIdx; i++){
817 aRegIdx[i] = ++pParse->nMem;
818 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000819 }
820
drhe00ee6e2008-06-20 15:24:01 +0000821 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000822 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000823 /* This block codes the top of loop only. The complete loop is the
824 ** following pseudocode (template 4):
825 **
826 ** rewind temp table
827 ** C: loop over rows of intermediate table
828 ** transfer values form intermediate table into <table>
829 ** end loop
830 ** D: ...
831 */
832 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
833 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000834 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000835 /* This block codes the top of loop only. The complete loop is the
836 ** following pseudocode (template 3):
837 **
838 ** C: yield X
839 ** if EOF goto D
840 ** insert the select result into <table> from R..R+n
841 ** goto C
842 ** D: ...
843 */
drh2b596da2012-07-23 21:43:19 +0000844 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
drhe00ee6e2008-06-20 15:24:01 +0000845 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh5974a302000-06-07 14:42:26 +0000846 }
drh1ccde152000-06-17 13:12:39 +0000847
drh6a288a32008-01-07 19:20:24 +0000848 /* Allocate registers for holding the rowid of the new row,
849 ** the content of the new row, and the assemblied row record.
850 */
drh6a288a32008-01-07 19:20:24 +0000851 regRowid = regIns = pParse->nMem+1;
852 pParse->nMem += pTab->nCol + 1;
853 if( IsVirtual(pTab) ){
854 regRowid++;
855 pParse->nMem++;
856 }
857 regData = regRowid+1;
858
drh5cf590c2003-04-24 01:45:04 +0000859 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000860 */
danielk19774adee202004-05-08 08:23:19 +0000861 endOfLoop = sqlite3VdbeMakeLabel(v);
danielk19772f886d12009-02-28 10:47:41 +0000862 if( tmask & TRIGGER_BEFORE ){
dan76d462e2009-08-30 11:42:51 +0000863 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000864
drh70ce3f02003-04-15 19:22:22 +0000865 /* build the NEW.* reference row. Note that if there is an INTEGER
866 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
867 ** translated into a unique ID for the row. But on a BEFORE trigger,
868 ** we do not know what the unique ID will be (because the insert has
869 ** not happened yet) so we substitute a rowid of -1
870 */
871 if( keyColumn<0 ){
dan76d462e2009-08-30 11:42:51 +0000872 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh70ce3f02003-04-15 19:22:22 +0000873 }else{
drh6a288a32008-01-07 19:20:24 +0000874 int j1;
drh7fe45902009-05-01 02:08:04 +0000875 if( useTempTable ){
dan76d462e2009-08-30 11:42:51 +0000876 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
drh7fe45902009-05-01 02:08:04 +0000877 }else{
878 assert( pSelect==0 ); /* Otherwise useTempTable is true */
dan76d462e2009-08-30 11:42:51 +0000879 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
drh7fe45902009-05-01 02:08:04 +0000880 }
dan76d462e2009-08-30 11:42:51 +0000881 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
882 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh6a288a32008-01-07 19:20:24 +0000883 sqlite3VdbeJumpHere(v, j1);
dan76d462e2009-08-30 11:42:51 +0000884 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
drh70ce3f02003-04-15 19:22:22 +0000885 }
886
danielk1977034ca142007-06-26 10:38:54 +0000887 /* Cannot have triggers on a virtual table. If it were possible,
888 ** this block would have to account for hidden column.
889 */
dan165921a2009-08-28 18:53:45 +0000890 assert( !IsVirtual(pTab) );
danielk1977034ca142007-06-26 10:38:54 +0000891
drh70ce3f02003-04-15 19:22:22 +0000892 /* Create the new column data
893 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000894 for(i=0; i<pTab->nCol; i++){
895 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000896 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000897 }else{
drh9adf9ac2002-05-15 11:44:13 +0000898 for(j=0; j<pColumn->nId; j++){
899 if( pColumn->a[j].idx==i ) break;
900 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000901 }
dan7ba45972010-03-30 12:40:32 +0000902 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
dan76d462e2009-08-30 11:42:51 +0000903 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
drh142e30d2002-08-28 03:00:58 +0000904 }else if( useTempTable ){
dan76d462e2009-08-30 11:42:51 +0000905 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000906 }else{
drhd6fe9612005-01-14 01:22:00 +0000907 assert( pSelect==0 ); /* Otherwise useTempTable is true */
dan76d462e2009-08-30 11:42:51 +0000908 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000909 }
910 }
danielk1977a37cdde2004-05-16 11:15:36 +0000911
912 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
913 ** do not attempt any conversions before assembling the record.
914 ** If this is a real table, attempt conversions as required by the
915 ** table column affinities.
916 */
917 if( !isView ){
dan76d462e2009-08-30 11:42:51 +0000918 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
danielk1977a37cdde2004-05-16 11:15:36 +0000919 sqlite3TableAffinityStr(v, pTab);
920 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000921
drh5cf590c2003-04-24 01:45:04 +0000922 /* Fire BEFORE or INSTEAD OF triggers */
dan165921a2009-08-28 18:53:45 +0000923 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
dan94d7f502009-09-24 09:05:49 +0000924 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
dan165921a2009-08-28 18:53:45 +0000925
dan76d462e2009-08-30 11:42:51 +0000926 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
drh70ce3f02003-04-15 19:22:22 +0000927 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000928
drh4a324312001-12-21 14:30:42 +0000929 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000930 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000931 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000932 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000933 */
drh5cf590c2003-04-24 01:45:04 +0000934 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000935 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000936 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000937 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000938 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000939 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000940 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000941 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000942 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000943 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000944 }else{
drhe4d90812007-03-29 05:51:49 +0000945 VdbeOp *pOp;
drh1db639c2008-01-17 02:36:28 +0000946 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
drh20411ea2009-05-29 19:00:12 +0000947 pOp = sqlite3VdbeGetOp(v, -1);
drh1b7ecbb2009-05-03 01:00:59 +0000948 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000949 appendFlag = 1;
950 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000951 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000952 pOp->p2 = regRowid;
953 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000954 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000955 }
drhf0863fe2005-06-12 21:35:51 +0000956 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000957 ** to generate a unique primary key value.
958 */
drhe4d90812007-03-29 05:51:49 +0000959 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000960 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000961 if( !IsVirtual(pTab) ){
962 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
963 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
964 sqlite3VdbeJumpHere(v, j1);
965 }else{
966 j1 = sqlite3VdbeCurrentAddr(v);
967 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
968 }
drh3c84ddf2008-01-09 02:15:38 +0000969 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000970 }
drh4cbdda92006-06-14 19:00:20 +0000971 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000972 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000973 }else{
drh04adf412008-01-08 18:57:50 +0000974 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000975 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000976 }
drh6a288a32008-01-07 19:20:24 +0000977 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000978
danielk1977c3f9bad2002-05-15 08:30:12 +0000979 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000980 ** with the first column.
981 */
danielk1977034ca142007-06-26 10:38:54 +0000982 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000983 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000984 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000985 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000986 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000987 ** Whenever this column is read, the record number will be substituted
988 ** in its place. So will fill this column with a NULL to avoid
989 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000990 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000991 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000992 }
993 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000994 if( IsHiddenColumn(&pTab->aCol[i]) ){
995 assert( IsVirtual(pTab) );
996 j = -1;
997 nHidden++;
998 }else{
999 j = i - nHidden;
1000 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001001 }else{
drh9adf9ac2002-05-15 11:44:13 +00001002 for(j=0; j<pColumn->nId; j++){
1003 if( pColumn->a[j].idx==i ) break;
1004 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001005 }
danielk1977034ca142007-06-26 10:38:54 +00001006 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +00001007 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +00001008 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +00001009 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +00001010 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +00001011 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +00001012 }else{
danielk1977287fb612008-01-04 19:10:28 +00001013 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +00001014 }
drhbed86902000-06-02 13:27:59 +00001015 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001016
1017 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +00001018 ** do the insertion.
1019 */
drh4cbdda92006-06-14 19:00:20 +00001020#ifndef SQLITE_OMIT_VIRTUALTABLE
1021 if( IsVirtual(pTab) ){
danielk1977595a5232009-07-24 17:58:53 +00001022 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
drh4f3dd152008-04-28 18:46:43 +00001023 sqlite3VtabMakeWritable(pParse, pTab);
danielk1977595a5232009-07-24 17:58:53 +00001024 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
danb061d052011-04-25 18:49:57 +00001025 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
dane0af83a2009-09-08 19:15:01 +00001026 sqlite3MayAbort(pParse);
drh4cbdda92006-06-14 19:00:20 +00001027 }else
1028#endif
1029 {
danielk1977de630352009-05-04 11:42:29 +00001030 int isReplace; /* Set to true if constraints may cause a replace */
1031 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
1032 keyColumn>=0, 0, onError, endOfLoop, &isReplace
drh04adf412008-01-08 18:57:50 +00001033 );
dane7a94d82009-10-01 16:09:04 +00001034 sqlite3FkCheck(pParse, pTab, 0, regIns);
drh04adf412008-01-08 18:57:50 +00001035 sqlite3CompleteInsertion(
dan2832ad42009-08-31 15:27:27 +00001036 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
danielk1977de630352009-05-04 11:42:29 +00001037 );
drh4cbdda92006-06-14 19:00:20 +00001038 }
drh5cf590c2003-04-24 01:45:04 +00001039 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001040
drh5cf590c2003-04-24 01:45:04 +00001041 /* Update the count of rows that are inserted
1042 */
1043 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +00001044 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +00001045 }
drh1ccde152000-06-17 13:12:39 +00001046
danielk19772f886d12009-02-28 10:47:41 +00001047 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +00001048 /* Code AFTER triggers */
dan165921a2009-08-28 18:53:45 +00001049 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
dan94d7f502009-09-24 09:05:49 +00001050 pTab, regData-2-pTab->nCol, onError, endOfLoop);
drh1bee3d72001-10-15 00:44:35 +00001051 }
1052
drhe00ee6e2008-06-20 15:24:01 +00001053 /* The bottom of the main insertion loop, if the data source
1054 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:12 +00001055 */
danielk19774adee202004-05-08 08:23:19 +00001056 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +00001057 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +00001058 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1059 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:36 +00001060 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:58 +00001061 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +00001062 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1063 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:26 +00001064 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001065
danielk1977e448dc42008-01-02 11:50:51 +00001066 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +00001067 /* Close all tables opened */
drh2eb95372008-06-06 15:04:36 +00001068 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +00001069 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh2eb95372008-06-06 15:04:36 +00001070 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +00001071 }
drhcce7d172000-05-31 15:34:51 +00001072 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001073
drh0b9f50d2009-06-23 20:28:53 +00001074insert_end:
drhf3388142004-11-13 03:48:06 +00001075 /* Update the sqlite_sequence table by storing the content of the
drh0b9f50d2009-06-23 20:28:53 +00001076 ** maximum rowid counter values recorded while inserting into
1077 ** autoincrement tables.
drh2958a4e2004-11-12 03:56:15 +00001078 */
dan165921a2009-08-28 18:53:45 +00001079 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
drh0b9f50d2009-06-23 20:28:53 +00001080 sqlite3AutoincrementEnd(pParse);
1081 }
drh2958a4e2004-11-12 03:56:15 +00001082
drh1bee3d72001-10-15 00:44:35 +00001083 /*
danielk1977e7de6f22004-11-05 06:02:06 +00001084 ** Return the number of rows inserted. If this routine is
1085 ** generating code because of a call to sqlite3NestedParse(), do not
1086 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +00001087 */
dan165921a2009-08-28 18:53:45 +00001088 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
drh6a288a32008-01-07 19:20:24 +00001089 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +00001090 sqlite3VdbeSetNumCols(v, 1);
danielk197710fb7492008-10-31 10:53:22 +00001091 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
drh1bee3d72001-10-15 00:44:35 +00001092 }
drhcce7d172000-05-31 15:34:51 +00001093
1094insert_cleanup:
drh633e6d52008-07-28 19:34:53 +00001095 sqlite3SrcListDelete(db, pTabList);
1096 sqlite3ExprListDelete(db, pList);
1097 sqlite3SelectDelete(db, pSelect);
1098 sqlite3IdListDelete(db, pColumn);
1099 sqlite3DbFree(db, aRegIdx);
drhcce7d172000-05-31 15:34:51 +00001100}
drh9cfcf5d2002-01-29 18:41:24 +00001101
dan75cbd982009-09-21 16:06:03 +00001102/* Make sure "isView" and other macros defined above are undefined. Otherwise
1103** thely may interfere with compilation of other functions in this file
1104** (or in another file, if this file becomes part of the amalgamation). */
1105#ifdef isView
1106 #undef isView
1107#endif
1108#ifdef pTrigger
1109 #undef pTrigger
1110#endif
1111#ifdef tmask
1112 #undef tmask
1113#endif
1114
1115
drh9cfcf5d2002-01-29 18:41:24 +00001116/*
drh6a288a32008-01-07 19:20:24 +00001117** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +00001118**
drh04adf412008-01-08 18:57:50 +00001119** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +00001120**
dan65a7cd12009-09-01 12:16:01 +00001121** 1. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +00001122**
dan65a7cd12009-09-01 12:16:01 +00001123** 2. The data in the first column of the entry after the update.
drh0ca3e242002-01-29 23:07:02 +00001124**
1125** i. Data from middle columns...
1126**
1127** N. The data in the last column of the entry after the update.
1128**
dan65a7cd12009-09-01 12:16:01 +00001129** The regRowid parameter is the index of the register containing (1).
drh04adf412008-01-08 18:57:50 +00001130**
dan65a7cd12009-09-01 12:16:01 +00001131** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
1132** the address of a register containing the rowid before the update takes
1133** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
1134** is false, indicating an INSERT statement, then a non-zero rowidChng
1135** indicates that the rowid was explicitly specified as part of the
1136** INSERT statement. If rowidChng is false, it means that the rowid is
1137** computed automatically in an insert or that the rowid value is not
1138** modified by an update.
drh0ca3e242002-01-29 23:07:02 +00001139**
drhaa9b8962008-01-08 02:57:55 +00001140** The code generated by this routine store new index entries into
1141** registers identified by aRegIdx[]. No index entry is created for
1142** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1143** the same as the order of indices on the linked list of indices
1144** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +00001145**
1146** This routine also generates code to check constraints. NOT NULL,
1147** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +00001148** then the appropriate action is performed. There are five possible
1149** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +00001150**
1151** Constraint type Action What Happens
1152** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +00001153** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +00001154** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +00001155** return code of SQLITE_CONSTRAINT.
1156**
drh1c928532002-01-31 15:54:21 +00001157** any ABORT Back out changes from the current command
1158** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +00001159** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +00001160** with SQLITE_CONSTRAINT.
1161**
drhe4c88c02012-01-04 12:57:45 +00001162** any FAIL Sqlite3_exec() returns immediately with a
drh1c928532002-01-31 15:54:21 +00001163** return code of SQLITE_CONSTRAINT. The
1164** transaction is not rolled back and any
1165** prior changes are retained.
1166**
drh9cfcf5d2002-01-29 18:41:24 +00001167** any IGNORE The record number and data is popped from
1168** the stack and there is an immediate jump
1169** to label ignoreDest.
1170**
1171** NOT NULL REPLACE The NULL value is replace by the default
1172** value for that column. If the default value
1173** is NULL, the action is the same as ABORT.
1174**
1175** UNIQUE REPLACE The other row that conflicts with the row
1176** being inserted is removed.
1177**
1178** CHECK REPLACE Illegal. The results in an exception.
1179**
drh1c928532002-01-31 15:54:21 +00001180** Which action to take is determined by the overrideError parameter.
1181** Or if overrideError==OE_Default, then the pParse->onError parameter
1182** is used. Or if pParse->onError==OE_Default then the onError value
1183** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001184**
drhaaab5722002-02-19 13:39:21 +00001185** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +00001186** cursor number "baseCur". All indices of pTab must also have open
1187** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001188** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001189** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001190*/
danielk19774adee202004-05-08 08:23:19 +00001191void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001192 Parse *pParse, /* The parser context */
1193 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001194 int baseCur, /* Index of a read/write cursor pointing at pTab */
1195 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001196 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drha05a7222008-01-19 03:35:58 +00001197 int rowidChng, /* True if the rowid might collide with existing entry */
drhb419a922002-01-30 16:17:23 +00001198 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001199 int overrideError, /* Override onError to this if not OE_Default */
danielk1977de630352009-05-04 11:42:29 +00001200 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1201 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
drh9cfcf5d2002-01-29 18:41:24 +00001202){
drh1b7ecbb2009-05-03 01:00:59 +00001203 int i; /* loop counter */
1204 Vdbe *v; /* VDBE under constrution */
1205 int nCol; /* Number of columns */
1206 int onError; /* Conflict resolution strategy */
drh1bd10f82008-12-10 21:19:56 +00001207 int j1; /* Addresss of jump instruction */
1208 int j2 = 0, j3; /* Addresses of jump instructions */
drh04adf412008-01-08 18:57:50 +00001209 int regData; /* Register containing first data column */
drh1b7ecbb2009-05-03 01:00:59 +00001210 int iCur; /* Table cursor number */
1211 Index *pIdx; /* Pointer to one of the indices */
drh2938f922012-03-07 19:13:29 +00001212 sqlite3 *db; /* Database connection */
drh1b7ecbb2009-05-03 01:00:59 +00001213 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
dan65a7cd12009-09-01 12:16:01 +00001214 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
drh9cfcf5d2002-01-29 18:41:24 +00001215
drh2938f922012-03-07 19:13:29 +00001216 db = pParse->db;
danielk19774adee202004-05-08 08:23:19 +00001217 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001218 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001219 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001220 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001221 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001222
1223 /* Test all NOT NULL constraints.
1224 */
1225 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001226 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001227 continue;
1228 }
drh9cfcf5d2002-01-29 18:41:24 +00001229 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001230 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001231 if( overrideError!=OE_Default ){
1232 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001233 }else if( onError==OE_Default ){
1234 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001235 }
danielk19777977a172004-11-09 12:44:37 +00001236 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001237 onError = OE_Abort;
1238 }
danielk1977b84f96f2005-01-20 11:32:23 +00001239 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1240 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001241 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001242 case OE_Abort:
dane0af83a2009-09-08 19:15:01 +00001243 sqlite3MayAbort(pParse);
1244 case OE_Rollback:
drh1c928532002-01-31 15:54:21 +00001245 case OE_Fail: {
drhf089aa42008-07-08 19:34:06 +00001246 char *zMsg;
drhc126e632011-03-06 21:28:32 +00001247 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
drhd91c1a12013-02-09 13:58:25 +00001248 SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
drh2938f922012-03-07 19:13:29 +00001249 zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
drhf089aa42008-07-08 19:34:06 +00001250 pTab->zName, pTab->aCol[i].zName);
drh66a51672008-01-03 00:01:23 +00001251 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001252 break;
1253 }
1254 case OE_Ignore: {
drh5053a792009-02-20 03:02:23 +00001255 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001256 break;
1257 }
drh098d1682009-05-02 15:46:46 +00001258 default: {
1259 assert( onError==OE_Replace );
drh5053a792009-02-20 03:02:23 +00001260 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
drh04adf412008-01-08 18:57:50 +00001261 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh5053a792009-02-20 03:02:23 +00001262 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001263 break;
1264 }
drh9cfcf5d2002-01-29 18:41:24 +00001265 }
1266 }
1267
1268 /* Test all CHECK constraints
1269 */
drhffe07b22005-11-03 00:41:17 +00001270#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +00001271 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1272 ExprList *pCheck = pTab->pCheck;
drhaa9b8962008-01-08 02:57:55 +00001273 pParse->ckBase = regData;
drhaa01c7e2006-03-15 16:26:10 +00001274 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2938f922012-03-07 19:13:29 +00001275 for(i=0; i<pCheck->nExpr; i++){
1276 int allOk = sqlite3VdbeMakeLabel(v);
drh2d8e9202012-12-08 04:10:44 +00001277 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
1278 if( onError==OE_Ignore ){
1279 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1280 }else{
1281 char *zConsName = pCheck->a[i].zName;
1282 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1283 if( zConsName ){
1284 zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
drh2938f922012-03-07 19:13:29 +00001285 }else{
drh2d8e9202012-12-08 04:10:44 +00001286 zConsName = 0;
drh2938f922012-03-07 19:13:29 +00001287 }
drhd91c1a12013-02-09 13:58:25 +00001288 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1289 onError, zConsName, P4_DYNAMIC);
drh2938f922012-03-07 19:13:29 +00001290 }
drh2d8e9202012-12-08 04:10:44 +00001291 sqlite3VdbeResolveLabel(v, allOk);
drhaa01c7e2006-03-15 16:26:10 +00001292 }
drhffe07b22005-11-03 00:41:17 +00001293 }
1294#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001295
drh0bd1f4e2002-06-06 18:54:39 +00001296 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1297 ** of the new record does not previously exist. Except, if this
1298 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001299 */
drhf0863fe2005-06-12 21:35:51 +00001300 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001301 onError = pTab->keyConf;
1302 if( overrideError!=OE_Default ){
1303 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001304 }else if( onError==OE_Default ){
1305 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001306 }
drha0217ba2003-06-01 01:10:33 +00001307
dane1e2ae22009-09-24 16:52:28 +00001308 if( isUpdate ){
1309 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
1310 }
1311 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1312 switch( onError ){
1313 default: {
1314 onError = OE_Abort;
1315 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001316 }
dane1e2ae22009-09-24 16:52:28 +00001317 case OE_Rollback:
1318 case OE_Abort:
1319 case OE_Fail: {
drhd91c1a12013-02-09 13:58:25 +00001320 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1321 onError, "PRIMARY KEY must be unique", P4_STATIC);
dane1e2ae22009-09-24 16:52:28 +00001322 break;
drh0ca3e242002-01-29 23:07:02 +00001323 }
dane1e2ae22009-09-24 16:52:28 +00001324 case OE_Replace: {
1325 /* If there are DELETE triggers on this table and the
1326 ** recursive-triggers flag is set, call GenerateRowDelete() to
mistachkind5578432012-08-25 10:01:29 +00001327 ** remove the conflicting row from the table. This will fire
dane1e2ae22009-09-24 16:52:28 +00001328 ** the triggers and remove both the table and index b-tree entries.
1329 **
1330 ** Otherwise, if there are no triggers or the recursive-triggers
danda730f62010-02-18 08:19:19 +00001331 ** flag is not set, but the table has one or more indexes, call
1332 ** GenerateRowIndexDelete(). This removes the index b-tree entries
1333 ** only. The table b-tree entry will be replaced by the new entry
1334 ** when it is inserted.
1335 **
1336 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1337 ** also invoke MultiWrite() to indicate that this VDBE may require
1338 ** statement rollback (if the statement is aborted after the delete
1339 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1340 ** but being more selective here allows statements like:
1341 **
1342 ** REPLACE INTO t(rowid) VALUES($newrowid)
1343 **
1344 ** to run without a statement journal if there are no indexes on the
1345 ** table.
1346 */
dane1e2ae22009-09-24 16:52:28 +00001347 Trigger *pTrigger = 0;
drh2938f922012-03-07 19:13:29 +00001348 if( db->flags&SQLITE_RecTriggers ){
dane1e2ae22009-09-24 16:52:28 +00001349 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1350 }
dane7a94d82009-10-01 16:09:04 +00001351 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
danda730f62010-02-18 08:19:19 +00001352 sqlite3MultiWrite(pParse);
dane1e2ae22009-09-24 16:52:28 +00001353 sqlite3GenerateRowDelete(
1354 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
1355 );
danda730f62010-02-18 08:19:19 +00001356 }else if( pTab->pIndex ){
1357 sqlite3MultiWrite(pParse);
dane1e2ae22009-09-24 16:52:28 +00001358 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1359 }
1360 seenReplace = 1;
1361 break;
drh5383ae52003-06-04 12:23:30 +00001362 }
dane1e2ae22009-09-24 16:52:28 +00001363 case OE_Ignore: {
1364 assert( seenReplace==0 );
1365 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1366 break;
1367 }
1368 }
1369 sqlite3VdbeJumpHere(v, j3);
1370 if( isUpdate ){
1371 sqlite3VdbeJumpHere(v, j2);
drh5383ae52003-06-04 12:23:30 +00001372 }
drh0ca3e242002-01-29 23:07:02 +00001373 }
drh0bd1f4e2002-06-06 18:54:39 +00001374
1375 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1376 ** index and making sure that duplicate entries do not already exist.
1377 ** Add the new records to the indices as we go.
1378 */
drhb2fe7d82003-04-20 17:29:23 +00001379 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001380 int regIdx;
1381 int regR;
drhb2b9d3d2013-08-01 01:14:43 +00001382 int addrSkipRow = 0;
drh2184fc72011-04-09 03:04:13 +00001383
drhaa9b8962008-01-08 02:57:55 +00001384 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001385
drhb2b9d3d2013-08-01 01:14:43 +00001386 if( pIdx->pPartIdxWhere ){
1387 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
1388 addrSkipRow = sqlite3VdbeMakeLabel(v);
1389 pParse->ckBase = regData;
1390 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
1391 SQLITE_JUMPIFNULL);
1392 pParse->ckBase = 0;
1393 }
1394
drhb2fe7d82003-04-20 17:29:23 +00001395 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001396 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001397 for(i=0; i<pIdx->nColumn; i++){
1398 int idx = pIdx->aiColumn[i];
1399 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001400 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001401 }else{
drh2d401ab2008-01-10 23:50:11 +00001402 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001403 }
1404 }
drh2d401ab2008-01-10 23:50:11 +00001405 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh1db639c2008-01-17 02:36:28 +00001406 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
drh8d129422011-04-05 12:25:19 +00001407 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
drhda250ea2008-04-01 05:07:14 +00001408 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001409
1410 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001411 onError = pIdx->onError;
danielk1977de630352009-05-04 11:42:29 +00001412 if( onError==OE_None ){
1413 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drh8a9789b2013-08-01 03:36:59 +00001414 sqlite3VdbeResolveLabel(v, addrSkipRow);
danielk1977de630352009-05-04 11:42:29 +00001415 continue; /* pIdx is not a UNIQUE index */
1416 }
drh9cfcf5d2002-01-29 18:41:24 +00001417 if( overrideError!=OE_Default ){
1418 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001419 }else if( onError==OE_Default ){
1420 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001421 }
drh5383ae52003-06-04 12:23:30 +00001422 if( seenReplace ){
1423 if( onError==OE_Ignore ) onError = OE_Replace;
1424 else if( onError==OE_Fail ) onError = OE_Abort;
1425 }
1426
drhb2fe7d82003-04-20 17:29:23 +00001427 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001428 regR = sqlite3GetTempReg(pParse);
dan65a7cd12009-09-01 12:16:01 +00001429 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
drh2d401ab2008-01-10 23:50:11 +00001430 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
danielk1977de630352009-05-04 11:42:29 +00001431 regR, SQLITE_INT_TO_PTR(regIdx),
mlcreecha9e852b2008-03-06 09:58:50 +00001432 P4_INT32);
danielk1977de630352009-05-04 11:42:29 +00001433 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001434
1435 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001436 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1437 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001438 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001439 case OE_Rollback:
1440 case OE_Abort:
1441 case OE_Fail: {
drh098d1682009-05-02 15:46:46 +00001442 int j;
1443 StrAccum errMsg;
1444 const char *zSep;
1445 char *zErr;
1446
1447 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
drh2938f922012-03-07 19:13:29 +00001448 errMsg.db = db;
drh098d1682009-05-02 15:46:46 +00001449 zSep = pIdx->nColumn>1 ? "columns " : "column ";
1450 for(j=0; j<pIdx->nColumn; j++){
drh37ed48e2003-08-05 13:13:38 +00001451 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
drh098d1682009-05-02 15:46:46 +00001452 sqlite3StrAccumAppend(&errMsg, zSep, -1);
1453 zSep = ", ";
1454 sqlite3StrAccumAppend(&errMsg, zCol, -1);
drh37ed48e2003-08-05 13:13:38 +00001455 }
drh098d1682009-05-02 15:46:46 +00001456 sqlite3StrAccumAppend(&errMsg,
1457 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
1458 zErr = sqlite3StrAccumFinish(&errMsg);
drhd91c1a12013-02-09 13:58:25 +00001459 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
1460 onError, zErr, 0);
drh098d1682009-05-02 15:46:46 +00001461 sqlite3DbFree(errMsg.db, zErr);
drh9cfcf5d2002-01-29 18:41:24 +00001462 break;
1463 }
1464 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001465 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001466 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001467 break;
1468 }
drh098d1682009-05-02 15:46:46 +00001469 default: {
dan2283d462009-09-08 15:55:15 +00001470 Trigger *pTrigger = 0;
drh098d1682009-05-02 15:46:46 +00001471 assert( onError==OE_Replace );
dan1bea5592009-09-24 11:31:21 +00001472 sqlite3MultiWrite(pParse);
drh2938f922012-03-07 19:13:29 +00001473 if( db->flags&SQLITE_RecTriggers ){
dan2283d462009-09-08 15:55:15 +00001474 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1475 }
1476 sqlite3GenerateRowDelete(
1477 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
1478 );
drh0ca3e242002-01-29 23:07:02 +00001479 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001480 break;
1481 }
drh9cfcf5d2002-01-29 18:41:24 +00001482 }
drh2d401ab2008-01-10 23:50:11 +00001483 sqlite3VdbeJumpHere(v, j3);
drhb2b9d3d2013-08-01 01:14:43 +00001484 sqlite3VdbeResolveLabel(v, addrSkipRow);
drh2d401ab2008-01-10 23:50:11 +00001485 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001486 }
dan1da40a32009-09-19 17:00:31 +00001487
danielk1977de630352009-05-04 11:42:29 +00001488 if( pbMayReplace ){
1489 *pbMayReplace = seenReplace;
1490 }
drh9cfcf5d2002-01-29 18:41:24 +00001491}
drh0ca3e242002-01-29 23:07:02 +00001492
1493/*
1494** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001495** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001496** A consecutive range of registers starting at regRowid contains the
1497** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001498**
drhb419a922002-01-30 16:17:23 +00001499** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001500** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001501*/
danielk19774adee202004-05-08 08:23:19 +00001502void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001503 Parse *pParse, /* The parser context */
1504 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001505 int baseCur, /* Index of a read/write cursor pointing at pTab */
1506 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001507 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh70ce3f02003-04-15 19:22:22 +00001508 int isUpdate, /* True for UPDATE, False for INSERT */
danielk1977de630352009-05-04 11:42:29 +00001509 int appendBias, /* True if this is likely to be an append */
1510 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
drh0ca3e242002-01-29 23:07:02 +00001511){
1512 int i;
1513 Vdbe *v;
drh0ca3e242002-01-29 23:07:02 +00001514 Index *pIdx;
drh1bd10f82008-12-10 21:19:56 +00001515 u8 pik_flags;
drh04adf412008-01-08 18:57:50 +00001516 int regData;
drhb7654112008-01-12 12:48:07 +00001517 int regRec;
drh0ca3e242002-01-29 23:07:02 +00001518
danielk19774adee202004-05-08 08:23:19 +00001519 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001520 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001521 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drhb2b9d3d2013-08-01 01:14:43 +00001522 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
drhaa9b8962008-01-08 02:57:55 +00001523 if( aRegIdx[i]==0 ) continue;
drhb2b9d3d2013-08-01 01:14:43 +00001524 if( pIdx->pPartIdxWhere ){
1525 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1526 }
drh04adf412008-01-08 18:57:50 +00001527 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
danielk1977de630352009-05-04 11:42:29 +00001528 if( useSeekResult ){
1529 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1530 }
drh0ca3e242002-01-29 23:07:02 +00001531 }
drh04adf412008-01-08 18:57:50 +00001532 regData = regRowid + 1;
drhb7654112008-01-12 12:48:07 +00001533 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001534 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +00001535 sqlite3TableAffinityStr(v, pTab);
drhda250ea2008-04-01 05:07:14 +00001536 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
drh4794f732004-11-05 17:17:50 +00001537 if( pParse->nested ){
1538 pik_flags = 0;
1539 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001540 pik_flags = OPFLAG_NCHANGE;
1541 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001542 }
drhe4d90812007-03-29 05:51:49 +00001543 if( appendBias ){
1544 pik_flags |= OPFLAG_APPEND;
1545 }
danielk1977de630352009-05-04 11:42:29 +00001546 if( useSeekResult ){
1547 pik_flags |= OPFLAG_USESEEKRESULT;
1548 }
drhb7654112008-01-12 12:48:07 +00001549 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
danielk197794eb6a12005-12-15 15:22:08 +00001550 if( !pParse->nested ){
drh8d129422011-04-05 12:25:19 +00001551 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
danielk197794eb6a12005-12-15 15:22:08 +00001552 }
drhb7654112008-01-12 12:48:07 +00001553 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001554}
drhcd446902004-02-24 01:05:31 +00001555
1556/*
drh290c1942004-08-21 17:54:45 +00001557** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001558** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001559** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001560**
1561** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001562*/
drhaa9b8962008-01-08 02:57:55 +00001563int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001564 Parse *pParse, /* Parsing context */
1565 Table *pTab, /* Table to be opened */
drhdfe88ec2008-11-03 20:55:06 +00001566 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001567 int op /* OP_OpenRead or OP_OpenWrite */
1568){
drhcd446902004-02-24 01:05:31 +00001569 int i;
drh4cbdda92006-06-14 19:00:20 +00001570 int iDb;
drhcd446902004-02-24 01:05:31 +00001571 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001572 Vdbe *v;
1573
drhaa9b8962008-01-08 02:57:55 +00001574 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001575 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1576 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001577 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001578 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001579 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001580 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001581 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001582 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001583 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001584 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001585 }
drh1b7ecbb2009-05-03 01:00:59 +00001586 if( pParse->nTab<baseCur+i ){
drh04adf412008-01-08 18:57:50 +00001587 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001588 }
drhaa9b8962008-01-08 02:57:55 +00001589 return i-1;
drhcd446902004-02-24 01:05:31 +00001590}
drh9d9cf222007-02-13 15:01:11 +00001591
drh91c58e22007-03-27 12:04:04 +00001592
1593#ifdef SQLITE_TEST
1594/*
1595** The following global variable is incremented whenever the
1596** transfer optimization is used. This is used for testing
1597** purposes only - to make sure the transfer optimization really
1598** is happening when it is suppose to.
1599*/
1600int sqlite3_xferopt_count;
1601#endif /* SQLITE_TEST */
1602
1603
drh9d9cf222007-02-13 15:01:11 +00001604#ifndef SQLITE_OMIT_XFER_OPT
1605/*
1606** Check to collation names to see if they are compatible.
1607*/
1608static int xferCompatibleCollation(const char *z1, const char *z2){
1609 if( z1==0 ){
1610 return z2==0;
1611 }
1612 if( z2==0 ){
1613 return 0;
1614 }
1615 return sqlite3StrICmp(z1, z2)==0;
1616}
1617
1618
1619/*
1620** Check to see if index pSrc is compatible as a source of data
1621** for index pDest in an insert transfer optimization. The rules
1622** for a compatible index:
1623**
1624** * The index is over the same set of columns
1625** * The same DESC and ASC markings occurs on all columns
1626** * The same onError processing (OE_Abort, OE_Ignore, etc)
1627** * The same collating sequence on each column
drhb2b9d3d2013-08-01 01:14:43 +00001628** * The index has the exact same WHERE clause
drh9d9cf222007-02-13 15:01:11 +00001629*/
1630static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1631 int i;
1632 assert( pDest && pSrc );
1633 assert( pDest->pTable!=pSrc->pTable );
1634 if( pDest->nColumn!=pSrc->nColumn ){
1635 return 0; /* Different number of columns */
1636 }
1637 if( pDest->onError!=pSrc->onError ){
1638 return 0; /* Different conflict resolution strategies */
1639 }
1640 for(i=0; i<pSrc->nColumn; i++){
1641 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1642 return 0; /* Different columns indexed */
1643 }
1644 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1645 return 0; /* Different sort orders */
1646 }
drh3f6e7812009-05-02 00:28:19 +00001647 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
drh60a713c2008-01-21 16:22:45 +00001648 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001649 }
1650 }
drh619a1302013-08-01 13:04:46 +00001651 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
drhb2b9d3d2013-08-01 01:14:43 +00001652 return 0; /* Different WHERE clauses */
1653 }
drh9d9cf222007-02-13 15:01:11 +00001654
1655 /* If no test above fails then the indices must be compatible */
1656 return 1;
1657}
1658
1659/*
1660** Attempt the transfer optimization on INSERTs of the form
1661**
1662** INSERT INTO tab1 SELECT * FROM tab2;
1663**
drhccdf1ba2011-11-04 14:36:02 +00001664** The xfer optimization transfers raw records from tab2 over to tab1.
1665** Columns are not decoded and reassemblied, which greatly improves
1666** performance. Raw index records are transferred in the same way.
drh9d9cf222007-02-13 15:01:11 +00001667**
drhccdf1ba2011-11-04 14:36:02 +00001668** The xfer optimization is only attempted if tab1 and tab2 are compatible.
1669** There are lots of rules for determining compatibility - see comments
1670** embedded in the code for details.
drh9d9cf222007-02-13 15:01:11 +00001671**
drhccdf1ba2011-11-04 14:36:02 +00001672** This routine returns TRUE if the optimization is guaranteed to be used.
1673** Sometimes the xfer optimization will only work if the destination table
1674** is empty - a factor that can only be determined at run-time. In that
1675** case, this routine generates code for the xfer optimization but also
1676** does a test to see if the destination table is empty and jumps over the
1677** xfer optimization code if the test fails. In that case, this routine
1678** returns FALSE so that the caller will know to go ahead and generate
1679** an unoptimized transfer. This routine also returns FALSE if there
1680** is no chance that the xfer optimization can be applied.
drh9d9cf222007-02-13 15:01:11 +00001681**
drhccdf1ba2011-11-04 14:36:02 +00001682** This optimization is particularly useful at making VACUUM run faster.
drh9d9cf222007-02-13 15:01:11 +00001683*/
1684static int xferOptimization(
1685 Parse *pParse, /* Parser context */
1686 Table *pDest, /* The table we are inserting into */
1687 Select *pSelect, /* A SELECT statement to use as the data source */
1688 int onError, /* How to handle constraint errors */
1689 int iDbDest /* The database of pDest */
1690){
1691 ExprList *pEList; /* The result set of the SELECT */
1692 Table *pSrc; /* The table in the FROM clause of SELECT */
1693 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1694 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1695 int i; /* Loop counter */
1696 int iDbSrc; /* The database of pSrc */
1697 int iSrc, iDest; /* Cursors from source and destination */
1698 int addr1, addr2; /* Loop addresses */
1699 int emptyDestTest; /* Address of test for empty pDest */
1700 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001701 Vdbe *v; /* The VDBE we are building */
1702 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001703 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001704 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001705 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001706
1707 if( pSelect==0 ){
1708 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1709 }
danielk19772f886d12009-02-28 10:47:41 +00001710 if( sqlite3TriggerList(pParse, pDest) ){
drh9d9cf222007-02-13 15:01:11 +00001711 return 0; /* tab1 must not have triggers */
1712 }
1713#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001714 if( pDest->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001715 return 0; /* tab1 must not be a virtual table */
1716 }
1717#endif
1718 if( onError==OE_Default ){
drhe7224a02011-11-04 00:23:53 +00001719 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
1720 if( onError==OE_Default ) onError = OE_Abort;
drh9d9cf222007-02-13 15:01:11 +00001721 }
danielk19775ce240a2007-09-03 17:30:06 +00001722 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001723 if( pSelect->pSrc->nSrc!=1 ){
1724 return 0; /* FROM clause must have exactly one term */
1725 }
1726 if( pSelect->pSrc->a[0].pSelect ){
1727 return 0; /* FROM clause cannot contain a subquery */
1728 }
1729 if( pSelect->pWhere ){
1730 return 0; /* SELECT may not have a WHERE clause */
1731 }
1732 if( pSelect->pOrderBy ){
1733 return 0; /* SELECT may not have an ORDER BY clause */
1734 }
drh8103b7d2007-02-24 13:23:51 +00001735 /* Do not need to test for a HAVING clause. If HAVING is present but
1736 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001737 if( pSelect->pGroupBy ){
1738 return 0; /* SELECT may not have a GROUP BY clause */
1739 }
1740 if( pSelect->pLimit ){
1741 return 0; /* SELECT may not have a LIMIT clause */
1742 }
drh8103b7d2007-02-24 13:23:51 +00001743 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001744 if( pSelect->pPrior ){
1745 return 0; /* SELECT may not be a compound query */
1746 }
drh7d10d5a2008-08-20 16:35:10 +00001747 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:11 +00001748 return 0; /* SELECT may not be DISTINCT */
1749 }
1750 pEList = pSelect->pEList;
1751 assert( pEList!=0 );
1752 if( pEList->nExpr!=1 ){
1753 return 0; /* The result set must have exactly one column */
1754 }
1755 assert( pEList->a[0].pExpr );
1756 if( pEList->a[0].pExpr->op!=TK_ALL ){
1757 return 0; /* The result set must be the special operator "*" */
1758 }
1759
1760 /* At this point we have established that the statement is of the
1761 ** correct syntactic form to participate in this optimization. Now
1762 ** we have to check the semantics.
1763 */
1764 pItem = pSelect->pSrc->a;
dan41fb5cd2012-10-04 19:33:00 +00001765 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
drh9d9cf222007-02-13 15:01:11 +00001766 if( pSrc==0 ){
1767 return 0; /* FROM clause does not contain a real table */
1768 }
1769 if( pSrc==pDest ){
1770 return 0; /* tab1 and tab2 may not be the same table */
1771 }
1772#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001773 if( pSrc->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001774 return 0; /* tab2 must not be a virtual table */
1775 }
1776#endif
1777 if( pSrc->pSelect ){
1778 return 0; /* tab2 may not be a view */
1779 }
1780 if( pDest->nCol!=pSrc->nCol ){
1781 return 0; /* Number of columns must be the same in tab1 and tab2 */
1782 }
1783 if( pDest->iPKey!=pSrc->iPKey ){
1784 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1785 }
1786 for(i=0; i<pDest->nCol; i++){
1787 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1788 return 0; /* Affinity must be the same on all columns */
1789 }
1790 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1791 return 0; /* Collating sequence must be the same on all columns */
1792 }
1793 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1794 return 0; /* tab2 must be NOT NULL if tab1 is */
1795 }
1796 }
1797 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001798 if( pDestIdx->onError!=OE_None ){
1799 destHasUniqueIdx = 1;
1800 }
drh9d9cf222007-02-13 15:01:11 +00001801 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1802 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1803 }
1804 if( pSrcIdx==0 ){
1805 return 0; /* pDestIdx has no corresponding index in pSrc */
1806 }
1807 }
drh7fc2f412007-03-29 00:08:24 +00001808#ifndef SQLITE_OMIT_CHECK
drh619a1302013-08-01 13:04:46 +00001809 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
drh8103b7d2007-02-24 13:23:51 +00001810 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1811 }
drh7fc2f412007-03-29 00:08:24 +00001812#endif
drh713de342011-04-24 22:56:07 +00001813#ifndef SQLITE_OMIT_FOREIGN_KEY
1814 /* Disallow the transfer optimization if the destination table constains
1815 ** any foreign key constraints. This is more restrictive than necessary.
1816 ** But the main beneficiary of the transfer optimization is the VACUUM
1817 ** command, and the VACUUM command disables foreign key constraints. So
1818 ** the extra complication to make this rule less restrictive is probably
1819 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1820 */
1821 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1822 return 0;
1823 }
1824#endif
dan16961242011-09-30 12:01:01 +00001825 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
drhccdf1ba2011-11-04 14:36:02 +00001826 return 0; /* xfer opt does not play well with PRAGMA count_changes */
dan16961242011-09-30 12:01:01 +00001827 }
drh9d9cf222007-02-13 15:01:11 +00001828
drhccdf1ba2011-11-04 14:36:02 +00001829 /* If we get this far, it means that the xfer optimization is at
1830 ** least a possibility, though it might only work if the destination
1831 ** table (tab1) is initially empty.
drh9d9cf222007-02-13 15:01:11 +00001832 */
drhdd735212007-02-24 13:53:05 +00001833#ifdef SQLITE_TEST
1834 sqlite3_xferopt_count++;
1835#endif
drh9d9cf222007-02-13 15:01:11 +00001836 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1837 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001838 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001839 iSrc = pParse->nTab++;
1840 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001841 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001842 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhccdf1ba2011-11-04 14:36:02 +00001843 if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
1844 || destHasUniqueIdx /* (2) */
1845 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
1846 ){
1847 /* In some circumstances, we are able to run the xfer optimization
1848 ** only if the destination table is initially empty. This code makes
1849 ** that determination. Conditions under which the destination must
1850 ** be empty:
drhf33c9fa2007-04-10 18:17:55 +00001851 **
drhccdf1ba2011-11-04 14:36:02 +00001852 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
1853 ** (If the destination is not initially empty, the rowid fields
1854 ** of index entries might need to change.)
1855 **
1856 ** (2) The destination has a unique index. (The xfer optimization
1857 ** is unable to test uniqueness.)
1858 **
1859 ** (3) onError is something other than OE_Abort and OE_Rollback.
drh9d9cf222007-02-13 15:01:11 +00001860 */
drh66a51672008-01-03 00:01:23 +00001861 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1862 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001863 sqlite3VdbeJumpHere(v, addr1);
1864 }else{
1865 emptyDestTest = 0;
1866 }
1867 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001868 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001869 regData = sqlite3GetTempReg(pParse);
1870 regRowid = sqlite3GetTempReg(pParse);
drh42242de2007-03-29 13:35:35 +00001871 if( pDest->iPKey>=0 ){
drhb7654112008-01-12 12:48:07 +00001872 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1873 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
drhd91c1a12013-02-09 13:58:25 +00001874 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
1875 onError, "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001876 sqlite3VdbeJumpHere(v, addr2);
drhb7654112008-01-12 12:48:07 +00001877 autoIncStep(pParse, regAutoinc, regRowid);
drhbd36ba62007-03-31 13:00:26 +00001878 }else if( pDest->pIndex==0 ){
drhb7654112008-01-12 12:48:07 +00001879 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
drh95bad4c2007-03-28 18:04:10 +00001880 }else{
drhb7654112008-01-12 12:48:07 +00001881 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
drh7d10d5a2008-08-20 16:35:10 +00001882 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
drh95bad4c2007-03-28 18:04:10 +00001883 }
drhb7654112008-01-12 12:48:07 +00001884 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1885 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1886 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
danielk19771f4aa332008-01-03 09:51:55 +00001887 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001888 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh9d9cf222007-02-13 15:01:11 +00001889 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh1b7ecbb2009-05-03 01:00:59 +00001890 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
drh9d9cf222007-02-13 15:01:11 +00001891 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1892 }
1893 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001894 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1895 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001896 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001897 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1898 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001899 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001900 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001901 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001902 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001903 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001904 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001905 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1906 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh66a51672008-01-03 00:01:23 +00001907 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001908 sqlite3VdbeJumpHere(v, addr1);
1909 }
1910 sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00001911 sqlite3ReleaseTempReg(pParse, regRowid);
1912 sqlite3ReleaseTempReg(pParse, regData);
drh66a51672008-01-03 00:01:23 +00001913 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1914 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001915 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001916 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001917 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001918 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001919 return 0;
1920 }else{
1921 return 1;
1922 }
1923}
1924#endif /* SQLITE_OMIT_XFER_OPT */