blob: 452939db942f2b41006374df75c9edd51b3abe00 [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;
28 if( IsVirtual(pTab) ) return;
29 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**
50** An extra 'b' is appended to the end of the string to cover the
51** 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 }
drh2d401ab2008-01-10 23:50:11 +000078 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
79 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);
242 addr = sqlite3VdbeCurrentAddr(v);
243 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
244 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
245 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
246 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
247 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
248 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
249 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
250 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
251 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
252 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
253 sqlite3VdbeAddOp0(v, OP_Close);
254 }
255}
256
257/*
drh9d9cf222007-02-13 15:01:11 +0000258** Update the maximum rowid for an autoincrement calculation.
259**
260** This routine should be called when the top of the stack holds a
261** new rowid that is about to be inserted. If that new rowid is
262** larger than the maximum rowid in the memId memory cell, then the
263** memory cell is updated. The stack is unchanged.
264*/
drh6a288a32008-01-07 19:20:24 +0000265static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000266 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000267 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000268 }
269}
270
271/*
drh0b9f50d2009-06-23 20:28:53 +0000272** This routine generates the code needed to write autoincrement
273** maximum rowid values back into the sqlite_sequence register.
274** Every statement that might do an INSERT into an autoincrement
275** table (either directly or through triggers) needs to call this
276** routine just before the "exit" code.
drh9d9cf222007-02-13 15:01:11 +0000277*/
drh0b9f50d2009-06-23 20:28:53 +0000278void sqlite3AutoincrementEnd(Parse *pParse){
279 AutoincInfo *p;
280 Vdbe *v = pParse->pVdbe;
281 sqlite3 *db = pParse->db;
drh6a288a32008-01-07 19:20:24 +0000282
drh0b9f50d2009-06-23 20:28:53 +0000283 assert( v );
284 for(p = pParse->pAinc; p; p = p->pNext){
285 Db *pDb = &db->aDb[p->iDb];
286 int j1, j2, j3, j4, j5;
287 int iRec;
288 int memId = p->regCtr;
289
290 iRec = sqlite3GetTempReg(pParse);
drh21206082011-04-04 18:22:02 +0000291 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drh0b9f50d2009-06-23 20:28:53 +0000292 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000293 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
drh0b9f50d2009-06-23 20:28:53 +0000294 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
295 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
296 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
297 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
298 sqlite3VdbeJumpHere(v, j2);
299 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
300 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
301 sqlite3VdbeJumpHere(v, j4);
302 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
drh6a288a32008-01-07 19:20:24 +0000303 sqlite3VdbeJumpHere(v, j1);
drh0b9f50d2009-06-23 20:28:53 +0000304 sqlite3VdbeJumpHere(v, j5);
danielk1977a7a8e142008-02-13 18:25:27 +0000305 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
drh0b9f50d2009-06-23 20:28:53 +0000306 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
drh35573352008-01-08 23:54:25 +0000307 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh0b9f50d2009-06-23 20:28:53 +0000308 sqlite3VdbeAddOp0(v, OP_Close);
309 sqlite3ReleaseTempReg(pParse, iRec);
drh9d9cf222007-02-13 15:01:11 +0000310 }
311}
312#else
313/*
314** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
315** above are all no-ops
316*/
317# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000318# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000319#endif /* SQLITE_OMIT_AUTOINCREMENT */
320
321
322/* Forward declaration */
323static int xferOptimization(
324 Parse *pParse, /* Parser context */
325 Table *pDest, /* The table we are inserting into */
326 Select *pSelect, /* A SELECT statement to use as the data source */
327 int onError, /* How to handle constraint errors */
328 int iDbDest /* The database of pDest */
329);
330
danielk19773d1bfea2004-05-14 11:00:53 +0000331/*
drh1ccde152000-06-17 13:12:39 +0000332** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000333**
334** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000335** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000336**
drh1ccde152000-06-17 13:12:39 +0000337** The IDLIST following the table name is always optional. If omitted,
338** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000339** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000340**
341** The pList parameter holds EXPRLIST in the first form of the INSERT
342** statement above, and pSelect is NULL. For the second form, pList is
343** NULL and pSelect is a pointer to the select statement used to generate
344** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000345**
drh9d9cf222007-02-13 15:01:11 +0000346** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000347** select with data coming from a VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01 +0000348** once straight down through. Pseudo-code follows (we call this
349** the "1st template"):
drh142e30d2002-08-28 03:00:58 +0000350**
351** open write cursor to <table> and its indices
352** puts VALUES clause expressions onto the stack
353** write the resulting record into <table>
354** cleanup
355**
drh9d9cf222007-02-13 15:01:11 +0000356** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000357**
358** INSERT INTO <table> SELECT ...
359**
drh9d9cf222007-02-13 15:01:11 +0000360** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
361** in other words if the SELECT pulls all columns from a single table
362** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
363** if <table2> and <table1> are distinct tables but have identical
364** schemas, including all the same indices, then a special optimization
365** is invoked that copies raw records from <table2> over to <table1>.
366** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01 +0000367** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000368**
369** open a write cursor to <table>
370** open read cursor on <table2>
371** transfer all records in <table2> over to <table>
372** close cursors
373** foreach index on <table>
374** open a write cursor on the <table> index
375** open a read cursor on the corresponding <table2> index
376** transfer all records from the read to the write cursors
377** close cursors
378** end foreach
379**
drhe00ee6e2008-06-20 15:24:01 +0000380** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11 +0000381** and the SELECT clause does not read from <table> at any time.
382** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000383**
drhe00ee6e2008-06-20 15:24:01 +0000384** EOF <- 0
385** X <- A
drh142e30d2002-08-28 03:00:58 +0000386** goto B
387** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000388** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000389** load values into registers R..R+n
390** yield X
drh142e30d2002-08-28 03:00:58 +0000391** end loop
392** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000393** EOF <- 1
394** yield X
drh142e30d2002-08-28 03:00:58 +0000395** goto A
drhe00ee6e2008-06-20 15:24:01 +0000396** B: open write cursor to <table> and its indices
397** C: yield X
398** if EOF goto D
399** insert the select result into <table> from R..R+n
400** goto C
drh142e30d2002-08-28 03:00:58 +0000401** D: cleanup
402**
drhe00ee6e2008-06-20 15:24:01 +0000403** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000404** values from a SELECT but the data is being inserted into a table
405** that is also read as part of the SELECT. In the third form,
406** we have to use a intermediate table to store the results of
407** the select. The template is like this:
408**
drhe00ee6e2008-06-20 15:24:01 +0000409** EOF <- 0
410** X <- A
drh142e30d2002-08-28 03:00:58 +0000411** goto B
412** A: setup for the SELECT
413** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000414** load value into register R..R+n
415** yield X
drh142e30d2002-08-28 03:00:58 +0000416** end loop
417** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000418** EOF <- 1
419** yield X
420** halt-error
421** B: open temp table
422** L: yield X
423** if EOF goto M
424** insert row from R..R+n into temp table
425** goto L
426** M: open write cursor to <table> and its indices
427** rewind temp table
428** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58 +0000429** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01 +0000430** end loop
431** D: cleanup
drhcce7d172000-05-31 15:34:51 +0000432*/
danielk19774adee202004-05-08 08:23:19 +0000433void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000434 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000435 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000436 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000437 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000438 IdList *pColumn, /* Column names corresponding to IDLIST. */
439 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000440){
drh6a288a32008-01-07 19:20:24 +0000441 sqlite3 *db; /* The main database structure */
442 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000443 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000444 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000445 int i, j, idx; /* Loop counters */
446 Vdbe *v; /* Generate code into this virtual machine */
447 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000448 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000449 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000450 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000451 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000452 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000453 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000454 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01 +0000455 int addrInsTop = 0; /* Jump to label "D" */
456 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
457 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
drh2eb95372008-06-06 15:04:36 +0000458 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24 +0000459 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000460 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000461 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000462
drh6a288a32008-01-07 19:20:24 +0000463 /* Register allocations */
drh1bd10f82008-12-10 21:19:56 +0000464 int regFromSelect = 0;/* Base register for data coming from SELECT */
drh6a288a32008-01-07 19:20:24 +0000465 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
466 int regRowCount = 0; /* Memory cell used for the row counter */
467 int regIns; /* Block of regs holding rowid+data being inserted */
468 int regRowid; /* registers holding insert rowid */
469 int regData; /* register holding first column to insert */
drh1bd10f82008-12-10 21:19:56 +0000470 int regEof = 0; /* Register recording end of SELECT data */
drhaa9b8962008-01-08 02:57:55 +0000471 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000472
drh798da522004-11-04 04:42:28 +0000473#ifndef SQLITE_OMIT_TRIGGER
474 int isView; /* True if attempting to insert into a view */
danielk19772f886d12009-02-28 10:47:41 +0000475 Trigger *pTrigger; /* List of triggers on pTab, if required */
476 int tmask; /* Mask of trigger times */
drh798da522004-11-04 04:42:28 +0000477#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000478
drh17435752007-08-16 04:30:38 +0000479 db = pParse->db;
drh1bd10f82008-12-10 21:19:56 +0000480 memset(&dest, 0, sizeof(dest));
drh17435752007-08-16 04:30:38 +0000481 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000482 goto insert_cleanup;
483 }
drhdaffd0e2001-04-11 14:28:42 +0000484
drh1ccde152000-06-17 13:12:39 +0000485 /* Locate the table into which we will be inserting new information.
486 */
drh113088e2003-03-20 01:16:58 +0000487 assert( pTabList->nSrc==1 );
488 zTab = pTabList->a[0].zName;
drh098d1682009-05-02 15:46:46 +0000489 if( NEVER(zTab==0) ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000490 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000491 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000492 goto insert_cleanup;
493 }
danielk1977da184232006-01-05 11:34:32 +0000494 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
495 assert( iDb<db->nDb );
496 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000497 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000498 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000499 goto insert_cleanup;
500 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000501
drhb7f91642004-10-31 02:22:47 +0000502 /* Figure out if we have any triggers and if the table being
503 ** inserted into is a view
504 */
505#ifndef SQLITE_OMIT_TRIGGER
danielk19772f886d12009-02-28 10:47:41 +0000506 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
drhb7f91642004-10-31 02:22:47 +0000507 isView = pTab->pSelect!=0;
508#else
danielk19772f886d12009-02-28 10:47:41 +0000509# define pTrigger 0
510# define tmask 0
drhb7f91642004-10-31 02:22:47 +0000511# define isView 0
512#endif
513#ifdef SQLITE_OMIT_VIEW
514# undef isView
515# define isView 0
516#endif
danielk19772f886d12009-02-28 10:47:41 +0000517 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
drhb7f91642004-10-31 02:22:47 +0000518
drhf573c992002-07-31 00:32:50 +0000519 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000520 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
521 ** module table).
drhf573c992002-07-31 00:32:50 +0000522 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000523 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000524 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000525 }
526
danielk1977595a5232009-07-24 17:58:53 +0000527 /* Ensure that:
528 * (a) the table is not read-only,
529 * (b) that if it is a view then ON INSERT triggers exist
530 */
531 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
532 goto insert_cleanup;
533 }
534
drh1ccde152000-06-17 13:12:39 +0000535 /* Allocate a VDBE
536 */
danielk19774adee202004-05-08 08:23:19 +0000537 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000538 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000539 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk19772f886d12009-02-28 10:47:41 +0000540 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
drh1ccde152000-06-17 13:12:39 +0000541
drh9d9cf222007-02-13 15:01:11 +0000542#ifndef SQLITE_OMIT_XFER_OPT
543 /* If the statement is of the form
544 **
545 ** INSERT INTO <table1> SELECT * FROM <table2>;
546 **
547 ** Then special optimizations can be applied that make the transfer
548 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000549 **
550 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000551 */
552 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
danielk19772f886d12009-02-28 10:47:41 +0000553 assert( !pTrigger );
drh9d9cf222007-02-13 15:01:11 +0000554 assert( pList==0 );
drh0b9f50d2009-06-23 20:28:53 +0000555 goto insert_end;
drh9d9cf222007-02-13 15:01:11 +0000556 }
557#endif /* SQLITE_OMIT_XFER_OPT */
558
drh2958a4e2004-11-12 03:56:15 +0000559 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000560 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000561 */
drh6a288a32008-01-07 19:20:24 +0000562 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000563
drh1ccde152000-06-17 13:12:39 +0000564 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000565 ** is coming from a SELECT statement, then generate a co-routine that
566 ** produces a single row of the SELECT on each invocation. The
567 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000568 */
drh5974a302000-06-07 14:42:26 +0000569 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000570 /* Data is coming from a SELECT. Generate code to implement that SELECT
drhe00ee6e2008-06-20 15:24:01 +0000571 ** as a co-routine. The code is common to both the 3rd and 4th
572 ** templates:
573 **
574 ** EOF <- 0
575 ** X <- A
576 ** goto B
577 ** A: setup for the SELECT
578 ** loop over the tables in the SELECT
579 ** load value into register R..R+n
580 ** yield X
581 ** end loop
582 ** cleanup after the SELECT
583 ** EOF <- 1
584 ** yield X
585 ** halt-error
586 **
587 ** On each invocation of the co-routine, it puts a single row of the
588 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
589 ** (These output registers are allocated by sqlite3Select().) When
590 ** the SELECT completes, it sets the EOF flag stored in regEof.
drh142e30d2002-08-28 03:00:58 +0000591 */
drhe00ee6e2008-06-20 15:24:01 +0000592 int rc, j1;
drh1013c932008-01-06 00:25:21 +0000593
drhe00ee6e2008-06-20 15:24:01 +0000594 regEof = ++pParse->nMem;
595 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
596 VdbeComment((v, "SELECT eof flag"));
drh92b01d52008-06-24 00:32:35 +0000597 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
drhe00ee6e2008-06-20 15:24:01 +0000598 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
drh92b01d52008-06-24 00:32:35 +0000599 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000600 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
601 VdbeComment((v, "Jump over SELECT coroutine"));
danielk1977b3bce662005-01-29 08:32:43 +0000602
603 /* Resolve the expressions in the SELECT statement and execute it. */
drh7d10d5a2008-08-20 16:35:10 +0000604 rc = sqlite3Select(pParse, pSelect, &dest);
drh098d1682009-05-02 15:46:46 +0000605 assert( pParse->nErr==0 || rc );
606 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000607 goto insert_cleanup;
608 }
drhe00ee6e2008-06-20 15:24:01 +0000609 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
drh92b01d52008-06-24 00:32:35 +0000610 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
drhe00ee6e2008-06-20 15:24:01 +0000611 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
612 VdbeComment((v, "End of SELECT coroutine"));
613 sqlite3VdbeJumpHere(v, j1); /* label B: */
danielk1977b3bce662005-01-29 08:32:43 +0000614
drh6a288a32008-01-07 19:20:24 +0000615 regFromSelect = dest.iMem;
drh5974a302000-06-07 14:42:26 +0000616 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000617 nColumn = pSelect->pEList->nExpr;
drhe00ee6e2008-06-20 15:24:01 +0000618 assert( dest.nMem==nColumn );
drh142e30d2002-08-28 03:00:58 +0000619
620 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000621 ** should be written into a temporary table (template 4). Set to
622 ** FALSE if each* row of the SELECT can be written directly into
623 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000624 **
625 ** A temp table must be used if the table being updated is also one
626 ** of the tables being read by the SELECT statement. Also use a
627 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000628 */
danielk1977595a5232009-07-24 17:58:53 +0000629 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000630 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000631 }
drh142e30d2002-08-28 03:00:58 +0000632
633 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000634 /* Invoke the coroutine to extract information from the SELECT
635 ** and add it to a transient table srcTab. The code generated
636 ** here is from the 4th template:
637 **
638 ** B: open temp table
639 ** L: yield X
640 ** if EOF goto M
641 ** insert row from R..R+n into temp table
642 ** goto L
643 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000644 */
drhdc5ea5c2008-12-10 17:19:59 +0000645 int regRec; /* Register to hold packed record */
646 int regTempRowid; /* Register to hold temp table ROWID */
647 int addrTop; /* Label "L" */
648 int addrIf; /* Address of jump to M */
drhb7654112008-01-12 12:48:07 +0000649
drh142e30d2002-08-28 03:00:58 +0000650 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000651 regRec = sqlite3GetTempReg(pParse);
drhdc5ea5c2008-12-10 17:19:59 +0000652 regTempRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000653 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh92b01d52008-06-24 00:32:35 +0000654 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000655 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh1db639c2008-01-17 02:36:28 +0000656 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000657 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
658 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drhe00ee6e2008-06-20 15:24:01 +0000659 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
660 sqlite3VdbeJumpHere(v, addrIf);
drhb7654112008-01-12 12:48:07 +0000661 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000662 sqlite3ReleaseTempReg(pParse, regTempRowid);
drh142e30d2002-08-28 03:00:58 +0000663 }
drh5974a302000-06-07 14:42:26 +0000664 }else{
drh142e30d2002-08-28 03:00:58 +0000665 /* This is the case if the data for the INSERT is coming from a VALUES
666 ** clause
667 */
danielk1977b3bce662005-01-29 08:32:43 +0000668 NameContext sNC;
669 memset(&sNC, 0, sizeof(sNC));
670 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000671 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000672 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000673 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000674 for(i=0; i<nColumn; i++){
drh7d10d5a2008-08-20 16:35:10 +0000675 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000676 goto insert_cleanup;
677 }
drhe64e7b22002-02-18 13:56:36 +0000678 }
drh5974a302000-06-07 14:42:26 +0000679 }
drh1ccde152000-06-17 13:12:39 +0000680
681 /* Make sure the number of columns in the source data matches the number
682 ** of columns to be inserted into the table.
683 */
danielk1977034ca142007-06-26 10:38:54 +0000684 if( IsVirtual(pTab) ){
685 for(i=0; i<pTab->nCol; i++){
686 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
687 }
688 }
689 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000690 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000691 "table %S has %d columns but %d values were supplied",
drhd51397a2009-05-01 15:17:48 +0000692 pTabList, 0, pTab->nCol-nHidden, nColumn);
drhcce7d172000-05-31 15:34:51 +0000693 goto insert_cleanup;
694 }
drh967e8b72000-06-21 13:59:10 +0000695 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000696 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000697 goto insert_cleanup;
698 }
drh1ccde152000-06-17 13:12:39 +0000699
700 /* If the INSERT statement included an IDLIST term, then make sure
701 ** all elements of the IDLIST really are columns of the table and
702 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000703 **
704 ** If the table has an INTEGER PRIMARY KEY column and that column
705 ** is named in the IDLIST, then record in the keyColumn variable
706 ** the index into IDLIST of the primary key column. keyColumn is
707 ** the index of the primary key as it appears in IDLIST, not as
708 ** is appears in the original table. (The index of the primary
709 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000710 */
drh967e8b72000-06-21 13:59:10 +0000711 if( pColumn ){
712 for(i=0; i<pColumn->nId; i++){
713 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000714 }
drh967e8b72000-06-21 13:59:10 +0000715 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000716 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000717 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000718 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000719 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000720 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000721 }
drhcce7d172000-05-31 15:34:51 +0000722 break;
723 }
724 }
725 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000726 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000727 keyColumn = i;
728 }else{
danielk19774adee202004-05-08 08:23:19 +0000729 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000730 pTabList, 0, pColumn->a[i].zName);
dan1db95102010-06-28 10:15:19 +0000731 pParse->checkSchema = 1;
drha0217ba2003-06-01 01:10:33 +0000732 goto insert_cleanup;
733 }
drhcce7d172000-05-31 15:34:51 +0000734 }
735 }
736 }
drh1ccde152000-06-17 13:12:39 +0000737
drhaacc5432002-01-06 17:07:40 +0000738 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000739 ** key, the set the keyColumn variable to the primary key column index
740 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000741 */
drh147d0cc2006-08-25 23:42:53 +0000742 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000743 keyColumn = pTab->iPKey;
744 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000745
drhfeeb1392002-04-09 03:28:01 +0000746 /* Initialize the count of rows to be inserted
747 */
drh142e30d2002-08-28 03:00:58 +0000748 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000749 regRowCount = ++pParse->nMem;
750 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000751 }
752
danielk1977e448dc42008-01-02 11:50:51 +0000753 /* If this is not a view, open the table and and all indices */
754 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000755 int nIdx;
drhaa9b8962008-01-08 02:57:55 +0000756
drh04adf412008-01-08 18:57:50 +0000757 baseCur = pParse->nTab;
758 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drh5c070532008-04-11 15:36:03 +0000759 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000760 if( aRegIdx==0 ){
761 goto insert_cleanup;
762 }
763 for(i=0; i<nIdx; i++){
764 aRegIdx[i] = ++pParse->nMem;
765 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000766 }
767
drhe00ee6e2008-06-20 15:24:01 +0000768 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000769 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000770 /* This block codes the top of loop only. The complete loop is the
771 ** following pseudocode (template 4):
772 **
773 ** rewind temp table
774 ** C: loop over rows of intermediate table
775 ** transfer values form intermediate table into <table>
776 ** end loop
777 ** D: ...
778 */
779 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
780 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000781 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000782 /* This block codes the top of loop only. The complete loop is the
783 ** following pseudocode (template 3):
784 **
785 ** C: yield X
786 ** if EOF goto D
787 ** insert the select result into <table> from R..R+n
788 ** goto C
789 ** D: ...
790 */
drh92b01d52008-06-24 00:32:35 +0000791 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000792 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh5974a302000-06-07 14:42:26 +0000793 }
drh1ccde152000-06-17 13:12:39 +0000794
drh6a288a32008-01-07 19:20:24 +0000795 /* Allocate registers for holding the rowid of the new row,
796 ** the content of the new row, and the assemblied row record.
797 */
drh6a288a32008-01-07 19:20:24 +0000798 regRowid = regIns = pParse->nMem+1;
799 pParse->nMem += pTab->nCol + 1;
800 if( IsVirtual(pTab) ){
801 regRowid++;
802 pParse->nMem++;
803 }
804 regData = regRowid+1;
805
drh5cf590c2003-04-24 01:45:04 +0000806 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000807 */
danielk19774adee202004-05-08 08:23:19 +0000808 endOfLoop = sqlite3VdbeMakeLabel(v);
danielk19772f886d12009-02-28 10:47:41 +0000809 if( tmask & TRIGGER_BEFORE ){
dan76d462e2009-08-30 11:42:51 +0000810 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000811
drh70ce3f02003-04-15 19:22:22 +0000812 /* build the NEW.* reference row. Note that if there is an INTEGER
813 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
814 ** translated into a unique ID for the row. But on a BEFORE trigger,
815 ** we do not know what the unique ID will be (because the insert has
816 ** not happened yet) so we substitute a rowid of -1
817 */
818 if( keyColumn<0 ){
dan76d462e2009-08-30 11:42:51 +0000819 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh70ce3f02003-04-15 19:22:22 +0000820 }else{
drh6a288a32008-01-07 19:20:24 +0000821 int j1;
drh7fe45902009-05-01 02:08:04 +0000822 if( useTempTable ){
dan76d462e2009-08-30 11:42:51 +0000823 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
drh7fe45902009-05-01 02:08:04 +0000824 }else{
825 assert( pSelect==0 ); /* Otherwise useTempTable is true */
dan76d462e2009-08-30 11:42:51 +0000826 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
drh7fe45902009-05-01 02:08:04 +0000827 }
dan76d462e2009-08-30 11:42:51 +0000828 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
829 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh6a288a32008-01-07 19:20:24 +0000830 sqlite3VdbeJumpHere(v, j1);
dan76d462e2009-08-30 11:42:51 +0000831 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
drh70ce3f02003-04-15 19:22:22 +0000832 }
833
danielk1977034ca142007-06-26 10:38:54 +0000834 /* Cannot have triggers on a virtual table. If it were possible,
835 ** this block would have to account for hidden column.
836 */
dan165921a2009-08-28 18:53:45 +0000837 assert( !IsVirtual(pTab) );
danielk1977034ca142007-06-26 10:38:54 +0000838
drh70ce3f02003-04-15 19:22:22 +0000839 /* Create the new column data
840 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000841 for(i=0; i<pTab->nCol; i++){
842 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000843 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000844 }else{
drh9adf9ac2002-05-15 11:44:13 +0000845 for(j=0; j<pColumn->nId; j++){
846 if( pColumn->a[j].idx==i ) break;
847 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000848 }
dan7ba45972010-03-30 12:40:32 +0000849 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
dan76d462e2009-08-30 11:42:51 +0000850 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
drh142e30d2002-08-28 03:00:58 +0000851 }else if( useTempTable ){
dan76d462e2009-08-30 11:42:51 +0000852 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000853 }else{
drhd6fe9612005-01-14 01:22:00 +0000854 assert( pSelect==0 ); /* Otherwise useTempTable is true */
dan76d462e2009-08-30 11:42:51 +0000855 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000856 }
857 }
danielk1977a37cdde2004-05-16 11:15:36 +0000858
859 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
860 ** do not attempt any conversions before assembling the record.
861 ** If this is a real table, attempt conversions as required by the
862 ** table column affinities.
863 */
864 if( !isView ){
dan76d462e2009-08-30 11:42:51 +0000865 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
danielk1977a37cdde2004-05-16 11:15:36 +0000866 sqlite3TableAffinityStr(v, pTab);
867 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000868
drh5cf590c2003-04-24 01:45:04 +0000869 /* Fire BEFORE or INSTEAD OF triggers */
dan165921a2009-08-28 18:53:45 +0000870 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
dan94d7f502009-09-24 09:05:49 +0000871 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
dan165921a2009-08-28 18:53:45 +0000872
dan76d462e2009-08-30 11:42:51 +0000873 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
drh70ce3f02003-04-15 19:22:22 +0000874 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000875
drh4a324312001-12-21 14:30:42 +0000876 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000877 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000878 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000879 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000880 */
drh5cf590c2003-04-24 01:45:04 +0000881 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000882 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000883 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000884 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000885 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000886 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000887 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000888 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000889 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000890 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000891 }else{
drhe4d90812007-03-29 05:51:49 +0000892 VdbeOp *pOp;
drh1db639c2008-01-17 02:36:28 +0000893 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
drh20411ea2009-05-29 19:00:12 +0000894 pOp = sqlite3VdbeGetOp(v, -1);
drh1b7ecbb2009-05-03 01:00:59 +0000895 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000896 appendFlag = 1;
897 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000898 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000899 pOp->p2 = regRowid;
900 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000901 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000902 }
drhf0863fe2005-06-12 21:35:51 +0000903 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000904 ** to generate a unique primary key value.
905 */
drhe4d90812007-03-29 05:51:49 +0000906 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000907 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000908 if( !IsVirtual(pTab) ){
909 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
910 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
911 sqlite3VdbeJumpHere(v, j1);
912 }else{
913 j1 = sqlite3VdbeCurrentAddr(v);
914 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
915 }
drh3c84ddf2008-01-09 02:15:38 +0000916 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000917 }
drh4cbdda92006-06-14 19:00:20 +0000918 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000919 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000920 }else{
drh04adf412008-01-08 18:57:50 +0000921 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000922 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000923 }
drh6a288a32008-01-07 19:20:24 +0000924 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000925
danielk1977c3f9bad2002-05-15 08:30:12 +0000926 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000927 ** with the first column.
928 */
danielk1977034ca142007-06-26 10:38:54 +0000929 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000930 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000931 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000932 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000933 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000934 ** Whenever this column is read, the record number will be substituted
935 ** in its place. So will fill this column with a NULL to avoid
936 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000937 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000938 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000939 }
940 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000941 if( IsHiddenColumn(&pTab->aCol[i]) ){
942 assert( IsVirtual(pTab) );
943 j = -1;
944 nHidden++;
945 }else{
946 j = i - nHidden;
947 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000948 }else{
drh9adf9ac2002-05-15 11:44:13 +0000949 for(j=0; j<pColumn->nId; j++){
950 if( pColumn->a[j].idx==i ) break;
951 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000952 }
danielk1977034ca142007-06-26 10:38:54 +0000953 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000954 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000955 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000956 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000957 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000958 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000959 }else{
danielk1977287fb612008-01-04 19:10:28 +0000960 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000961 }
drhbed86902000-06-02 13:27:59 +0000962 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000963
964 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000965 ** do the insertion.
966 */
drh4cbdda92006-06-14 19:00:20 +0000967#ifndef SQLITE_OMIT_VIRTUALTABLE
968 if( IsVirtual(pTab) ){
danielk1977595a5232009-07-24 17:58:53 +0000969 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
drh4f3dd152008-04-28 18:46:43 +0000970 sqlite3VtabMakeWritable(pParse, pTab);
danielk1977595a5232009-07-24 17:58:53 +0000971 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
danb061d052011-04-25 18:49:57 +0000972 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
dane0af83a2009-09-08 19:15:01 +0000973 sqlite3MayAbort(pParse);
drh4cbdda92006-06-14 19:00:20 +0000974 }else
975#endif
976 {
danielk1977de630352009-05-04 11:42:29 +0000977 int isReplace; /* Set to true if constraints may cause a replace */
978 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
979 keyColumn>=0, 0, onError, endOfLoop, &isReplace
drh04adf412008-01-08 18:57:50 +0000980 );
dane7a94d82009-10-01 16:09:04 +0000981 sqlite3FkCheck(pParse, pTab, 0, regIns);
drh04adf412008-01-08 18:57:50 +0000982 sqlite3CompleteInsertion(
dan2832ad42009-08-31 15:27:27 +0000983 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
danielk1977de630352009-05-04 11:42:29 +0000984 );
drh4cbdda92006-06-14 19:00:20 +0000985 }
drh5cf590c2003-04-24 01:45:04 +0000986 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000987
drh5cf590c2003-04-24 01:45:04 +0000988 /* Update the count of rows that are inserted
989 */
990 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000991 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000992 }
drh1ccde152000-06-17 13:12:39 +0000993
danielk19772f886d12009-02-28 10:47:41 +0000994 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000995 /* Code AFTER triggers */
dan165921a2009-08-28 18:53:45 +0000996 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
dan94d7f502009-09-24 09:05:49 +0000997 pTab, regData-2-pTab->nCol, onError, endOfLoop);
drh1bee3d72001-10-15 00:44:35 +0000998 }
999
drhe00ee6e2008-06-20 15:24:01 +00001000 /* The bottom of the main insertion loop, if the data source
1001 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:12 +00001002 */
danielk19774adee202004-05-08 08:23:19 +00001003 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +00001004 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +00001005 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1006 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:36 +00001007 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:58 +00001008 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +00001009 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1010 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:26 +00001011 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001012
danielk1977e448dc42008-01-02 11:50:51 +00001013 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +00001014 /* Close all tables opened */
drh2eb95372008-06-06 15:04:36 +00001015 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +00001016 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh2eb95372008-06-06 15:04:36 +00001017 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +00001018 }
drhcce7d172000-05-31 15:34:51 +00001019 }
danielk1977c3f9bad2002-05-15 08:30:12 +00001020
drh0b9f50d2009-06-23 20:28:53 +00001021insert_end:
drhf3388142004-11-13 03:48:06 +00001022 /* Update the sqlite_sequence table by storing the content of the
drh0b9f50d2009-06-23 20:28:53 +00001023 ** maximum rowid counter values recorded while inserting into
1024 ** autoincrement tables.
drh2958a4e2004-11-12 03:56:15 +00001025 */
dan165921a2009-08-28 18:53:45 +00001026 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
drh0b9f50d2009-06-23 20:28:53 +00001027 sqlite3AutoincrementEnd(pParse);
1028 }
drh2958a4e2004-11-12 03:56:15 +00001029
drh1bee3d72001-10-15 00:44:35 +00001030 /*
danielk1977e7de6f22004-11-05 06:02:06 +00001031 ** Return the number of rows inserted. If this routine is
1032 ** generating code because of a call to sqlite3NestedParse(), do not
1033 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +00001034 */
dan165921a2009-08-28 18:53:45 +00001035 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
drh6a288a32008-01-07 19:20:24 +00001036 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +00001037 sqlite3VdbeSetNumCols(v, 1);
danielk197710fb7492008-10-31 10:53:22 +00001038 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
drh1bee3d72001-10-15 00:44:35 +00001039 }
drhcce7d172000-05-31 15:34:51 +00001040
1041insert_cleanup:
drh633e6d52008-07-28 19:34:53 +00001042 sqlite3SrcListDelete(db, pTabList);
1043 sqlite3ExprListDelete(db, pList);
1044 sqlite3SelectDelete(db, pSelect);
1045 sqlite3IdListDelete(db, pColumn);
1046 sqlite3DbFree(db, aRegIdx);
drhcce7d172000-05-31 15:34:51 +00001047}
drh9cfcf5d2002-01-29 18:41:24 +00001048
dan75cbd982009-09-21 16:06:03 +00001049/* Make sure "isView" and other macros defined above are undefined. Otherwise
1050** thely may interfere with compilation of other functions in this file
1051** (or in another file, if this file becomes part of the amalgamation). */
1052#ifdef isView
1053 #undef isView
1054#endif
1055#ifdef pTrigger
1056 #undef pTrigger
1057#endif
1058#ifdef tmask
1059 #undef tmask
1060#endif
1061
1062
drh9cfcf5d2002-01-29 18:41:24 +00001063/*
drh6a288a32008-01-07 19:20:24 +00001064** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +00001065**
drh04adf412008-01-08 18:57:50 +00001066** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +00001067**
dan65a7cd12009-09-01 12:16:01 +00001068** 1. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +00001069**
dan65a7cd12009-09-01 12:16:01 +00001070** 2. The data in the first column of the entry after the update.
drh0ca3e242002-01-29 23:07:02 +00001071**
1072** i. Data from middle columns...
1073**
1074** N. The data in the last column of the entry after the update.
1075**
dan65a7cd12009-09-01 12:16:01 +00001076** The regRowid parameter is the index of the register containing (1).
drh04adf412008-01-08 18:57:50 +00001077**
dan65a7cd12009-09-01 12:16:01 +00001078** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
1079** the address of a register containing the rowid before the update takes
1080** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
1081** is false, indicating an INSERT statement, then a non-zero rowidChng
1082** indicates that the rowid was explicitly specified as part of the
1083** INSERT statement. If rowidChng is false, it means that the rowid is
1084** computed automatically in an insert or that the rowid value is not
1085** modified by an update.
drh0ca3e242002-01-29 23:07:02 +00001086**
drhaa9b8962008-01-08 02:57:55 +00001087** The code generated by this routine store new index entries into
1088** registers identified by aRegIdx[]. No index entry is created for
1089** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1090** the same as the order of indices on the linked list of indices
1091** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +00001092**
1093** This routine also generates code to check constraints. NOT NULL,
1094** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +00001095** then the appropriate action is performed. There are five possible
1096** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +00001097**
1098** Constraint type Action What Happens
1099** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +00001100** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +00001101** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +00001102** return code of SQLITE_CONSTRAINT.
1103**
drh1c928532002-01-31 15:54:21 +00001104** any ABORT Back out changes from the current command
1105** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +00001106** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +00001107** with SQLITE_CONSTRAINT.
1108**
1109** any FAIL Sqlite_exec() returns immediately with a
1110** return code of SQLITE_CONSTRAINT. The
1111** transaction is not rolled back and any
1112** prior changes are retained.
1113**
drh9cfcf5d2002-01-29 18:41:24 +00001114** any IGNORE The record number and data is popped from
1115** the stack and there is an immediate jump
1116** to label ignoreDest.
1117**
1118** NOT NULL REPLACE The NULL value is replace by the default
1119** value for that column. If the default value
1120** is NULL, the action is the same as ABORT.
1121**
1122** UNIQUE REPLACE The other row that conflicts with the row
1123** being inserted is removed.
1124**
1125** CHECK REPLACE Illegal. The results in an exception.
1126**
drh1c928532002-01-31 15:54:21 +00001127** Which action to take is determined by the overrideError parameter.
1128** Or if overrideError==OE_Default, then the pParse->onError parameter
1129** is used. Or if pParse->onError==OE_Default then the onError value
1130** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001131**
drhaaab5722002-02-19 13:39:21 +00001132** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +00001133** cursor number "baseCur". All indices of pTab must also have open
1134** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001135** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001136** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001137*/
danielk19774adee202004-05-08 08:23:19 +00001138void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001139 Parse *pParse, /* The parser context */
1140 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001141 int baseCur, /* Index of a read/write cursor pointing at pTab */
1142 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001143 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drha05a7222008-01-19 03:35:58 +00001144 int rowidChng, /* True if the rowid might collide with existing entry */
drhb419a922002-01-30 16:17:23 +00001145 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001146 int overrideError, /* Override onError to this if not OE_Default */
danielk1977de630352009-05-04 11:42:29 +00001147 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1148 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
drh9cfcf5d2002-01-29 18:41:24 +00001149){
drh1b7ecbb2009-05-03 01:00:59 +00001150 int i; /* loop counter */
1151 Vdbe *v; /* VDBE under constrution */
1152 int nCol; /* Number of columns */
1153 int onError; /* Conflict resolution strategy */
drh1bd10f82008-12-10 21:19:56 +00001154 int j1; /* Addresss of jump instruction */
1155 int j2 = 0, j3; /* Addresses of jump instructions */
drh04adf412008-01-08 18:57:50 +00001156 int regData; /* Register containing first data column */
drh1b7ecbb2009-05-03 01:00:59 +00001157 int iCur; /* Table cursor number */
1158 Index *pIdx; /* Pointer to one of the indices */
1159 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
dan65a7cd12009-09-01 12:16:01 +00001160 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
drh9cfcf5d2002-01-29 18:41:24 +00001161
danielk19774adee202004-05-08 08:23:19 +00001162 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001163 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001164 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001165 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001166 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001167
1168 /* Test all NOT NULL constraints.
1169 */
1170 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001171 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001172 continue;
1173 }
drh9cfcf5d2002-01-29 18:41:24 +00001174 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001175 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001176 if( overrideError!=OE_Default ){
1177 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001178 }else if( onError==OE_Default ){
1179 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001180 }
danielk19777977a172004-11-09 12:44:37 +00001181 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001182 onError = OE_Abort;
1183 }
danielk1977b84f96f2005-01-20 11:32:23 +00001184 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1185 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001186 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001187 case OE_Abort:
dane0af83a2009-09-08 19:15:01 +00001188 sqlite3MayAbort(pParse);
1189 case OE_Rollback:
drh1c928532002-01-31 15:54:21 +00001190 case OE_Fail: {
drhf089aa42008-07-08 19:34:06 +00001191 char *zMsg;
drhc126e632011-03-06 21:28:32 +00001192 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
drh5053a792009-02-20 03:02:23 +00001193 SQLITE_CONSTRAINT, onError, regData+i);
drhf089aa42008-07-08 19:34:06 +00001194 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1195 pTab->zName, pTab->aCol[i].zName);
drh66a51672008-01-03 00:01:23 +00001196 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001197 break;
1198 }
1199 case OE_Ignore: {
drh5053a792009-02-20 03:02:23 +00001200 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001201 break;
1202 }
drh098d1682009-05-02 15:46:46 +00001203 default: {
1204 assert( onError==OE_Replace );
drh5053a792009-02-20 03:02:23 +00001205 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
drh04adf412008-01-08 18:57:50 +00001206 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh5053a792009-02-20 03:02:23 +00001207 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001208 break;
1209 }
drh9cfcf5d2002-01-29 18:41:24 +00001210 }
1211 }
1212
1213 /* Test all CHECK constraints
1214 */
drhffe07b22005-11-03 00:41:17 +00001215#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001216 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001217 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001218 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001219 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001220 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001221 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001222 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001223 }else{
drh6dc84902010-08-03 13:08:54 +00001224 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
dane0af83a2009-09-08 19:15:01 +00001225 sqlite3HaltConstraint(pParse, onError, 0, 0);
drhaa01c7e2006-03-15 16:26:10 +00001226 }
drhffe07b22005-11-03 00:41:17 +00001227 sqlite3VdbeResolveLabel(v, allOk);
1228 }
1229#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001230
drh0bd1f4e2002-06-06 18:54:39 +00001231 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1232 ** of the new record does not previously exist. Except, if this
1233 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001234 */
drhf0863fe2005-06-12 21:35:51 +00001235 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001236 onError = pTab->keyConf;
1237 if( overrideError!=OE_Default ){
1238 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001239 }else if( onError==OE_Default ){
1240 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001241 }
drha0217ba2003-06-01 01:10:33 +00001242
dane1e2ae22009-09-24 16:52:28 +00001243 if( isUpdate ){
1244 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
1245 }
1246 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1247 switch( onError ){
1248 default: {
1249 onError = OE_Abort;
1250 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001251 }
dane1e2ae22009-09-24 16:52:28 +00001252 case OE_Rollback:
1253 case OE_Abort:
1254 case OE_Fail: {
1255 sqlite3HaltConstraint(
1256 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
1257 break;
drh0ca3e242002-01-29 23:07:02 +00001258 }
dane1e2ae22009-09-24 16:52:28 +00001259 case OE_Replace: {
1260 /* If there are DELETE triggers on this table and the
1261 ** recursive-triggers flag is set, call GenerateRowDelete() to
1262 ** remove the conflicting row from the the table. This will fire
1263 ** the triggers and remove both the table and index b-tree entries.
1264 **
1265 ** Otherwise, if there are no triggers or the recursive-triggers
danda730f62010-02-18 08:19:19 +00001266 ** flag is not set, but the table has one or more indexes, call
1267 ** GenerateRowIndexDelete(). This removes the index b-tree entries
1268 ** only. The table b-tree entry will be replaced by the new entry
1269 ** when it is inserted.
1270 **
1271 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1272 ** also invoke MultiWrite() to indicate that this VDBE may require
1273 ** statement rollback (if the statement is aborted after the delete
1274 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1275 ** but being more selective here allows statements like:
1276 **
1277 ** REPLACE INTO t(rowid) VALUES($newrowid)
1278 **
1279 ** to run without a statement journal if there are no indexes on the
1280 ** table.
1281 */
dane1e2ae22009-09-24 16:52:28 +00001282 Trigger *pTrigger = 0;
1283 if( pParse->db->flags&SQLITE_RecTriggers ){
1284 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1285 }
dane7a94d82009-10-01 16:09:04 +00001286 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
danda730f62010-02-18 08:19:19 +00001287 sqlite3MultiWrite(pParse);
dane1e2ae22009-09-24 16:52:28 +00001288 sqlite3GenerateRowDelete(
1289 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
1290 );
danda730f62010-02-18 08:19:19 +00001291 }else if( pTab->pIndex ){
1292 sqlite3MultiWrite(pParse);
dane1e2ae22009-09-24 16:52:28 +00001293 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1294 }
1295 seenReplace = 1;
1296 break;
drh5383ae52003-06-04 12:23:30 +00001297 }
dane1e2ae22009-09-24 16:52:28 +00001298 case OE_Ignore: {
1299 assert( seenReplace==0 );
1300 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1301 break;
1302 }
1303 }
1304 sqlite3VdbeJumpHere(v, j3);
1305 if( isUpdate ){
1306 sqlite3VdbeJumpHere(v, j2);
drh5383ae52003-06-04 12:23:30 +00001307 }
drh0ca3e242002-01-29 23:07:02 +00001308 }
drh0bd1f4e2002-06-06 18:54:39 +00001309
1310 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1311 ** index and making sure that duplicate entries do not already exist.
1312 ** Add the new records to the indices as we go.
1313 */
drhb2fe7d82003-04-20 17:29:23 +00001314 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001315 int regIdx;
1316 int regR;
drh2184fc72011-04-09 03:04:13 +00001317
drhaa9b8962008-01-08 02:57:55 +00001318 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001319
1320 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001321 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001322 for(i=0; i<pIdx->nColumn; i++){
1323 int idx = pIdx->aiColumn[i];
1324 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001325 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001326 }else{
drh2d401ab2008-01-10 23:50:11 +00001327 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001328 }
1329 }
drh2d401ab2008-01-10 23:50:11 +00001330 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh1db639c2008-01-17 02:36:28 +00001331 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
drh8d129422011-04-05 12:25:19 +00001332 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
drhda250ea2008-04-01 05:07:14 +00001333 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001334
1335 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001336 onError = pIdx->onError;
danielk1977de630352009-05-04 11:42:29 +00001337 if( onError==OE_None ){
1338 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1339 continue; /* pIdx is not a UNIQUE index */
1340 }
drh9cfcf5d2002-01-29 18:41:24 +00001341 if( overrideError!=OE_Default ){
1342 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001343 }else if( onError==OE_Default ){
1344 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001345 }
drh5383ae52003-06-04 12:23:30 +00001346 if( seenReplace ){
1347 if( onError==OE_Ignore ) onError = OE_Replace;
1348 else if( onError==OE_Fail ) onError = OE_Abort;
1349 }
1350
drhb2fe7d82003-04-20 17:29:23 +00001351 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001352 regR = sqlite3GetTempReg(pParse);
dan65a7cd12009-09-01 12:16:01 +00001353 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
drh2d401ab2008-01-10 23:50:11 +00001354 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
danielk1977de630352009-05-04 11:42:29 +00001355 regR, SQLITE_INT_TO_PTR(regIdx),
mlcreecha9e852b2008-03-06 09:58:50 +00001356 P4_INT32);
danielk1977de630352009-05-04 11:42:29 +00001357 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001358
1359 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001360 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1361 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001362 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001363 case OE_Rollback:
1364 case OE_Abort:
1365 case OE_Fail: {
drh098d1682009-05-02 15:46:46 +00001366 int j;
1367 StrAccum errMsg;
1368 const char *zSep;
1369 char *zErr;
1370
1371 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
1372 errMsg.db = pParse->db;
1373 zSep = pIdx->nColumn>1 ? "columns " : "column ";
1374 for(j=0; j<pIdx->nColumn; j++){
drh37ed48e2003-08-05 13:13:38 +00001375 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
drh098d1682009-05-02 15:46:46 +00001376 sqlite3StrAccumAppend(&errMsg, zSep, -1);
1377 zSep = ", ";
1378 sqlite3StrAccumAppend(&errMsg, zCol, -1);
drh37ed48e2003-08-05 13:13:38 +00001379 }
drh098d1682009-05-02 15:46:46 +00001380 sqlite3StrAccumAppend(&errMsg,
1381 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
1382 zErr = sqlite3StrAccumFinish(&errMsg);
dane0af83a2009-09-08 19:15:01 +00001383 sqlite3HaltConstraint(pParse, onError, zErr, 0);
drh098d1682009-05-02 15:46:46 +00001384 sqlite3DbFree(errMsg.db, zErr);
drh9cfcf5d2002-01-29 18:41:24 +00001385 break;
1386 }
1387 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001388 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001389 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001390 break;
1391 }
drh098d1682009-05-02 15:46:46 +00001392 default: {
dan2283d462009-09-08 15:55:15 +00001393 Trigger *pTrigger = 0;
drh098d1682009-05-02 15:46:46 +00001394 assert( onError==OE_Replace );
dan1bea5592009-09-24 11:31:21 +00001395 sqlite3MultiWrite(pParse);
dan2283d462009-09-08 15:55:15 +00001396 if( pParse->db->flags&SQLITE_RecTriggers ){
1397 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1398 }
1399 sqlite3GenerateRowDelete(
1400 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
1401 );
drh0ca3e242002-01-29 23:07:02 +00001402 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001403 break;
1404 }
drh9cfcf5d2002-01-29 18:41:24 +00001405 }
drh2d401ab2008-01-10 23:50:11 +00001406 sqlite3VdbeJumpHere(v, j3);
1407 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001408 }
dan1da40a32009-09-19 17:00:31 +00001409
danielk1977de630352009-05-04 11:42:29 +00001410 if( pbMayReplace ){
1411 *pbMayReplace = seenReplace;
1412 }
drh9cfcf5d2002-01-29 18:41:24 +00001413}
drh0ca3e242002-01-29 23:07:02 +00001414
1415/*
1416** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001417** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001418** A consecutive range of registers starting at regRowid contains the
1419** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001420**
drhb419a922002-01-30 16:17:23 +00001421** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001422** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001423*/
danielk19774adee202004-05-08 08:23:19 +00001424void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001425 Parse *pParse, /* The parser context */
1426 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001427 int baseCur, /* Index of a read/write cursor pointing at pTab */
1428 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001429 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh70ce3f02003-04-15 19:22:22 +00001430 int isUpdate, /* True for UPDATE, False for INSERT */
danielk1977de630352009-05-04 11:42:29 +00001431 int appendBias, /* True if this is likely to be an append */
1432 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
drh0ca3e242002-01-29 23:07:02 +00001433){
1434 int i;
1435 Vdbe *v;
1436 int nIdx;
1437 Index *pIdx;
drh1bd10f82008-12-10 21:19:56 +00001438 u8 pik_flags;
drh04adf412008-01-08 18:57:50 +00001439 int regData;
drhb7654112008-01-12 12:48:07 +00001440 int regRec;
drh0ca3e242002-01-29 23:07:02 +00001441
danielk19774adee202004-05-08 08:23:19 +00001442 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001443 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001444 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001445 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1446 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001447 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001448 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
danielk1977de630352009-05-04 11:42:29 +00001449 if( useSeekResult ){
1450 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1451 }
drh0ca3e242002-01-29 23:07:02 +00001452 }
drh04adf412008-01-08 18:57:50 +00001453 regData = regRowid + 1;
drhb7654112008-01-12 12:48:07 +00001454 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001455 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +00001456 sqlite3TableAffinityStr(v, pTab);
drhda250ea2008-04-01 05:07:14 +00001457 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
drh4794f732004-11-05 17:17:50 +00001458 if( pParse->nested ){
1459 pik_flags = 0;
1460 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001461 pik_flags = OPFLAG_NCHANGE;
1462 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001463 }
drhe4d90812007-03-29 05:51:49 +00001464 if( appendBias ){
1465 pik_flags |= OPFLAG_APPEND;
1466 }
danielk1977de630352009-05-04 11:42:29 +00001467 if( useSeekResult ){
1468 pik_flags |= OPFLAG_USESEEKRESULT;
1469 }
drhb7654112008-01-12 12:48:07 +00001470 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
danielk197794eb6a12005-12-15 15:22:08 +00001471 if( !pParse->nested ){
drh8d129422011-04-05 12:25:19 +00001472 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
danielk197794eb6a12005-12-15 15:22:08 +00001473 }
drhb7654112008-01-12 12:48:07 +00001474 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001475}
drhcd446902004-02-24 01:05:31 +00001476
1477/*
drh290c1942004-08-21 17:54:45 +00001478** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001479** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001480** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001481**
1482** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001483*/
drhaa9b8962008-01-08 02:57:55 +00001484int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001485 Parse *pParse, /* Parsing context */
1486 Table *pTab, /* Table to be opened */
drhdfe88ec2008-11-03 20:55:06 +00001487 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001488 int op /* OP_OpenRead or OP_OpenWrite */
1489){
drhcd446902004-02-24 01:05:31 +00001490 int i;
drh4cbdda92006-06-14 19:00:20 +00001491 int iDb;
drhcd446902004-02-24 01:05:31 +00001492 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001493 Vdbe *v;
1494
drhaa9b8962008-01-08 02:57:55 +00001495 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001496 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1497 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001498 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001499 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001500 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001501 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001502 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001503 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001504 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001505 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001506 }
drh1b7ecbb2009-05-03 01:00:59 +00001507 if( pParse->nTab<baseCur+i ){
drh04adf412008-01-08 18:57:50 +00001508 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001509 }
drhaa9b8962008-01-08 02:57:55 +00001510 return i-1;
drhcd446902004-02-24 01:05:31 +00001511}
drh9d9cf222007-02-13 15:01:11 +00001512
drh91c58e22007-03-27 12:04:04 +00001513
1514#ifdef SQLITE_TEST
1515/*
1516** The following global variable is incremented whenever the
1517** transfer optimization is used. This is used for testing
1518** purposes only - to make sure the transfer optimization really
1519** is happening when it is suppose to.
1520*/
1521int sqlite3_xferopt_count;
1522#endif /* SQLITE_TEST */
1523
1524
drh9d9cf222007-02-13 15:01:11 +00001525#ifndef SQLITE_OMIT_XFER_OPT
1526/*
1527** Check to collation names to see if they are compatible.
1528*/
1529static int xferCompatibleCollation(const char *z1, const char *z2){
1530 if( z1==0 ){
1531 return z2==0;
1532 }
1533 if( z2==0 ){
1534 return 0;
1535 }
1536 return sqlite3StrICmp(z1, z2)==0;
1537}
1538
1539
1540/*
1541** Check to see if index pSrc is compatible as a source of data
1542** for index pDest in an insert transfer optimization. The rules
1543** for a compatible index:
1544**
1545** * The index is over the same set of columns
1546** * The same DESC and ASC markings occurs on all columns
1547** * The same onError processing (OE_Abort, OE_Ignore, etc)
1548** * The same collating sequence on each column
1549*/
1550static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1551 int i;
1552 assert( pDest && pSrc );
1553 assert( pDest->pTable!=pSrc->pTable );
1554 if( pDest->nColumn!=pSrc->nColumn ){
1555 return 0; /* Different number of columns */
1556 }
1557 if( pDest->onError!=pSrc->onError ){
1558 return 0; /* Different conflict resolution strategies */
1559 }
1560 for(i=0; i<pSrc->nColumn; i++){
1561 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1562 return 0; /* Different columns indexed */
1563 }
1564 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1565 return 0; /* Different sort orders */
1566 }
drh3f6e7812009-05-02 00:28:19 +00001567 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
drh60a713c2008-01-21 16:22:45 +00001568 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001569 }
1570 }
1571
1572 /* If no test above fails then the indices must be compatible */
1573 return 1;
1574}
1575
1576/*
1577** Attempt the transfer optimization on INSERTs of the form
1578**
1579** INSERT INTO tab1 SELECT * FROM tab2;
1580**
1581** This optimization is only attempted if
1582**
1583** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001584** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001585**
1586** (2) tab1 and tab2 are different tables
1587**
1588** (3) There must be no triggers on tab1
1589**
1590** (4) The result set of the SELECT statement is "*"
1591**
1592** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1593** or LIMIT clause.
1594**
1595** (6) The SELECT statement is a simple (not a compound) select that
1596** contains only tab2 in its FROM clause
1597**
1598** This method for implementing the INSERT transfers raw records from
1599** tab2 over to tab1. The columns are not decoded. Raw records from
1600** the indices of tab2 are transfered to tab1 as well. In so doing,
1601** the resulting tab1 has much less fragmentation.
1602**
1603** This routine returns TRUE if the optimization is attempted. If any
1604** of the conditions above fail so that the optimization should not
1605** be attempted, then this routine returns FALSE.
1606*/
1607static int xferOptimization(
1608 Parse *pParse, /* Parser context */
1609 Table *pDest, /* The table we are inserting into */
1610 Select *pSelect, /* A SELECT statement to use as the data source */
1611 int onError, /* How to handle constraint errors */
1612 int iDbDest /* The database of pDest */
1613){
1614 ExprList *pEList; /* The result set of the SELECT */
1615 Table *pSrc; /* The table in the FROM clause of SELECT */
1616 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1617 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1618 int i; /* Loop counter */
1619 int iDbSrc; /* The database of pSrc */
1620 int iSrc, iDest; /* Cursors from source and destination */
1621 int addr1, addr2; /* Loop addresses */
1622 int emptyDestTest; /* Address of test for empty pDest */
1623 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001624 Vdbe *v; /* The VDBE we are building */
1625 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001626 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001627 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001628 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001629
1630 if( pSelect==0 ){
1631 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1632 }
danielk19772f886d12009-02-28 10:47:41 +00001633 if( sqlite3TriggerList(pParse, pDest) ){
drh9d9cf222007-02-13 15:01:11 +00001634 return 0; /* tab1 must not have triggers */
1635 }
1636#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001637 if( pDest->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001638 return 0; /* tab1 must not be a virtual table */
1639 }
1640#endif
1641 if( onError==OE_Default ){
1642 onError = OE_Abort;
1643 }
1644 if( onError!=OE_Abort && onError!=OE_Rollback ){
1645 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1646 }
danielk19775ce240a2007-09-03 17:30:06 +00001647 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001648 if( pSelect->pSrc->nSrc!=1 ){
1649 return 0; /* FROM clause must have exactly one term */
1650 }
1651 if( pSelect->pSrc->a[0].pSelect ){
1652 return 0; /* FROM clause cannot contain a subquery */
1653 }
1654 if( pSelect->pWhere ){
1655 return 0; /* SELECT may not have a WHERE clause */
1656 }
1657 if( pSelect->pOrderBy ){
1658 return 0; /* SELECT may not have an ORDER BY clause */
1659 }
drh8103b7d2007-02-24 13:23:51 +00001660 /* Do not need to test for a HAVING clause. If HAVING is present but
1661 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001662 if( pSelect->pGroupBy ){
1663 return 0; /* SELECT may not have a GROUP BY clause */
1664 }
1665 if( pSelect->pLimit ){
1666 return 0; /* SELECT may not have a LIMIT clause */
1667 }
drh8103b7d2007-02-24 13:23:51 +00001668 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001669 if( pSelect->pPrior ){
1670 return 0; /* SELECT may not be a compound query */
1671 }
drh7d10d5a2008-08-20 16:35:10 +00001672 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:11 +00001673 return 0; /* SELECT may not be DISTINCT */
1674 }
1675 pEList = pSelect->pEList;
1676 assert( pEList!=0 );
1677 if( pEList->nExpr!=1 ){
1678 return 0; /* The result set must have exactly one column */
1679 }
1680 assert( pEList->a[0].pExpr );
1681 if( pEList->a[0].pExpr->op!=TK_ALL ){
1682 return 0; /* The result set must be the special operator "*" */
1683 }
1684
1685 /* At this point we have established that the statement is of the
1686 ** correct syntactic form to participate in this optimization. Now
1687 ** we have to check the semantics.
1688 */
1689 pItem = pSelect->pSrc->a;
drhca424112008-01-25 15:04:48 +00001690 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
drh9d9cf222007-02-13 15:01:11 +00001691 if( pSrc==0 ){
1692 return 0; /* FROM clause does not contain a real table */
1693 }
1694 if( pSrc==pDest ){
1695 return 0; /* tab1 and tab2 may not be the same table */
1696 }
1697#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001698 if( pSrc->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001699 return 0; /* tab2 must not be a virtual table */
1700 }
1701#endif
1702 if( pSrc->pSelect ){
1703 return 0; /* tab2 may not be a view */
1704 }
1705 if( pDest->nCol!=pSrc->nCol ){
1706 return 0; /* Number of columns must be the same in tab1 and tab2 */
1707 }
1708 if( pDest->iPKey!=pSrc->iPKey ){
1709 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1710 }
1711 for(i=0; i<pDest->nCol; i++){
1712 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1713 return 0; /* Affinity must be the same on all columns */
1714 }
1715 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1716 return 0; /* Collating sequence must be the same on all columns */
1717 }
1718 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1719 return 0; /* tab2 must be NOT NULL if tab1 is */
1720 }
1721 }
1722 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001723 if( pDestIdx->onError!=OE_None ){
1724 destHasUniqueIdx = 1;
1725 }
drh9d9cf222007-02-13 15:01:11 +00001726 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1727 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1728 }
1729 if( pSrcIdx==0 ){
1730 return 0; /* pDestIdx has no corresponding index in pSrc */
1731 }
1732 }
drh7fc2f412007-03-29 00:08:24 +00001733#ifndef SQLITE_OMIT_CHECK
drh1d9da702010-01-07 15:17:02 +00001734 if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001735 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1736 }
drh7fc2f412007-03-29 00:08:24 +00001737#endif
drh713de342011-04-24 22:56:07 +00001738#ifndef SQLITE_OMIT_FOREIGN_KEY
1739 /* Disallow the transfer optimization if the destination table constains
1740 ** any foreign key constraints. This is more restrictive than necessary.
1741 ** But the main beneficiary of the transfer optimization is the VACUUM
1742 ** command, and the VACUUM command disables foreign key constraints. So
1743 ** the extra complication to make this rule less restrictive is probably
1744 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1745 */
1746 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1747 return 0;
1748 }
1749#endif
drh9d9cf222007-02-13 15:01:11 +00001750
1751 /* If we get this far, it means either:
1752 **
1753 ** * We can always do the transfer if the table contains an
1754 ** an integer primary key
1755 **
1756 ** * We can conditionally do the transfer if the destination
1757 ** table is empty.
1758 */
drhdd735212007-02-24 13:53:05 +00001759#ifdef SQLITE_TEST
1760 sqlite3_xferopt_count++;
1761#endif
drh9d9cf222007-02-13 15:01:11 +00001762 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1763 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001764 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001765 iSrc = pParse->nTab++;
1766 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001767 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001768 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001769 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001770 /* If tables do not have an INTEGER PRIMARY KEY and there
1771 ** are indices to be copied and the destination is not empty,
1772 ** we have to disallow the transfer optimization because the
1773 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001774 **
1775 ** Or if the destination has a UNIQUE index and is not empty,
1776 ** we also disallow the transfer optimization because we cannot
1777 ** insure that all entries in the union of DEST and SRC will be
1778 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001779 */
drh66a51672008-01-03 00:01:23 +00001780 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1781 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001782 sqlite3VdbeJumpHere(v, addr1);
1783 }else{
1784 emptyDestTest = 0;
1785 }
1786 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001787 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001788 regData = sqlite3GetTempReg(pParse);
1789 regRowid = sqlite3GetTempReg(pParse);
drh42242de2007-03-29 13:35:35 +00001790 if( pDest->iPKey>=0 ){
drhb7654112008-01-12 12:48:07 +00001791 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1792 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
dane0af83a2009-09-08 19:15:01 +00001793 sqlite3HaltConstraint(
1794 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001795 sqlite3VdbeJumpHere(v, addr2);
drhb7654112008-01-12 12:48:07 +00001796 autoIncStep(pParse, regAutoinc, regRowid);
drhbd36ba62007-03-31 13:00:26 +00001797 }else if( pDest->pIndex==0 ){
drhb7654112008-01-12 12:48:07 +00001798 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
drh95bad4c2007-03-28 18:04:10 +00001799 }else{
drhb7654112008-01-12 12:48:07 +00001800 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
drh7d10d5a2008-08-20 16:35:10 +00001801 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
drh95bad4c2007-03-28 18:04:10 +00001802 }
drhb7654112008-01-12 12:48:07 +00001803 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1804 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1805 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
danielk19771f4aa332008-01-03 09:51:55 +00001806 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001807 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh9d9cf222007-02-13 15:01:11 +00001808 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh1b7ecbb2009-05-03 01:00:59 +00001809 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
drh9d9cf222007-02-13 15:01:11 +00001810 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1811 }
1812 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001813 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1814 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001815 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001816 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1817 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001818 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001819 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001820 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001821 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001822 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001823 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001824 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1825 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh66a51672008-01-03 00:01:23 +00001826 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001827 sqlite3VdbeJumpHere(v, addr1);
1828 }
1829 sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00001830 sqlite3ReleaseTempReg(pParse, regRowid);
1831 sqlite3ReleaseTempReg(pParse, regData);
drh66a51672008-01-03 00:01:23 +00001832 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1833 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001834 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001835 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001836 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001837 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001838 return 0;
1839 }else{
1840 return 1;
1841 }
1842}
1843#endif /* SQLITE_OMIT_XFER_OPT */