blob: b77dffc6899c5db8c56912b587be62d1f0133e94 [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**
drh48d11782007-11-23 15:02:19 +000015** $Id: insert.c,v 1.193 2007/11/23 15:02:19 drh 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);
113 if( pOp->opcode==OP_OpenRead ){
114 VdbeOp *pPrior = &pOp[-1];
115 int tnum = pOp->p2;
116 assert( i>iStartAddr );
117 assert( pPrior->opcode==OP_Integer );
118 if( pPrior->p1==iDb ){
119 Index *pIndex;
120 if( tnum==pTab->tnum ){
121 return 1;
122 }
123 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
124 if( tnum==pIndex->tnum ){
125 return 1;
126 }
127 }
128 }
129 }
130 if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){
131 assert( pOp->p3!=0 );
132 assert( pOp->p3type==P3_VTAB );
133 return 1;
danielk19774d887782005-02-08 08:42:27 +0000134 }
135 }
136 return 0;
137}
danielk19773d1bfea2004-05-14 11:00:53 +0000138
drh9d9cf222007-02-13 15:01:11 +0000139#ifndef SQLITE_OMIT_AUTOINCREMENT
140/*
141** Write out code to initialize the autoincrement logic. This code
142** looks up the current autoincrement value in the sqlite_sequence
143** table and stores that value in a memory cell. Code generated by
144** autoIncStep() will keep that memory cell holding the largest
145** rowid value. Code generated by autoIncEnd() will write the new
146** largest value of the counter back into the sqlite_sequence table.
147**
148** This routine returns the index of the mem[] cell that contains
149** the maximum rowid counter.
150**
151** Two memory cells are allocated. The next memory cell after the
152** one returned holds the rowid in sqlite_sequence where we will
153** write back the revised maximum rowid.
154*/
155static int autoIncBegin(
156 Parse *pParse, /* Parsing context */
157 int iDb, /* Index of the database holding pTab */
158 Table *pTab /* The table we are writing to */
159){
160 int memId = 0;
161 if( pTab->autoInc ){
162 Vdbe *v = pParse->pVdbe;
163 Db *pDb = &pParse->db->aDb[iDb];
164 int iCur = pParse->nTab;
165 int addr;
166 assert( v );
167 addr = sqlite3VdbeCurrentAddr(v);
168 memId = pParse->nMem+1;
169 pParse->nMem += 2;
170 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
171 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
172 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
173 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
174 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
175 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
176 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
177 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
178 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
179 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
180 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
181 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
182 }
183 return memId;
184}
185
186/*
187** Update the maximum rowid for an autoincrement calculation.
188**
189** This routine should be called when the top of the stack holds a
190** new rowid that is about to be inserted. If that new rowid is
191** larger than the maximum rowid in the memId memory cell, then the
192** memory cell is updated. The stack is unchanged.
193*/
194static void autoIncStep(Parse *pParse, int memId){
195 if( memId>0 ){
196 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
197 }
198}
199
200/*
201** After doing one or more inserts, the maximum rowid is stored
202** in mem[memId]. Generate code to write this value back into the
203** the sqlite_sequence table.
204*/
205static void autoIncEnd(
206 Parse *pParse, /* The parsing context */
207 int iDb, /* Index of the database holding pTab */
208 Table *pTab, /* Table we are inserting into */
209 int memId /* Memory cell holding the maximum rowid */
210){
211 if( pTab->autoInc ){
212 int iCur = pParse->nTab;
213 Vdbe *v = pParse->pVdbe;
214 Db *pDb = &pParse->db->aDb[iDb];
215 int addr;
216 assert( v );
217 addr = sqlite3VdbeCurrentAddr(v);
218 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
219 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
220 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
221 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
222 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
223 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
224 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
225 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
drhe4d90812007-03-29 05:51:49 +0000226 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
drh9d9cf222007-02-13 15:01:11 +0000227 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
228 }
229}
230#else
231/*
232** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
233** above are all no-ops
234*/
235# define autoIncBegin(A,B,C) (0)
236# define autoIncStep(A,B)
237# define autoIncEnd(A,B,C,D)
238#endif /* SQLITE_OMIT_AUTOINCREMENT */
239
240
241/* Forward declaration */
242static int xferOptimization(
243 Parse *pParse, /* Parser context */
244 Table *pDest, /* The table we are inserting into */
245 Select *pSelect, /* A SELECT statement to use as the data source */
246 int onError, /* How to handle constraint errors */
247 int iDbDest /* The database of pDest */
248);
249
danielk19773d1bfea2004-05-14 11:00:53 +0000250/*
drh1ccde152000-06-17 13:12:39 +0000251** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000252**
253** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000254** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000255**
drh1ccde152000-06-17 13:12:39 +0000256** The IDLIST following the table name is always optional. If omitted,
257** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000258** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000259**
260** The pList parameter holds EXPRLIST in the first form of the INSERT
261** statement above, and pSelect is NULL. For the second form, pList is
262** NULL and pSelect is a pointer to the select statement used to generate
263** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000264**
drh9d9cf222007-02-13 15:01:11 +0000265** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000266** select with data coming from a VALUES clause, the code executes
267** once straight down through. The template looks like this:
268**
269** open write cursor to <table> and its indices
270** puts VALUES clause expressions onto the stack
271** write the resulting record into <table>
272** cleanup
273**
drh9d9cf222007-02-13 15:01:11 +0000274** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000275**
276** INSERT INTO <table> SELECT ...
277**
drh9d9cf222007-02-13 15:01:11 +0000278** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
279** in other words if the SELECT pulls all columns from a single table
280** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
281** if <table2> and <table1> are distinct tables but have identical
282** schemas, including all the same indices, then a special optimization
283** is invoked that copies raw records from <table2> over to <table1>.
284** See the xferOptimization() function for the implementation of this
285** template. This is the second template.
286**
287** open a write cursor to <table>
288** open read cursor on <table2>
289** transfer all records in <table2> over to <table>
290** close cursors
291** foreach index on <table>
292** open a write cursor on the <table> index
293** open a read cursor on the corresponding <table2> index
294** transfer all records from the read to the write cursors
295** close cursors
296** end foreach
297**
298** The third template is for when the second template does not apply
299** and the SELECT clause does not read from <table> at any time.
300** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000301**
302** goto B
303** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000304** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000305** gosub C
306** end loop
307** cleanup after the SELECT
308** goto D
309** B: open write cursor to <table> and its indices
310** goto A
311** C: insert the select result into <table>
312** return
313** D: cleanup
314**
drh9d9cf222007-02-13 15:01:11 +0000315** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000316** values from a SELECT but the data is being inserted into a table
317** that is also read as part of the SELECT. In the third form,
318** we have to use a intermediate table to store the results of
319** the select. The template is like this:
320**
321** goto B
322** A: setup for the SELECT
323** loop over the tables in the SELECT
324** gosub C
325** end loop
326** cleanup after the SELECT
327** goto D
328** C: insert the select result into the intermediate table
329** return
330** B: open a cursor to an intermediate table
331** goto A
332** D: open write cursor to <table> and its indices
333** loop over the intermediate table
334** transfer values form intermediate table into <table>
335** end the loop
336** cleanup
drhcce7d172000-05-31 15:34:51 +0000337*/
danielk19774adee202004-05-08 08:23:19 +0000338void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000339 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000340 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000341 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000342 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000343 IdList *pColumn, /* Column names corresponding to IDLIST. */
344 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000345){
drh5974a302000-06-07 14:42:26 +0000346 Table *pTab; /* The table to insert into */
drh113088e2003-03-20 01:16:58 +0000347 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000348 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000349 int i, j, idx; /* Loop counters */
350 Vdbe *v; /* Generate code into this virtual machine */
351 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000352 int nColumn; /* Number of columns in the data */
danielk1977cfe9a692004-06-16 12:00:29 +0000353 int base = 0; /* VDBE Cursor number for pTab */
354 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
drh9bb575f2004-09-06 17:24:11 +0000355 sqlite3 *db; /* The main database structure */
drh4a324312001-12-21 14:30:42 +0000356 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000357 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000358 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000359 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
360 int iSelectLoop = 0; /* Address of code that implements the SELECT */
361 int iCleanup = 0; /* Address of the cleanup code */
362 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
363 int iCntMem = 0; /* Memory cell used for the row counter */
drh798da522004-11-04 04:42:28 +0000364 int newIdx = -1; /* Cursor for the NEW table */
drh2958a4e2004-11-12 03:56:15 +0000365 Db *pDb; /* The database containing table being inserted into */
366 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
drhe4d90812007-03-29 05:51:49 +0000367 int appendFlag = 0; /* True if the insert is likely to be an append */
danielk1977da184232006-01-05 11:34:32 +0000368 int iDb;
drhcce7d172000-05-31 15:34:51 +0000369
danielk1977034ca142007-06-26 10:38:54 +0000370 int nHidden = 0;
371
drh798da522004-11-04 04:42:28 +0000372#ifndef SQLITE_OMIT_TRIGGER
373 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000374 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000375#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000376
drh17435752007-08-16 04:30:38 +0000377 db = pParse->db;
378 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000379 goto insert_cleanup;
380 }
drhdaffd0e2001-04-11 14:28:42 +0000381
drh1ccde152000-06-17 13:12:39 +0000382 /* Locate the table into which we will be inserting new information.
383 */
drh113088e2003-03-20 01:16:58 +0000384 assert( pTabList->nSrc==1 );
385 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000386 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000387 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000388 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000389 goto insert_cleanup;
390 }
danielk1977da184232006-01-05 11:34:32 +0000391 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
392 assert( iDb<db->nDb );
393 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000394 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000395 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000396 goto insert_cleanup;
397 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000398
drhb7f91642004-10-31 02:22:47 +0000399 /* Figure out if we have any triggers and if the table being
400 ** inserted into is a view
401 */
402#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000403 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000404 isView = pTab->pSelect!=0;
405#else
drhdca76842004-12-07 14:06:13 +0000406# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000407# define isView 0
408#endif
409#ifdef SQLITE_OMIT_VIEW
410# undef isView
411# define isView 0
412#endif
413
danielk1977c3f9bad2002-05-15 08:30:12 +0000414 /* Ensure that:
415 * (a) the table is not read-only,
416 * (b) that if it is a view then ON INSERT triggers exist
417 */
drhdca76842004-12-07 14:06:13 +0000418 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000419 goto insert_cleanup;
420 }
drh43617e92006-03-06 20:55:46 +0000421 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000422
drhf573c992002-07-31 00:32:50 +0000423 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000424 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
425 ** module table).
drhf573c992002-07-31 00:32:50 +0000426 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000427 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000428 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000429 }
430
drh1ccde152000-06-17 13:12:39 +0000431 /* Allocate a VDBE
432 */
danielk19774adee202004-05-08 08:23:19 +0000433 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000434 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000435 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000436 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000437
danielk1977c3f9bad2002-05-15 08:30:12 +0000438 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000439 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000440 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000441 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000442
drh9d9cf222007-02-13 15:01:11 +0000443#ifndef SQLITE_OMIT_XFER_OPT
444 /* If the statement is of the form
445 **
446 ** INSERT INTO <table1> SELECT * FROM <table2>;
447 **
448 ** Then special optimizations can be applied that make the transfer
449 ** very fast and which reduce fragmentation of indices.
450 */
451 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
452 assert( !triggers_exist );
453 assert( pList==0 );
454 goto insert_cleanup;
455 }
456#endif /* SQLITE_OMIT_XFER_OPT */
457
drh2958a4e2004-11-12 03:56:15 +0000458 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000459 ** sqlite_sequence table and store it in memory cell counterMem. Also
460 ** remember the rowid of the sqlite_sequence table entry in memory cell
461 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000462 */
drh9d9cf222007-02-13 15:01:11 +0000463 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000464
drh1ccde152000-06-17 13:12:39 +0000465 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000466 ** is coming from a SELECT statement, then this step also generates
467 ** all the code to implement the SELECT statement and invoke a subroutine
468 ** to process each row of the result. (Template 2.) If the SELECT
469 ** statement uses the the table that is being inserted into, then the
470 ** subroutine is also coded here. That subroutine stores the SELECT
471 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000472 */
drh5974a302000-06-07 14:42:26 +0000473 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000474 /* Data is coming from a SELECT. Generate code to implement that SELECT
475 */
476 int rc, iInitCode;
danielk19774adee202004-05-08 08:23:19 +0000477 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
478 iSelectLoop = sqlite3VdbeCurrentAddr(v);
479 iInsertBlock = sqlite3VdbeMakeLabel(v);
danielk1977b3bce662005-01-29 08:32:43 +0000480
481 /* Resolve the expressions in the SELECT statement and execute it. */
482 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
drh17435752007-08-16 04:30:38 +0000483 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000484 goto insert_cleanup;
485 }
danielk1977b3bce662005-01-29 08:32:43 +0000486
danielk19774adee202004-05-08 08:23:19 +0000487 iCleanup = sqlite3VdbeMakeLabel(v);
488 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000489 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000490 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000491
492 /* Set useTempTable to TRUE if the result of the SELECT statement
493 ** should be written into a temporary table. Set to FALSE if each
494 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000495 **
496 ** A temp table must be used if the table being updated is also one
497 ** of the tables being read by the SELECT statement. Also use a
498 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000499 */
drh48d11782007-11-23 15:02:19 +0000500 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000501 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000502 }
drh142e30d2002-08-28 03:00:58 +0000503
504 if( useTempTable ){
505 /* Generate the subroutine that SELECT calls to process each row of
506 ** the result. Store the result in a temporary table
507 */
508 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000509 sqlite3VdbeResolveLabel(v, iInsertBlock);
510 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf0863fe2005-06-12 21:35:51 +0000511 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
danielk19774adee202004-05-08 08:23:19 +0000512 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhe4d90812007-03-29 05:51:49 +0000513 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
danielk19774adee202004-05-08 08:23:19 +0000514 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000515
516 /* The following code runs first because the GOTO at the very top
517 ** of the program jumps to it. Create the temporary table, then jump
518 ** back up and execute the SELECT code above.
519 */
drhd654be82005-09-20 17:42:23 +0000520 sqlite3VdbeJumpHere(v, iInitCode);
drhb9bb7c12006-06-11 23:41:55 +0000521 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
drhb6f54522004-05-20 02:42:16 +0000522 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
danielk19774adee202004-05-08 08:23:19 +0000523 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
524 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000525 }else{
drhd654be82005-09-20 17:42:23 +0000526 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000527 }
drh5974a302000-06-07 14:42:26 +0000528 }else{
drh142e30d2002-08-28 03:00:58 +0000529 /* This is the case if the data for the INSERT is coming from a VALUES
530 ** clause
531 */
danielk1977b3bce662005-01-29 08:32:43 +0000532 NameContext sNC;
533 memset(&sNC, 0, sizeof(sNC));
534 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000535 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000536 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000537 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000538 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000539 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000540 goto insert_cleanup;
541 }
drhe64e7b22002-02-18 13:56:36 +0000542 }
drh5974a302000-06-07 14:42:26 +0000543 }
drh1ccde152000-06-17 13:12:39 +0000544
545 /* Make sure the number of columns in the source data matches the number
546 ** of columns to be inserted into the table.
547 */
danielk1977034ca142007-06-26 10:38:54 +0000548 if( IsVirtual(pTab) ){
549 for(i=0; i<pTab->nCol; i++){
550 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
551 }
552 }
553 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000554 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000555 "table %S has %d columns but %d values were supplied",
556 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000557 goto insert_cleanup;
558 }
drh967e8b72000-06-21 13:59:10 +0000559 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000560 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000561 goto insert_cleanup;
562 }
drh1ccde152000-06-17 13:12:39 +0000563
564 /* If the INSERT statement included an IDLIST term, then make sure
565 ** all elements of the IDLIST really are columns of the table and
566 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000567 **
568 ** If the table has an INTEGER PRIMARY KEY column and that column
569 ** is named in the IDLIST, then record in the keyColumn variable
570 ** the index into IDLIST of the primary key column. keyColumn is
571 ** the index of the primary key as it appears in IDLIST, not as
572 ** is appears in the original table. (The index of the primary
573 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000574 */
drh967e8b72000-06-21 13:59:10 +0000575 if( pColumn ){
576 for(i=0; i<pColumn->nId; i++){
577 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000578 }
drh967e8b72000-06-21 13:59:10 +0000579 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000580 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000581 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000582 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000583 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000584 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000585 }
drhcce7d172000-05-31 15:34:51 +0000586 break;
587 }
588 }
589 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000590 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000591 keyColumn = i;
592 }else{
danielk19774adee202004-05-08 08:23:19 +0000593 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000594 pTabList, 0, pColumn->a[i].zName);
595 pParse->nErr++;
596 goto insert_cleanup;
597 }
drhcce7d172000-05-31 15:34:51 +0000598 }
599 }
600 }
drh1ccde152000-06-17 13:12:39 +0000601
drhaacc5432002-01-06 17:07:40 +0000602 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000603 ** key, the set the keyColumn variable to the primary key column index
604 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000605 */
drh147d0cc2006-08-25 23:42:53 +0000606 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000607 keyColumn = pTab->iPKey;
608 }
609
drh142e30d2002-08-28 03:00:58 +0000610 /* Open the temp table for FOR EACH ROW triggers
611 */
drhdca76842004-12-07 14:06:13 +0000612 if( triggers_exist ){
danielk19774adee202004-05-08 08:23:19 +0000613 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
danielk197784ac9d02004-05-18 09:58:06 +0000614 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000615 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000616
drhfeeb1392002-04-09 03:28:01 +0000617 /* Initialize the count of rows to be inserted
618 */
drh142e30d2002-08-28 03:00:58 +0000619 if( db->flags & SQLITE_CountRows ){
620 iCntMem = pParse->nMem++;
drhd654be82005-09-20 17:42:23 +0000621 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000622 }
623
danielk1977c3f9bad2002-05-15 08:30:12 +0000624 /* Open tables and indices if there are no row triggers */
drhdca76842004-12-07 14:06:13 +0000625 if( !triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000626 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000627 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000628 }
629
drh142e30d2002-08-28 03:00:58 +0000630 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000631 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000632 ** source is a subroutine call from the SELECT statement, then we need
633 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000634 */
drh142e30d2002-08-28 03:00:58 +0000635 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000636 iBreak = sqlite3VdbeMakeLabel(v);
637 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
638 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000639 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000640 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
641 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh5974a302000-06-07 14:42:26 +0000642 }
drh1ccde152000-06-17 13:12:39 +0000643
drh5cf590c2003-04-24 01:45:04 +0000644 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000645 */
danielk19774adee202004-05-08 08:23:19 +0000646 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000647 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000648
drh70ce3f02003-04-15 19:22:22 +0000649 /* build the NEW.* reference row. Note that if there is an INTEGER
650 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
651 ** translated into a unique ID for the row. But on a BEFORE trigger,
652 ** we do not know what the unique ID will be (because the insert has
653 ** not happened yet) so we substitute a rowid of -1
654 */
655 if( keyColumn<0 ){
danielk19774adee202004-05-08 08:23:19 +0000656 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000657 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000658 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000659 }else{
drhd6fe9612005-01-14 01:22:00 +0000660 assert( pSelect==0 ); /* Otherwise useTempTable is true */
danielk19774adee202004-05-08 08:23:19 +0000661 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
662 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
663 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
664 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
665 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000666 }
667
danielk1977034ca142007-06-26 10:38:54 +0000668 /* Cannot have triggers on a virtual table. If it were possible,
669 ** this block would have to account for hidden column.
670 */
671 assert(!IsVirtual(pTab));
672
drh70ce3f02003-04-15 19:22:22 +0000673 /* Create the new column data
674 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000675 for(i=0; i<pTab->nCol; i++){
676 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000677 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000678 }else{
drh9adf9ac2002-05-15 11:44:13 +0000679 for(j=0; j<pColumn->nId; j++){
680 if( pColumn->a[j].idx==i ) break;
681 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000682 }
683 if( pColumn && j>=pColumn->nId ){
danielk19777977a172004-11-09 12:44:37 +0000684 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000685 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000686 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000687 }else{
drhd6fe9612005-01-14 01:22:00 +0000688 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000689 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000690 }
691 }
danielk19774adee202004-05-08 08:23:19 +0000692 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000693
694 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
695 ** do not attempt any conversions before assembling the record.
696 ** If this is a real table, attempt conversions as required by the
697 ** table column affinities.
698 */
699 if( !isView ){
700 sqlite3TableAffinityStr(v, pTab);
701 }
drhf0863fe2005-06-12 21:35:51 +0000702 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000703
drh5cf590c2003-04-24 01:45:04 +0000704 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000705 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
drhb2fe7d82003-04-20 17:29:23 +0000706 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000707 goto insert_cleanup;
708 }
drh70ce3f02003-04-15 19:22:22 +0000709 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000710
drh70ce3f02003-04-15 19:22:22 +0000711 /* If any triggers exists, the opening of tables and indices is deferred
712 ** until now.
713 */
drhdca76842004-12-07 14:06:13 +0000714 if( triggers_exist && !isView ){
drh5cf590c2003-04-24 01:45:04 +0000715 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000716 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000717 }
718
drh4a324312001-12-21 14:30:42 +0000719 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000720 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000721 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000722 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000723 */
drh5cf590c2003-04-24 01:45:04 +0000724 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000725 if( IsVirtual(pTab) ){
726 /* The row that the VUpdate opcode will delete: none */
727 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
728 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000729 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000730 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000731 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh142e30d2002-08-28 03:00:58 +0000732 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000733 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000734 }else{
drhe4d90812007-03-29 05:51:49 +0000735 VdbeOp *pOp;
danielk19774adee202004-05-08 08:23:19 +0000736 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
drhe4d90812007-03-29 05:51:49 +0000737 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000738 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000739 appendFlag = 1;
740 pOp->opcode = OP_NewRowid;
741 pOp->p1 = base;
742 pOp->p2 = counterMem;
743 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000744 }
drhf0863fe2005-06-12 21:35:51 +0000745 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000746 ** to generate a unique primary key value.
747 */
drhe4d90812007-03-29 05:51:49 +0000748 if( !appendFlag ){
749 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
750 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
751 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
752 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
753 }
drh4cbdda92006-06-14 19:00:20 +0000754 }else if( IsVirtual(pTab) ){
755 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000756 }else{
drhf0863fe2005-06-12 21:35:51 +0000757 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
drhe4d90812007-03-29 05:51:49 +0000758 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000759 }
drh9d9cf222007-02-13 15:01:11 +0000760 autoIncStep(pParse, counterMem);
drh4a324312001-12-21 14:30:42 +0000761
danielk1977c3f9bad2002-05-15 08:30:12 +0000762 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000763 ** with the first column.
764 */
danielk1977034ca142007-06-26 10:38:54 +0000765 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000766 for(i=0; i<pTab->nCol; i++){
767 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000768 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000769 ** Whenever this column is read, the record number will be substituted
770 ** in its place. So will fill this column with a NULL to avoid
771 ** taking up data space with information that will never be used. */
drhf0863fe2005-06-12 21:35:51 +0000772 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh9adf9ac2002-05-15 11:44:13 +0000773 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000774 }
775 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000776 if( IsHiddenColumn(&pTab->aCol[i]) ){
777 assert( IsVirtual(pTab) );
778 j = -1;
779 nHidden++;
780 }else{
781 j = i - nHidden;
782 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000783 }else{
drh9adf9ac2002-05-15 11:44:13 +0000784 for(j=0; j<pColumn->nId; j++){
785 if( pColumn->a[j].idx==i ) break;
786 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000787 }
danielk1977034ca142007-06-26 10:38:54 +0000788 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk19777977a172004-11-09 12:44:37 +0000789 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000790 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000791 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
drh142e30d2002-08-28 03:00:58 +0000792 }else if( pSelect ){
drh16ed8a62006-08-29 18:46:14 +0000793 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000794 }else{
danielk19774adee202004-05-08 08:23:19 +0000795 sqlite3ExprCode(pParse, pList->a[j].pExpr);
drh5974a302000-06-07 14:42:26 +0000796 }
drhbed86902000-06-02 13:27:59 +0000797 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000798
799 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000800 ** do the insertion.
801 */
drh4cbdda92006-06-14 19:00:20 +0000802#ifndef SQLITE_OMIT_VIRTUALTABLE
803 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000804 pParse->pVirtualLock = pTab;
danielk19771f6eec52006-06-16 06:17:47 +0000805 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
drh4cbdda92006-06-14 19:00:20 +0000806 (const char*)pTab->pVtab, P3_VTAB);
807 }else
808#endif
809 {
810 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
811 0, onError, endOfLoop);
812 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000813 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
814 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000815 }
drh5cf590c2003-04-24 01:45:04 +0000816 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000817
drh5cf590c2003-04-24 01:45:04 +0000818 /* Update the count of rows that are inserted
819 */
820 if( (db->flags & SQLITE_CountRows)!=0 ){
drh15007a92006-01-08 18:10:17 +0000821 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
drh5974a302000-06-07 14:42:26 +0000822 }
drh1ccde152000-06-17 13:12:39 +0000823
drhdca76842004-12-07 14:06:13 +0000824 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000825 /* Close all tables opened */
drh5cf590c2003-04-24 01:45:04 +0000826 if( !isView ){
danielk19774adee202004-05-08 08:23:19 +0000827 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000828 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000829 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000830 }
831 }
drh1bee3d72001-10-15 00:44:35 +0000832
danielk1977c3f9bad2002-05-15 08:30:12 +0000833 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000834 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
835 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000836 goto insert_cleanup;
837 }
drh1bee3d72001-10-15 00:44:35 +0000838 }
839
drh1ccde152000-06-17 13:12:39 +0000840 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000841 */
danielk19774adee202004-05-08 08:23:19 +0000842 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000843 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000844 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
845 sqlite3VdbeResolveLabel(v, iBreak);
846 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000847 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000848 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
849 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
850 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000851 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000852
drh4cbdda92006-06-14 19:00:20 +0000853 if( !triggers_exist && !IsVirtual(pTab) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000854 /* Close all tables opened */
danielk19774adee202004-05-08 08:23:19 +0000855 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000856 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000857 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000858 }
drhcce7d172000-05-31 15:34:51 +0000859 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000860
drhf3388142004-11-13 03:48:06 +0000861 /* Update the sqlite_sequence table by storing the content of the
862 ** counter value in memory counterMem back into the sqlite_sequence
863 ** table.
drh2958a4e2004-11-12 03:56:15 +0000864 */
drh9d9cf222007-02-13 15:01:11 +0000865 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000866
drh1bee3d72001-10-15 00:44:35 +0000867 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000868 ** Return the number of rows inserted. If this routine is
869 ** generating code because of a call to sqlite3NestedParse(), do not
870 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000871 */
danielk1977cc6bd382005-01-10 02:48:49 +0000872 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +0000873 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
874 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
danielk197722322fd2004-05-25 23:35:17 +0000875 sqlite3VdbeSetNumCols(v, 1);
danielk1977955de522006-02-10 02:27:42 +0000876 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000877 }
drhcce7d172000-05-31 15:34:51 +0000878
879insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000880 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000881 sqlite3ExprListDelete(pList);
882 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000883 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000884}
drh9cfcf5d2002-01-29 18:41:24 +0000885
drh9cfcf5d2002-01-29 18:41:24 +0000886/*
887** Generate code to do a constraint check prior to an INSERT or an UPDATE.
888**
889** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000890** the following values:
891**
drhf0863fe2005-06-12 21:35:51 +0000892** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000893** value is omitted unless we are doing an UPDATE that involves a
894** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000895**
drhf0863fe2005-06-12 21:35:51 +0000896** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000897**
898** 3. The data in the first column of the entry after the update.
899**
900** i. Data from middle columns...
901**
902** N. The data in the last column of the entry after the update.
903**
drhf0863fe2005-06-12 21:35:51 +0000904** The old rowid shown as entry (1) above is omitted unless both isUpdate
905** and rowidChng are 1. isUpdate is true for UPDATEs and false for
906** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000907**
908** The code generated by this routine pushes additional entries onto
909** the stack which are the keys for new index entries for the new record.
910** The order of index keys is the same as the order of the indices on
911** the pTable->pIndex list. A key is only created for index i if
912** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000913**
914** This routine also generates code to check constraints. NOT NULL,
915** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000916** then the appropriate action is performed. There are five possible
917** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000918**
919** Constraint type Action What Happens
920** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000921** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000922** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000923** return code of SQLITE_CONSTRAINT.
924**
drh1c928532002-01-31 15:54:21 +0000925** any ABORT Back out changes from the current command
926** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000927** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000928** with SQLITE_CONSTRAINT.
929**
930** any FAIL Sqlite_exec() returns immediately with a
931** return code of SQLITE_CONSTRAINT. The
932** transaction is not rolled back and any
933** prior changes are retained.
934**
drh9cfcf5d2002-01-29 18:41:24 +0000935** any IGNORE The record number and data is popped from
936** the stack and there is an immediate jump
937** to label ignoreDest.
938**
939** NOT NULL REPLACE The NULL value is replace by the default
940** value for that column. If the default value
941** is NULL, the action is the same as ABORT.
942**
943** UNIQUE REPLACE The other row that conflicts with the row
944** being inserted is removed.
945**
946** CHECK REPLACE Illegal. The results in an exception.
947**
drh1c928532002-01-31 15:54:21 +0000948** Which action to take is determined by the overrideError parameter.
949** Or if overrideError==OE_Default, then the pParse->onError parameter
950** is used. Or if pParse->onError==OE_Default then the onError value
951** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000952**
drhaaab5722002-02-19 13:39:21 +0000953** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000954** cursor number "base". All indices of pTab must also have open
955** read/write cursors with cursor number base+i for the i-th cursor.
956** Except, if there is no possibility of a REPLACE action then
957** cursors do not need to be open for indices where aIdxUsed[i]==0.
958**
959** If the isUpdate flag is true, it means that the "base" cursor is
960** initially pointing to an entry that is being updated. The isUpdate
961** flag causes extra code to be generated so that the "base" cursor
962** is still pointing at the same entry after the routine returns.
963** Without the isUpdate flag, the "base" cursor might be moved.
964*/
danielk19774adee202004-05-08 08:23:19 +0000965void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000966 Parse *pParse, /* The parser context */
967 Table *pTab, /* the table into which we are inserting */
968 int base, /* Index of a read/write cursor pointing at pTab */
969 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000970 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000971 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000972 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000973 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000974){
975 int i;
976 Vdbe *v;
977 int nCol;
978 int onError;
979 int addr;
980 int extra;
drh0ca3e242002-01-29 23:07:02 +0000981 int iCur;
982 Index *pIdx;
983 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000984 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000985 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000986
danielk19774adee202004-05-08 08:23:19 +0000987 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000988 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000989 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000990 nCol = pTab->nCol;
991
992 /* Test all NOT NULL constraints.
993 */
994 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000995 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +0000996 continue;
997 }
drh9cfcf5d2002-01-29 18:41:24 +0000998 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +0000999 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001000 if( overrideError!=OE_Default ){
1001 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001002 }else if( onError==OE_Default ){
1003 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001004 }
danielk19777977a172004-11-09 12:44:37 +00001005 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001006 onError = OE_Abort;
1007 }
danielk19774adee202004-05-08 08:23:19 +00001008 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
1009 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +00001010 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1011 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001012 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001013 case OE_Rollback:
1014 case OE_Abort:
1015 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001016 char *zMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00001017 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1018 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001019 " may not be NULL", (char*)0);
danielk19774adee202004-05-08 08:23:19 +00001020 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001021 break;
1022 }
1023 case OE_Ignore: {
drhf0863fe2005-06-12 21:35:51 +00001024 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001025 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001026 break;
1027 }
1028 case OE_Replace: {
danielk19777977a172004-11-09 12:44:37 +00001029 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
danielk19774adee202004-05-08 08:23:19 +00001030 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001031 break;
1032 }
drh9cfcf5d2002-01-29 18:41:24 +00001033 }
drhd654be82005-09-20 17:42:23 +00001034 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001035 }
1036
1037 /* Test all CHECK constraints
1038 */
drhffe07b22005-11-03 00:41:17 +00001039#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001040 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001041 int allOk = sqlite3VdbeMakeLabel(v);
1042 assert( pParse->ckOffset==0 );
1043 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001044 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001045 assert( pParse->ckOffset==nCol );
1046 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001047 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001048 if( onError==OE_Ignore ){
drhaa01c7e2006-03-15 16:26:10 +00001049 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1050 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1051 }else{
1052 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1053 }
drhffe07b22005-11-03 00:41:17 +00001054 sqlite3VdbeResolveLabel(v, allOk);
1055 }
1056#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001057
drh0bd1f4e2002-06-06 18:54:39 +00001058 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1059 ** of the new record does not previously exist. Except, if this
1060 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001061 */
drhf0863fe2005-06-12 21:35:51 +00001062 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001063 onError = pTab->keyConf;
1064 if( overrideError!=OE_Default ){
1065 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001066 }else if( onError==OE_Default ){
1067 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001068 }
drha0217ba2003-06-01 01:10:33 +00001069
drh5383ae52003-06-04 12:23:30 +00001070 if( isUpdate ){
danielk19774adee202004-05-08 08:23:19 +00001071 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1072 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1073 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001074 }
danielk19774adee202004-05-08 08:23:19 +00001075 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1076 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001077 switch( onError ){
1078 default: {
1079 onError = OE_Abort;
1080 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001081 }
drh5383ae52003-06-04 12:23:30 +00001082 case OE_Rollback:
1083 case OE_Abort:
1084 case OE_Fail: {
danielk19774adee202004-05-08 08:23:19 +00001085 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
drh701a0ae2004-02-22 20:05:00 +00001086 "PRIMARY KEY must be unique", P3_STATIC);
drh5383ae52003-06-04 12:23:30 +00001087 break;
drh0ca3e242002-01-29 23:07:02 +00001088 }
drh5383ae52003-06-04 12:23:30 +00001089 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001090 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001091 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001092 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001093 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001094 }
1095 seenReplace = 1;
1096 break;
drh0ca3e242002-01-29 23:07:02 +00001097 }
drh5383ae52003-06-04 12:23:30 +00001098 case OE_Ignore: {
1099 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001100 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001101 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001102 break;
1103 }
1104 }
drhd654be82005-09-20 17:42:23 +00001105 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001106 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001107 sqlite3VdbeJumpHere(v, jumpInst1);
danielk19774adee202004-05-08 08:23:19 +00001108 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001109 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001110 }
1111 }
drh0bd1f4e2002-06-06 18:54:39 +00001112
1113 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1114 ** index and making sure that duplicate entries do not already exist.
1115 ** Add the new records to the indices as we go.
1116 */
drhb2fe7d82003-04-20 17:29:23 +00001117 extra = -1;
1118 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1119 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1120 extra++;
1121
1122 /* Create a key for accessing the index entry */
danielk19774adee202004-05-08 08:23:19 +00001123 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001124 for(i=0; i<pIdx->nColumn; i++){
1125 int idx = pIdx->aiColumn[i];
1126 if( idx==pTab->iPKey ){
danielk19774adee202004-05-08 08:23:19 +00001127 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001128 }else{
danielk19774adee202004-05-08 08:23:19 +00001129 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001130 }
1131 }
drh7f057c92005-06-24 03:53:06 +00001132 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001133 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001134
1135 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001136 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001137 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001138 if( overrideError!=OE_Default ){
1139 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001140 }else if( onError==OE_Default ){
1141 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001142 }
drh5383ae52003-06-04 12:23:30 +00001143 if( seenReplace ){
1144 if( onError==OE_Ignore ) onError = OE_Replace;
1145 else if( onError==OE_Fail ) onError = OE_Abort;
1146 }
1147
drhb2fe7d82003-04-20 17:29:23 +00001148
1149 /* Check to see if the new index entry will be unique */
drhf0863fe2005-06-12 21:35:51 +00001150 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
danielk19774adee202004-05-08 08:23:19 +00001151 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001152
1153 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001154 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1155 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001156 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001157 case OE_Rollback:
1158 case OE_Abort:
1159 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001160 int j, n1, n2;
1161 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001162 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1163 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001164 n1 = strlen(zErrMsg);
1165 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1166 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1167 n2 = strlen(zCol);
1168 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001169 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001170 n1 += 2;
1171 }
1172 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001173 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001174 n1 += 3;
1175 break;
1176 }else{
drh5bb3eb92007-05-04 13:15:55 +00001177 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001178 n1 += n2;
1179 }
1180 }
drh5bb3eb92007-05-04 13:15:55 +00001181 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001182 pIdx->nColumn>1 ? " are not unique" : " is not unique");
danielk19774adee202004-05-08 08:23:19 +00001183 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001184 break;
1185 }
1186 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001187 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001188 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001189 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001190 break;
1191 }
1192 case OE_Replace: {
danielk19774adee202004-05-08 08:23:19 +00001193 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001194 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001195 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001196 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001197 }
drh0ca3e242002-01-29 23:07:02 +00001198 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001199 break;
1200 }
drh9cfcf5d2002-01-29 18:41:24 +00001201 }
drh0bd1f4e2002-06-06 18:54:39 +00001202#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001203 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001204#endif
drhd654be82005-09-20 17:42:23 +00001205 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001206 }
1207}
drh0ca3e242002-01-29 23:07:02 +00001208
1209/*
1210** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001211** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001212** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001213** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001214** entries in all indices and in the main table.
1215**
drhb419a922002-01-30 16:17:23 +00001216** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001217** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001218*/
danielk19774adee202004-05-08 08:23:19 +00001219void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001220 Parse *pParse, /* The parser context */
1221 Table *pTab, /* the table into which we are inserting */
1222 int base, /* Index of a read/write cursor pointing at pTab */
1223 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001224 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001225 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001226 int newIdx, /* Index of NEW table for triggers. -1 if none */
1227 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001228){
1229 int i;
1230 Vdbe *v;
1231 int nIdx;
1232 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001233 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001234
danielk19774adee202004-05-08 08:23:19 +00001235 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001236 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001237 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001238 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1239 for(i=nIdx-1; i>=0; i--){
1240 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drhf0863fe2005-06-12 21:35:51 +00001241 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001242 }
danielk19774adee202004-05-08 08:23:19 +00001243 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001244 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001245#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001246 if( newIdx>=0 ){
danielk19774adee202004-05-08 08:23:19 +00001247 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1248 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhf0863fe2005-06-12 21:35:51 +00001249 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001250 }
danielk1977b84f96f2005-01-20 11:32:23 +00001251#endif
drh4794f732004-11-05 17:17:50 +00001252 if( pParse->nested ){
1253 pik_flags = 0;
1254 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001255 pik_flags = OPFLAG_NCHANGE;
1256 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001257 }
drhe4d90812007-03-29 05:51:49 +00001258 if( appendBias ){
1259 pik_flags |= OPFLAG_APPEND;
1260 }
drhf0863fe2005-06-12 21:35:51 +00001261 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001262 if( !pParse->nested ){
1263 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1264 }
danielk1977b28af712004-06-21 06:50:26 +00001265
drhf0863fe2005-06-12 21:35:51 +00001266 if( isUpdate && rowidChng ){
danielk19774adee202004-05-08 08:23:19 +00001267 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001268 }
1269}
drhcd446902004-02-24 01:05:31 +00001270
1271/*
drh290c1942004-08-21 17:54:45 +00001272** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001273** indices of that table. The "base" parameter is the cursor number used
1274** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001275*/
drh290c1942004-08-21 17:54:45 +00001276void sqlite3OpenTableAndIndices(
1277 Parse *pParse, /* Parsing context */
1278 Table *pTab, /* Table to be opened */
1279 int base, /* Cursor number assigned to the table */
1280 int op /* OP_OpenRead or OP_OpenWrite */
1281){
drhcd446902004-02-24 01:05:31 +00001282 int i;
drh4cbdda92006-06-14 19:00:20 +00001283 int iDb;
drhcd446902004-02-24 01:05:31 +00001284 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001285 Vdbe *v;
1286
1287 if( IsVirtual(pTab) ) return;
1288 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1289 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001290 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001291 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001292 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001293 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001294 assert( pIdx->pSchema==pTab->pSchema );
1295 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001296 VdbeComment((v, "# %s", pIdx->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00001297 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
drhcd446902004-02-24 01:05:31 +00001298 }
drh290c1942004-08-21 17:54:45 +00001299 if( pParse->nTab<=base+i ){
1300 pParse->nTab = base+i;
1301 }
drhcd446902004-02-24 01:05:31 +00001302}
drh9d9cf222007-02-13 15:01:11 +00001303
drh91c58e22007-03-27 12:04:04 +00001304
1305#ifdef SQLITE_TEST
1306/*
1307** The following global variable is incremented whenever the
1308** transfer optimization is used. This is used for testing
1309** purposes only - to make sure the transfer optimization really
1310** is happening when it is suppose to.
1311*/
1312int sqlite3_xferopt_count;
1313#endif /* SQLITE_TEST */
1314
1315
drh9d9cf222007-02-13 15:01:11 +00001316#ifndef SQLITE_OMIT_XFER_OPT
1317/*
1318** Check to collation names to see if they are compatible.
1319*/
1320static int xferCompatibleCollation(const char *z1, const char *z2){
1321 if( z1==0 ){
1322 return z2==0;
1323 }
1324 if( z2==0 ){
1325 return 0;
1326 }
1327 return sqlite3StrICmp(z1, z2)==0;
1328}
1329
1330
1331/*
1332** Check to see if index pSrc is compatible as a source of data
1333** for index pDest in an insert transfer optimization. The rules
1334** for a compatible index:
1335**
1336** * The index is over the same set of columns
1337** * The same DESC and ASC markings occurs on all columns
1338** * The same onError processing (OE_Abort, OE_Ignore, etc)
1339** * The same collating sequence on each column
1340*/
1341static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1342 int i;
1343 assert( pDest && pSrc );
1344 assert( pDest->pTable!=pSrc->pTable );
1345 if( pDest->nColumn!=pSrc->nColumn ){
1346 return 0; /* Different number of columns */
1347 }
1348 if( pDest->onError!=pSrc->onError ){
1349 return 0; /* Different conflict resolution strategies */
1350 }
1351 for(i=0; i<pSrc->nColumn; i++){
1352 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1353 return 0; /* Different columns indexed */
1354 }
1355 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1356 return 0; /* Different sort orders */
1357 }
1358 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1359 return 0; /* Different sort orders */
1360 }
1361 }
1362
1363 /* If no test above fails then the indices must be compatible */
1364 return 1;
1365}
1366
1367/*
1368** Attempt the transfer optimization on INSERTs of the form
1369**
1370** INSERT INTO tab1 SELECT * FROM tab2;
1371**
1372** This optimization is only attempted if
1373**
1374** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001375** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001376**
1377** (2) tab1 and tab2 are different tables
1378**
1379** (3) There must be no triggers on tab1
1380**
1381** (4) The result set of the SELECT statement is "*"
1382**
1383** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1384** or LIMIT clause.
1385**
1386** (6) The SELECT statement is a simple (not a compound) select that
1387** contains only tab2 in its FROM clause
1388**
1389** This method for implementing the INSERT transfers raw records from
1390** tab2 over to tab1. The columns are not decoded. Raw records from
1391** the indices of tab2 are transfered to tab1 as well. In so doing,
1392** the resulting tab1 has much less fragmentation.
1393**
1394** This routine returns TRUE if the optimization is attempted. If any
1395** of the conditions above fail so that the optimization should not
1396** be attempted, then this routine returns FALSE.
1397*/
1398static int xferOptimization(
1399 Parse *pParse, /* Parser context */
1400 Table *pDest, /* The table we are inserting into */
1401 Select *pSelect, /* A SELECT statement to use as the data source */
1402 int onError, /* How to handle constraint errors */
1403 int iDbDest /* The database of pDest */
1404){
1405 ExprList *pEList; /* The result set of the SELECT */
1406 Table *pSrc; /* The table in the FROM clause of SELECT */
1407 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1408 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1409 int i; /* Loop counter */
1410 int iDbSrc; /* The database of pSrc */
1411 int iSrc, iDest; /* Cursors from source and destination */
1412 int addr1, addr2; /* Loop addresses */
1413 int emptyDestTest; /* Address of test for empty pDest */
1414 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001415 Vdbe *v; /* The VDBE we are building */
1416 KeyInfo *pKey; /* Key information for an index */
1417 int counterMem; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001418 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001419
1420 if( pSelect==0 ){
1421 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1422 }
1423 if( pDest->pTrigger ){
1424 return 0; /* tab1 must not have triggers */
1425 }
1426#ifndef SQLITE_OMIT_VIRTUALTABLE
1427 if( pDest->isVirtual ){
1428 return 0; /* tab1 must not be a virtual table */
1429 }
1430#endif
1431 if( onError==OE_Default ){
1432 onError = OE_Abort;
1433 }
1434 if( onError!=OE_Abort && onError!=OE_Rollback ){
1435 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1436 }
danielk19775ce240a2007-09-03 17:30:06 +00001437 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001438 if( pSelect->pSrc->nSrc!=1 ){
1439 return 0; /* FROM clause must have exactly one term */
1440 }
1441 if( pSelect->pSrc->a[0].pSelect ){
1442 return 0; /* FROM clause cannot contain a subquery */
1443 }
1444 if( pSelect->pWhere ){
1445 return 0; /* SELECT may not have a WHERE clause */
1446 }
1447 if( pSelect->pOrderBy ){
1448 return 0; /* SELECT may not have an ORDER BY clause */
1449 }
drh8103b7d2007-02-24 13:23:51 +00001450 /* Do not need to test for a HAVING clause. If HAVING is present but
1451 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001452 if( pSelect->pGroupBy ){
1453 return 0; /* SELECT may not have a GROUP BY clause */
1454 }
1455 if( pSelect->pLimit ){
1456 return 0; /* SELECT may not have a LIMIT clause */
1457 }
drh8103b7d2007-02-24 13:23:51 +00001458 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001459 if( pSelect->pPrior ){
1460 return 0; /* SELECT may not be a compound query */
1461 }
1462 if( pSelect->isDistinct ){
1463 return 0; /* SELECT may not be DISTINCT */
1464 }
1465 pEList = pSelect->pEList;
1466 assert( pEList!=0 );
1467 if( pEList->nExpr!=1 ){
1468 return 0; /* The result set must have exactly one column */
1469 }
1470 assert( pEList->a[0].pExpr );
1471 if( pEList->a[0].pExpr->op!=TK_ALL ){
1472 return 0; /* The result set must be the special operator "*" */
1473 }
1474
1475 /* At this point we have established that the statement is of the
1476 ** correct syntactic form to participate in this optimization. Now
1477 ** we have to check the semantics.
1478 */
1479 pItem = pSelect->pSrc->a;
1480 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1481 if( pSrc==0 ){
1482 return 0; /* FROM clause does not contain a real table */
1483 }
1484 if( pSrc==pDest ){
1485 return 0; /* tab1 and tab2 may not be the same table */
1486 }
1487#ifndef SQLITE_OMIT_VIRTUALTABLE
1488 if( pSrc->isVirtual ){
1489 return 0; /* tab2 must not be a virtual table */
1490 }
1491#endif
1492 if( pSrc->pSelect ){
1493 return 0; /* tab2 may not be a view */
1494 }
1495 if( pDest->nCol!=pSrc->nCol ){
1496 return 0; /* Number of columns must be the same in tab1 and tab2 */
1497 }
1498 if( pDest->iPKey!=pSrc->iPKey ){
1499 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1500 }
1501 for(i=0; i<pDest->nCol; i++){
1502 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1503 return 0; /* Affinity must be the same on all columns */
1504 }
1505 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1506 return 0; /* Collating sequence must be the same on all columns */
1507 }
1508 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1509 return 0; /* tab2 must be NOT NULL if tab1 is */
1510 }
1511 }
1512 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001513 if( pDestIdx->onError!=OE_None ){
1514 destHasUniqueIdx = 1;
1515 }
drh9d9cf222007-02-13 15:01:11 +00001516 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1517 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1518 }
1519 if( pSrcIdx==0 ){
1520 return 0; /* pDestIdx has no corresponding index in pSrc */
1521 }
1522 }
drh7fc2f412007-03-29 00:08:24 +00001523#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001524 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001525 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1526 }
drh7fc2f412007-03-29 00:08:24 +00001527#endif
drh9d9cf222007-02-13 15:01:11 +00001528
1529 /* If we get this far, it means either:
1530 **
1531 ** * We can always do the transfer if the table contains an
1532 ** an integer primary key
1533 **
1534 ** * We can conditionally do the transfer if the destination
1535 ** table is empty.
1536 */
drhdd735212007-02-24 13:53:05 +00001537#ifdef SQLITE_TEST
1538 sqlite3_xferopt_count++;
1539#endif
drh9d9cf222007-02-13 15:01:11 +00001540 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1541 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001542 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001543 iSrc = pParse->nTab++;
1544 iDest = pParse->nTab++;
1545 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1546 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001547 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001548 /* If tables do not have an INTEGER PRIMARY KEY and there
1549 ** are indices to be copied and the destination is not empty,
1550 ** we have to disallow the transfer optimization because the
1551 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001552 **
1553 ** Or if the destination has a UNIQUE index and is not empty,
1554 ** we also disallow the transfer optimization because we cannot
1555 ** insure that all entries in the union of DEST and SRC will be
1556 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001557 */
1558 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1559 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1560 sqlite3VdbeJumpHere(v, addr1);
1561 }else{
1562 emptyDestTest = 0;
1563 }
1564 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1565 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001566 if( pDest->iPKey>=0 ){
drhbd36ba62007-03-31 13:00:26 +00001567 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh95bad4c2007-03-28 18:04:10 +00001568 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1569 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1570 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1571 "PRIMARY KEY must be unique", P3_STATIC);
1572 sqlite3VdbeJumpHere(v, addr2);
1573 autoIncStep(pParse, counterMem);
drhbd36ba62007-03-31 13:00:26 +00001574 }else if( pDest->pIndex==0 ){
1575 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
drh95bad4c2007-03-28 18:04:10 +00001576 }else{
drhbd36ba62007-03-31 13:00:26 +00001577 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001578 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001579 }
drh9d9cf222007-02-13 15:01:11 +00001580 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001581 sqlite3VdbeOp3(v, OP_Insert, iDest,
1582 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
drh9d9cf222007-02-13 15:01:11 +00001583 pDest->zName, 0);
1584 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1585 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1586 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1587 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1588 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1589 }
1590 assert( pSrcIdx );
1591 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1592 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1593 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1594 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1595 VdbeComment((v, "# %s", pSrcIdx->zName));
1596 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1597 (char*)pKey, P3_KEYINFO_HANDOFF);
1598 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1599 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1600 VdbeComment((v, "# %s", pDestIdx->zName));
1601 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1602 (char*)pKey, P3_KEYINFO_HANDOFF);
1603 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1604 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001605 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
drh9d9cf222007-02-13 15:01:11 +00001606 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1607 sqlite3VdbeJumpHere(v, addr1);
1608 }
1609 sqlite3VdbeJumpHere(v, emptySrcTest);
1610 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1611 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1612 if( emptyDestTest ){
1613 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1614 sqlite3VdbeJumpHere(v, emptyDestTest);
1615 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1616 return 0;
1617 }else{
1618 return 1;
1619 }
1620}
1621#endif /* SQLITE_OMIT_XFER_OPT */