blob: a2a417f74e5747577534814b8015153978d765f4 [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**
drhabb6fca2007-08-16 12:24:01 +000015** $Id: insert.c,v 1.190 2007/08/16 12:24:02 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/*
102** Return non-zero if SELECT statement p opens the table with rootpage
103** iTab in database iDb. This is used to see if a statement of the form
104** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
105** table for the results of the SELECT.
106**
107** No checking is done for sub-selects that are part of expressions.
108*/
danielk1977e501b892006-01-09 06:29:47 +0000109static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
danielk19774d887782005-02-08 08:42:27 +0000110 int i;
111 struct SrcList_item *pItem;
112 if( p->pSrc==0 ) return 0;
113 for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
114 if( pItem->pSelect ){
danielk1977da184232006-01-05 11:34:32 +0000115 if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
danielk19774d887782005-02-08 08:42:27 +0000116 }else{
danielk1977da184232006-01-05 11:34:32 +0000117 if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
danielk19774d887782005-02-08 08:42:27 +0000118 }
119 }
120 return 0;
121}
danielk19773d1bfea2004-05-14 11:00:53 +0000122
drh9d9cf222007-02-13 15:01:11 +0000123#ifndef SQLITE_OMIT_AUTOINCREMENT
124/*
125** Write out code to initialize the autoincrement logic. This code
126** looks up the current autoincrement value in the sqlite_sequence
127** table and stores that value in a memory cell. Code generated by
128** autoIncStep() will keep that memory cell holding the largest
129** rowid value. Code generated by autoIncEnd() will write the new
130** largest value of the counter back into the sqlite_sequence table.
131**
132** This routine returns the index of the mem[] cell that contains
133** the maximum rowid counter.
134**
135** Two memory cells are allocated. The next memory cell after the
136** one returned holds the rowid in sqlite_sequence where we will
137** write back the revised maximum rowid.
138*/
139static int autoIncBegin(
140 Parse *pParse, /* Parsing context */
141 int iDb, /* Index of the database holding pTab */
142 Table *pTab /* The table we are writing to */
143){
144 int memId = 0;
145 if( pTab->autoInc ){
146 Vdbe *v = pParse->pVdbe;
147 Db *pDb = &pParse->db->aDb[iDb];
148 int iCur = pParse->nTab;
149 int addr;
150 assert( v );
151 addr = sqlite3VdbeCurrentAddr(v);
152 memId = pParse->nMem+1;
153 pParse->nMem += 2;
154 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
155 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
156 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
157 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
158 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
159 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
160 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
161 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
162 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
163 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
164 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
165 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
166 }
167 return memId;
168}
169
170/*
171** Update the maximum rowid for an autoincrement calculation.
172**
173** This routine should be called when the top of the stack holds a
174** new rowid that is about to be inserted. If that new rowid is
175** larger than the maximum rowid in the memId memory cell, then the
176** memory cell is updated. The stack is unchanged.
177*/
178static void autoIncStep(Parse *pParse, int memId){
179 if( memId>0 ){
180 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
181 }
182}
183
184/*
185** After doing one or more inserts, the maximum rowid is stored
186** in mem[memId]. Generate code to write this value back into the
187** the sqlite_sequence table.
188*/
189static void autoIncEnd(
190 Parse *pParse, /* The parsing context */
191 int iDb, /* Index of the database holding pTab */
192 Table *pTab, /* Table we are inserting into */
193 int memId /* Memory cell holding the maximum rowid */
194){
195 if( pTab->autoInc ){
196 int iCur = pParse->nTab;
197 Vdbe *v = pParse->pVdbe;
198 Db *pDb = &pParse->db->aDb[iDb];
199 int addr;
200 assert( v );
201 addr = sqlite3VdbeCurrentAddr(v);
202 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
203 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
204 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
205 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
206 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
207 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
208 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
209 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
drhe4d90812007-03-29 05:51:49 +0000210 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
drh9d9cf222007-02-13 15:01:11 +0000211 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
212 }
213}
214#else
215/*
216** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
217** above are all no-ops
218*/
219# define autoIncBegin(A,B,C) (0)
220# define autoIncStep(A,B)
221# define autoIncEnd(A,B,C,D)
222#endif /* SQLITE_OMIT_AUTOINCREMENT */
223
224
225/* Forward declaration */
226static int xferOptimization(
227 Parse *pParse, /* Parser context */
228 Table *pDest, /* The table we are inserting into */
229 Select *pSelect, /* A SELECT statement to use as the data source */
230 int onError, /* How to handle constraint errors */
231 int iDbDest /* The database of pDest */
232);
233
danielk19773d1bfea2004-05-14 11:00:53 +0000234/*
drh1ccde152000-06-17 13:12:39 +0000235** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000236**
237** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000238** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000239**
drh1ccde152000-06-17 13:12:39 +0000240** The IDLIST following the table name is always optional. If omitted,
241** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000242** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000243**
244** The pList parameter holds EXPRLIST in the first form of the INSERT
245** statement above, and pSelect is NULL. For the second form, pList is
246** NULL and pSelect is a pointer to the select statement used to generate
247** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000248**
drh9d9cf222007-02-13 15:01:11 +0000249** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000250** select with data coming from a VALUES clause, the code executes
251** once straight down through. The template looks like this:
252**
253** open write cursor to <table> and its indices
254** puts VALUES clause expressions onto the stack
255** write the resulting record into <table>
256** cleanup
257**
drh9d9cf222007-02-13 15:01:11 +0000258** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000259**
260** INSERT INTO <table> SELECT ...
261**
drh9d9cf222007-02-13 15:01:11 +0000262** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
263** in other words if the SELECT pulls all columns from a single table
264** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
265** if <table2> and <table1> are distinct tables but have identical
266** schemas, including all the same indices, then a special optimization
267** is invoked that copies raw records from <table2> over to <table1>.
268** See the xferOptimization() function for the implementation of this
269** template. This is the second template.
270**
271** open a write cursor to <table>
272** open read cursor on <table2>
273** transfer all records in <table2> over to <table>
274** close cursors
275** foreach index on <table>
276** open a write cursor on the <table> index
277** open a read cursor on the corresponding <table2> index
278** transfer all records from the read to the write cursors
279** close cursors
280** end foreach
281**
282** The third template is for when the second template does not apply
283** and the SELECT clause does not read from <table> at any time.
284** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000285**
286** goto B
287** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000288** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000289** gosub C
290** end loop
291** cleanup after the SELECT
292** goto D
293** B: open write cursor to <table> and its indices
294** goto A
295** C: insert the select result into <table>
296** return
297** D: cleanup
298**
drh9d9cf222007-02-13 15:01:11 +0000299** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000300** values from a SELECT but the data is being inserted into a table
301** that is also read as part of the SELECT. In the third form,
302** we have to use a intermediate table to store the results of
303** the select. The template is like this:
304**
305** goto B
306** A: setup for the SELECT
307** loop over the tables in the SELECT
308** gosub C
309** end loop
310** cleanup after the SELECT
311** goto D
312** C: insert the select result into the intermediate table
313** return
314** B: open a cursor to an intermediate table
315** goto A
316** D: open write cursor to <table> and its indices
317** loop over the intermediate table
318** transfer values form intermediate table into <table>
319** end the loop
320** cleanup
drhcce7d172000-05-31 15:34:51 +0000321*/
danielk19774adee202004-05-08 08:23:19 +0000322void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000323 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000324 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000325 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000326 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000327 IdList *pColumn, /* Column names corresponding to IDLIST. */
328 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000329){
drh5974a302000-06-07 14:42:26 +0000330 Table *pTab; /* The table to insert into */
drh113088e2003-03-20 01:16:58 +0000331 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000332 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000333 int i, j, idx; /* Loop counters */
334 Vdbe *v; /* Generate code into this virtual machine */
335 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000336 int nColumn; /* Number of columns in the data */
danielk1977cfe9a692004-06-16 12:00:29 +0000337 int base = 0; /* VDBE Cursor number for pTab */
338 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
drh9bb575f2004-09-06 17:24:11 +0000339 sqlite3 *db; /* The main database structure */
drh4a324312001-12-21 14:30:42 +0000340 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000341 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000342 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000343 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
344 int iSelectLoop = 0; /* Address of code that implements the SELECT */
345 int iCleanup = 0; /* Address of the cleanup code */
346 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
347 int iCntMem = 0; /* Memory cell used for the row counter */
drh798da522004-11-04 04:42:28 +0000348 int newIdx = -1; /* Cursor for the NEW table */
drh2958a4e2004-11-12 03:56:15 +0000349 Db *pDb; /* The database containing table being inserted into */
350 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
drhe4d90812007-03-29 05:51:49 +0000351 int appendFlag = 0; /* True if the insert is likely to be an append */
danielk1977da184232006-01-05 11:34:32 +0000352 int iDb;
drhcce7d172000-05-31 15:34:51 +0000353
danielk1977034ca142007-06-26 10:38:54 +0000354 int nHidden = 0;
355
drh798da522004-11-04 04:42:28 +0000356#ifndef SQLITE_OMIT_TRIGGER
357 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000358 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000359#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000360
drh17435752007-08-16 04:30:38 +0000361 db = pParse->db;
362 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000363 goto insert_cleanup;
364 }
drhdaffd0e2001-04-11 14:28:42 +0000365
drh1ccde152000-06-17 13:12:39 +0000366 /* Locate the table into which we will be inserting new information.
367 */
drh113088e2003-03-20 01:16:58 +0000368 assert( pTabList->nSrc==1 );
369 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000370 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000371 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000372 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000373 goto insert_cleanup;
374 }
danielk1977da184232006-01-05 11:34:32 +0000375 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
376 assert( iDb<db->nDb );
377 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000378 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000379 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000380 goto insert_cleanup;
381 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000382
drhb7f91642004-10-31 02:22:47 +0000383 /* Figure out if we have any triggers and if the table being
384 ** inserted into is a view
385 */
386#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000387 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000388 isView = pTab->pSelect!=0;
389#else
drhdca76842004-12-07 14:06:13 +0000390# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000391# define isView 0
392#endif
393#ifdef SQLITE_OMIT_VIEW
394# undef isView
395# define isView 0
396#endif
397
danielk1977c3f9bad2002-05-15 08:30:12 +0000398 /* Ensure that:
399 * (a) the table is not read-only,
400 * (b) that if it is a view then ON INSERT triggers exist
401 */
drhdca76842004-12-07 14:06:13 +0000402 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000403 goto insert_cleanup;
404 }
drh43617e92006-03-06 20:55:46 +0000405 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000406
drhf573c992002-07-31 00:32:50 +0000407 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000408 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
409 ** module table).
drhf573c992002-07-31 00:32:50 +0000410 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000411 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000412 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000413 }
414
drh1ccde152000-06-17 13:12:39 +0000415 /* Allocate a VDBE
416 */
danielk19774adee202004-05-08 08:23:19 +0000417 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000418 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000419 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000420 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000421
danielk1977c3f9bad2002-05-15 08:30:12 +0000422 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000423 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000424 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000425 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000426
drh9d9cf222007-02-13 15:01:11 +0000427#ifndef SQLITE_OMIT_XFER_OPT
428 /* If the statement is of the form
429 **
430 ** INSERT INTO <table1> SELECT * FROM <table2>;
431 **
432 ** Then special optimizations can be applied that make the transfer
433 ** very fast and which reduce fragmentation of indices.
434 */
435 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
436 assert( !triggers_exist );
437 assert( pList==0 );
438 goto insert_cleanup;
439 }
440#endif /* SQLITE_OMIT_XFER_OPT */
441
drh2958a4e2004-11-12 03:56:15 +0000442 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000443 ** sqlite_sequence table and store it in memory cell counterMem. Also
444 ** remember the rowid of the sqlite_sequence table entry in memory cell
445 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000446 */
drh9d9cf222007-02-13 15:01:11 +0000447 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000448
drh1ccde152000-06-17 13:12:39 +0000449 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000450 ** is coming from a SELECT statement, then this step also generates
451 ** all the code to implement the SELECT statement and invoke a subroutine
452 ** to process each row of the result. (Template 2.) If the SELECT
453 ** statement uses the the table that is being inserted into, then the
454 ** subroutine is also coded here. That subroutine stores the SELECT
455 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000456 */
drh5974a302000-06-07 14:42:26 +0000457 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000458 /* Data is coming from a SELECT. Generate code to implement that SELECT
459 */
460 int rc, iInitCode;
danielk19774adee202004-05-08 08:23:19 +0000461 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
462 iSelectLoop = sqlite3VdbeCurrentAddr(v);
463 iInsertBlock = sqlite3VdbeMakeLabel(v);
danielk1977b3bce662005-01-29 08:32:43 +0000464
465 /* Resolve the expressions in the SELECT statement and execute it. */
466 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
drh17435752007-08-16 04:30:38 +0000467 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000468 goto insert_cleanup;
469 }
danielk1977b3bce662005-01-29 08:32:43 +0000470
danielk19774adee202004-05-08 08:23:19 +0000471 iCleanup = sqlite3VdbeMakeLabel(v);
472 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000473 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000474 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000475
476 /* Set useTempTable to TRUE if the result of the SELECT statement
477 ** should be written into a temporary table. Set to FALSE if each
478 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000479 **
480 ** A temp table must be used if the table being updated is also one
481 ** of the tables being read by the SELECT statement. Also use a
482 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000483 */
danielk1977da184232006-01-05 11:34:32 +0000484 if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
drh048c5302003-04-03 01:50:44 +0000485 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000486 }
drh142e30d2002-08-28 03:00:58 +0000487
488 if( useTempTable ){
489 /* Generate the subroutine that SELECT calls to process each row of
490 ** the result. Store the result in a temporary table
491 */
492 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000493 sqlite3VdbeResolveLabel(v, iInsertBlock);
494 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf0863fe2005-06-12 21:35:51 +0000495 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
danielk19774adee202004-05-08 08:23:19 +0000496 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhe4d90812007-03-29 05:51:49 +0000497 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
danielk19774adee202004-05-08 08:23:19 +0000498 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000499
500 /* The following code runs first because the GOTO at the very top
501 ** of the program jumps to it. Create the temporary table, then jump
502 ** back up and execute the SELECT code above.
503 */
drhd654be82005-09-20 17:42:23 +0000504 sqlite3VdbeJumpHere(v, iInitCode);
drhb9bb7c12006-06-11 23:41:55 +0000505 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
drhb6f54522004-05-20 02:42:16 +0000506 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
danielk19774adee202004-05-08 08:23:19 +0000507 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
508 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000509 }else{
drhd654be82005-09-20 17:42:23 +0000510 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000511 }
drh5974a302000-06-07 14:42:26 +0000512 }else{
drh142e30d2002-08-28 03:00:58 +0000513 /* This is the case if the data for the INSERT is coming from a VALUES
514 ** clause
515 */
danielk1977b3bce662005-01-29 08:32:43 +0000516 NameContext sNC;
517 memset(&sNC, 0, sizeof(sNC));
518 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000519 srcTab = -1;
drh142e30d2002-08-28 03:00:58 +0000520 useTempTable = 0;
drh147d0cc2006-08-25 23:42:53 +0000521 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000522 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000523 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000524 goto insert_cleanup;
525 }
drhe64e7b22002-02-18 13:56:36 +0000526 }
drh5974a302000-06-07 14:42:26 +0000527 }
drh1ccde152000-06-17 13:12:39 +0000528
529 /* Make sure the number of columns in the source data matches the number
530 ** of columns to be inserted into the table.
531 */
danielk1977034ca142007-06-26 10:38:54 +0000532 if( IsVirtual(pTab) ){
533 for(i=0; i<pTab->nCol; i++){
534 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
535 }
536 }
537 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000538 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000539 "table %S has %d columns but %d values were supplied",
540 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000541 goto insert_cleanup;
542 }
drh967e8b72000-06-21 13:59:10 +0000543 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000544 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000545 goto insert_cleanup;
546 }
drh1ccde152000-06-17 13:12:39 +0000547
548 /* If the INSERT statement included an IDLIST term, then make sure
549 ** all elements of the IDLIST really are columns of the table and
550 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000551 **
552 ** If the table has an INTEGER PRIMARY KEY column and that column
553 ** is named in the IDLIST, then record in the keyColumn variable
554 ** the index into IDLIST of the primary key column. keyColumn is
555 ** the index of the primary key as it appears in IDLIST, not as
556 ** is appears in the original table. (The index of the primary
557 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000558 */
drh967e8b72000-06-21 13:59:10 +0000559 if( pColumn ){
560 for(i=0; i<pColumn->nId; i++){
561 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000562 }
drh967e8b72000-06-21 13:59:10 +0000563 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000564 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000565 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000566 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000567 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000568 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000569 }
drhcce7d172000-05-31 15:34:51 +0000570 break;
571 }
572 }
573 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000574 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000575 keyColumn = i;
576 }else{
danielk19774adee202004-05-08 08:23:19 +0000577 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000578 pTabList, 0, pColumn->a[i].zName);
579 pParse->nErr++;
580 goto insert_cleanup;
581 }
drhcce7d172000-05-31 15:34:51 +0000582 }
583 }
584 }
drh1ccde152000-06-17 13:12:39 +0000585
drhaacc5432002-01-06 17:07:40 +0000586 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000587 ** key, the set the keyColumn variable to the primary key column index
588 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000589 */
drh147d0cc2006-08-25 23:42:53 +0000590 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000591 keyColumn = pTab->iPKey;
592 }
593
drh142e30d2002-08-28 03:00:58 +0000594 /* Open the temp table for FOR EACH ROW triggers
595 */
drhdca76842004-12-07 14:06:13 +0000596 if( triggers_exist ){
danielk19774adee202004-05-08 08:23:19 +0000597 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
danielk197784ac9d02004-05-18 09:58:06 +0000598 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000599 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000600
drhfeeb1392002-04-09 03:28:01 +0000601 /* Initialize the count of rows to be inserted
602 */
drh142e30d2002-08-28 03:00:58 +0000603 if( db->flags & SQLITE_CountRows ){
604 iCntMem = pParse->nMem++;
drhd654be82005-09-20 17:42:23 +0000605 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000606 }
607
danielk1977c3f9bad2002-05-15 08:30:12 +0000608 /* Open tables and indices if there are no row triggers */
drhdca76842004-12-07 14:06:13 +0000609 if( !triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000610 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000611 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000612 }
613
drh142e30d2002-08-28 03:00:58 +0000614 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000615 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000616 ** source is a subroutine call from the SELECT statement, then we need
617 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000618 */
drh142e30d2002-08-28 03:00:58 +0000619 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000620 iBreak = sqlite3VdbeMakeLabel(v);
621 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
622 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000623 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000624 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
625 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh5974a302000-06-07 14:42:26 +0000626 }
drh1ccde152000-06-17 13:12:39 +0000627
drh5cf590c2003-04-24 01:45:04 +0000628 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000629 */
danielk19774adee202004-05-08 08:23:19 +0000630 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000631 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000632
drh70ce3f02003-04-15 19:22:22 +0000633 /* build the NEW.* reference row. Note that if there is an INTEGER
634 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
635 ** translated into a unique ID for the row. But on a BEFORE trigger,
636 ** we do not know what the unique ID will be (because the insert has
637 ** not happened yet) so we substitute a rowid of -1
638 */
639 if( keyColumn<0 ){
danielk19774adee202004-05-08 08:23:19 +0000640 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000641 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000642 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000643 }else{
drhd6fe9612005-01-14 01:22:00 +0000644 assert( pSelect==0 ); /* Otherwise useTempTable is true */
danielk19774adee202004-05-08 08:23:19 +0000645 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
646 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
647 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
648 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
649 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000650 }
651
danielk1977034ca142007-06-26 10:38:54 +0000652 /* Cannot have triggers on a virtual table. If it were possible,
653 ** this block would have to account for hidden column.
654 */
655 assert(!IsVirtual(pTab));
656
drh70ce3f02003-04-15 19:22:22 +0000657 /* Create the new column data
658 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000659 for(i=0; i<pTab->nCol; i++){
660 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000661 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000662 }else{
drh9adf9ac2002-05-15 11:44:13 +0000663 for(j=0; j<pColumn->nId; j++){
664 if( pColumn->a[j].idx==i ) break;
665 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000666 }
667 if( pColumn && j>=pColumn->nId ){
danielk19777977a172004-11-09 12:44:37 +0000668 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000669 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000670 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000671 }else{
drhd6fe9612005-01-14 01:22:00 +0000672 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000673 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000674 }
675 }
danielk19774adee202004-05-08 08:23:19 +0000676 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000677
678 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
679 ** do not attempt any conversions before assembling the record.
680 ** If this is a real table, attempt conversions as required by the
681 ** table column affinities.
682 */
683 if( !isView ){
684 sqlite3TableAffinityStr(v, pTab);
685 }
drhf0863fe2005-06-12 21:35:51 +0000686 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000687
drh5cf590c2003-04-24 01:45:04 +0000688 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000689 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
drhb2fe7d82003-04-20 17:29:23 +0000690 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000691 goto insert_cleanup;
692 }
drh70ce3f02003-04-15 19:22:22 +0000693 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000694
drh70ce3f02003-04-15 19:22:22 +0000695 /* If any triggers exists, the opening of tables and indices is deferred
696 ** until now.
697 */
drhdca76842004-12-07 14:06:13 +0000698 if( triggers_exist && !isView ){
drh5cf590c2003-04-24 01:45:04 +0000699 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000700 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000701 }
702
drh4a324312001-12-21 14:30:42 +0000703 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000704 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000705 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000706 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000707 */
drh5cf590c2003-04-24 01:45:04 +0000708 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000709 if( IsVirtual(pTab) ){
710 /* The row that the VUpdate opcode will delete: none */
711 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
712 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000713 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000714 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000715 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh142e30d2002-08-28 03:00:58 +0000716 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000717 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000718 }else{
drhe4d90812007-03-29 05:51:49 +0000719 VdbeOp *pOp;
danielk19774adee202004-05-08 08:23:19 +0000720 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
drhe4d90812007-03-29 05:51:49 +0000721 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000722 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000723 appendFlag = 1;
724 pOp->opcode = OP_NewRowid;
725 pOp->p1 = base;
726 pOp->p2 = counterMem;
727 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000728 }
drhf0863fe2005-06-12 21:35:51 +0000729 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000730 ** to generate a unique primary key value.
731 */
drhe4d90812007-03-29 05:51:49 +0000732 if( !appendFlag ){
733 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
734 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
735 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
736 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
737 }
drh4cbdda92006-06-14 19:00:20 +0000738 }else if( IsVirtual(pTab) ){
739 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000740 }else{
drhf0863fe2005-06-12 21:35:51 +0000741 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
drhe4d90812007-03-29 05:51:49 +0000742 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000743 }
drh9d9cf222007-02-13 15:01:11 +0000744 autoIncStep(pParse, counterMem);
drh4a324312001-12-21 14:30:42 +0000745
danielk1977c3f9bad2002-05-15 08:30:12 +0000746 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000747 ** with the first column.
748 */
danielk1977034ca142007-06-26 10:38:54 +0000749 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000750 for(i=0; i<pTab->nCol; i++){
751 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000752 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000753 ** Whenever this column is read, the record number will be substituted
754 ** in its place. So will fill this column with a NULL to avoid
755 ** taking up data space with information that will never be used. */
drhf0863fe2005-06-12 21:35:51 +0000756 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh9adf9ac2002-05-15 11:44:13 +0000757 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000758 }
759 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000760 if( IsHiddenColumn(&pTab->aCol[i]) ){
761 assert( IsVirtual(pTab) );
762 j = -1;
763 nHidden++;
764 }else{
765 j = i - nHidden;
766 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000767 }else{
drh9adf9ac2002-05-15 11:44:13 +0000768 for(j=0; j<pColumn->nId; j++){
769 if( pColumn->a[j].idx==i ) break;
770 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000771 }
danielk1977034ca142007-06-26 10:38:54 +0000772 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk19777977a172004-11-09 12:44:37 +0000773 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000774 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000775 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
drh142e30d2002-08-28 03:00:58 +0000776 }else if( pSelect ){
drh16ed8a62006-08-29 18:46:14 +0000777 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000778 }else{
danielk19774adee202004-05-08 08:23:19 +0000779 sqlite3ExprCode(pParse, pList->a[j].pExpr);
drh5974a302000-06-07 14:42:26 +0000780 }
drhbed86902000-06-02 13:27:59 +0000781 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000782
783 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000784 ** do the insertion.
785 */
drh4cbdda92006-06-14 19:00:20 +0000786#ifndef SQLITE_OMIT_VIRTUALTABLE
787 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000788 pParse->pVirtualLock = pTab;
danielk19771f6eec52006-06-16 06:17:47 +0000789 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
drh4cbdda92006-06-14 19:00:20 +0000790 (const char*)pTab->pVtab, P3_VTAB);
791 }else
792#endif
793 {
794 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
795 0, onError, endOfLoop);
796 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000797 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
798 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000799 }
drh5cf590c2003-04-24 01:45:04 +0000800 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000801
drh5cf590c2003-04-24 01:45:04 +0000802 /* Update the count of rows that are inserted
803 */
804 if( (db->flags & SQLITE_CountRows)!=0 ){
drh15007a92006-01-08 18:10:17 +0000805 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
drh5974a302000-06-07 14:42:26 +0000806 }
drh1ccde152000-06-17 13:12:39 +0000807
drhdca76842004-12-07 14:06:13 +0000808 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000809 /* Close all tables opened */
drh5cf590c2003-04-24 01:45:04 +0000810 if( !isView ){
danielk19774adee202004-05-08 08:23:19 +0000811 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000812 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000813 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000814 }
815 }
drh1bee3d72001-10-15 00:44:35 +0000816
danielk1977c3f9bad2002-05-15 08:30:12 +0000817 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000818 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
819 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000820 goto insert_cleanup;
821 }
drh1bee3d72001-10-15 00:44:35 +0000822 }
823
drh1ccde152000-06-17 13:12:39 +0000824 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000825 */
danielk19774adee202004-05-08 08:23:19 +0000826 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000827 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000828 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
829 sqlite3VdbeResolveLabel(v, iBreak);
830 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000831 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000832 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
833 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
834 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000835 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000836
drh4cbdda92006-06-14 19:00:20 +0000837 if( !triggers_exist && !IsVirtual(pTab) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000838 /* Close all tables opened */
danielk19774adee202004-05-08 08:23:19 +0000839 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000840 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000841 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000842 }
drhcce7d172000-05-31 15:34:51 +0000843 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000844
drhf3388142004-11-13 03:48:06 +0000845 /* Update the sqlite_sequence table by storing the content of the
846 ** counter value in memory counterMem back into the sqlite_sequence
847 ** table.
drh2958a4e2004-11-12 03:56:15 +0000848 */
drh9d9cf222007-02-13 15:01:11 +0000849 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000850
drh1bee3d72001-10-15 00:44:35 +0000851 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000852 ** Return the number of rows inserted. If this routine is
853 ** generating code because of a call to sqlite3NestedParse(), do not
854 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000855 */
danielk1977cc6bd382005-01-10 02:48:49 +0000856 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +0000857 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
858 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
danielk197722322fd2004-05-25 23:35:17 +0000859 sqlite3VdbeSetNumCols(v, 1);
danielk1977955de522006-02-10 02:27:42 +0000860 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000861 }
drhcce7d172000-05-31 15:34:51 +0000862
863insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000864 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000865 sqlite3ExprListDelete(pList);
866 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000867 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000868}
drh9cfcf5d2002-01-29 18:41:24 +0000869
drh9cfcf5d2002-01-29 18:41:24 +0000870/*
871** Generate code to do a constraint check prior to an INSERT or an UPDATE.
872**
873** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000874** the following values:
875**
drhf0863fe2005-06-12 21:35:51 +0000876** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000877** value is omitted unless we are doing an UPDATE that involves a
878** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000879**
drhf0863fe2005-06-12 21:35:51 +0000880** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000881**
882** 3. The data in the first column of the entry after the update.
883**
884** i. Data from middle columns...
885**
886** N. The data in the last column of the entry after the update.
887**
drhf0863fe2005-06-12 21:35:51 +0000888** The old rowid shown as entry (1) above is omitted unless both isUpdate
889** and rowidChng are 1. isUpdate is true for UPDATEs and false for
890** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000891**
892** The code generated by this routine pushes additional entries onto
893** the stack which are the keys for new index entries for the new record.
894** The order of index keys is the same as the order of the indices on
895** the pTable->pIndex list. A key is only created for index i if
896** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000897**
898** This routine also generates code to check constraints. NOT NULL,
899** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000900** then the appropriate action is performed. There are five possible
901** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000902**
903** Constraint type Action What Happens
904** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000905** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000906** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000907** return code of SQLITE_CONSTRAINT.
908**
drh1c928532002-01-31 15:54:21 +0000909** any ABORT Back out changes from the current command
910** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000911** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000912** with SQLITE_CONSTRAINT.
913**
914** any FAIL Sqlite_exec() returns immediately with a
915** return code of SQLITE_CONSTRAINT. The
916** transaction is not rolled back and any
917** prior changes are retained.
918**
drh9cfcf5d2002-01-29 18:41:24 +0000919** any IGNORE The record number and data is popped from
920** the stack and there is an immediate jump
921** to label ignoreDest.
922**
923** NOT NULL REPLACE The NULL value is replace by the default
924** value for that column. If the default value
925** is NULL, the action is the same as ABORT.
926**
927** UNIQUE REPLACE The other row that conflicts with the row
928** being inserted is removed.
929**
930** CHECK REPLACE Illegal. The results in an exception.
931**
drh1c928532002-01-31 15:54:21 +0000932** Which action to take is determined by the overrideError parameter.
933** Or if overrideError==OE_Default, then the pParse->onError parameter
934** is used. Or if pParse->onError==OE_Default then the onError value
935** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000936**
drhaaab5722002-02-19 13:39:21 +0000937** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000938** cursor number "base". All indices of pTab must also have open
939** read/write cursors with cursor number base+i for the i-th cursor.
940** Except, if there is no possibility of a REPLACE action then
941** cursors do not need to be open for indices where aIdxUsed[i]==0.
942**
943** If the isUpdate flag is true, it means that the "base" cursor is
944** initially pointing to an entry that is being updated. The isUpdate
945** flag causes extra code to be generated so that the "base" cursor
946** is still pointing at the same entry after the routine returns.
947** Without the isUpdate flag, the "base" cursor might be moved.
948*/
danielk19774adee202004-05-08 08:23:19 +0000949void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000950 Parse *pParse, /* The parser context */
951 Table *pTab, /* the table into which we are inserting */
952 int base, /* Index of a read/write cursor pointing at pTab */
953 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000954 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000955 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000956 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000957 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000958){
959 int i;
960 Vdbe *v;
961 int nCol;
962 int onError;
963 int addr;
964 int extra;
drh0ca3e242002-01-29 23:07:02 +0000965 int iCur;
966 Index *pIdx;
967 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000968 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000969 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000970
danielk19774adee202004-05-08 08:23:19 +0000971 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000972 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000973 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000974 nCol = pTab->nCol;
975
976 /* Test all NOT NULL constraints.
977 */
978 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000979 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +0000980 continue;
981 }
drh9cfcf5d2002-01-29 18:41:24 +0000982 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +0000983 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +0000984 if( overrideError!=OE_Default ){
985 onError = overrideError;
drha996e472003-05-16 02:30:27 +0000986 }else if( onError==OE_Default ){
987 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +0000988 }
danielk19777977a172004-11-09 12:44:37 +0000989 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +0000990 onError = OE_Abort;
991 }
danielk19774adee202004-05-08 08:23:19 +0000992 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
993 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +0000994 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
995 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +0000996 switch( onError ){
drh1c928532002-01-31 15:54:21 +0000997 case OE_Rollback:
998 case OE_Abort:
999 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001000 char *zMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00001001 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1002 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001003 " may not be NULL", (char*)0);
danielk19774adee202004-05-08 08:23:19 +00001004 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001005 break;
1006 }
1007 case OE_Ignore: {
drhf0863fe2005-06-12 21:35:51 +00001008 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001009 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001010 break;
1011 }
1012 case OE_Replace: {
danielk19777977a172004-11-09 12:44:37 +00001013 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
danielk19774adee202004-05-08 08:23:19 +00001014 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001015 break;
1016 }
drh9cfcf5d2002-01-29 18:41:24 +00001017 }
drhd654be82005-09-20 17:42:23 +00001018 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001019 }
1020
1021 /* Test all CHECK constraints
1022 */
drhffe07b22005-11-03 00:41:17 +00001023#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001024 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001025 int allOk = sqlite3VdbeMakeLabel(v);
1026 assert( pParse->ckOffset==0 );
1027 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001028 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001029 assert( pParse->ckOffset==nCol );
1030 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001031 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001032 if( onError==OE_Ignore ){
drhaa01c7e2006-03-15 16:26:10 +00001033 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1034 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1035 }else{
1036 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1037 }
drhffe07b22005-11-03 00:41:17 +00001038 sqlite3VdbeResolveLabel(v, allOk);
1039 }
1040#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001041
drh0bd1f4e2002-06-06 18:54:39 +00001042 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1043 ** of the new record does not previously exist. Except, if this
1044 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001045 */
drhf0863fe2005-06-12 21:35:51 +00001046 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001047 onError = pTab->keyConf;
1048 if( overrideError!=OE_Default ){
1049 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001050 }else if( onError==OE_Default ){
1051 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001052 }
drha0217ba2003-06-01 01:10:33 +00001053
drh5383ae52003-06-04 12:23:30 +00001054 if( isUpdate ){
danielk19774adee202004-05-08 08:23:19 +00001055 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1056 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1057 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001058 }
danielk19774adee202004-05-08 08:23:19 +00001059 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1060 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001061 switch( onError ){
1062 default: {
1063 onError = OE_Abort;
1064 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001065 }
drh5383ae52003-06-04 12:23:30 +00001066 case OE_Rollback:
1067 case OE_Abort:
1068 case OE_Fail: {
danielk19774adee202004-05-08 08:23:19 +00001069 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
drh701a0ae2004-02-22 20:05:00 +00001070 "PRIMARY KEY must be unique", P3_STATIC);
drh5383ae52003-06-04 12:23:30 +00001071 break;
drh0ca3e242002-01-29 23:07:02 +00001072 }
drh5383ae52003-06-04 12:23:30 +00001073 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001074 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001075 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001076 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001077 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001078 }
1079 seenReplace = 1;
1080 break;
drh0ca3e242002-01-29 23:07:02 +00001081 }
drh5383ae52003-06-04 12:23:30 +00001082 case OE_Ignore: {
1083 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001084 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001085 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001086 break;
1087 }
1088 }
drhd654be82005-09-20 17:42:23 +00001089 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001090 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001091 sqlite3VdbeJumpHere(v, jumpInst1);
danielk19774adee202004-05-08 08:23:19 +00001092 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001093 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001094 }
1095 }
drh0bd1f4e2002-06-06 18:54:39 +00001096
1097 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1098 ** index and making sure that duplicate entries do not already exist.
1099 ** Add the new records to the indices as we go.
1100 */
drhb2fe7d82003-04-20 17:29:23 +00001101 extra = -1;
1102 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1103 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1104 extra++;
1105
1106 /* Create a key for accessing the index entry */
danielk19774adee202004-05-08 08:23:19 +00001107 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001108 for(i=0; i<pIdx->nColumn; i++){
1109 int idx = pIdx->aiColumn[i];
1110 if( idx==pTab->iPKey ){
danielk19774adee202004-05-08 08:23:19 +00001111 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001112 }else{
danielk19774adee202004-05-08 08:23:19 +00001113 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001114 }
1115 }
drh7f057c92005-06-24 03:53:06 +00001116 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001117 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001118
1119 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001120 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001121 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001122 if( overrideError!=OE_Default ){
1123 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001124 }else if( onError==OE_Default ){
1125 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001126 }
drh5383ae52003-06-04 12:23:30 +00001127 if( seenReplace ){
1128 if( onError==OE_Ignore ) onError = OE_Replace;
1129 else if( onError==OE_Fail ) onError = OE_Abort;
1130 }
1131
drhb2fe7d82003-04-20 17:29:23 +00001132
1133 /* Check to see if the new index entry will be unique */
drhf0863fe2005-06-12 21:35:51 +00001134 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
danielk19774adee202004-05-08 08:23:19 +00001135 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001136
1137 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001138 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1139 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001140 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001141 case OE_Rollback:
1142 case OE_Abort:
1143 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001144 int j, n1, n2;
1145 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001146 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1147 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001148 n1 = strlen(zErrMsg);
1149 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1150 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1151 n2 = strlen(zCol);
1152 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001153 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001154 n1 += 2;
1155 }
1156 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001157 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001158 n1 += 3;
1159 break;
1160 }else{
drh5bb3eb92007-05-04 13:15:55 +00001161 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001162 n1 += n2;
1163 }
1164 }
drh5bb3eb92007-05-04 13:15:55 +00001165 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001166 pIdx->nColumn>1 ? " are not unique" : " is not unique");
danielk19774adee202004-05-08 08:23:19 +00001167 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001168 break;
1169 }
1170 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001171 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001172 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001173 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001174 break;
1175 }
1176 case OE_Replace: {
danielk19774adee202004-05-08 08:23:19 +00001177 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001178 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001179 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001180 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001181 }
drh0ca3e242002-01-29 23:07:02 +00001182 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001183 break;
1184 }
drh9cfcf5d2002-01-29 18:41:24 +00001185 }
drh0bd1f4e2002-06-06 18:54:39 +00001186#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001187 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001188#endif
drhd654be82005-09-20 17:42:23 +00001189 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001190 }
1191}
drh0ca3e242002-01-29 23:07:02 +00001192
1193/*
1194** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001195** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001196** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001197** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001198** entries in all indices and in the main table.
1199**
drhb419a922002-01-30 16:17:23 +00001200** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001201** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001202*/
danielk19774adee202004-05-08 08:23:19 +00001203void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001204 Parse *pParse, /* The parser context */
1205 Table *pTab, /* the table into which we are inserting */
1206 int base, /* Index of a read/write cursor pointing at pTab */
1207 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001208 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001209 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001210 int newIdx, /* Index of NEW table for triggers. -1 if none */
1211 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001212){
1213 int i;
1214 Vdbe *v;
1215 int nIdx;
1216 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001217 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001218
danielk19774adee202004-05-08 08:23:19 +00001219 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001220 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001221 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001222 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1223 for(i=nIdx-1; i>=0; i--){
1224 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drhf0863fe2005-06-12 21:35:51 +00001225 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001226 }
danielk19774adee202004-05-08 08:23:19 +00001227 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001228 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001229#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001230 if( newIdx>=0 ){
danielk19774adee202004-05-08 08:23:19 +00001231 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1232 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhf0863fe2005-06-12 21:35:51 +00001233 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001234 }
danielk1977b84f96f2005-01-20 11:32:23 +00001235#endif
drh4794f732004-11-05 17:17:50 +00001236 if( pParse->nested ){
1237 pik_flags = 0;
1238 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001239 pik_flags = OPFLAG_NCHANGE;
1240 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001241 }
drhe4d90812007-03-29 05:51:49 +00001242 if( appendBias ){
1243 pik_flags |= OPFLAG_APPEND;
1244 }
drhf0863fe2005-06-12 21:35:51 +00001245 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001246 if( !pParse->nested ){
1247 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1248 }
danielk1977b28af712004-06-21 06:50:26 +00001249
drhf0863fe2005-06-12 21:35:51 +00001250 if( isUpdate && rowidChng ){
danielk19774adee202004-05-08 08:23:19 +00001251 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001252 }
1253}
drhcd446902004-02-24 01:05:31 +00001254
1255/*
drh290c1942004-08-21 17:54:45 +00001256** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001257** indices of that table. The "base" parameter is the cursor number used
1258** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001259*/
drh290c1942004-08-21 17:54:45 +00001260void sqlite3OpenTableAndIndices(
1261 Parse *pParse, /* Parsing context */
1262 Table *pTab, /* Table to be opened */
1263 int base, /* Cursor number assigned to the table */
1264 int op /* OP_OpenRead or OP_OpenWrite */
1265){
drhcd446902004-02-24 01:05:31 +00001266 int i;
drh4cbdda92006-06-14 19:00:20 +00001267 int iDb;
drhcd446902004-02-24 01:05:31 +00001268 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001269 Vdbe *v;
1270
1271 if( IsVirtual(pTab) ) return;
1272 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1273 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001274 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001275 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001276 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001277 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001278 assert( pIdx->pSchema==pTab->pSchema );
1279 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001280 VdbeComment((v, "# %s", pIdx->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00001281 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
drhcd446902004-02-24 01:05:31 +00001282 }
drh290c1942004-08-21 17:54:45 +00001283 if( pParse->nTab<=base+i ){
1284 pParse->nTab = base+i;
1285 }
drhcd446902004-02-24 01:05:31 +00001286}
drh9d9cf222007-02-13 15:01:11 +00001287
drh91c58e22007-03-27 12:04:04 +00001288
1289#ifdef SQLITE_TEST
1290/*
1291** The following global variable is incremented whenever the
1292** transfer optimization is used. This is used for testing
1293** purposes only - to make sure the transfer optimization really
1294** is happening when it is suppose to.
1295*/
1296int sqlite3_xferopt_count;
1297#endif /* SQLITE_TEST */
1298
1299
drh9d9cf222007-02-13 15:01:11 +00001300#ifndef SQLITE_OMIT_XFER_OPT
1301/*
1302** Check to collation names to see if they are compatible.
1303*/
1304static int xferCompatibleCollation(const char *z1, const char *z2){
1305 if( z1==0 ){
1306 return z2==0;
1307 }
1308 if( z2==0 ){
1309 return 0;
1310 }
1311 return sqlite3StrICmp(z1, z2)==0;
1312}
1313
1314
1315/*
1316** Check to see if index pSrc is compatible as a source of data
1317** for index pDest in an insert transfer optimization. The rules
1318** for a compatible index:
1319**
1320** * The index is over the same set of columns
1321** * The same DESC and ASC markings occurs on all columns
1322** * The same onError processing (OE_Abort, OE_Ignore, etc)
1323** * The same collating sequence on each column
1324*/
1325static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1326 int i;
1327 assert( pDest && pSrc );
1328 assert( pDest->pTable!=pSrc->pTable );
1329 if( pDest->nColumn!=pSrc->nColumn ){
1330 return 0; /* Different number of columns */
1331 }
1332 if( pDest->onError!=pSrc->onError ){
1333 return 0; /* Different conflict resolution strategies */
1334 }
1335 for(i=0; i<pSrc->nColumn; i++){
1336 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1337 return 0; /* Different columns indexed */
1338 }
1339 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1340 return 0; /* Different sort orders */
1341 }
1342 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1343 return 0; /* Different sort orders */
1344 }
1345 }
1346
1347 /* If no test above fails then the indices must be compatible */
1348 return 1;
1349}
1350
1351/*
1352** Attempt the transfer optimization on INSERTs of the form
1353**
1354** INSERT INTO tab1 SELECT * FROM tab2;
1355**
1356** This optimization is only attempted if
1357**
1358** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001359** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001360**
1361** (2) tab1 and tab2 are different tables
1362**
1363** (3) There must be no triggers on tab1
1364**
1365** (4) The result set of the SELECT statement is "*"
1366**
1367** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1368** or LIMIT clause.
1369**
1370** (6) The SELECT statement is a simple (not a compound) select that
1371** contains only tab2 in its FROM clause
1372**
1373** This method for implementing the INSERT transfers raw records from
1374** tab2 over to tab1. The columns are not decoded. Raw records from
1375** the indices of tab2 are transfered to tab1 as well. In so doing,
1376** the resulting tab1 has much less fragmentation.
1377**
1378** This routine returns TRUE if the optimization is attempted. If any
1379** of the conditions above fail so that the optimization should not
1380** be attempted, then this routine returns FALSE.
1381*/
1382static int xferOptimization(
1383 Parse *pParse, /* Parser context */
1384 Table *pDest, /* The table we are inserting into */
1385 Select *pSelect, /* A SELECT statement to use as the data source */
1386 int onError, /* How to handle constraint errors */
1387 int iDbDest /* The database of pDest */
1388){
1389 ExprList *pEList; /* The result set of the SELECT */
1390 Table *pSrc; /* The table in the FROM clause of SELECT */
1391 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1392 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1393 int i; /* Loop counter */
1394 int iDbSrc; /* The database of pSrc */
1395 int iSrc, iDest; /* Cursors from source and destination */
1396 int addr1, addr2; /* Loop addresses */
1397 int emptyDestTest; /* Address of test for empty pDest */
1398 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001399 Vdbe *v; /* The VDBE we are building */
1400 KeyInfo *pKey; /* Key information for an index */
1401 int counterMem; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001402 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001403
1404 if( pSelect==0 ){
1405 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1406 }
1407 if( pDest->pTrigger ){
1408 return 0; /* tab1 must not have triggers */
1409 }
1410#ifndef SQLITE_OMIT_VIRTUALTABLE
1411 if( pDest->isVirtual ){
1412 return 0; /* tab1 must not be a virtual table */
1413 }
1414#endif
1415 if( onError==OE_Default ){
1416 onError = OE_Abort;
1417 }
1418 if( onError!=OE_Abort && onError!=OE_Rollback ){
1419 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1420 }
1421 if( pSelect->pSrc==0 ){
1422 return 0; /* SELECT must have a FROM clause */
1423 }
1424 if( pSelect->pSrc->nSrc!=1 ){
1425 return 0; /* FROM clause must have exactly one term */
1426 }
1427 if( pSelect->pSrc->a[0].pSelect ){
1428 return 0; /* FROM clause cannot contain a subquery */
1429 }
1430 if( pSelect->pWhere ){
1431 return 0; /* SELECT may not have a WHERE clause */
1432 }
1433 if( pSelect->pOrderBy ){
1434 return 0; /* SELECT may not have an ORDER BY clause */
1435 }
drh8103b7d2007-02-24 13:23:51 +00001436 /* Do not need to test for a HAVING clause. If HAVING is present but
1437 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001438 if( pSelect->pGroupBy ){
1439 return 0; /* SELECT may not have a GROUP BY clause */
1440 }
1441 if( pSelect->pLimit ){
1442 return 0; /* SELECT may not have a LIMIT clause */
1443 }
drh8103b7d2007-02-24 13:23:51 +00001444 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001445 if( pSelect->pPrior ){
1446 return 0; /* SELECT may not be a compound query */
1447 }
1448 if( pSelect->isDistinct ){
1449 return 0; /* SELECT may not be DISTINCT */
1450 }
1451 pEList = pSelect->pEList;
1452 assert( pEList!=0 );
1453 if( pEList->nExpr!=1 ){
1454 return 0; /* The result set must have exactly one column */
1455 }
1456 assert( pEList->a[0].pExpr );
1457 if( pEList->a[0].pExpr->op!=TK_ALL ){
1458 return 0; /* The result set must be the special operator "*" */
1459 }
1460
1461 /* At this point we have established that the statement is of the
1462 ** correct syntactic form to participate in this optimization. Now
1463 ** we have to check the semantics.
1464 */
1465 pItem = pSelect->pSrc->a;
1466 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1467 if( pSrc==0 ){
1468 return 0; /* FROM clause does not contain a real table */
1469 }
1470 if( pSrc==pDest ){
1471 return 0; /* tab1 and tab2 may not be the same table */
1472 }
1473#ifndef SQLITE_OMIT_VIRTUALTABLE
1474 if( pSrc->isVirtual ){
1475 return 0; /* tab2 must not be a virtual table */
1476 }
1477#endif
1478 if( pSrc->pSelect ){
1479 return 0; /* tab2 may not be a view */
1480 }
1481 if( pDest->nCol!=pSrc->nCol ){
1482 return 0; /* Number of columns must be the same in tab1 and tab2 */
1483 }
1484 if( pDest->iPKey!=pSrc->iPKey ){
1485 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1486 }
1487 for(i=0; i<pDest->nCol; i++){
1488 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1489 return 0; /* Affinity must be the same on all columns */
1490 }
1491 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1492 return 0; /* Collating sequence must be the same on all columns */
1493 }
1494 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1495 return 0; /* tab2 must be NOT NULL if tab1 is */
1496 }
1497 }
1498 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001499 if( pDestIdx->onError!=OE_None ){
1500 destHasUniqueIdx = 1;
1501 }
drh9d9cf222007-02-13 15:01:11 +00001502 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1503 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1504 }
1505 if( pSrcIdx==0 ){
1506 return 0; /* pDestIdx has no corresponding index in pSrc */
1507 }
1508 }
drh7fc2f412007-03-29 00:08:24 +00001509#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001510 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001511 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1512 }
drh7fc2f412007-03-29 00:08:24 +00001513#endif
drh9d9cf222007-02-13 15:01:11 +00001514
1515 /* If we get this far, it means either:
1516 **
1517 ** * We can always do the transfer if the table contains an
1518 ** an integer primary key
1519 **
1520 ** * We can conditionally do the transfer if the destination
1521 ** table is empty.
1522 */
drhdd735212007-02-24 13:53:05 +00001523#ifdef SQLITE_TEST
1524 sqlite3_xferopt_count++;
1525#endif
drh9d9cf222007-02-13 15:01:11 +00001526 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1527 v = sqlite3GetVdbe(pParse);
1528 iSrc = pParse->nTab++;
1529 iDest = pParse->nTab++;
1530 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1531 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001532 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001533 /* If tables do not have an INTEGER PRIMARY KEY and there
1534 ** are indices to be copied and the destination is not empty,
1535 ** we have to disallow the transfer optimization because the
1536 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001537 **
1538 ** Or if the destination has a UNIQUE index and is not empty,
1539 ** we also disallow the transfer optimization because we cannot
1540 ** insure that all entries in the union of DEST and SRC will be
1541 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001542 */
1543 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1544 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1545 sqlite3VdbeJumpHere(v, addr1);
1546 }else{
1547 emptyDestTest = 0;
1548 }
1549 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1550 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001551 if( pDest->iPKey>=0 ){
drhbd36ba62007-03-31 13:00:26 +00001552 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh95bad4c2007-03-28 18:04:10 +00001553 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1554 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1555 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1556 "PRIMARY KEY must be unique", P3_STATIC);
1557 sqlite3VdbeJumpHere(v, addr2);
1558 autoIncStep(pParse, counterMem);
drhbd36ba62007-03-31 13:00:26 +00001559 }else if( pDest->pIndex==0 ){
1560 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
drh95bad4c2007-03-28 18:04:10 +00001561 }else{
drhbd36ba62007-03-31 13:00:26 +00001562 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001563 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001564 }
drh9d9cf222007-02-13 15:01:11 +00001565 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001566 sqlite3VdbeOp3(v, OP_Insert, iDest,
1567 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
drh9d9cf222007-02-13 15:01:11 +00001568 pDest->zName, 0);
1569 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1570 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1571 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1572 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1573 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1574 }
1575 assert( pSrcIdx );
1576 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1577 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1578 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1579 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1580 VdbeComment((v, "# %s", pSrcIdx->zName));
1581 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1582 (char*)pKey, P3_KEYINFO_HANDOFF);
1583 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1584 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1585 VdbeComment((v, "# %s", pDestIdx->zName));
1586 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1587 (char*)pKey, P3_KEYINFO_HANDOFF);
1588 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1589 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001590 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
drh9d9cf222007-02-13 15:01:11 +00001591 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1592 sqlite3VdbeJumpHere(v, addr1);
1593 }
1594 sqlite3VdbeJumpHere(v, emptySrcTest);
1595 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1596 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1597 if( emptyDestTest ){
1598 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1599 sqlite3VdbeJumpHere(v, emptyDestTest);
1600 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1601 return 0;
1602 }else{
1603 return 1;
1604 }
1605}
1606#endif /* SQLITE_OMIT_XFER_OPT */