blob: 943afcdbbffa0c84bba3c8de3a7692704f1b940b [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**
danielk19776c8c8ce2008-01-02 16:27:09 +000015** $Id: insert.c,v 1.201 2008/01/02 16:27:10 danielk1977 Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
19/*
danielk19773d1bfea2004-05-14 11:00:53 +000020** Set P3 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000021** string for index pIdx. A column affinity string has one character
danielk19773d1bfea2004-05-14 11:00:53 +000022** for each column in the table, according to the affinity of the column:
23**
24** Character Column affinity
25** ------------------------------
drh3eda0402005-11-24 13:15:32 +000026** 'a' TEXT
27** 'b' NONE
28** 'c' NUMERIC
29** 'd' INTEGER
30** 'e' REAL
danielk19773d1bfea2004-05-14 11:00:53 +000031*/
danielk1977a37cdde2004-05-16 11:15:36 +000032void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
33 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000034 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000035 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000036 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000037 **
38 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000039 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000040 ** up.
41 */
42 int n;
43 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000044 sqlite3 *db = sqlite3VdbeDb(v);
drh17435752007-08-16 04:30:38 +000045 pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
danielk1977a37cdde2004-05-16 11:15:36 +000046 if( !pIdx->zColAff ){
47 return;
48 }
49 for(n=0; n<pIdx->nColumn; n++){
50 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
51 }
52 pIdx->zColAff[pIdx->nColumn] = '\0';
53 }
danielk19773d1bfea2004-05-14 11:00:53 +000054
drh956bc922004-07-24 17:38:29 +000055 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000056}
57
58/*
59** Set P3 of the most recently inserted opcode to a column affinity
60** string for table pTab. A column affinity string has one character
61** for each column indexed by the index, according to the affinity of the
62** column:
63**
64** Character Column affinity
65** ------------------------------
drh3eda0402005-11-24 13:15:32 +000066** 'a' TEXT
67** 'b' NONE
68** 'c' NUMERIC
69** 'd' INTEGER
70** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000071*/
72void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000073 /* The first time a column affinity string for a particular table
74 ** is required, it is allocated and populated here. It is then
75 ** stored as a member of the Table structure for subsequent use.
76 **
77 ** The column affinity string will eventually be deleted by
78 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
79 */
80 if( !pTab->zColAff ){
81 char *zColAff;
82 int i;
drhabb6fca2007-08-16 12:24:01 +000083 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +000084
drh17435752007-08-16 04:30:38 +000085 zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000086 if( !zColAff ){
danielk1977a37cdde2004-05-16 11:15:36 +000087 return;
danielk19773d1bfea2004-05-14 11:00:53 +000088 }
89
90 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000091 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000092 }
93 zColAff[pTab->nCol] = '\0';
94
95 pTab->zColAff = zColAff;
96 }
97
drh956bc922004-07-24 17:38:29 +000098 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +000099}
100
danielk19774d887782005-02-08 08:42:27 +0000101/*
drh48d11782007-11-23 15:02:19 +0000102** Return non-zero if the table pTab in database iDb or any of its indices
103** have been opened at any point in the VDBE program beginning at location
104** iStartAddr throught the end of the program. This is used to see if
105** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
106** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000107*/
drh48d11782007-11-23 15:02:19 +0000108static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000109 int i;
drh48d11782007-11-23 15:02:19 +0000110 int iEnd = sqlite3VdbeCurrentAddr(v);
111 for(i=iStartAddr; i<iEnd; i++){
112 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000113 assert( pOp!=0 );
drh48d11782007-11-23 15:02:19 +0000114 if( pOp->opcode==OP_OpenRead ){
115 VdbeOp *pPrior = &pOp[-1];
116 int tnum = pOp->p2;
117 assert( i>iStartAddr );
118 assert( pPrior->opcode==OP_Integer );
119 if( pPrior->p1==iDb ){
120 Index *pIndex;
121 if( tnum==pTab->tnum ){
122 return 1;
123 }
124 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
125 if( tnum==pIndex->tnum ){
126 return 1;
127 }
128 }
129 }
130 }
drh543165e2007-11-27 14:46:41 +0000131#ifndef SQLITE_OMIT_VIRTUALTABLE
drhd4e70eb2008-01-02 00:34:36 +0000132 if( pOp->opcode==OP_VOpen && pOp->p3.p==(const char*)pTab->pVtab ){
133 assert( pOp->p3.p!=0 );
drh48d11782007-11-23 15:02:19 +0000134 assert( pOp->p3type==P3_VTAB );
135 return 1;
danielk19774d887782005-02-08 08:42:27 +0000136 }
drh543165e2007-11-27 14:46:41 +0000137#endif
danielk19774d887782005-02-08 08:42:27 +0000138 }
139 return 0;
140}
danielk19773d1bfea2004-05-14 11:00:53 +0000141
drh9d9cf222007-02-13 15:01:11 +0000142#ifndef SQLITE_OMIT_AUTOINCREMENT
143/*
144** Write out code to initialize the autoincrement logic. This code
145** looks up the current autoincrement value in the sqlite_sequence
146** table and stores that value in a memory cell. Code generated by
147** autoIncStep() will keep that memory cell holding the largest
148** rowid value. Code generated by autoIncEnd() will write the new
149** largest value of the counter back into the sqlite_sequence table.
150**
151** This routine returns the index of the mem[] cell that contains
152** the maximum rowid counter.
153**
154** Two memory cells are allocated. The next memory cell after the
155** one returned holds the rowid in sqlite_sequence where we will
156** write back the revised maximum rowid.
157*/
158static int autoIncBegin(
159 Parse *pParse, /* Parsing context */
160 int iDb, /* Index of the database holding pTab */
161 Table *pTab /* The table we are writing to */
162){
163 int memId = 0;
164 if( pTab->autoInc ){
165 Vdbe *v = pParse->pVdbe;
166 Db *pDb = &pParse->db->aDb[iDb];
167 int iCur = pParse->nTab;
168 int addr;
169 assert( v );
170 addr = sqlite3VdbeCurrentAddr(v);
171 memId = pParse->nMem+1;
172 pParse->nMem += 2;
173 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
174 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
175 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
176 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
177 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
178 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
179 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
180 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
181 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
182 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
183 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
184 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
185 }
186 return memId;
187}
188
189/*
190** Update the maximum rowid for an autoincrement calculation.
191**
192** This routine should be called when the top of the stack holds a
193** new rowid that is about to be inserted. If that new rowid is
194** larger than the maximum rowid in the memId memory cell, then the
195** memory cell is updated. The stack is unchanged.
196*/
197static void autoIncStep(Parse *pParse, int memId){
198 if( memId>0 ){
199 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
200 }
201}
202
203/*
204** After doing one or more inserts, the maximum rowid is stored
205** in mem[memId]. Generate code to write this value back into the
206** the sqlite_sequence table.
207*/
208static void autoIncEnd(
209 Parse *pParse, /* The parsing context */
210 int iDb, /* Index of the database holding pTab */
211 Table *pTab, /* Table we are inserting into */
212 int memId /* Memory cell holding the maximum rowid */
213){
214 if( pTab->autoInc ){
215 int iCur = pParse->nTab;
216 Vdbe *v = pParse->pVdbe;
217 Db *pDb = &pParse->db->aDb[iDb];
218 int addr;
219 assert( v );
220 addr = sqlite3VdbeCurrentAddr(v);
221 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
222 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
223 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
224 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
225 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
226 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
227 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
228 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
drhe4d90812007-03-29 05:51:49 +0000229 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
drh9d9cf222007-02-13 15:01:11 +0000230 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
231 }
232}
233#else
234/*
235** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
236** above are all no-ops
237*/
238# define autoIncBegin(A,B,C) (0)
239# define autoIncStep(A,B)
240# define autoIncEnd(A,B,C,D)
241#endif /* SQLITE_OMIT_AUTOINCREMENT */
242
243
244/* Forward declaration */
245static int xferOptimization(
246 Parse *pParse, /* Parser context */
247 Table *pDest, /* The table we are inserting into */
248 Select *pSelect, /* A SELECT statement to use as the data source */
249 int onError, /* How to handle constraint errors */
250 int iDbDest /* The database of pDest */
251);
252
danielk19773d1bfea2004-05-14 11:00:53 +0000253/*
drh1ccde152000-06-17 13:12:39 +0000254** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000255**
256** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000257** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000258**
drh1ccde152000-06-17 13:12:39 +0000259** The IDLIST following the table name is always optional. If omitted,
260** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000261** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000262**
263** The pList parameter holds EXPRLIST in the first form of the INSERT
264** statement above, and pSelect is NULL. For the second form, pList is
265** NULL and pSelect is a pointer to the select statement used to generate
266** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000267**
drh9d9cf222007-02-13 15:01:11 +0000268** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000269** select with data coming from a VALUES clause, the code executes
270** once straight down through. The template looks like this:
271**
272** open write cursor to <table> and its indices
273** puts VALUES clause expressions onto the stack
274** write the resulting record into <table>
275** cleanup
276**
drh9d9cf222007-02-13 15:01:11 +0000277** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000278**
279** INSERT INTO <table> SELECT ...
280**
drh9d9cf222007-02-13 15:01:11 +0000281** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
282** in other words if the SELECT pulls all columns from a single table
283** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
284** if <table2> and <table1> are distinct tables but have identical
285** schemas, including all the same indices, then a special optimization
286** is invoked that copies raw records from <table2> over to <table1>.
287** See the xferOptimization() function for the implementation of this
288** template. This is the second template.
289**
290** open a write cursor to <table>
291** open read cursor on <table2>
292** transfer all records in <table2> over to <table>
293** close cursors
294** foreach index on <table>
295** open a write cursor on the <table> index
296** open a read cursor on the corresponding <table2> index
297** transfer all records from the read to the write cursors
298** close cursors
299** end foreach
300**
301** The third template is for when the second template does not apply
302** and the SELECT clause does not read from <table> at any time.
303** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000304**
305** goto B
306** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000307** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000308** gosub C
309** end loop
310** cleanup after the SELECT
311** goto D
312** B: open write cursor to <table> and its indices
313** goto A
314** C: insert the select result into <table>
315** return
316** D: cleanup
317**
drh9d9cf222007-02-13 15:01:11 +0000318** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000319** values from a SELECT but the data is being inserted into a table
320** that is also read as part of the SELECT. In the third form,
321** we have to use a intermediate table to store the results of
322** the select. The template is like this:
323**
324** goto B
325** A: setup for the SELECT
326** loop over the tables in the SELECT
327** gosub C
328** end loop
329** cleanup after the SELECT
330** goto D
331** C: insert the select result into the intermediate table
332** return
333** B: open a cursor to an intermediate table
334** goto A
335** D: open write cursor to <table> and its indices
336** loop over the intermediate table
337** transfer values form intermediate table into <table>
338** end the loop
339** cleanup
drhcce7d172000-05-31 15:34:51 +0000340*/
danielk19774adee202004-05-08 08:23:19 +0000341void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000342 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000343 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000344 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000345 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000346 IdList *pColumn, /* Column names corresponding to IDLIST. */
347 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000348){
drh5974a302000-06-07 14:42:26 +0000349 Table *pTab; /* The table to insert into */
drh113088e2003-03-20 01:16:58 +0000350 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000351 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000352 int i, j, idx; /* Loop counters */
353 Vdbe *v; /* Generate code into this virtual machine */
354 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000355 int nColumn; /* Number of columns in the data */
danielk1977cfe9a692004-06-16 12:00:29 +0000356 int base = 0; /* VDBE Cursor number for pTab */
357 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
drh9bb575f2004-09-06 17:24:11 +0000358 sqlite3 *db; /* The main database structure */
drh4a324312001-12-21 14:30:42 +0000359 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000360 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000361 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000362 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
363 int iSelectLoop = 0; /* Address of code that implements the SELECT */
364 int iCleanup = 0; /* Address of the cleanup code */
365 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
366 int iCntMem = 0; /* Memory cell used for the row counter */
drh798da522004-11-04 04:42:28 +0000367 int newIdx = -1; /* Cursor for the NEW table */
drh2958a4e2004-11-12 03:56:15 +0000368 Db *pDb; /* The database containing table being inserted into */
369 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
drhe4d90812007-03-29 05:51:49 +0000370 int appendFlag = 0; /* True if the insert is likely to be an append */
danielk1977da184232006-01-05 11:34:32 +0000371 int iDb;
drhcce7d172000-05-31 15:34:51 +0000372
danielk1977034ca142007-06-26 10:38:54 +0000373 int nHidden = 0;
374
drh798da522004-11-04 04:42:28 +0000375#ifndef SQLITE_OMIT_TRIGGER
376 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000377 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000378#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000379
drh17435752007-08-16 04:30:38 +0000380 db = pParse->db;
381 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000382 goto insert_cleanup;
383 }
drhdaffd0e2001-04-11 14:28:42 +0000384
drh1ccde152000-06-17 13:12:39 +0000385 /* Locate the table into which we will be inserting new information.
386 */
drh113088e2003-03-20 01:16:58 +0000387 assert( pTabList->nSrc==1 );
388 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000389 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000390 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000391 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000392 goto insert_cleanup;
393 }
danielk1977da184232006-01-05 11:34:32 +0000394 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
395 assert( iDb<db->nDb );
396 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000397 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000398 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000399 goto insert_cleanup;
400 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000401
drhb7f91642004-10-31 02:22:47 +0000402 /* Figure out if we have any triggers and if the table being
403 ** inserted into is a view
404 */
405#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000406 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000407 isView = pTab->pSelect!=0;
408#else
drhdca76842004-12-07 14:06:13 +0000409# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000410# define isView 0
411#endif
412#ifdef SQLITE_OMIT_VIEW
413# undef isView
414# define isView 0
415#endif
416
danielk1977c3f9bad2002-05-15 08:30:12 +0000417 /* Ensure that:
418 * (a) the table is not read-only,
419 * (b) that if it is a view then ON INSERT triggers exist
420 */
drhdca76842004-12-07 14:06:13 +0000421 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000422 goto insert_cleanup;
423 }
drh43617e92006-03-06 20:55:46 +0000424 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000425
drhf573c992002-07-31 00:32:50 +0000426 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000427 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
428 ** module table).
drhf573c992002-07-31 00:32:50 +0000429 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000430 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000431 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000432 }
433
drh1ccde152000-06-17 13:12:39 +0000434 /* Allocate a VDBE
435 */
danielk19774adee202004-05-08 08:23:19 +0000436 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000437 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000438 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000439 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000440
danielk1977c3f9bad2002-05-15 08:30:12 +0000441 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000442 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000443 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000444 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000445
drh9d9cf222007-02-13 15:01:11 +0000446#ifndef SQLITE_OMIT_XFER_OPT
447 /* If the statement is of the form
448 **
449 ** INSERT INTO <table1> SELECT * FROM <table2>;
450 **
451 ** Then special optimizations can be applied that make the transfer
452 ** very fast and which reduce fragmentation of indices.
453 */
454 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
455 assert( !triggers_exist );
456 assert( pList==0 );
457 goto insert_cleanup;
458 }
459#endif /* SQLITE_OMIT_XFER_OPT */
460
drh2958a4e2004-11-12 03:56:15 +0000461 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000462 ** sqlite_sequence table and store it in memory cell counterMem. Also
463 ** remember the rowid of the sqlite_sequence table entry in memory cell
464 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000465 */
drh9d9cf222007-02-13 15:01:11 +0000466 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000467
drh1ccde152000-06-17 13:12:39 +0000468 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000469 ** is coming from a SELECT statement, then this step also generates
470 ** all the code to implement the SELECT statement and invoke a subroutine
471 ** to process each row of the result. (Template 2.) If the SELECT
472 ** statement uses the the table that is being inserted into, then the
473 ** subroutine is also coded here. That subroutine stores the SELECT
474 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000475 */
drh5974a302000-06-07 14:42:26 +0000476 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000477 /* Data is coming from a SELECT. Generate code to implement that SELECT
478 */
danielk19776c8c8ce2008-01-02 16:27:09 +0000479 SelectDest dest = {SRT_Subroutine, 0, 0};
drh142e30d2002-08-28 03:00:58 +0000480 int rc, iInitCode;
danielk19774adee202004-05-08 08:23:19 +0000481 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
482 iSelectLoop = sqlite3VdbeCurrentAddr(v);
483 iInsertBlock = sqlite3VdbeMakeLabel(v);
danielk19776c8c8ce2008-01-02 16:27:09 +0000484 dest.iParm = iInsertBlock;
danielk1977b3bce662005-01-29 08:32:43 +0000485
486 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000487 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
drh17435752007-08-16 04:30:38 +0000488 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000489 goto insert_cleanup;
490 }
danielk1977b3bce662005-01-29 08:32:43 +0000491
danielk19774adee202004-05-08 08:23:19 +0000492 iCleanup = sqlite3VdbeMakeLabel(v);
493 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000494 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000495 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000496
497 /* Set useTempTable to TRUE if the result of the SELECT statement
498 ** should be written into a temporary table. Set to FALSE if each
499 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000500 **
501 ** A temp table must be used if the table being updated is also one
502 ** of the tables being read by the SELECT statement. Also use a
503 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000504 */
drh48d11782007-11-23 15:02:19 +0000505 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000506 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000507 }
drh142e30d2002-08-28 03:00:58 +0000508
509 if( useTempTable ){
510 /* Generate the subroutine that SELECT calls to process each row of
511 ** the result. Store the result in a temporary table
512 */
513 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000514 sqlite3VdbeResolveLabel(v, iInsertBlock);
danielk1977997a9042007-12-12 17:42:53 +0000515 sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000516 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf0863fe2005-06-12 21:35:51 +0000517 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
danielk19774adee202004-05-08 08:23:19 +0000518 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhe4d90812007-03-29 05:51:49 +0000519 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
danielk19774adee202004-05-08 08:23:19 +0000520 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000521
522 /* The following code runs first because the GOTO at the very top
523 ** of the program jumps to it. Create the temporary table, then jump
524 ** back up and execute the SELECT code above.
525 */
drhd654be82005-09-20 17:42:23 +0000526 sqlite3VdbeJumpHere(v, iInitCode);
drhb9bb7c12006-06-11 23:41:55 +0000527 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
drhb6f54522004-05-20 02:42:16 +0000528 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
danielk19774adee202004-05-08 08:23:19 +0000529 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
530 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000531 }else{
drhd654be82005-09-20 17:42:23 +0000532 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000533 }
drh5974a302000-06-07 14:42:26 +0000534 }else{
drh142e30d2002-08-28 03:00:58 +0000535 /* This is the case if the data for the INSERT is coming from a VALUES
536 ** clause
537 */
danielk1977b3bce662005-01-29 08:32:43 +0000538 NameContext sNC;
539 memset(&sNC, 0, sizeof(sNC));
540 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000541 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000542 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000543 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000544 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000545 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000546 goto insert_cleanup;
547 }
drhe64e7b22002-02-18 13:56:36 +0000548 }
drh5974a302000-06-07 14:42:26 +0000549 }
drh1ccde152000-06-17 13:12:39 +0000550
551 /* Make sure the number of columns in the source data matches the number
552 ** of columns to be inserted into the table.
553 */
danielk1977034ca142007-06-26 10:38:54 +0000554 if( IsVirtual(pTab) ){
555 for(i=0; i<pTab->nCol; i++){
556 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
557 }
558 }
559 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000560 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000561 "table %S has %d columns but %d values were supplied",
562 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000563 goto insert_cleanup;
564 }
drh967e8b72000-06-21 13:59:10 +0000565 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000566 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000567 goto insert_cleanup;
568 }
drh1ccde152000-06-17 13:12:39 +0000569
570 /* If the INSERT statement included an IDLIST term, then make sure
571 ** all elements of the IDLIST really are columns of the table and
572 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000573 **
574 ** If the table has an INTEGER PRIMARY KEY column and that column
575 ** is named in the IDLIST, then record in the keyColumn variable
576 ** the index into IDLIST of the primary key column. keyColumn is
577 ** the index of the primary key as it appears in IDLIST, not as
578 ** is appears in the original table. (The index of the primary
579 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000580 */
drh967e8b72000-06-21 13:59:10 +0000581 if( pColumn ){
582 for(i=0; i<pColumn->nId; i++){
583 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000584 }
drh967e8b72000-06-21 13:59:10 +0000585 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000586 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000587 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000588 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000589 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000590 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000591 }
drhcce7d172000-05-31 15:34:51 +0000592 break;
593 }
594 }
595 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000596 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000597 keyColumn = i;
598 }else{
danielk19774adee202004-05-08 08:23:19 +0000599 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000600 pTabList, 0, pColumn->a[i].zName);
601 pParse->nErr++;
602 goto insert_cleanup;
603 }
drhcce7d172000-05-31 15:34:51 +0000604 }
605 }
606 }
drh1ccde152000-06-17 13:12:39 +0000607
drhaacc5432002-01-06 17:07:40 +0000608 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000609 ** key, the set the keyColumn variable to the primary key column index
610 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000611 */
drh147d0cc2006-08-25 23:42:53 +0000612 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000613 keyColumn = pTab->iPKey;
614 }
615
drh142e30d2002-08-28 03:00:58 +0000616 /* Open the temp table for FOR EACH ROW triggers
617 */
drhdca76842004-12-07 14:06:13 +0000618 if( triggers_exist ){
danielk19774adee202004-05-08 08:23:19 +0000619 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
danielk197784ac9d02004-05-18 09:58:06 +0000620 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000621 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000622
drhfeeb1392002-04-09 03:28:01 +0000623 /* Initialize the count of rows to be inserted
624 */
drh142e30d2002-08-28 03:00:58 +0000625 if( db->flags & SQLITE_CountRows ){
626 iCntMem = pParse->nMem++;
drhd654be82005-09-20 17:42:23 +0000627 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000628 }
629
danielk1977e448dc42008-01-02 11:50:51 +0000630 /* If this is not a view, open the table and and all indices */
631 if( !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000632 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000633 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000634 }
635
drh142e30d2002-08-28 03:00:58 +0000636 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000637 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000638 ** source is a subroutine call from the SELECT statement, then we need
639 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000640 */
drh142e30d2002-08-28 03:00:58 +0000641 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000642 iBreak = sqlite3VdbeMakeLabel(v);
643 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
644 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000645 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000646 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
647 sqlite3VdbeResolveLabel(v, iInsertBlock);
danielk1977997a9042007-12-12 17:42:53 +0000648 sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000649 }
drh1ccde152000-06-17 13:12:39 +0000650
drh5cf590c2003-04-24 01:45:04 +0000651 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000652 */
danielk19774adee202004-05-08 08:23:19 +0000653 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000654 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000655
drh70ce3f02003-04-15 19:22:22 +0000656 /* build the NEW.* reference row. Note that if there is an INTEGER
657 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
658 ** translated into a unique ID for the row. But on a BEFORE trigger,
659 ** we do not know what the unique ID will be (because the insert has
660 ** not happened yet) so we substitute a rowid of -1
661 */
662 if( keyColumn<0 ){
danielk19774adee202004-05-08 08:23:19 +0000663 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000664 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000665 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000666 }else{
drhd6fe9612005-01-14 01:22:00 +0000667 assert( pSelect==0 ); /* Otherwise useTempTable is true */
danielk19774adee202004-05-08 08:23:19 +0000668 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
669 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
670 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
671 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
672 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000673 }
674
danielk1977034ca142007-06-26 10:38:54 +0000675 /* Cannot have triggers on a virtual table. If it were possible,
676 ** this block would have to account for hidden column.
677 */
678 assert(!IsVirtual(pTab));
679
drh70ce3f02003-04-15 19:22:22 +0000680 /* Create the new column data
681 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000682 for(i=0; i<pTab->nCol; i++){
683 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000684 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000685 }else{
drh9adf9ac2002-05-15 11:44:13 +0000686 for(j=0; j<pColumn->nId; j++){
687 if( pColumn->a[j].idx==i ) break;
688 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000689 }
690 if( pColumn && j>=pColumn->nId ){
danielk19777977a172004-11-09 12:44:37 +0000691 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000692 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000693 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000694 }else{
drhd6fe9612005-01-14 01:22:00 +0000695 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000696 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000697 }
698 }
danielk19774adee202004-05-08 08:23:19 +0000699 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000700
701 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
702 ** do not attempt any conversions before assembling the record.
703 ** If this is a real table, attempt conversions as required by the
704 ** table column affinities.
705 */
706 if( !isView ){
707 sqlite3TableAffinityStr(v, pTab);
708 }
drhf0863fe2005-06-12 21:35:51 +0000709 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000710
drh5cf590c2003-04-24 01:45:04 +0000711 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000712 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000713 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000714 goto insert_cleanup;
715 }
drh70ce3f02003-04-15 19:22:22 +0000716 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000717
drh4a324312001-12-21 14:30:42 +0000718 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000719 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000720 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000721 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000722 */
drh5cf590c2003-04-24 01:45:04 +0000723 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000724 if( IsVirtual(pTab) ){
725 /* The row that the VUpdate opcode will delete: none */
726 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
727 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000728 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000729 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000730 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh142e30d2002-08-28 03:00:58 +0000731 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000732 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000733 }else{
drhe4d90812007-03-29 05:51:49 +0000734 VdbeOp *pOp;
danielk19774adee202004-05-08 08:23:19 +0000735 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
drhe4d90812007-03-29 05:51:49 +0000736 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000737 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000738 appendFlag = 1;
739 pOp->opcode = OP_NewRowid;
740 pOp->p1 = base;
741 pOp->p2 = counterMem;
742 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000743 }
drhf0863fe2005-06-12 21:35:51 +0000744 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000745 ** to generate a unique primary key value.
746 */
drhe4d90812007-03-29 05:51:49 +0000747 if( !appendFlag ){
748 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
749 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
750 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
751 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
752 }
drh4cbdda92006-06-14 19:00:20 +0000753 }else if( IsVirtual(pTab) ){
754 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000755 }else{
drhf0863fe2005-06-12 21:35:51 +0000756 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
drhe4d90812007-03-29 05:51:49 +0000757 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000758 }
drh9d9cf222007-02-13 15:01:11 +0000759 autoIncStep(pParse, counterMem);
drh4a324312001-12-21 14:30:42 +0000760
danielk1977c3f9bad2002-05-15 08:30:12 +0000761 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000762 ** with the first column.
763 */
danielk1977034ca142007-06-26 10:38:54 +0000764 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000765 for(i=0; i<pTab->nCol; i++){
766 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000767 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000768 ** Whenever this column is read, the record number will be substituted
769 ** in its place. So will fill this column with a NULL to avoid
770 ** taking up data space with information that will never be used. */
drhf0863fe2005-06-12 21:35:51 +0000771 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh9adf9ac2002-05-15 11:44:13 +0000772 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000773 }
774 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000775 if( IsHiddenColumn(&pTab->aCol[i]) ){
776 assert( IsVirtual(pTab) );
777 j = -1;
778 nHidden++;
779 }else{
780 j = i - nHidden;
781 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000782 }else{
drh9adf9ac2002-05-15 11:44:13 +0000783 for(j=0; j<pColumn->nId; j++){
784 if( pColumn->a[j].idx==i ) break;
785 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000786 }
danielk1977034ca142007-06-26 10:38:54 +0000787 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk19777977a172004-11-09 12:44:37 +0000788 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000789 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000790 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
drh142e30d2002-08-28 03:00:58 +0000791 }else if( pSelect ){
drh16ed8a62006-08-29 18:46:14 +0000792 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000793 }else{
danielk19774adee202004-05-08 08:23:19 +0000794 sqlite3ExprCode(pParse, pList->a[j].pExpr);
drh5974a302000-06-07 14:42:26 +0000795 }
drhbed86902000-06-02 13:27:59 +0000796 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000797
798 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000799 ** do the insertion.
800 */
drh4cbdda92006-06-14 19:00:20 +0000801#ifndef SQLITE_OMIT_VIRTUALTABLE
802 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000803 pParse->pVirtualLock = pTab;
danielk19771f6eec52006-06-16 06:17:47 +0000804 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
drh4cbdda92006-06-14 19:00:20 +0000805 (const char*)pTab->pVtab, P3_VTAB);
806 }else
807#endif
808 {
809 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
810 0, onError, endOfLoop);
811 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000812 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
813 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000814 }
drh5cf590c2003-04-24 01:45:04 +0000815 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000816
drh5cf590c2003-04-24 01:45:04 +0000817 /* Update the count of rows that are inserted
818 */
819 if( (db->flags & SQLITE_CountRows)!=0 ){
drh15007a92006-01-08 18:10:17 +0000820 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
drh5974a302000-06-07 14:42:26 +0000821 }
drh1ccde152000-06-17 13:12:39 +0000822
drhdca76842004-12-07 14:06:13 +0000823 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000824 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000825 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000826 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000827 goto insert_cleanup;
828 }
drh1bee3d72001-10-15 00:44:35 +0000829 }
830
drh1ccde152000-06-17 13:12:39 +0000831 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000832 */
danielk19774adee202004-05-08 08:23:19 +0000833 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000834 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000835 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
836 sqlite3VdbeResolveLabel(v, iBreak);
837 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000838 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000839 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
840 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
841 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000842 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000843
danielk1977e448dc42008-01-02 11:50:51 +0000844 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000845 /* Close all tables opened */
danielk19774adee202004-05-08 08:23:19 +0000846 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000847 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000848 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000849 }
drhcce7d172000-05-31 15:34:51 +0000850 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000851
drhf3388142004-11-13 03:48:06 +0000852 /* Update the sqlite_sequence table by storing the content of the
853 ** counter value in memory counterMem back into the sqlite_sequence
854 ** table.
drh2958a4e2004-11-12 03:56:15 +0000855 */
drh9d9cf222007-02-13 15:01:11 +0000856 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000857
drh1bee3d72001-10-15 00:44:35 +0000858 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000859 ** Return the number of rows inserted. If this routine is
860 ** generating code because of a call to sqlite3NestedParse(), do not
861 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000862 */
danielk1977cc6bd382005-01-10 02:48:49 +0000863 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drhd4e70eb2008-01-02 00:34:36 +0000864 sqlite3VdbeAddOp(v, OP_ResultRow, iCntMem, 1);
danielk197722322fd2004-05-25 23:35:17 +0000865 sqlite3VdbeSetNumCols(v, 1);
danielk1977955de522006-02-10 02:27:42 +0000866 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000867 }
drhcce7d172000-05-31 15:34:51 +0000868
869insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000870 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000871 sqlite3ExprListDelete(pList);
872 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000873 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000874}
drh9cfcf5d2002-01-29 18:41:24 +0000875
drh9cfcf5d2002-01-29 18:41:24 +0000876/*
877** Generate code to do a constraint check prior to an INSERT or an UPDATE.
878**
879** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000880** the following values:
881**
drhf0863fe2005-06-12 21:35:51 +0000882** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000883** value is omitted unless we are doing an UPDATE that involves a
884** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000885**
drhf0863fe2005-06-12 21:35:51 +0000886** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000887**
888** 3. The data in the first column of the entry after the update.
889**
890** i. Data from middle columns...
891**
892** N. The data in the last column of the entry after the update.
893**
drhf0863fe2005-06-12 21:35:51 +0000894** The old rowid shown as entry (1) above is omitted unless both isUpdate
895** and rowidChng are 1. isUpdate is true for UPDATEs and false for
896** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000897**
898** The code generated by this routine pushes additional entries onto
899** the stack which are the keys for new index entries for the new record.
900** The order of index keys is the same as the order of the indices on
901** the pTable->pIndex list. A key is only created for index i if
902** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000903**
904** This routine also generates code to check constraints. NOT NULL,
905** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000906** then the appropriate action is performed. There are five possible
907** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000908**
909** Constraint type Action What Happens
910** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000911** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000912** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000913** return code of SQLITE_CONSTRAINT.
914**
drh1c928532002-01-31 15:54:21 +0000915** any ABORT Back out changes from the current command
916** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000917** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000918** with SQLITE_CONSTRAINT.
919**
920** any FAIL Sqlite_exec() returns immediately with a
921** return code of SQLITE_CONSTRAINT. The
922** transaction is not rolled back and any
923** prior changes are retained.
924**
drh9cfcf5d2002-01-29 18:41:24 +0000925** any IGNORE The record number and data is popped from
926** the stack and there is an immediate jump
927** to label ignoreDest.
928**
929** NOT NULL REPLACE The NULL value is replace by the default
930** value for that column. If the default value
931** is NULL, the action is the same as ABORT.
932**
933** UNIQUE REPLACE The other row that conflicts with the row
934** being inserted is removed.
935**
936** CHECK REPLACE Illegal. The results in an exception.
937**
drh1c928532002-01-31 15:54:21 +0000938** Which action to take is determined by the overrideError parameter.
939** Or if overrideError==OE_Default, then the pParse->onError parameter
940** is used. Or if pParse->onError==OE_Default then the onError value
941** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000942**
drhaaab5722002-02-19 13:39:21 +0000943** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000944** cursor number "base". All indices of pTab must also have open
945** read/write cursors with cursor number base+i for the i-th cursor.
946** Except, if there is no possibility of a REPLACE action then
947** cursors do not need to be open for indices where aIdxUsed[i]==0.
948**
949** If the isUpdate flag is true, it means that the "base" cursor is
950** initially pointing to an entry that is being updated. The isUpdate
951** flag causes extra code to be generated so that the "base" cursor
952** is still pointing at the same entry after the routine returns.
953** Without the isUpdate flag, the "base" cursor might be moved.
954*/
danielk19774adee202004-05-08 08:23:19 +0000955void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000956 Parse *pParse, /* The parser context */
957 Table *pTab, /* the table into which we are inserting */
958 int base, /* Index of a read/write cursor pointing at pTab */
959 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000960 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000961 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000962 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000963 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000964){
965 int i;
966 Vdbe *v;
967 int nCol;
968 int onError;
969 int addr;
970 int extra;
drh0ca3e242002-01-29 23:07:02 +0000971 int iCur;
972 Index *pIdx;
973 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000974 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000975 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000976
danielk19774adee202004-05-08 08:23:19 +0000977 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000978 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000979 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000980 nCol = pTab->nCol;
981
982 /* Test all NOT NULL constraints.
983 */
984 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000985 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +0000986 continue;
987 }
drh9cfcf5d2002-01-29 18:41:24 +0000988 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +0000989 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +0000990 if( overrideError!=OE_Default ){
991 onError = overrideError;
drha996e472003-05-16 02:30:27 +0000992 }else if( onError==OE_Default ){
993 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +0000994 }
danielk19777977a172004-11-09 12:44:37 +0000995 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +0000996 onError = OE_Abort;
997 }
danielk19774adee202004-05-08 08:23:19 +0000998 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
999 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +00001000 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1001 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001002 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001003 case OE_Rollback:
1004 case OE_Abort:
1005 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001006 char *zMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00001007 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1008 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001009 " may not be NULL", (char*)0);
danielk19774adee202004-05-08 08:23:19 +00001010 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001011 break;
1012 }
1013 case OE_Ignore: {
drhf0863fe2005-06-12 21:35:51 +00001014 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001015 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001016 break;
1017 }
1018 case OE_Replace: {
danielk19777977a172004-11-09 12:44:37 +00001019 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
danielk19774adee202004-05-08 08:23:19 +00001020 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001021 break;
1022 }
drh9cfcf5d2002-01-29 18:41:24 +00001023 }
drhd654be82005-09-20 17:42:23 +00001024 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001025 }
1026
1027 /* Test all CHECK constraints
1028 */
drhffe07b22005-11-03 00:41:17 +00001029#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001030 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001031 int allOk = sqlite3VdbeMakeLabel(v);
1032 assert( pParse->ckOffset==0 );
1033 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001034 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001035 assert( pParse->ckOffset==nCol );
1036 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001037 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001038 if( onError==OE_Ignore ){
drhaa01c7e2006-03-15 16:26:10 +00001039 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1040 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1041 }else{
1042 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1043 }
drhffe07b22005-11-03 00:41:17 +00001044 sqlite3VdbeResolveLabel(v, allOk);
1045 }
1046#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001047
drh0bd1f4e2002-06-06 18:54:39 +00001048 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1049 ** of the new record does not previously exist. Except, if this
1050 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001051 */
drhf0863fe2005-06-12 21:35:51 +00001052 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001053 onError = pTab->keyConf;
1054 if( overrideError!=OE_Default ){
1055 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001056 }else if( onError==OE_Default ){
1057 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001058 }
drha0217ba2003-06-01 01:10:33 +00001059
drh5383ae52003-06-04 12:23:30 +00001060 if( isUpdate ){
danielk19774adee202004-05-08 08:23:19 +00001061 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1062 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1063 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001064 }
danielk19774adee202004-05-08 08:23:19 +00001065 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1066 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001067 switch( onError ){
1068 default: {
1069 onError = OE_Abort;
1070 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001071 }
drh5383ae52003-06-04 12:23:30 +00001072 case OE_Rollback:
1073 case OE_Abort:
1074 case OE_Fail: {
danielk19774adee202004-05-08 08:23:19 +00001075 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
drh701a0ae2004-02-22 20:05:00 +00001076 "PRIMARY KEY must be unique", P3_STATIC);
drh5383ae52003-06-04 12:23:30 +00001077 break;
drh0ca3e242002-01-29 23:07:02 +00001078 }
drh5383ae52003-06-04 12:23:30 +00001079 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001080 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001081 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001082 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001083 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001084 }
1085 seenReplace = 1;
1086 break;
drh0ca3e242002-01-29 23:07:02 +00001087 }
drh5383ae52003-06-04 12:23:30 +00001088 case OE_Ignore: {
1089 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001090 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001091 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001092 break;
1093 }
1094 }
drhd654be82005-09-20 17:42:23 +00001095 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001096 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001097 sqlite3VdbeJumpHere(v, jumpInst1);
danielk19774adee202004-05-08 08:23:19 +00001098 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001099 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001100 }
1101 }
drh0bd1f4e2002-06-06 18:54:39 +00001102
1103 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1104 ** index and making sure that duplicate entries do not already exist.
1105 ** Add the new records to the indices as we go.
1106 */
drhb2fe7d82003-04-20 17:29:23 +00001107 extra = -1;
1108 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1109 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1110 extra++;
1111
1112 /* Create a key for accessing the index entry */
danielk19774adee202004-05-08 08:23:19 +00001113 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001114 for(i=0; i<pIdx->nColumn; i++){
1115 int idx = pIdx->aiColumn[i];
1116 if( idx==pTab->iPKey ){
danielk19774adee202004-05-08 08:23:19 +00001117 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001118 }else{
danielk19774adee202004-05-08 08:23:19 +00001119 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001120 }
1121 }
drh7f057c92005-06-24 03:53:06 +00001122 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001123 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001124
1125 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001126 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001127 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001128 if( overrideError!=OE_Default ){
1129 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001130 }else if( onError==OE_Default ){
1131 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001132 }
drh5383ae52003-06-04 12:23:30 +00001133 if( seenReplace ){
1134 if( onError==OE_Ignore ) onError = OE_Replace;
1135 else if( onError==OE_Fail ) onError = OE_Abort;
1136 }
1137
drhb2fe7d82003-04-20 17:29:23 +00001138
1139 /* Check to see if the new index entry will be unique */
drhf0863fe2005-06-12 21:35:51 +00001140 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
danielk19774adee202004-05-08 08:23:19 +00001141 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001142
1143 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001144 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1145 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001146 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001147 case OE_Rollback:
1148 case OE_Abort:
1149 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001150 int j, n1, n2;
1151 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001152 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1153 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001154 n1 = strlen(zErrMsg);
1155 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1156 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1157 n2 = strlen(zCol);
1158 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001159 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001160 n1 += 2;
1161 }
1162 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001163 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001164 n1 += 3;
1165 break;
1166 }else{
drh5bb3eb92007-05-04 13:15:55 +00001167 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001168 n1 += n2;
1169 }
1170 }
drh5bb3eb92007-05-04 13:15:55 +00001171 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001172 pIdx->nColumn>1 ? " are not unique" : " is not unique");
danielk19774adee202004-05-08 08:23:19 +00001173 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001174 break;
1175 }
1176 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001177 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001178 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001179 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001180 break;
1181 }
1182 case OE_Replace: {
danielk19774adee202004-05-08 08:23:19 +00001183 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001184 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001185 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001186 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001187 }
drh0ca3e242002-01-29 23:07:02 +00001188 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001189 break;
1190 }
drh9cfcf5d2002-01-29 18:41:24 +00001191 }
drh0bd1f4e2002-06-06 18:54:39 +00001192#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001193 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001194#endif
drhd654be82005-09-20 17:42:23 +00001195 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001196 }
1197}
drh0ca3e242002-01-29 23:07:02 +00001198
1199/*
1200** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001201** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001202** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001203** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001204** entries in all indices and in the main table.
1205**
drhb419a922002-01-30 16:17:23 +00001206** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001207** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001208*/
danielk19774adee202004-05-08 08:23:19 +00001209void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001210 Parse *pParse, /* The parser context */
1211 Table *pTab, /* the table into which we are inserting */
1212 int base, /* Index of a read/write cursor pointing at pTab */
1213 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001214 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001215 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001216 int newIdx, /* Index of NEW table for triggers. -1 if none */
1217 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001218){
1219 int i;
1220 Vdbe *v;
1221 int nIdx;
1222 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001223 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001224
danielk19774adee202004-05-08 08:23:19 +00001225 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001226 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001227 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001228 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1229 for(i=nIdx-1; i>=0; i--){
1230 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drhf0863fe2005-06-12 21:35:51 +00001231 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001232 }
danielk19774adee202004-05-08 08:23:19 +00001233 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001234 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001235#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001236 if( newIdx>=0 ){
danielk19774adee202004-05-08 08:23:19 +00001237 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1238 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhf0863fe2005-06-12 21:35:51 +00001239 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001240 }
danielk1977b84f96f2005-01-20 11:32:23 +00001241#endif
drh4794f732004-11-05 17:17:50 +00001242 if( pParse->nested ){
1243 pik_flags = 0;
1244 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001245 pik_flags = OPFLAG_NCHANGE;
1246 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001247 }
drhe4d90812007-03-29 05:51:49 +00001248 if( appendBias ){
1249 pik_flags |= OPFLAG_APPEND;
1250 }
drhf0863fe2005-06-12 21:35:51 +00001251 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001252 if( !pParse->nested ){
1253 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1254 }
danielk1977b28af712004-06-21 06:50:26 +00001255
drhf0863fe2005-06-12 21:35:51 +00001256 if( isUpdate && rowidChng ){
danielk19774adee202004-05-08 08:23:19 +00001257 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001258 }
1259}
drhcd446902004-02-24 01:05:31 +00001260
1261/*
drh290c1942004-08-21 17:54:45 +00001262** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001263** indices of that table. The "base" parameter is the cursor number used
1264** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001265*/
drh290c1942004-08-21 17:54:45 +00001266void sqlite3OpenTableAndIndices(
1267 Parse *pParse, /* Parsing context */
1268 Table *pTab, /* Table to be opened */
1269 int base, /* Cursor number assigned to the table */
1270 int op /* OP_OpenRead or OP_OpenWrite */
1271){
drhcd446902004-02-24 01:05:31 +00001272 int i;
drh4cbdda92006-06-14 19:00:20 +00001273 int iDb;
drhcd446902004-02-24 01:05:31 +00001274 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001275 Vdbe *v;
1276
1277 if( IsVirtual(pTab) ) return;
1278 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1279 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001280 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001281 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001282 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001283 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001284 assert( pIdx->pSchema==pTab->pSchema );
1285 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drhd4e70eb2008-01-02 00:34:36 +00001286 VdbeComment((v, "%s", pIdx->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00001287 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
drhcd446902004-02-24 01:05:31 +00001288 }
drh290c1942004-08-21 17:54:45 +00001289 if( pParse->nTab<=base+i ){
1290 pParse->nTab = base+i;
1291 }
drhcd446902004-02-24 01:05:31 +00001292}
drh9d9cf222007-02-13 15:01:11 +00001293
drh91c58e22007-03-27 12:04:04 +00001294
1295#ifdef SQLITE_TEST
1296/*
1297** The following global variable is incremented whenever the
1298** transfer optimization is used. This is used for testing
1299** purposes only - to make sure the transfer optimization really
1300** is happening when it is suppose to.
1301*/
1302int sqlite3_xferopt_count;
1303#endif /* SQLITE_TEST */
1304
1305
drh9d9cf222007-02-13 15:01:11 +00001306#ifndef SQLITE_OMIT_XFER_OPT
1307/*
1308** Check to collation names to see if they are compatible.
1309*/
1310static int xferCompatibleCollation(const char *z1, const char *z2){
1311 if( z1==0 ){
1312 return z2==0;
1313 }
1314 if( z2==0 ){
1315 return 0;
1316 }
1317 return sqlite3StrICmp(z1, z2)==0;
1318}
1319
1320
1321/*
1322** Check to see if index pSrc is compatible as a source of data
1323** for index pDest in an insert transfer optimization. The rules
1324** for a compatible index:
1325**
1326** * The index is over the same set of columns
1327** * The same DESC and ASC markings occurs on all columns
1328** * The same onError processing (OE_Abort, OE_Ignore, etc)
1329** * The same collating sequence on each column
1330*/
1331static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1332 int i;
1333 assert( pDest && pSrc );
1334 assert( pDest->pTable!=pSrc->pTable );
1335 if( pDest->nColumn!=pSrc->nColumn ){
1336 return 0; /* Different number of columns */
1337 }
1338 if( pDest->onError!=pSrc->onError ){
1339 return 0; /* Different conflict resolution strategies */
1340 }
1341 for(i=0; i<pSrc->nColumn; i++){
1342 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1343 return 0; /* Different columns indexed */
1344 }
1345 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1346 return 0; /* Different sort orders */
1347 }
1348 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1349 return 0; /* Different sort orders */
1350 }
1351 }
1352
1353 /* If no test above fails then the indices must be compatible */
1354 return 1;
1355}
1356
1357/*
1358** Attempt the transfer optimization on INSERTs of the form
1359**
1360** INSERT INTO tab1 SELECT * FROM tab2;
1361**
1362** This optimization is only attempted if
1363**
1364** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001365** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001366**
1367** (2) tab1 and tab2 are different tables
1368**
1369** (3) There must be no triggers on tab1
1370**
1371** (4) The result set of the SELECT statement is "*"
1372**
1373** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1374** or LIMIT clause.
1375**
1376** (6) The SELECT statement is a simple (not a compound) select that
1377** contains only tab2 in its FROM clause
1378**
1379** This method for implementing the INSERT transfers raw records from
1380** tab2 over to tab1. The columns are not decoded. Raw records from
1381** the indices of tab2 are transfered to tab1 as well. In so doing,
1382** the resulting tab1 has much less fragmentation.
1383**
1384** This routine returns TRUE if the optimization is attempted. If any
1385** of the conditions above fail so that the optimization should not
1386** be attempted, then this routine returns FALSE.
1387*/
1388static int xferOptimization(
1389 Parse *pParse, /* Parser context */
1390 Table *pDest, /* The table we are inserting into */
1391 Select *pSelect, /* A SELECT statement to use as the data source */
1392 int onError, /* How to handle constraint errors */
1393 int iDbDest /* The database of pDest */
1394){
1395 ExprList *pEList; /* The result set of the SELECT */
1396 Table *pSrc; /* The table in the FROM clause of SELECT */
1397 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1398 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1399 int i; /* Loop counter */
1400 int iDbSrc; /* The database of pSrc */
1401 int iSrc, iDest; /* Cursors from source and destination */
1402 int addr1, addr2; /* Loop addresses */
1403 int emptyDestTest; /* Address of test for empty pDest */
1404 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001405 Vdbe *v; /* The VDBE we are building */
1406 KeyInfo *pKey; /* Key information for an index */
1407 int counterMem; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001408 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001409
1410 if( pSelect==0 ){
1411 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1412 }
1413 if( pDest->pTrigger ){
1414 return 0; /* tab1 must not have triggers */
1415 }
1416#ifndef SQLITE_OMIT_VIRTUALTABLE
1417 if( pDest->isVirtual ){
1418 return 0; /* tab1 must not be a virtual table */
1419 }
1420#endif
1421 if( onError==OE_Default ){
1422 onError = OE_Abort;
1423 }
1424 if( onError!=OE_Abort && onError!=OE_Rollback ){
1425 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1426 }
danielk19775ce240a2007-09-03 17:30:06 +00001427 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001428 if( pSelect->pSrc->nSrc!=1 ){
1429 return 0; /* FROM clause must have exactly one term */
1430 }
1431 if( pSelect->pSrc->a[0].pSelect ){
1432 return 0; /* FROM clause cannot contain a subquery */
1433 }
1434 if( pSelect->pWhere ){
1435 return 0; /* SELECT may not have a WHERE clause */
1436 }
1437 if( pSelect->pOrderBy ){
1438 return 0; /* SELECT may not have an ORDER BY clause */
1439 }
drh8103b7d2007-02-24 13:23:51 +00001440 /* Do not need to test for a HAVING clause. If HAVING is present but
1441 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001442 if( pSelect->pGroupBy ){
1443 return 0; /* SELECT may not have a GROUP BY clause */
1444 }
1445 if( pSelect->pLimit ){
1446 return 0; /* SELECT may not have a LIMIT clause */
1447 }
drh8103b7d2007-02-24 13:23:51 +00001448 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001449 if( pSelect->pPrior ){
1450 return 0; /* SELECT may not be a compound query */
1451 }
1452 if( pSelect->isDistinct ){
1453 return 0; /* SELECT may not be DISTINCT */
1454 }
1455 pEList = pSelect->pEList;
1456 assert( pEList!=0 );
1457 if( pEList->nExpr!=1 ){
1458 return 0; /* The result set must have exactly one column */
1459 }
1460 assert( pEList->a[0].pExpr );
1461 if( pEList->a[0].pExpr->op!=TK_ALL ){
1462 return 0; /* The result set must be the special operator "*" */
1463 }
1464
1465 /* At this point we have established that the statement is of the
1466 ** correct syntactic form to participate in this optimization. Now
1467 ** we have to check the semantics.
1468 */
1469 pItem = pSelect->pSrc->a;
1470 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1471 if( pSrc==0 ){
1472 return 0; /* FROM clause does not contain a real table */
1473 }
1474 if( pSrc==pDest ){
1475 return 0; /* tab1 and tab2 may not be the same table */
1476 }
1477#ifndef SQLITE_OMIT_VIRTUALTABLE
1478 if( pSrc->isVirtual ){
1479 return 0; /* tab2 must not be a virtual table */
1480 }
1481#endif
1482 if( pSrc->pSelect ){
1483 return 0; /* tab2 may not be a view */
1484 }
1485 if( pDest->nCol!=pSrc->nCol ){
1486 return 0; /* Number of columns must be the same in tab1 and tab2 */
1487 }
1488 if( pDest->iPKey!=pSrc->iPKey ){
1489 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1490 }
1491 for(i=0; i<pDest->nCol; i++){
1492 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1493 return 0; /* Affinity must be the same on all columns */
1494 }
1495 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1496 return 0; /* Collating sequence must be the same on all columns */
1497 }
1498 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1499 return 0; /* tab2 must be NOT NULL if tab1 is */
1500 }
1501 }
1502 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001503 if( pDestIdx->onError!=OE_None ){
1504 destHasUniqueIdx = 1;
1505 }
drh9d9cf222007-02-13 15:01:11 +00001506 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1507 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1508 }
1509 if( pSrcIdx==0 ){
1510 return 0; /* pDestIdx has no corresponding index in pSrc */
1511 }
1512 }
drh7fc2f412007-03-29 00:08:24 +00001513#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001514 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001515 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1516 }
drh7fc2f412007-03-29 00:08:24 +00001517#endif
drh9d9cf222007-02-13 15:01:11 +00001518
1519 /* If we get this far, it means either:
1520 **
1521 ** * We can always do the transfer if the table contains an
1522 ** an integer primary key
1523 **
1524 ** * We can conditionally do the transfer if the destination
1525 ** table is empty.
1526 */
drhdd735212007-02-24 13:53:05 +00001527#ifdef SQLITE_TEST
1528 sqlite3_xferopt_count++;
1529#endif
drh9d9cf222007-02-13 15:01:11 +00001530 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1531 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001532 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001533 iSrc = pParse->nTab++;
1534 iDest = pParse->nTab++;
1535 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1536 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001537 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001538 /* If tables do not have an INTEGER PRIMARY KEY and there
1539 ** are indices to be copied and the destination is not empty,
1540 ** we have to disallow the transfer optimization because the
1541 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001542 **
1543 ** Or if the destination has a UNIQUE index and is not empty,
1544 ** we also disallow the transfer optimization because we cannot
1545 ** insure that all entries in the union of DEST and SRC will be
1546 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001547 */
1548 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1549 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1550 sqlite3VdbeJumpHere(v, addr1);
1551 }else{
1552 emptyDestTest = 0;
1553 }
1554 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1555 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001556 if( pDest->iPKey>=0 ){
drhbd36ba62007-03-31 13:00:26 +00001557 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh95bad4c2007-03-28 18:04:10 +00001558 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1559 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1560 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1561 "PRIMARY KEY must be unique", P3_STATIC);
1562 sqlite3VdbeJumpHere(v, addr2);
1563 autoIncStep(pParse, counterMem);
drhbd36ba62007-03-31 13:00:26 +00001564 }else if( pDest->pIndex==0 ){
1565 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
drh95bad4c2007-03-28 18:04:10 +00001566 }else{
drhbd36ba62007-03-31 13:00:26 +00001567 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001568 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001569 }
drh9d9cf222007-02-13 15:01:11 +00001570 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001571 sqlite3VdbeOp3(v, OP_Insert, iDest,
1572 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
drh9d9cf222007-02-13 15:01:11 +00001573 pDest->zName, 0);
1574 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1575 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1576 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1577 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1578 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1579 }
1580 assert( pSrcIdx );
1581 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1582 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1583 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1584 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
drhd4e70eb2008-01-02 00:34:36 +00001585 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001586 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1587 (char*)pKey, P3_KEYINFO_HANDOFF);
1588 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1589 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
drhd4e70eb2008-01-02 00:34:36 +00001590 VdbeComment((v, "%s", pDestIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001591 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1592 (char*)pKey, P3_KEYINFO_HANDOFF);
1593 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1594 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001595 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
drh9d9cf222007-02-13 15:01:11 +00001596 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1597 sqlite3VdbeJumpHere(v, addr1);
1598 }
1599 sqlite3VdbeJumpHere(v, emptySrcTest);
1600 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1601 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1602 if( emptyDestTest ){
1603 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1604 sqlite3VdbeJumpHere(v, emptyDestTest);
1605 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1606 return 0;
1607 }else{
1608 return 1;
1609 }
1610}
1611#endif /* SQLITE_OMIT_XFER_OPT */