blob: ba9426d61cc2bad54c27b601d85bccd2e59c245c [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**
drh2e06c672007-07-23 19:39:46 +000015** $Id: insert.c,v 1.188 2007/07/23 19:39:47 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;
44 pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
45 if( !pIdx->zColAff ){
46 return;
47 }
48 for(n=0; n<pIdx->nColumn; n++){
49 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
50 }
51 pIdx->zColAff[pIdx->nColumn] = '\0';
52 }
danielk19773d1bfea2004-05-14 11:00:53 +000053
drh956bc922004-07-24 17:38:29 +000054 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000055}
56
57/*
58** Set P3 of the most recently inserted opcode to a column affinity
59** string for table pTab. A column affinity string has one character
60** for each column indexed by the index, according to the affinity of the
61** column:
62**
63** Character Column affinity
64** ------------------------------
drh3eda0402005-11-24 13:15:32 +000065** 'a' TEXT
66** 'b' NONE
67** 'c' NUMERIC
68** 'd' INTEGER
69** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000070*/
71void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000072 /* The first time a column affinity string for a particular table
73 ** is required, it is allocated and populated here. It is then
74 ** stored as a member of the Table structure for subsequent use.
75 **
76 ** The column affinity string will eventually be deleted by
77 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
78 */
79 if( !pTab->zColAff ){
80 char *zColAff;
81 int i;
82
danielk1977a37cdde2004-05-16 11:15:36 +000083 zColAff = (char *)sqliteMalloc(pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000084 if( !zColAff ){
danielk1977a37cdde2004-05-16 11:15:36 +000085 return;
danielk19773d1bfea2004-05-14 11:00:53 +000086 }
87
88 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000089 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000090 }
91 zColAff[pTab->nCol] = '\0';
92
93 pTab->zColAff = zColAff;
94 }
95
drh956bc922004-07-24 17:38:29 +000096 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +000097}
98
danielk19774d887782005-02-08 08:42:27 +000099/*
100** Return non-zero if SELECT statement p opens the table with rootpage
101** iTab in database iDb. This is used to see if a statement of the form
102** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
103** table for the results of the SELECT.
104**
105** No checking is done for sub-selects that are part of expressions.
106*/
danielk1977e501b892006-01-09 06:29:47 +0000107static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
danielk19774d887782005-02-08 08:42:27 +0000108 int i;
109 struct SrcList_item *pItem;
110 if( p->pSrc==0 ) return 0;
111 for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
112 if( pItem->pSelect ){
danielk1977da184232006-01-05 11:34:32 +0000113 if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
danielk19774d887782005-02-08 08:42:27 +0000114 }else{
danielk1977da184232006-01-05 11:34:32 +0000115 if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
danielk19774d887782005-02-08 08:42:27 +0000116 }
117 }
118 return 0;
119}
danielk19773d1bfea2004-05-14 11:00:53 +0000120
drh9d9cf222007-02-13 15:01:11 +0000121#ifndef SQLITE_OMIT_AUTOINCREMENT
122/*
123** Write out code to initialize the autoincrement logic. This code
124** looks up the current autoincrement value in the sqlite_sequence
125** table and stores that value in a memory cell. Code generated by
126** autoIncStep() will keep that memory cell holding the largest
127** rowid value. Code generated by autoIncEnd() will write the new
128** largest value of the counter back into the sqlite_sequence table.
129**
130** This routine returns the index of the mem[] cell that contains
131** the maximum rowid counter.
132**
133** Two memory cells are allocated. The next memory cell after the
134** one returned holds the rowid in sqlite_sequence where we will
135** write back the revised maximum rowid.
136*/
137static int autoIncBegin(
138 Parse *pParse, /* Parsing context */
139 int iDb, /* Index of the database holding pTab */
140 Table *pTab /* The table we are writing to */
141){
142 int memId = 0;
143 if( pTab->autoInc ){
144 Vdbe *v = pParse->pVdbe;
145 Db *pDb = &pParse->db->aDb[iDb];
146 int iCur = pParse->nTab;
147 int addr;
148 assert( v );
149 addr = sqlite3VdbeCurrentAddr(v);
150 memId = pParse->nMem+1;
151 pParse->nMem += 2;
152 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
153 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
154 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
155 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
156 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
157 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
158 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
159 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
160 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
161 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
162 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
163 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
164 }
165 return memId;
166}
167
168/*
169** Update the maximum rowid for an autoincrement calculation.
170**
171** This routine should be called when the top of the stack holds a
172** new rowid that is about to be inserted. If that new rowid is
173** larger than the maximum rowid in the memId memory cell, then the
174** memory cell is updated. The stack is unchanged.
175*/
176static void autoIncStep(Parse *pParse, int memId){
177 if( memId>0 ){
178 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
179 }
180}
181
182/*
183** After doing one or more inserts, the maximum rowid is stored
184** in mem[memId]. Generate code to write this value back into the
185** the sqlite_sequence table.
186*/
187static void autoIncEnd(
188 Parse *pParse, /* The parsing context */
189 int iDb, /* Index of the database holding pTab */
190 Table *pTab, /* Table we are inserting into */
191 int memId /* Memory cell holding the maximum rowid */
192){
193 if( pTab->autoInc ){
194 int iCur = pParse->nTab;
195 Vdbe *v = pParse->pVdbe;
196 Db *pDb = &pParse->db->aDb[iDb];
197 int addr;
198 assert( v );
199 addr = sqlite3VdbeCurrentAddr(v);
200 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
201 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
202 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
203 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
204 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
205 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
206 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
207 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
drhe4d90812007-03-29 05:51:49 +0000208 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
drh9d9cf222007-02-13 15:01:11 +0000209 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
210 }
211}
212#else
213/*
214** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
215** above are all no-ops
216*/
217# define autoIncBegin(A,B,C) (0)
218# define autoIncStep(A,B)
219# define autoIncEnd(A,B,C,D)
220#endif /* SQLITE_OMIT_AUTOINCREMENT */
221
222
223/* Forward declaration */
224static int xferOptimization(
225 Parse *pParse, /* Parser context */
226 Table *pDest, /* The table we are inserting into */
227 Select *pSelect, /* A SELECT statement to use as the data source */
228 int onError, /* How to handle constraint errors */
229 int iDbDest /* The database of pDest */
230);
231
danielk19773d1bfea2004-05-14 11:00:53 +0000232/*
drh1ccde152000-06-17 13:12:39 +0000233** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000234**
235** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000236** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000237**
drh1ccde152000-06-17 13:12:39 +0000238** The IDLIST following the table name is always optional. If omitted,
239** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000240** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000241**
242** The pList parameter holds EXPRLIST in the first form of the INSERT
243** statement above, and pSelect is NULL. For the second form, pList is
244** NULL and pSelect is a pointer to the select statement used to generate
245** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000246**
drh9d9cf222007-02-13 15:01:11 +0000247** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000248** select with data coming from a VALUES clause, the code executes
249** once straight down through. The template looks like this:
250**
251** open write cursor to <table> and its indices
252** puts VALUES clause expressions onto the stack
253** write the resulting record into <table>
254** cleanup
255**
drh9d9cf222007-02-13 15:01:11 +0000256** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000257**
258** INSERT INTO <table> SELECT ...
259**
drh9d9cf222007-02-13 15:01:11 +0000260** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
261** in other words if the SELECT pulls all columns from a single table
262** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
263** if <table2> and <table1> are distinct tables but have identical
264** schemas, including all the same indices, then a special optimization
265** is invoked that copies raw records from <table2> over to <table1>.
266** See the xferOptimization() function for the implementation of this
267** template. This is the second template.
268**
269** open a write cursor to <table>
270** open read cursor on <table2>
271** transfer all records in <table2> over to <table>
272** close cursors
273** foreach index on <table>
274** open a write cursor on the <table> index
275** open a read cursor on the corresponding <table2> index
276** transfer all records from the read to the write cursors
277** close cursors
278** end foreach
279**
280** The third template is for when the second template does not apply
281** and the SELECT clause does not read from <table> at any time.
282** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000283**
284** goto B
285** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000286** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000287** gosub C
288** end loop
289** cleanup after the SELECT
290** goto D
291** B: open write cursor to <table> and its indices
292** goto A
293** C: insert the select result into <table>
294** return
295** D: cleanup
296**
drh9d9cf222007-02-13 15:01:11 +0000297** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000298** values from a SELECT but the data is being inserted into a table
299** that is also read as part of the SELECT. In the third form,
300** we have to use a intermediate table to store the results of
301** the select. The template is like this:
302**
303** goto B
304** A: setup for the SELECT
305** loop over the tables in the SELECT
306** gosub C
307** end loop
308** cleanup after the SELECT
309** goto D
310** C: insert the select result into the intermediate table
311** return
312** B: open a cursor to an intermediate table
313** goto A
314** D: open write cursor to <table> and its indices
315** loop over the intermediate table
316** transfer values form intermediate table into <table>
317** end the loop
318** cleanup
drhcce7d172000-05-31 15:34:51 +0000319*/
danielk19774adee202004-05-08 08:23:19 +0000320void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000321 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000322 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000323 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000324 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000325 IdList *pColumn, /* Column names corresponding to IDLIST. */
326 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000327){
drh5974a302000-06-07 14:42:26 +0000328 Table *pTab; /* The table to insert into */
drh113088e2003-03-20 01:16:58 +0000329 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000330 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000331 int i, j, idx; /* Loop counters */
332 Vdbe *v; /* Generate code into this virtual machine */
333 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000334 int nColumn; /* Number of columns in the data */
danielk1977cfe9a692004-06-16 12:00:29 +0000335 int base = 0; /* VDBE Cursor number for pTab */
336 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
drh9bb575f2004-09-06 17:24:11 +0000337 sqlite3 *db; /* The main database structure */
drh4a324312001-12-21 14:30:42 +0000338 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000339 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000340 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000341 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
342 int iSelectLoop = 0; /* Address of code that implements the SELECT */
343 int iCleanup = 0; /* Address of the cleanup code */
344 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
345 int iCntMem = 0; /* Memory cell used for the row counter */
drh798da522004-11-04 04:42:28 +0000346 int newIdx = -1; /* Cursor for the NEW table */
drh2958a4e2004-11-12 03:56:15 +0000347 Db *pDb; /* The database containing table being inserted into */
348 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
drhe4d90812007-03-29 05:51:49 +0000349 int appendFlag = 0; /* True if the insert is likely to be an append */
danielk1977da184232006-01-05 11:34:32 +0000350 int iDb;
drhcce7d172000-05-31 15:34:51 +0000351
danielk1977034ca142007-06-26 10:38:54 +0000352 int nHidden = 0;
353
drh798da522004-11-04 04:42:28 +0000354#ifndef SQLITE_OMIT_TRIGGER
355 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000356 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000357#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000358
danielk19779e128002006-01-18 16:51:35 +0000359 if( pParse->nErr || sqlite3MallocFailed() ){
drh6f7adc82006-01-11 21:41:20 +0000360 goto insert_cleanup;
361 }
drhecdc7532001-09-23 02:35:53 +0000362 db = pParse->db;
drhdaffd0e2001-04-11 14:28:42 +0000363
drh1ccde152000-06-17 13:12:39 +0000364 /* Locate the table into which we will be inserting new information.
365 */
drh113088e2003-03-20 01:16:58 +0000366 assert( pTabList->nSrc==1 );
367 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000368 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000369 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000370 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000371 goto insert_cleanup;
372 }
danielk1977da184232006-01-05 11:34:32 +0000373 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
374 assert( iDb<db->nDb );
375 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000376 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000377 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000378 goto insert_cleanup;
379 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000380
drhb7f91642004-10-31 02:22:47 +0000381 /* Figure out if we have any triggers and if the table being
382 ** inserted into is a view
383 */
384#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000385 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000386 isView = pTab->pSelect!=0;
387#else
drhdca76842004-12-07 14:06:13 +0000388# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000389# define isView 0
390#endif
391#ifdef SQLITE_OMIT_VIEW
392# undef isView
393# define isView 0
394#endif
395
danielk1977c3f9bad2002-05-15 08:30:12 +0000396 /* Ensure that:
397 * (a) the table is not read-only,
398 * (b) that if it is a view then ON INSERT triggers exist
399 */
drhdca76842004-12-07 14:06:13 +0000400 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000401 goto insert_cleanup;
402 }
drh43617e92006-03-06 20:55:46 +0000403 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000404
drhf573c992002-07-31 00:32:50 +0000405 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000406 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
407 ** module table).
drhf573c992002-07-31 00:32:50 +0000408 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000409 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000410 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000411 }
412
drh1ccde152000-06-17 13:12:39 +0000413 /* Allocate a VDBE
414 */
danielk19774adee202004-05-08 08:23:19 +0000415 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000416 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000417 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000418 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000419
danielk1977c3f9bad2002-05-15 08:30:12 +0000420 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000421 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000422 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000423 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000424
drh9d9cf222007-02-13 15:01:11 +0000425#ifndef SQLITE_OMIT_XFER_OPT
426 /* If the statement is of the form
427 **
428 ** INSERT INTO <table1> SELECT * FROM <table2>;
429 **
430 ** Then special optimizations can be applied that make the transfer
431 ** very fast and which reduce fragmentation of indices.
432 */
433 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
434 assert( !triggers_exist );
435 assert( pList==0 );
436 goto insert_cleanup;
437 }
438#endif /* SQLITE_OMIT_XFER_OPT */
439
drh2958a4e2004-11-12 03:56:15 +0000440 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000441 ** sqlite_sequence table and store it in memory cell counterMem. Also
442 ** remember the rowid of the sqlite_sequence table entry in memory cell
443 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000444 */
drh9d9cf222007-02-13 15:01:11 +0000445 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000446
drh1ccde152000-06-17 13:12:39 +0000447 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000448 ** is coming from a SELECT statement, then this step also generates
449 ** all the code to implement the SELECT statement and invoke a subroutine
450 ** to process each row of the result. (Template 2.) If the SELECT
451 ** statement uses the the table that is being inserted into, then the
452 ** subroutine is also coded here. That subroutine stores the SELECT
453 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000454 */
drh5974a302000-06-07 14:42:26 +0000455 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000456 /* Data is coming from a SELECT. Generate code to implement that SELECT
457 */
458 int rc, iInitCode;
danielk19774adee202004-05-08 08:23:19 +0000459 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
460 iSelectLoop = sqlite3VdbeCurrentAddr(v);
461 iInsertBlock = sqlite3VdbeMakeLabel(v);
danielk1977b3bce662005-01-29 08:32:43 +0000462
463 /* Resolve the expressions in the SELECT statement and execute it. */
464 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
danielk19779e128002006-01-18 16:51:35 +0000465 if( rc || pParse->nErr || sqlite3MallocFailed() ){
drh6f7adc82006-01-11 21:41:20 +0000466 goto insert_cleanup;
467 }
danielk1977b3bce662005-01-29 08:32:43 +0000468
danielk19774adee202004-05-08 08:23:19 +0000469 iCleanup = sqlite3VdbeMakeLabel(v);
470 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000471 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000472 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000473
474 /* Set useTempTable to TRUE if the result of the SELECT statement
475 ** should be written into a temporary table. Set to FALSE if each
476 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000477 **
478 ** A temp table must be used if the table being updated is also one
479 ** of the tables being read by the SELECT statement. Also use a
480 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000481 */
danielk1977da184232006-01-05 11:34:32 +0000482 if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
drh048c5302003-04-03 01:50:44 +0000483 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000484 }
drh142e30d2002-08-28 03:00:58 +0000485
486 if( useTempTable ){
487 /* Generate the subroutine that SELECT calls to process each row of
488 ** the result. Store the result in a temporary table
489 */
490 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000491 sqlite3VdbeResolveLabel(v, iInsertBlock);
492 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf0863fe2005-06-12 21:35:51 +0000493 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
danielk19774adee202004-05-08 08:23:19 +0000494 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhe4d90812007-03-29 05:51:49 +0000495 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
danielk19774adee202004-05-08 08:23:19 +0000496 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000497
498 /* The following code runs first because the GOTO at the very top
499 ** of the program jumps to it. Create the temporary table, then jump
500 ** back up and execute the SELECT code above.
501 */
drhd654be82005-09-20 17:42:23 +0000502 sqlite3VdbeJumpHere(v, iInitCode);
drhb9bb7c12006-06-11 23:41:55 +0000503 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
drhb6f54522004-05-20 02:42:16 +0000504 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
danielk19774adee202004-05-08 08:23:19 +0000505 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
506 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000507 }else{
drhd654be82005-09-20 17:42:23 +0000508 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000509 }
drh5974a302000-06-07 14:42:26 +0000510 }else{
drh142e30d2002-08-28 03:00:58 +0000511 /* This is the case if the data for the INSERT is coming from a VALUES
512 ** clause
513 */
danielk1977b3bce662005-01-29 08:32:43 +0000514 NameContext sNC;
515 memset(&sNC, 0, sizeof(sNC));
516 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000517 srcTab = -1;
drh142e30d2002-08-28 03:00:58 +0000518 useTempTable = 0;
drh147d0cc2006-08-25 23:42:53 +0000519 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000520 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000521 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000522 goto insert_cleanup;
523 }
drhe64e7b22002-02-18 13:56:36 +0000524 }
drh5974a302000-06-07 14:42:26 +0000525 }
drh1ccde152000-06-17 13:12:39 +0000526
527 /* Make sure the number of columns in the source data matches the number
528 ** of columns to be inserted into the table.
529 */
danielk1977034ca142007-06-26 10:38:54 +0000530 if( IsVirtual(pTab) ){
531 for(i=0; i<pTab->nCol; i++){
532 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
533 }
534 }
535 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000536 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000537 "table %S has %d columns but %d values were supplied",
538 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000539 goto insert_cleanup;
540 }
drh967e8b72000-06-21 13:59:10 +0000541 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000542 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000543 goto insert_cleanup;
544 }
drh1ccde152000-06-17 13:12:39 +0000545
546 /* If the INSERT statement included an IDLIST term, then make sure
547 ** all elements of the IDLIST really are columns of the table and
548 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000549 **
550 ** If the table has an INTEGER PRIMARY KEY column and that column
551 ** is named in the IDLIST, then record in the keyColumn variable
552 ** the index into IDLIST of the primary key column. keyColumn is
553 ** the index of the primary key as it appears in IDLIST, not as
554 ** is appears in the original table. (The index of the primary
555 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000556 */
drh967e8b72000-06-21 13:59:10 +0000557 if( pColumn ){
558 for(i=0; i<pColumn->nId; i++){
559 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000560 }
drh967e8b72000-06-21 13:59:10 +0000561 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000562 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000563 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000564 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000565 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000566 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000567 }
drhcce7d172000-05-31 15:34:51 +0000568 break;
569 }
570 }
571 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000572 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000573 keyColumn = i;
574 }else{
danielk19774adee202004-05-08 08:23:19 +0000575 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000576 pTabList, 0, pColumn->a[i].zName);
577 pParse->nErr++;
578 goto insert_cleanup;
579 }
drhcce7d172000-05-31 15:34:51 +0000580 }
581 }
582 }
drh1ccde152000-06-17 13:12:39 +0000583
drhaacc5432002-01-06 17:07:40 +0000584 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000585 ** key, the set the keyColumn variable to the primary key column index
586 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000587 */
drh147d0cc2006-08-25 23:42:53 +0000588 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000589 keyColumn = pTab->iPKey;
590 }
591
drh142e30d2002-08-28 03:00:58 +0000592 /* Open the temp table for FOR EACH ROW triggers
593 */
drhdca76842004-12-07 14:06:13 +0000594 if( triggers_exist ){
danielk19774adee202004-05-08 08:23:19 +0000595 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
danielk197784ac9d02004-05-18 09:58:06 +0000596 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000597 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000598
drhfeeb1392002-04-09 03:28:01 +0000599 /* Initialize the count of rows to be inserted
600 */
drh142e30d2002-08-28 03:00:58 +0000601 if( db->flags & SQLITE_CountRows ){
602 iCntMem = pParse->nMem++;
drhd654be82005-09-20 17:42:23 +0000603 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000604 }
605
danielk1977c3f9bad2002-05-15 08:30:12 +0000606 /* Open tables and indices if there are no row triggers */
drhdca76842004-12-07 14:06:13 +0000607 if( !triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000608 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000609 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000610 }
611
drh142e30d2002-08-28 03:00:58 +0000612 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000613 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000614 ** source is a subroutine call from the SELECT statement, then we need
615 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000616 */
drh142e30d2002-08-28 03:00:58 +0000617 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000618 iBreak = sqlite3VdbeMakeLabel(v);
619 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
620 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000621 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000622 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
623 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh5974a302000-06-07 14:42:26 +0000624 }
drh1ccde152000-06-17 13:12:39 +0000625
drh5cf590c2003-04-24 01:45:04 +0000626 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000627 */
danielk19774adee202004-05-08 08:23:19 +0000628 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000629 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000630
drh70ce3f02003-04-15 19:22:22 +0000631 /* build the NEW.* reference row. Note that if there is an INTEGER
632 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
633 ** translated into a unique ID for the row. But on a BEFORE trigger,
634 ** we do not know what the unique ID will be (because the insert has
635 ** not happened yet) so we substitute a rowid of -1
636 */
637 if( keyColumn<0 ){
danielk19774adee202004-05-08 08:23:19 +0000638 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000639 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000640 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000641 }else{
drhd6fe9612005-01-14 01:22:00 +0000642 assert( pSelect==0 ); /* Otherwise useTempTable is true */
danielk19774adee202004-05-08 08:23:19 +0000643 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
644 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
645 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
646 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
647 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000648 }
649
danielk1977034ca142007-06-26 10:38:54 +0000650 /* Cannot have triggers on a virtual table. If it were possible,
651 ** this block would have to account for hidden column.
652 */
653 assert(!IsVirtual(pTab));
654
drh70ce3f02003-04-15 19:22:22 +0000655 /* Create the new column data
656 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000657 for(i=0; i<pTab->nCol; i++){
658 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000659 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000660 }else{
drh9adf9ac2002-05-15 11:44:13 +0000661 for(j=0; j<pColumn->nId; j++){
662 if( pColumn->a[j].idx==i ) break;
663 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000664 }
665 if( pColumn && j>=pColumn->nId ){
danielk19777977a172004-11-09 12:44:37 +0000666 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000667 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000668 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000669 }else{
drhd6fe9612005-01-14 01:22:00 +0000670 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000671 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000672 }
673 }
danielk19774adee202004-05-08 08:23:19 +0000674 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000675
676 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
677 ** do not attempt any conversions before assembling the record.
678 ** If this is a real table, attempt conversions as required by the
679 ** table column affinities.
680 */
681 if( !isView ){
682 sqlite3TableAffinityStr(v, pTab);
683 }
drhf0863fe2005-06-12 21:35:51 +0000684 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000685
drh5cf590c2003-04-24 01:45:04 +0000686 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000687 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
drhb2fe7d82003-04-20 17:29:23 +0000688 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000689 goto insert_cleanup;
690 }
drh70ce3f02003-04-15 19:22:22 +0000691 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000692
drh70ce3f02003-04-15 19:22:22 +0000693 /* If any triggers exists, the opening of tables and indices is deferred
694 ** until now.
695 */
drhdca76842004-12-07 14:06:13 +0000696 if( triggers_exist && !isView ){
drh5cf590c2003-04-24 01:45:04 +0000697 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000698 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000699 }
700
drh4a324312001-12-21 14:30:42 +0000701 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000702 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000703 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000704 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000705 */
drh5cf590c2003-04-24 01:45:04 +0000706 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000707 if( IsVirtual(pTab) ){
708 /* The row that the VUpdate opcode will delete: none */
709 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
710 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000711 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000712 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000713 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh142e30d2002-08-28 03:00:58 +0000714 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000715 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000716 }else{
drhe4d90812007-03-29 05:51:49 +0000717 VdbeOp *pOp;
danielk19774adee202004-05-08 08:23:19 +0000718 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
drhe4d90812007-03-29 05:51:49 +0000719 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000720 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000721 appendFlag = 1;
722 pOp->opcode = OP_NewRowid;
723 pOp->p1 = base;
724 pOp->p2 = counterMem;
725 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000726 }
drhf0863fe2005-06-12 21:35:51 +0000727 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000728 ** to generate a unique primary key value.
729 */
drhe4d90812007-03-29 05:51:49 +0000730 if( !appendFlag ){
731 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
732 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
733 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
734 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
735 }
drh4cbdda92006-06-14 19:00:20 +0000736 }else if( IsVirtual(pTab) ){
737 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000738 }else{
drhf0863fe2005-06-12 21:35:51 +0000739 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
drhe4d90812007-03-29 05:51:49 +0000740 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000741 }
drh9d9cf222007-02-13 15:01:11 +0000742 autoIncStep(pParse, counterMem);
drh4a324312001-12-21 14:30:42 +0000743
danielk1977c3f9bad2002-05-15 08:30:12 +0000744 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000745 ** with the first column.
746 */
danielk1977034ca142007-06-26 10:38:54 +0000747 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000748 for(i=0; i<pTab->nCol; i++){
749 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000750 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000751 ** Whenever this column is read, the record number will be substituted
752 ** in its place. So will fill this column with a NULL to avoid
753 ** taking up data space with information that will never be used. */
drhf0863fe2005-06-12 21:35:51 +0000754 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh9adf9ac2002-05-15 11:44:13 +0000755 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000756 }
757 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000758 if( IsHiddenColumn(&pTab->aCol[i]) ){
759 assert( IsVirtual(pTab) );
760 j = -1;
761 nHidden++;
762 }else{
763 j = i - nHidden;
764 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000765 }else{
drh9adf9ac2002-05-15 11:44:13 +0000766 for(j=0; j<pColumn->nId; j++){
767 if( pColumn->a[j].idx==i ) break;
768 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000769 }
danielk1977034ca142007-06-26 10:38:54 +0000770 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk19777977a172004-11-09 12:44:37 +0000771 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000772 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000773 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
drh142e30d2002-08-28 03:00:58 +0000774 }else if( pSelect ){
drh16ed8a62006-08-29 18:46:14 +0000775 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000776 }else{
danielk19774adee202004-05-08 08:23:19 +0000777 sqlite3ExprCode(pParse, pList->a[j].pExpr);
drh5974a302000-06-07 14:42:26 +0000778 }
drhbed86902000-06-02 13:27:59 +0000779 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000780
781 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000782 ** do the insertion.
783 */
drh4cbdda92006-06-14 19:00:20 +0000784#ifndef SQLITE_OMIT_VIRTUALTABLE
785 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000786 pParse->pVirtualLock = pTab;
danielk19771f6eec52006-06-16 06:17:47 +0000787 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
drh4cbdda92006-06-14 19:00:20 +0000788 (const char*)pTab->pVtab, P3_VTAB);
789 }else
790#endif
791 {
792 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
793 0, onError, endOfLoop);
794 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000795 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
796 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000797 }
drh5cf590c2003-04-24 01:45:04 +0000798 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000799
drh5cf590c2003-04-24 01:45:04 +0000800 /* Update the count of rows that are inserted
801 */
802 if( (db->flags & SQLITE_CountRows)!=0 ){
drh15007a92006-01-08 18:10:17 +0000803 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
drh5974a302000-06-07 14:42:26 +0000804 }
drh1ccde152000-06-17 13:12:39 +0000805
drhdca76842004-12-07 14:06:13 +0000806 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000807 /* Close all tables opened */
drh5cf590c2003-04-24 01:45:04 +0000808 if( !isView ){
danielk19774adee202004-05-08 08:23:19 +0000809 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000810 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000811 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000812 }
813 }
drh1bee3d72001-10-15 00:44:35 +0000814
danielk1977c3f9bad2002-05-15 08:30:12 +0000815 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000816 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
817 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000818 goto insert_cleanup;
819 }
drh1bee3d72001-10-15 00:44:35 +0000820 }
821
drh1ccde152000-06-17 13:12:39 +0000822 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000823 */
danielk19774adee202004-05-08 08:23:19 +0000824 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000825 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000826 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
827 sqlite3VdbeResolveLabel(v, iBreak);
828 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000829 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000830 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
831 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
832 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000833 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000834
drh4cbdda92006-06-14 19:00:20 +0000835 if( !triggers_exist && !IsVirtual(pTab) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000836 /* Close all tables opened */
danielk19774adee202004-05-08 08:23:19 +0000837 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000838 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000839 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000840 }
drhcce7d172000-05-31 15:34:51 +0000841 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000842
drhf3388142004-11-13 03:48:06 +0000843 /* Update the sqlite_sequence table by storing the content of the
844 ** counter value in memory counterMem back into the sqlite_sequence
845 ** table.
drh2958a4e2004-11-12 03:56:15 +0000846 */
drh9d9cf222007-02-13 15:01:11 +0000847 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000848
drh1bee3d72001-10-15 00:44:35 +0000849 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000850 ** Return the number of rows inserted. If this routine is
851 ** generating code because of a call to sqlite3NestedParse(), do not
852 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000853 */
danielk1977cc6bd382005-01-10 02:48:49 +0000854 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +0000855 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
856 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
danielk197722322fd2004-05-25 23:35:17 +0000857 sqlite3VdbeSetNumCols(v, 1);
danielk1977955de522006-02-10 02:27:42 +0000858 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000859 }
drhcce7d172000-05-31 15:34:51 +0000860
861insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000862 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000863 sqlite3ExprListDelete(pList);
864 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000865 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000866}
drh9cfcf5d2002-01-29 18:41:24 +0000867
drh9cfcf5d2002-01-29 18:41:24 +0000868/*
869** Generate code to do a constraint check prior to an INSERT or an UPDATE.
870**
871** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000872** the following values:
873**
drhf0863fe2005-06-12 21:35:51 +0000874** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000875** value is omitted unless we are doing an UPDATE that involves a
876** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000877**
drhf0863fe2005-06-12 21:35:51 +0000878** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000879**
880** 3. The data in the first column of the entry after the update.
881**
882** i. Data from middle columns...
883**
884** N. The data in the last column of the entry after the update.
885**
drhf0863fe2005-06-12 21:35:51 +0000886** The old rowid shown as entry (1) above is omitted unless both isUpdate
887** and rowidChng are 1. isUpdate is true for UPDATEs and false for
888** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000889**
890** The code generated by this routine pushes additional entries onto
891** the stack which are the keys for new index entries for the new record.
892** The order of index keys is the same as the order of the indices on
893** the pTable->pIndex list. A key is only created for index i if
894** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000895**
896** This routine also generates code to check constraints. NOT NULL,
897** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000898** then the appropriate action is performed. There are five possible
899** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000900**
901** Constraint type Action What Happens
902** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000903** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000904** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000905** return code of SQLITE_CONSTRAINT.
906**
drh1c928532002-01-31 15:54:21 +0000907** any ABORT Back out changes from the current command
908** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000909** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000910** with SQLITE_CONSTRAINT.
911**
912** any FAIL Sqlite_exec() returns immediately with a
913** return code of SQLITE_CONSTRAINT. The
914** transaction is not rolled back and any
915** prior changes are retained.
916**
drh9cfcf5d2002-01-29 18:41:24 +0000917** any IGNORE The record number and data is popped from
918** the stack and there is an immediate jump
919** to label ignoreDest.
920**
921** NOT NULL REPLACE The NULL value is replace by the default
922** value for that column. If the default value
923** is NULL, the action is the same as ABORT.
924**
925** UNIQUE REPLACE The other row that conflicts with the row
926** being inserted is removed.
927**
928** CHECK REPLACE Illegal. The results in an exception.
929**
drh1c928532002-01-31 15:54:21 +0000930** Which action to take is determined by the overrideError parameter.
931** Or if overrideError==OE_Default, then the pParse->onError parameter
932** is used. Or if pParse->onError==OE_Default then the onError value
933** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000934**
drhaaab5722002-02-19 13:39:21 +0000935** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000936** cursor number "base". All indices of pTab must also have open
937** read/write cursors with cursor number base+i for the i-th cursor.
938** Except, if there is no possibility of a REPLACE action then
939** cursors do not need to be open for indices where aIdxUsed[i]==0.
940**
941** If the isUpdate flag is true, it means that the "base" cursor is
942** initially pointing to an entry that is being updated. The isUpdate
943** flag causes extra code to be generated so that the "base" cursor
944** is still pointing at the same entry after the routine returns.
945** Without the isUpdate flag, the "base" cursor might be moved.
946*/
danielk19774adee202004-05-08 08:23:19 +0000947void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000948 Parse *pParse, /* The parser context */
949 Table *pTab, /* the table into which we are inserting */
950 int base, /* Index of a read/write cursor pointing at pTab */
951 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000952 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000953 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000954 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000955 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000956){
957 int i;
958 Vdbe *v;
959 int nCol;
960 int onError;
961 int addr;
962 int extra;
drh0ca3e242002-01-29 23:07:02 +0000963 int iCur;
964 Index *pIdx;
965 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000966 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000967 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000968
danielk19774adee202004-05-08 08:23:19 +0000969 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000970 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000971 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000972 nCol = pTab->nCol;
973
974 /* Test all NOT NULL constraints.
975 */
976 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000977 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +0000978 continue;
979 }
drh9cfcf5d2002-01-29 18:41:24 +0000980 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +0000981 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +0000982 if( overrideError!=OE_Default ){
983 onError = overrideError;
drha996e472003-05-16 02:30:27 +0000984 }else if( onError==OE_Default ){
985 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +0000986 }
danielk19777977a172004-11-09 12:44:37 +0000987 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +0000988 onError = OE_Abort;
989 }
danielk19774adee202004-05-08 08:23:19 +0000990 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
991 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +0000992 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
993 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +0000994 switch( onError ){
drh1c928532002-01-31 15:54:21 +0000995 case OE_Rollback:
996 case OE_Abort:
997 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +0000998 char *zMsg = 0;
danielk19774adee202004-05-08 08:23:19 +0000999 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1000 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001001 " may not be NULL", (char*)0);
danielk19774adee202004-05-08 08:23:19 +00001002 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001003 break;
1004 }
1005 case OE_Ignore: {
drhf0863fe2005-06-12 21:35:51 +00001006 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001007 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001008 break;
1009 }
1010 case OE_Replace: {
danielk19777977a172004-11-09 12:44:37 +00001011 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
danielk19774adee202004-05-08 08:23:19 +00001012 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001013 break;
1014 }
drh9cfcf5d2002-01-29 18:41:24 +00001015 }
drhd654be82005-09-20 17:42:23 +00001016 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001017 }
1018
1019 /* Test all CHECK constraints
1020 */
drhffe07b22005-11-03 00:41:17 +00001021#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001022 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001023 int allOk = sqlite3VdbeMakeLabel(v);
1024 assert( pParse->ckOffset==0 );
1025 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001026 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001027 assert( pParse->ckOffset==nCol );
1028 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001029 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001030 if( onError==OE_Ignore ){
drhaa01c7e2006-03-15 16:26:10 +00001031 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1032 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1033 }else{
1034 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1035 }
drhffe07b22005-11-03 00:41:17 +00001036 sqlite3VdbeResolveLabel(v, allOk);
1037 }
1038#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001039
drh0bd1f4e2002-06-06 18:54:39 +00001040 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1041 ** of the new record does not previously exist. Except, if this
1042 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001043 */
drhf0863fe2005-06-12 21:35:51 +00001044 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001045 onError = pTab->keyConf;
1046 if( overrideError!=OE_Default ){
1047 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001048 }else if( onError==OE_Default ){
1049 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001050 }
drha0217ba2003-06-01 01:10:33 +00001051
drh5383ae52003-06-04 12:23:30 +00001052 if( isUpdate ){
danielk19774adee202004-05-08 08:23:19 +00001053 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1054 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1055 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001056 }
danielk19774adee202004-05-08 08:23:19 +00001057 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1058 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001059 switch( onError ){
1060 default: {
1061 onError = OE_Abort;
1062 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001063 }
drh5383ae52003-06-04 12:23:30 +00001064 case OE_Rollback:
1065 case OE_Abort:
1066 case OE_Fail: {
danielk19774adee202004-05-08 08:23:19 +00001067 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
drh701a0ae2004-02-22 20:05:00 +00001068 "PRIMARY KEY must be unique", P3_STATIC);
drh5383ae52003-06-04 12:23:30 +00001069 break;
drh0ca3e242002-01-29 23:07:02 +00001070 }
drh5383ae52003-06-04 12:23:30 +00001071 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001072 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001073 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001074 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001075 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001076 }
1077 seenReplace = 1;
1078 break;
drh0ca3e242002-01-29 23:07:02 +00001079 }
drh5383ae52003-06-04 12:23:30 +00001080 case OE_Ignore: {
1081 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001082 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001083 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001084 break;
1085 }
1086 }
drhd654be82005-09-20 17:42:23 +00001087 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001088 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001089 sqlite3VdbeJumpHere(v, jumpInst1);
danielk19774adee202004-05-08 08:23:19 +00001090 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001091 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001092 }
1093 }
drh0bd1f4e2002-06-06 18:54:39 +00001094
1095 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1096 ** index and making sure that duplicate entries do not already exist.
1097 ** Add the new records to the indices as we go.
1098 */
drhb2fe7d82003-04-20 17:29:23 +00001099 extra = -1;
1100 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1101 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1102 extra++;
1103
1104 /* Create a key for accessing the index entry */
danielk19774adee202004-05-08 08:23:19 +00001105 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001106 for(i=0; i<pIdx->nColumn; i++){
1107 int idx = pIdx->aiColumn[i];
1108 if( idx==pTab->iPKey ){
danielk19774adee202004-05-08 08:23:19 +00001109 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001110 }else{
danielk19774adee202004-05-08 08:23:19 +00001111 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001112 }
1113 }
drh7f057c92005-06-24 03:53:06 +00001114 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001115 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001116
1117 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001118 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001119 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001120 if( overrideError!=OE_Default ){
1121 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001122 }else if( onError==OE_Default ){
1123 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001124 }
drh5383ae52003-06-04 12:23:30 +00001125 if( seenReplace ){
1126 if( onError==OE_Ignore ) onError = OE_Replace;
1127 else if( onError==OE_Fail ) onError = OE_Abort;
1128 }
1129
drhb2fe7d82003-04-20 17:29:23 +00001130
1131 /* Check to see if the new index entry will be unique */
drhf0863fe2005-06-12 21:35:51 +00001132 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
danielk19774adee202004-05-08 08:23:19 +00001133 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001134
1135 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001136 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1137 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001138 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001139 case OE_Rollback:
1140 case OE_Abort:
1141 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001142 int j, n1, n2;
1143 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001144 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1145 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001146 n1 = strlen(zErrMsg);
1147 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1148 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1149 n2 = strlen(zCol);
1150 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001151 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001152 n1 += 2;
1153 }
1154 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001155 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001156 n1 += 3;
1157 break;
1158 }else{
drh5bb3eb92007-05-04 13:15:55 +00001159 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001160 n1 += n2;
1161 }
1162 }
drh5bb3eb92007-05-04 13:15:55 +00001163 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001164 pIdx->nColumn>1 ? " are not unique" : " is not unique");
danielk19774adee202004-05-08 08:23:19 +00001165 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001166 break;
1167 }
1168 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001169 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001170 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001171 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001172 break;
1173 }
1174 case OE_Replace: {
danielk19774adee202004-05-08 08:23:19 +00001175 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001176 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001177 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001178 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001179 }
drh0ca3e242002-01-29 23:07:02 +00001180 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001181 break;
1182 }
drh9cfcf5d2002-01-29 18:41:24 +00001183 }
drh0bd1f4e2002-06-06 18:54:39 +00001184#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001185 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001186#endif
drhd654be82005-09-20 17:42:23 +00001187 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001188 }
1189}
drh0ca3e242002-01-29 23:07:02 +00001190
1191/*
1192** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001193** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001194** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001195** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001196** entries in all indices and in the main table.
1197**
drhb419a922002-01-30 16:17:23 +00001198** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001199** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001200*/
danielk19774adee202004-05-08 08:23:19 +00001201void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001202 Parse *pParse, /* The parser context */
1203 Table *pTab, /* the table into which we are inserting */
1204 int base, /* Index of a read/write cursor pointing at pTab */
1205 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001206 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001207 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001208 int newIdx, /* Index of NEW table for triggers. -1 if none */
1209 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001210){
1211 int i;
1212 Vdbe *v;
1213 int nIdx;
1214 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001215 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001216
danielk19774adee202004-05-08 08:23:19 +00001217 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001218 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001219 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001220 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1221 for(i=nIdx-1; i>=0; i--){
1222 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drhf0863fe2005-06-12 21:35:51 +00001223 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001224 }
danielk19774adee202004-05-08 08:23:19 +00001225 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001226 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001227#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001228 if( newIdx>=0 ){
danielk19774adee202004-05-08 08:23:19 +00001229 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1230 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhf0863fe2005-06-12 21:35:51 +00001231 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001232 }
danielk1977b84f96f2005-01-20 11:32:23 +00001233#endif
drh4794f732004-11-05 17:17:50 +00001234 if( pParse->nested ){
1235 pik_flags = 0;
1236 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001237 pik_flags = OPFLAG_NCHANGE;
1238 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001239 }
drhe4d90812007-03-29 05:51:49 +00001240 if( appendBias ){
1241 pik_flags |= OPFLAG_APPEND;
1242 }
drhf0863fe2005-06-12 21:35:51 +00001243 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001244 if( !pParse->nested ){
1245 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1246 }
danielk1977b28af712004-06-21 06:50:26 +00001247
drhf0863fe2005-06-12 21:35:51 +00001248 if( isUpdate && rowidChng ){
danielk19774adee202004-05-08 08:23:19 +00001249 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001250 }
1251}
drhcd446902004-02-24 01:05:31 +00001252
1253/*
drh290c1942004-08-21 17:54:45 +00001254** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001255** indices of that table. The "base" parameter is the cursor number used
1256** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001257*/
drh290c1942004-08-21 17:54:45 +00001258void sqlite3OpenTableAndIndices(
1259 Parse *pParse, /* Parsing context */
1260 Table *pTab, /* Table to be opened */
1261 int base, /* Cursor number assigned to the table */
1262 int op /* OP_OpenRead or OP_OpenWrite */
1263){
drhcd446902004-02-24 01:05:31 +00001264 int i;
drh4cbdda92006-06-14 19:00:20 +00001265 int iDb;
drhcd446902004-02-24 01:05:31 +00001266 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001267 Vdbe *v;
1268
1269 if( IsVirtual(pTab) ) return;
1270 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1271 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001272 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001273 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001274 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001275 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001276 assert( pIdx->pSchema==pTab->pSchema );
1277 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001278 VdbeComment((v, "# %s", pIdx->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00001279 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
drhcd446902004-02-24 01:05:31 +00001280 }
drh290c1942004-08-21 17:54:45 +00001281 if( pParse->nTab<=base+i ){
1282 pParse->nTab = base+i;
1283 }
drhcd446902004-02-24 01:05:31 +00001284}
drh9d9cf222007-02-13 15:01:11 +00001285
drh91c58e22007-03-27 12:04:04 +00001286
1287#ifdef SQLITE_TEST
1288/*
1289** The following global variable is incremented whenever the
1290** transfer optimization is used. This is used for testing
1291** purposes only - to make sure the transfer optimization really
1292** is happening when it is suppose to.
1293*/
1294int sqlite3_xferopt_count;
1295#endif /* SQLITE_TEST */
1296
1297
drh9d9cf222007-02-13 15:01:11 +00001298#ifndef SQLITE_OMIT_XFER_OPT
1299/*
1300** Check to collation names to see if they are compatible.
1301*/
1302static int xferCompatibleCollation(const char *z1, const char *z2){
1303 if( z1==0 ){
1304 return z2==0;
1305 }
1306 if( z2==0 ){
1307 return 0;
1308 }
1309 return sqlite3StrICmp(z1, z2)==0;
1310}
1311
1312
1313/*
1314** Check to see if index pSrc is compatible as a source of data
1315** for index pDest in an insert transfer optimization. The rules
1316** for a compatible index:
1317**
1318** * The index is over the same set of columns
1319** * The same DESC and ASC markings occurs on all columns
1320** * The same onError processing (OE_Abort, OE_Ignore, etc)
1321** * The same collating sequence on each column
1322*/
1323static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1324 int i;
1325 assert( pDest && pSrc );
1326 assert( pDest->pTable!=pSrc->pTable );
1327 if( pDest->nColumn!=pSrc->nColumn ){
1328 return 0; /* Different number of columns */
1329 }
1330 if( pDest->onError!=pSrc->onError ){
1331 return 0; /* Different conflict resolution strategies */
1332 }
1333 for(i=0; i<pSrc->nColumn; i++){
1334 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1335 return 0; /* Different columns indexed */
1336 }
1337 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1338 return 0; /* Different sort orders */
1339 }
1340 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1341 return 0; /* Different sort orders */
1342 }
1343 }
1344
1345 /* If no test above fails then the indices must be compatible */
1346 return 1;
1347}
1348
1349/*
1350** Attempt the transfer optimization on INSERTs of the form
1351**
1352** INSERT INTO tab1 SELECT * FROM tab2;
1353**
1354** This optimization is only attempted if
1355**
1356** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001357** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001358**
1359** (2) tab1 and tab2 are different tables
1360**
1361** (3) There must be no triggers on tab1
1362**
1363** (4) The result set of the SELECT statement is "*"
1364**
1365** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1366** or LIMIT clause.
1367**
1368** (6) The SELECT statement is a simple (not a compound) select that
1369** contains only tab2 in its FROM clause
1370**
1371** This method for implementing the INSERT transfers raw records from
1372** tab2 over to tab1. The columns are not decoded. Raw records from
1373** the indices of tab2 are transfered to tab1 as well. In so doing,
1374** the resulting tab1 has much less fragmentation.
1375**
1376** This routine returns TRUE if the optimization is attempted. If any
1377** of the conditions above fail so that the optimization should not
1378** be attempted, then this routine returns FALSE.
1379*/
1380static int xferOptimization(
1381 Parse *pParse, /* Parser context */
1382 Table *pDest, /* The table we are inserting into */
1383 Select *pSelect, /* A SELECT statement to use as the data source */
1384 int onError, /* How to handle constraint errors */
1385 int iDbDest /* The database of pDest */
1386){
1387 ExprList *pEList; /* The result set of the SELECT */
1388 Table *pSrc; /* The table in the FROM clause of SELECT */
1389 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1390 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1391 int i; /* Loop counter */
1392 int iDbSrc; /* The database of pSrc */
1393 int iSrc, iDest; /* Cursors from source and destination */
1394 int addr1, addr2; /* Loop addresses */
1395 int emptyDestTest; /* Address of test for empty pDest */
1396 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001397 Vdbe *v; /* The VDBE we are building */
1398 KeyInfo *pKey; /* Key information for an index */
1399 int counterMem; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001400 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001401
1402 if( pSelect==0 ){
1403 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1404 }
1405 if( pDest->pTrigger ){
1406 return 0; /* tab1 must not have triggers */
1407 }
1408#ifndef SQLITE_OMIT_VIRTUALTABLE
1409 if( pDest->isVirtual ){
1410 return 0; /* tab1 must not be a virtual table */
1411 }
1412#endif
1413 if( onError==OE_Default ){
1414 onError = OE_Abort;
1415 }
1416 if( onError!=OE_Abort && onError!=OE_Rollback ){
1417 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1418 }
1419 if( pSelect->pSrc==0 ){
1420 return 0; /* SELECT must have a FROM clause */
1421 }
1422 if( pSelect->pSrc->nSrc!=1 ){
1423 return 0; /* FROM clause must have exactly one term */
1424 }
1425 if( pSelect->pSrc->a[0].pSelect ){
1426 return 0; /* FROM clause cannot contain a subquery */
1427 }
1428 if( pSelect->pWhere ){
1429 return 0; /* SELECT may not have a WHERE clause */
1430 }
1431 if( pSelect->pOrderBy ){
1432 return 0; /* SELECT may not have an ORDER BY clause */
1433 }
drh8103b7d2007-02-24 13:23:51 +00001434 /* Do not need to test for a HAVING clause. If HAVING is present but
1435 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001436 if( pSelect->pGroupBy ){
1437 return 0; /* SELECT may not have a GROUP BY clause */
1438 }
1439 if( pSelect->pLimit ){
1440 return 0; /* SELECT may not have a LIMIT clause */
1441 }
drh8103b7d2007-02-24 13:23:51 +00001442 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001443 if( pSelect->pPrior ){
1444 return 0; /* SELECT may not be a compound query */
1445 }
1446 if( pSelect->isDistinct ){
1447 return 0; /* SELECT may not be DISTINCT */
1448 }
1449 pEList = pSelect->pEList;
1450 assert( pEList!=0 );
1451 if( pEList->nExpr!=1 ){
1452 return 0; /* The result set must have exactly one column */
1453 }
1454 assert( pEList->a[0].pExpr );
1455 if( pEList->a[0].pExpr->op!=TK_ALL ){
1456 return 0; /* The result set must be the special operator "*" */
1457 }
1458
1459 /* At this point we have established that the statement is of the
1460 ** correct syntactic form to participate in this optimization. Now
1461 ** we have to check the semantics.
1462 */
1463 pItem = pSelect->pSrc->a;
1464 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1465 if( pSrc==0 ){
1466 return 0; /* FROM clause does not contain a real table */
1467 }
1468 if( pSrc==pDest ){
1469 return 0; /* tab1 and tab2 may not be the same table */
1470 }
1471#ifndef SQLITE_OMIT_VIRTUALTABLE
1472 if( pSrc->isVirtual ){
1473 return 0; /* tab2 must not be a virtual table */
1474 }
1475#endif
1476 if( pSrc->pSelect ){
1477 return 0; /* tab2 may not be a view */
1478 }
1479 if( pDest->nCol!=pSrc->nCol ){
1480 return 0; /* Number of columns must be the same in tab1 and tab2 */
1481 }
1482 if( pDest->iPKey!=pSrc->iPKey ){
1483 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1484 }
1485 for(i=0; i<pDest->nCol; i++){
1486 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1487 return 0; /* Affinity must be the same on all columns */
1488 }
1489 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1490 return 0; /* Collating sequence must be the same on all columns */
1491 }
1492 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1493 return 0; /* tab2 must be NOT NULL if tab1 is */
1494 }
1495 }
1496 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001497 if( pDestIdx->onError!=OE_None ){
1498 destHasUniqueIdx = 1;
1499 }
drh9d9cf222007-02-13 15:01:11 +00001500 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1501 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1502 }
1503 if( pSrcIdx==0 ){
1504 return 0; /* pDestIdx has no corresponding index in pSrc */
1505 }
1506 }
drh7fc2f412007-03-29 00:08:24 +00001507#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001508 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001509 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1510 }
drh7fc2f412007-03-29 00:08:24 +00001511#endif
drh9d9cf222007-02-13 15:01:11 +00001512
1513 /* If we get this far, it means either:
1514 **
1515 ** * We can always do the transfer if the table contains an
1516 ** an integer primary key
1517 **
1518 ** * We can conditionally do the transfer if the destination
1519 ** table is empty.
1520 */
drhdd735212007-02-24 13:53:05 +00001521#ifdef SQLITE_TEST
1522 sqlite3_xferopt_count++;
1523#endif
drh9d9cf222007-02-13 15:01:11 +00001524 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1525 v = sqlite3GetVdbe(pParse);
1526 iSrc = pParse->nTab++;
1527 iDest = pParse->nTab++;
1528 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1529 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001530 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001531 /* If tables do not have an INTEGER PRIMARY KEY and there
1532 ** are indices to be copied and the destination is not empty,
1533 ** we have to disallow the transfer optimization because the
1534 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001535 **
1536 ** Or if the destination has a UNIQUE index and is not empty,
1537 ** we also disallow the transfer optimization because we cannot
1538 ** insure that all entries in the union of DEST and SRC will be
1539 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001540 */
1541 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1542 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1543 sqlite3VdbeJumpHere(v, addr1);
1544 }else{
1545 emptyDestTest = 0;
1546 }
1547 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1548 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001549 if( pDest->iPKey>=0 ){
drhbd36ba62007-03-31 13:00:26 +00001550 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh95bad4c2007-03-28 18:04:10 +00001551 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1552 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1553 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1554 "PRIMARY KEY must be unique", P3_STATIC);
1555 sqlite3VdbeJumpHere(v, addr2);
1556 autoIncStep(pParse, counterMem);
drhbd36ba62007-03-31 13:00:26 +00001557 }else if( pDest->pIndex==0 ){
1558 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
drh95bad4c2007-03-28 18:04:10 +00001559 }else{
drhbd36ba62007-03-31 13:00:26 +00001560 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001561 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001562 }
drh9d9cf222007-02-13 15:01:11 +00001563 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001564 sqlite3VdbeOp3(v, OP_Insert, iDest,
1565 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
drh9d9cf222007-02-13 15:01:11 +00001566 pDest->zName, 0);
1567 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1568 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1569 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1570 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1571 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1572 }
1573 assert( pSrcIdx );
1574 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1575 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1576 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1577 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1578 VdbeComment((v, "# %s", pSrcIdx->zName));
1579 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1580 (char*)pKey, P3_KEYINFO_HANDOFF);
1581 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1582 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1583 VdbeComment((v, "# %s", pDestIdx->zName));
1584 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1585 (char*)pKey, P3_KEYINFO_HANDOFF);
1586 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1587 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001588 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
drh9d9cf222007-02-13 15:01:11 +00001589 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1590 sqlite3VdbeJumpHere(v, addr1);
1591 }
1592 sqlite3VdbeJumpHere(v, emptySrcTest);
1593 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1594 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1595 if( emptyDestTest ){
1596 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1597 sqlite3VdbeJumpHere(v, emptyDestTest);
1598 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1599 return 0;
1600 }else{
1601 return 1;
1602 }
1603}
1604#endif /* SQLITE_OMIT_XFER_OPT */