blob: 947e16b7a1adbd52df3484fcf787c4bd663a1477 [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**
drh42242de2007-03-29 13:35:35 +000015** $Id: insert.c,v 1.181 2007/03/29 13:35:36 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
drh798da522004-11-04 04:42:28 +0000352#ifndef SQLITE_OMIT_TRIGGER
353 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000354 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000355#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000356
danielk19779e128002006-01-18 16:51:35 +0000357 if( pParse->nErr || sqlite3MallocFailed() ){
drh6f7adc82006-01-11 21:41:20 +0000358 goto insert_cleanup;
359 }
drhecdc7532001-09-23 02:35:53 +0000360 db = pParse->db;
drhdaffd0e2001-04-11 14:28:42 +0000361
drh1ccde152000-06-17 13:12:39 +0000362 /* Locate the table into which we will be inserting new information.
363 */
drh113088e2003-03-20 01:16:58 +0000364 assert( pTabList->nSrc==1 );
365 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000366 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000367 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000368 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000369 goto insert_cleanup;
370 }
danielk1977da184232006-01-05 11:34:32 +0000371 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
372 assert( iDb<db->nDb );
373 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000374 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000375 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000376 goto insert_cleanup;
377 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000378
drhb7f91642004-10-31 02:22:47 +0000379 /* Figure out if we have any triggers and if the table being
380 ** inserted into is a view
381 */
382#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000383 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000384 isView = pTab->pSelect!=0;
385#else
drhdca76842004-12-07 14:06:13 +0000386# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000387# define isView 0
388#endif
389#ifdef SQLITE_OMIT_VIEW
390# undef isView
391# define isView 0
392#endif
393
danielk1977c3f9bad2002-05-15 08:30:12 +0000394 /* Ensure that:
395 * (a) the table is not read-only,
396 * (b) that if it is a view then ON INSERT triggers exist
397 */
drhdca76842004-12-07 14:06:13 +0000398 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000399 goto insert_cleanup;
400 }
drh43617e92006-03-06 20:55:46 +0000401 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000402
drhf573c992002-07-31 00:32:50 +0000403 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000404 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
405 ** module table).
drhf573c992002-07-31 00:32:50 +0000406 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000407 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000408 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000409 }
410
drh1ccde152000-06-17 13:12:39 +0000411 /* Allocate a VDBE
412 */
danielk19774adee202004-05-08 08:23:19 +0000413 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000414 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000415 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000416 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000417
danielk1977c3f9bad2002-05-15 08:30:12 +0000418 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000419 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000420 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000421 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000422
drh9d9cf222007-02-13 15:01:11 +0000423#ifndef SQLITE_OMIT_XFER_OPT
424 /* If the statement is of the form
425 **
426 ** INSERT INTO <table1> SELECT * FROM <table2>;
427 **
428 ** Then special optimizations can be applied that make the transfer
429 ** very fast and which reduce fragmentation of indices.
430 */
431 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
432 assert( !triggers_exist );
433 assert( pList==0 );
434 goto insert_cleanup;
435 }
436#endif /* SQLITE_OMIT_XFER_OPT */
437
drh2958a4e2004-11-12 03:56:15 +0000438 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000439 ** sqlite_sequence table and store it in memory cell counterMem. Also
440 ** remember the rowid of the sqlite_sequence table entry in memory cell
441 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000442 */
drh9d9cf222007-02-13 15:01:11 +0000443 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000444
drh1ccde152000-06-17 13:12:39 +0000445 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000446 ** is coming from a SELECT statement, then this step also generates
447 ** all the code to implement the SELECT statement and invoke a subroutine
448 ** to process each row of the result. (Template 2.) If the SELECT
449 ** statement uses the the table that is being inserted into, then the
450 ** subroutine is also coded here. That subroutine stores the SELECT
451 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000452 */
drh5974a302000-06-07 14:42:26 +0000453 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000454 /* Data is coming from a SELECT. Generate code to implement that SELECT
455 */
456 int rc, iInitCode;
danielk19774adee202004-05-08 08:23:19 +0000457 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
458 iSelectLoop = sqlite3VdbeCurrentAddr(v);
459 iInsertBlock = sqlite3VdbeMakeLabel(v);
danielk1977b3bce662005-01-29 08:32:43 +0000460
461 /* Resolve the expressions in the SELECT statement and execute it. */
462 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
danielk19779e128002006-01-18 16:51:35 +0000463 if( rc || pParse->nErr || sqlite3MallocFailed() ){
drh6f7adc82006-01-11 21:41:20 +0000464 goto insert_cleanup;
465 }
danielk1977b3bce662005-01-29 08:32:43 +0000466
danielk19774adee202004-05-08 08:23:19 +0000467 iCleanup = sqlite3VdbeMakeLabel(v);
468 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000469 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000470 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000471
472 /* Set useTempTable to TRUE if the result of the SELECT statement
473 ** should be written into a temporary table. Set to FALSE if each
474 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000475 **
476 ** A temp table must be used if the table being updated is also one
477 ** of the tables being read by the SELECT statement. Also use a
478 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000479 */
danielk1977da184232006-01-05 11:34:32 +0000480 if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
drh048c5302003-04-03 01:50:44 +0000481 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000482 }
drh142e30d2002-08-28 03:00:58 +0000483
484 if( useTempTable ){
485 /* Generate the subroutine that SELECT calls to process each row of
486 ** the result. Store the result in a temporary table
487 */
488 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000489 sqlite3VdbeResolveLabel(v, iInsertBlock);
490 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf0863fe2005-06-12 21:35:51 +0000491 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
danielk19774adee202004-05-08 08:23:19 +0000492 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhe4d90812007-03-29 05:51:49 +0000493 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
danielk19774adee202004-05-08 08:23:19 +0000494 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000495
496 /* The following code runs first because the GOTO at the very top
497 ** of the program jumps to it. Create the temporary table, then jump
498 ** back up and execute the SELECT code above.
499 */
drhd654be82005-09-20 17:42:23 +0000500 sqlite3VdbeJumpHere(v, iInitCode);
drhb9bb7c12006-06-11 23:41:55 +0000501 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
drhb6f54522004-05-20 02:42:16 +0000502 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
danielk19774adee202004-05-08 08:23:19 +0000503 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
504 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000505 }else{
drhd654be82005-09-20 17:42:23 +0000506 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000507 }
drh5974a302000-06-07 14:42:26 +0000508 }else{
drh142e30d2002-08-28 03:00:58 +0000509 /* This is the case if the data for the INSERT is coming from a VALUES
510 ** clause
511 */
danielk1977b3bce662005-01-29 08:32:43 +0000512 NameContext sNC;
513 memset(&sNC, 0, sizeof(sNC));
514 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000515 srcTab = -1;
drh142e30d2002-08-28 03:00:58 +0000516 useTempTable = 0;
drh147d0cc2006-08-25 23:42:53 +0000517 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000518 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000519 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000520 goto insert_cleanup;
521 }
drhe64e7b22002-02-18 13:56:36 +0000522 }
drh5974a302000-06-07 14:42:26 +0000523 }
drh1ccde152000-06-17 13:12:39 +0000524
525 /* Make sure the number of columns in the source data matches the number
526 ** of columns to be inserted into the table.
527 */
drh147d0cc2006-08-25 23:42:53 +0000528 if( pColumn==0 && nColumn && nColumn!=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000529 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000530 "table %S has %d columns but %d values were supplied",
531 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000532 goto insert_cleanup;
533 }
drh967e8b72000-06-21 13:59:10 +0000534 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000535 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000536 goto insert_cleanup;
537 }
drh1ccde152000-06-17 13:12:39 +0000538
539 /* If the INSERT statement included an IDLIST term, then make sure
540 ** all elements of the IDLIST really are columns of the table and
541 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000542 **
543 ** If the table has an INTEGER PRIMARY KEY column and that column
544 ** is named in the IDLIST, then record in the keyColumn variable
545 ** the index into IDLIST of the primary key column. keyColumn is
546 ** the index of the primary key as it appears in IDLIST, not as
547 ** is appears in the original table. (The index of the primary
548 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000549 */
drh967e8b72000-06-21 13:59:10 +0000550 if( pColumn ){
551 for(i=0; i<pColumn->nId; i++){
552 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000553 }
drh967e8b72000-06-21 13:59:10 +0000554 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000555 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000556 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000557 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000558 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000559 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000560 }
drhcce7d172000-05-31 15:34:51 +0000561 break;
562 }
563 }
564 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000565 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000566 keyColumn = i;
567 }else{
danielk19774adee202004-05-08 08:23:19 +0000568 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000569 pTabList, 0, pColumn->a[i].zName);
570 pParse->nErr++;
571 goto insert_cleanup;
572 }
drhcce7d172000-05-31 15:34:51 +0000573 }
574 }
575 }
drh1ccde152000-06-17 13:12:39 +0000576
drhaacc5432002-01-06 17:07:40 +0000577 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000578 ** key, the set the keyColumn variable to the primary key column index
579 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000580 */
drh147d0cc2006-08-25 23:42:53 +0000581 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000582 keyColumn = pTab->iPKey;
583 }
584
drh142e30d2002-08-28 03:00:58 +0000585 /* Open the temp table for FOR EACH ROW triggers
586 */
drhdca76842004-12-07 14:06:13 +0000587 if( triggers_exist ){
danielk19774adee202004-05-08 08:23:19 +0000588 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
danielk197784ac9d02004-05-18 09:58:06 +0000589 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000590 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000591
drhfeeb1392002-04-09 03:28:01 +0000592 /* Initialize the count of rows to be inserted
593 */
drh142e30d2002-08-28 03:00:58 +0000594 if( db->flags & SQLITE_CountRows ){
595 iCntMem = pParse->nMem++;
drhd654be82005-09-20 17:42:23 +0000596 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000597 }
598
danielk1977c3f9bad2002-05-15 08:30:12 +0000599 /* Open tables and indices if there are no row triggers */
drhdca76842004-12-07 14:06:13 +0000600 if( !triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000601 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000602 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000603 }
604
drh142e30d2002-08-28 03:00:58 +0000605 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000606 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000607 ** source is a subroutine call from the SELECT statement, then we need
608 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000609 */
drh142e30d2002-08-28 03:00:58 +0000610 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000611 iBreak = sqlite3VdbeMakeLabel(v);
612 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
613 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000614 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000615 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
616 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh5974a302000-06-07 14:42:26 +0000617 }
drh1ccde152000-06-17 13:12:39 +0000618
drh5cf590c2003-04-24 01:45:04 +0000619 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000620 */
danielk19774adee202004-05-08 08:23:19 +0000621 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000622 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000623
drh70ce3f02003-04-15 19:22:22 +0000624 /* build the NEW.* reference row. Note that if there is an INTEGER
625 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
626 ** translated into a unique ID for the row. But on a BEFORE trigger,
627 ** we do not know what the unique ID will be (because the insert has
628 ** not happened yet) so we substitute a rowid of -1
629 */
630 if( keyColumn<0 ){
danielk19774adee202004-05-08 08:23:19 +0000631 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000632 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000633 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000634 }else{
drhd6fe9612005-01-14 01:22:00 +0000635 assert( pSelect==0 ); /* Otherwise useTempTable is true */
danielk19774adee202004-05-08 08:23:19 +0000636 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
637 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
638 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
639 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
640 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000641 }
642
643 /* Create the new column data
644 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000645 for(i=0; i<pTab->nCol; i++){
646 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000647 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000648 }else{
drh9adf9ac2002-05-15 11:44:13 +0000649 for(j=0; j<pColumn->nId; j++){
650 if( pColumn->a[j].idx==i ) break;
651 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000652 }
653 if( pColumn && j>=pColumn->nId ){
danielk19777977a172004-11-09 12:44:37 +0000654 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000655 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000656 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000657 }else{
drhd6fe9612005-01-14 01:22:00 +0000658 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000659 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000660 }
661 }
danielk19774adee202004-05-08 08:23:19 +0000662 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000663
664 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
665 ** do not attempt any conversions before assembling the record.
666 ** If this is a real table, attempt conversions as required by the
667 ** table column affinities.
668 */
669 if( !isView ){
670 sqlite3TableAffinityStr(v, pTab);
671 }
drhf0863fe2005-06-12 21:35:51 +0000672 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000673
drh5cf590c2003-04-24 01:45:04 +0000674 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000675 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
drhb2fe7d82003-04-20 17:29:23 +0000676 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000677 goto insert_cleanup;
678 }
drh70ce3f02003-04-15 19:22:22 +0000679 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000680
drh70ce3f02003-04-15 19:22:22 +0000681 /* If any triggers exists, the opening of tables and indices is deferred
682 ** until now.
683 */
drhdca76842004-12-07 14:06:13 +0000684 if( triggers_exist && !isView ){
drh5cf590c2003-04-24 01:45:04 +0000685 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000686 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000687 }
688
drh4a324312001-12-21 14:30:42 +0000689 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000690 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000691 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000692 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000693 */
drh5cf590c2003-04-24 01:45:04 +0000694 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000695 if( IsVirtual(pTab) ){
696 /* The row that the VUpdate opcode will delete: none */
697 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
698 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000699 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000700 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000701 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh142e30d2002-08-28 03:00:58 +0000702 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000703 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000704 }else{
drhe4d90812007-03-29 05:51:49 +0000705 VdbeOp *pOp;
danielk19774adee202004-05-08 08:23:19 +0000706 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
drhe4d90812007-03-29 05:51:49 +0000707 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
708 if( pOp->opcode==OP_Null ){
709 appendFlag = 1;
710 pOp->opcode = OP_NewRowid;
711 pOp->p1 = base;
712 pOp->p2 = counterMem;
713 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000714 }
drhf0863fe2005-06-12 21:35:51 +0000715 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000716 ** to generate a unique primary key value.
717 */
drhe4d90812007-03-29 05:51:49 +0000718 if( !appendFlag ){
719 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
720 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
721 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
722 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
723 }
drh4cbdda92006-06-14 19:00:20 +0000724 }else if( IsVirtual(pTab) ){
725 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000726 }else{
drhf0863fe2005-06-12 21:35:51 +0000727 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
drhe4d90812007-03-29 05:51:49 +0000728 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000729 }
drh9d9cf222007-02-13 15:01:11 +0000730 autoIncStep(pParse, counterMem);
drh4a324312001-12-21 14:30:42 +0000731
danielk1977c3f9bad2002-05-15 08:30:12 +0000732 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000733 ** with the first column.
734 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000735 for(i=0; i<pTab->nCol; i++){
736 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000737 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000738 ** Whenever this column is read, the record number will be substituted
739 ** in its place. So will fill this column with a NULL to avoid
740 ** taking up data space with information that will never be used. */
drhf0863fe2005-06-12 21:35:51 +0000741 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh9adf9ac2002-05-15 11:44:13 +0000742 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000743 }
744 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000745 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000746 }else{
drh9adf9ac2002-05-15 11:44:13 +0000747 for(j=0; j<pColumn->nId; j++){
748 if( pColumn->a[j].idx==i ) break;
749 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000750 }
drh147d0cc2006-08-25 23:42:53 +0000751 if( nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk19777977a172004-11-09 12:44:37 +0000752 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000753 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000754 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
drh142e30d2002-08-28 03:00:58 +0000755 }else if( pSelect ){
drh16ed8a62006-08-29 18:46:14 +0000756 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000757 }else{
danielk19774adee202004-05-08 08:23:19 +0000758 sqlite3ExprCode(pParse, pList->a[j].pExpr);
drh5974a302000-06-07 14:42:26 +0000759 }
drhbed86902000-06-02 13:27:59 +0000760 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000761
762 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000763 ** do the insertion.
764 */
drh4cbdda92006-06-14 19:00:20 +0000765#ifndef SQLITE_OMIT_VIRTUALTABLE
766 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000767 pParse->pVirtualLock = pTab;
danielk19771f6eec52006-06-16 06:17:47 +0000768 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
drh4cbdda92006-06-14 19:00:20 +0000769 (const char*)pTab->pVtab, P3_VTAB);
770 }else
771#endif
772 {
773 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
774 0, onError, endOfLoop);
775 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000776 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
777 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000778 }
drh5cf590c2003-04-24 01:45:04 +0000779 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000780
drh5cf590c2003-04-24 01:45:04 +0000781 /* Update the count of rows that are inserted
782 */
783 if( (db->flags & SQLITE_CountRows)!=0 ){
drh15007a92006-01-08 18:10:17 +0000784 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
drh5974a302000-06-07 14:42:26 +0000785 }
drh1ccde152000-06-17 13:12:39 +0000786
drhdca76842004-12-07 14:06:13 +0000787 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000788 /* Close all tables opened */
drh5cf590c2003-04-24 01:45:04 +0000789 if( !isView ){
danielk19774adee202004-05-08 08:23:19 +0000790 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000791 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000792 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000793 }
794 }
drh1bee3d72001-10-15 00:44:35 +0000795
danielk1977c3f9bad2002-05-15 08:30:12 +0000796 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000797 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
798 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000799 goto insert_cleanup;
800 }
drh1bee3d72001-10-15 00:44:35 +0000801 }
802
drh1ccde152000-06-17 13:12:39 +0000803 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000804 */
danielk19774adee202004-05-08 08:23:19 +0000805 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000806 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000807 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
808 sqlite3VdbeResolveLabel(v, iBreak);
809 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000810 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000811 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
812 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
813 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000814 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000815
drh4cbdda92006-06-14 19:00:20 +0000816 if( !triggers_exist && !IsVirtual(pTab) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000817 /* Close all tables opened */
danielk19774adee202004-05-08 08:23:19 +0000818 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000819 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000820 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000821 }
drhcce7d172000-05-31 15:34:51 +0000822 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000823
drhf3388142004-11-13 03:48:06 +0000824 /* Update the sqlite_sequence table by storing the content of the
825 ** counter value in memory counterMem back into the sqlite_sequence
826 ** table.
drh2958a4e2004-11-12 03:56:15 +0000827 */
drh9d9cf222007-02-13 15:01:11 +0000828 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000829
drh1bee3d72001-10-15 00:44:35 +0000830 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000831 ** Return the number of rows inserted. If this routine is
832 ** generating code because of a call to sqlite3NestedParse(), do not
833 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000834 */
danielk1977cc6bd382005-01-10 02:48:49 +0000835 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +0000836 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
837 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
danielk197722322fd2004-05-25 23:35:17 +0000838 sqlite3VdbeSetNumCols(v, 1);
danielk1977955de522006-02-10 02:27:42 +0000839 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000840 }
drhcce7d172000-05-31 15:34:51 +0000841
842insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000843 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000844 sqlite3ExprListDelete(pList);
845 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000846 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000847}
drh9cfcf5d2002-01-29 18:41:24 +0000848
drh9cfcf5d2002-01-29 18:41:24 +0000849/*
850** Generate code to do a constraint check prior to an INSERT or an UPDATE.
851**
852** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000853** the following values:
854**
drhf0863fe2005-06-12 21:35:51 +0000855** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000856** value is omitted unless we are doing an UPDATE that involves a
857** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000858**
drhf0863fe2005-06-12 21:35:51 +0000859** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000860**
861** 3. The data in the first column of the entry after the update.
862**
863** i. Data from middle columns...
864**
865** N. The data in the last column of the entry after the update.
866**
drhf0863fe2005-06-12 21:35:51 +0000867** The old rowid shown as entry (1) above is omitted unless both isUpdate
868** and rowidChng are 1. isUpdate is true for UPDATEs and false for
869** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000870**
871** The code generated by this routine pushes additional entries onto
872** the stack which are the keys for new index entries for the new record.
873** The order of index keys is the same as the order of the indices on
874** the pTable->pIndex list. A key is only created for index i if
875** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000876**
877** This routine also generates code to check constraints. NOT NULL,
878** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000879** then the appropriate action is performed. There are five possible
880** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000881**
882** Constraint type Action What Happens
883** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000884** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000885** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000886** return code of SQLITE_CONSTRAINT.
887**
drh1c928532002-01-31 15:54:21 +0000888** any ABORT Back out changes from the current command
889** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000890** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000891** with SQLITE_CONSTRAINT.
892**
893** any FAIL Sqlite_exec() returns immediately with a
894** return code of SQLITE_CONSTRAINT. The
895** transaction is not rolled back and any
896** prior changes are retained.
897**
drh9cfcf5d2002-01-29 18:41:24 +0000898** any IGNORE The record number and data is popped from
899** the stack and there is an immediate jump
900** to label ignoreDest.
901**
902** NOT NULL REPLACE The NULL value is replace by the default
903** value for that column. If the default value
904** is NULL, the action is the same as ABORT.
905**
906** UNIQUE REPLACE The other row that conflicts with the row
907** being inserted is removed.
908**
909** CHECK REPLACE Illegal. The results in an exception.
910**
drh1c928532002-01-31 15:54:21 +0000911** Which action to take is determined by the overrideError parameter.
912** Or if overrideError==OE_Default, then the pParse->onError parameter
913** is used. Or if pParse->onError==OE_Default then the onError value
914** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000915**
drhaaab5722002-02-19 13:39:21 +0000916** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000917** cursor number "base". All indices of pTab must also have open
918** read/write cursors with cursor number base+i for the i-th cursor.
919** Except, if there is no possibility of a REPLACE action then
920** cursors do not need to be open for indices where aIdxUsed[i]==0.
921**
922** If the isUpdate flag is true, it means that the "base" cursor is
923** initially pointing to an entry that is being updated. The isUpdate
924** flag causes extra code to be generated so that the "base" cursor
925** is still pointing at the same entry after the routine returns.
926** Without the isUpdate flag, the "base" cursor might be moved.
927*/
danielk19774adee202004-05-08 08:23:19 +0000928void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000929 Parse *pParse, /* The parser context */
930 Table *pTab, /* the table into which we are inserting */
931 int base, /* Index of a read/write cursor pointing at pTab */
932 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000933 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000934 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000935 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000936 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000937){
938 int i;
939 Vdbe *v;
940 int nCol;
941 int onError;
942 int addr;
943 int extra;
drh0ca3e242002-01-29 23:07:02 +0000944 int iCur;
945 Index *pIdx;
946 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000947 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000948 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000949
danielk19774adee202004-05-08 08:23:19 +0000950 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000951 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000952 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000953 nCol = pTab->nCol;
954
955 /* Test all NOT NULL constraints.
956 */
957 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000958 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +0000959 continue;
960 }
drh9cfcf5d2002-01-29 18:41:24 +0000961 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +0000962 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +0000963 if( overrideError!=OE_Default ){
964 onError = overrideError;
drha996e472003-05-16 02:30:27 +0000965 }else if( onError==OE_Default ){
966 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +0000967 }
danielk19777977a172004-11-09 12:44:37 +0000968 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +0000969 onError = OE_Abort;
970 }
danielk19774adee202004-05-08 08:23:19 +0000971 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
972 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +0000973 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
974 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +0000975 switch( onError ){
drh1c928532002-01-31 15:54:21 +0000976 case OE_Rollback:
977 case OE_Abort:
978 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +0000979 char *zMsg = 0;
danielk19774adee202004-05-08 08:23:19 +0000980 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
981 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +0000982 " may not be NULL", (char*)0);
danielk19774adee202004-05-08 08:23:19 +0000983 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +0000984 break;
985 }
986 case OE_Ignore: {
drhf0863fe2005-06-12 21:35:51 +0000987 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +0000988 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +0000989 break;
990 }
991 case OE_Replace: {
danielk19777977a172004-11-09 12:44:37 +0000992 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
danielk19774adee202004-05-08 08:23:19 +0000993 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
drh9cfcf5d2002-01-29 18:41:24 +0000994 break;
995 }
drh9cfcf5d2002-01-29 18:41:24 +0000996 }
drhd654be82005-09-20 17:42:23 +0000997 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +0000998 }
999
1000 /* Test all CHECK constraints
1001 */
drhffe07b22005-11-03 00:41:17 +00001002#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001003 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001004 int allOk = sqlite3VdbeMakeLabel(v);
1005 assert( pParse->ckOffset==0 );
1006 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001007 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001008 assert( pParse->ckOffset==nCol );
1009 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001010 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1011 if( onError==OE_Ignore || onError==OE_Replace ){
1012 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1013 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1014 }else{
1015 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1016 }
drhffe07b22005-11-03 00:41:17 +00001017 sqlite3VdbeResolveLabel(v, allOk);
1018 }
1019#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001020
drh0bd1f4e2002-06-06 18:54:39 +00001021 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1022 ** of the new record does not previously exist. Except, if this
1023 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001024 */
drhf0863fe2005-06-12 21:35:51 +00001025 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001026 onError = pTab->keyConf;
1027 if( overrideError!=OE_Default ){
1028 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001029 }else if( onError==OE_Default ){
1030 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001031 }
drha0217ba2003-06-01 01:10:33 +00001032
drh5383ae52003-06-04 12:23:30 +00001033 if( isUpdate ){
danielk19774adee202004-05-08 08:23:19 +00001034 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1035 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1036 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001037 }
danielk19774adee202004-05-08 08:23:19 +00001038 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1039 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001040 switch( onError ){
1041 default: {
1042 onError = OE_Abort;
1043 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001044 }
drh5383ae52003-06-04 12:23:30 +00001045 case OE_Rollback:
1046 case OE_Abort:
1047 case OE_Fail: {
danielk19774adee202004-05-08 08:23:19 +00001048 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
drh701a0ae2004-02-22 20:05:00 +00001049 "PRIMARY KEY must be unique", P3_STATIC);
drh5383ae52003-06-04 12:23:30 +00001050 break;
drh0ca3e242002-01-29 23:07:02 +00001051 }
drh5383ae52003-06-04 12:23:30 +00001052 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001053 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001054 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001055 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001056 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001057 }
1058 seenReplace = 1;
1059 break;
drh0ca3e242002-01-29 23:07:02 +00001060 }
drh5383ae52003-06-04 12:23:30 +00001061 case OE_Ignore: {
1062 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001063 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001064 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001065 break;
1066 }
1067 }
drhd654be82005-09-20 17:42:23 +00001068 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001069 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001070 sqlite3VdbeJumpHere(v, jumpInst1);
danielk19774adee202004-05-08 08:23:19 +00001071 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001072 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001073 }
1074 }
drh0bd1f4e2002-06-06 18:54:39 +00001075
1076 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1077 ** index and making sure that duplicate entries do not already exist.
1078 ** Add the new records to the indices as we go.
1079 */
drhb2fe7d82003-04-20 17:29:23 +00001080 extra = -1;
1081 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1082 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1083 extra++;
1084
1085 /* Create a key for accessing the index entry */
danielk19774adee202004-05-08 08:23:19 +00001086 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001087 for(i=0; i<pIdx->nColumn; i++){
1088 int idx = pIdx->aiColumn[i];
1089 if( idx==pTab->iPKey ){
danielk19774adee202004-05-08 08:23:19 +00001090 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001091 }else{
danielk19774adee202004-05-08 08:23:19 +00001092 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001093 }
1094 }
drh7f057c92005-06-24 03:53:06 +00001095 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001096 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001097
1098 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001099 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001100 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001101 if( overrideError!=OE_Default ){
1102 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001103 }else if( onError==OE_Default ){
1104 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001105 }
drh5383ae52003-06-04 12:23:30 +00001106 if( seenReplace ){
1107 if( onError==OE_Ignore ) onError = OE_Replace;
1108 else if( onError==OE_Fail ) onError = OE_Abort;
1109 }
1110
drhb2fe7d82003-04-20 17:29:23 +00001111
1112 /* Check to see if the new index entry will be unique */
drhf0863fe2005-06-12 21:35:51 +00001113 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
danielk19774adee202004-05-08 08:23:19 +00001114 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001115
1116 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001117 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1118 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001119 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001120 case OE_Rollback:
1121 case OE_Abort:
1122 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001123 int j, n1, n2;
1124 char zErrMsg[200];
1125 strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
1126 n1 = strlen(zErrMsg);
1127 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1128 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1129 n2 = strlen(zCol);
1130 if( j>0 ){
1131 strcpy(&zErrMsg[n1], ", ");
1132 n1 += 2;
1133 }
1134 if( n1+n2>sizeof(zErrMsg)-30 ){
1135 strcpy(&zErrMsg[n1], "...");
1136 n1 += 3;
1137 break;
1138 }else{
1139 strcpy(&zErrMsg[n1], zCol);
1140 n1 += n2;
1141 }
1142 }
1143 strcpy(&zErrMsg[n1],
1144 pIdx->nColumn>1 ? " are not unique" : " is not unique");
danielk19774adee202004-05-08 08:23:19 +00001145 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001146 break;
1147 }
1148 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001149 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001150 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001151 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001152 break;
1153 }
1154 case OE_Replace: {
danielk19774adee202004-05-08 08:23:19 +00001155 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001156 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001157 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001158 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001159 }
drh0ca3e242002-01-29 23:07:02 +00001160 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001161 break;
1162 }
drh9cfcf5d2002-01-29 18:41:24 +00001163 }
drh0bd1f4e2002-06-06 18:54:39 +00001164#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001165 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001166#endif
drhd654be82005-09-20 17:42:23 +00001167 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001168 }
1169}
drh0ca3e242002-01-29 23:07:02 +00001170
1171/*
1172** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001173** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001174** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001175** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001176** entries in all indices and in the main table.
1177**
drhb419a922002-01-30 16:17:23 +00001178** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001179** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001180*/
danielk19774adee202004-05-08 08:23:19 +00001181void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001182 Parse *pParse, /* The parser context */
1183 Table *pTab, /* the table into which we are inserting */
1184 int base, /* Index of a read/write cursor pointing at pTab */
1185 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001186 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001187 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001188 int newIdx, /* Index of NEW table for triggers. -1 if none */
1189 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001190){
1191 int i;
1192 Vdbe *v;
1193 int nIdx;
1194 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001195 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001196
danielk19774adee202004-05-08 08:23:19 +00001197 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001198 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001199 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001200 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1201 for(i=nIdx-1; i>=0; i--){
1202 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drhf0863fe2005-06-12 21:35:51 +00001203 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001204 }
danielk19774adee202004-05-08 08:23:19 +00001205 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001206 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001207#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001208 if( newIdx>=0 ){
danielk19774adee202004-05-08 08:23:19 +00001209 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1210 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhf0863fe2005-06-12 21:35:51 +00001211 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001212 }
danielk1977b84f96f2005-01-20 11:32:23 +00001213#endif
drh4794f732004-11-05 17:17:50 +00001214 if( pParse->nested ){
1215 pik_flags = 0;
1216 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001217 pik_flags = OPFLAG_NCHANGE;
1218 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001219 }
drhe4d90812007-03-29 05:51:49 +00001220 if( appendBias ){
1221 pik_flags |= OPFLAG_APPEND;
1222 }
drhf0863fe2005-06-12 21:35:51 +00001223 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001224 if( !pParse->nested ){
1225 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1226 }
danielk1977b28af712004-06-21 06:50:26 +00001227
drhf0863fe2005-06-12 21:35:51 +00001228 if( isUpdate && rowidChng ){
danielk19774adee202004-05-08 08:23:19 +00001229 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001230 }
1231}
drhcd446902004-02-24 01:05:31 +00001232
1233/*
drh290c1942004-08-21 17:54:45 +00001234** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001235** indices of that table. The "base" parameter is the cursor number used
1236** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001237*/
drh290c1942004-08-21 17:54:45 +00001238void sqlite3OpenTableAndIndices(
1239 Parse *pParse, /* Parsing context */
1240 Table *pTab, /* Table to be opened */
1241 int base, /* Cursor number assigned to the table */
1242 int op /* OP_OpenRead or OP_OpenWrite */
1243){
drhcd446902004-02-24 01:05:31 +00001244 int i;
drh4cbdda92006-06-14 19:00:20 +00001245 int iDb;
drhcd446902004-02-24 01:05:31 +00001246 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001247 Vdbe *v;
1248
1249 if( IsVirtual(pTab) ) return;
1250 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1251 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001252 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001253 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001254 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001255 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001256 assert( pIdx->pSchema==pTab->pSchema );
1257 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001258 VdbeComment((v, "# %s", pIdx->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00001259 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
drhcd446902004-02-24 01:05:31 +00001260 }
drh290c1942004-08-21 17:54:45 +00001261 if( pParse->nTab<=base+i ){
1262 pParse->nTab = base+i;
1263 }
drhcd446902004-02-24 01:05:31 +00001264}
drh9d9cf222007-02-13 15:01:11 +00001265
drh91c58e22007-03-27 12:04:04 +00001266
1267#ifdef SQLITE_TEST
1268/*
1269** The following global variable is incremented whenever the
1270** transfer optimization is used. This is used for testing
1271** purposes only - to make sure the transfer optimization really
1272** is happening when it is suppose to.
1273*/
1274int sqlite3_xferopt_count;
1275#endif /* SQLITE_TEST */
1276
1277
drh9d9cf222007-02-13 15:01:11 +00001278#ifndef SQLITE_OMIT_XFER_OPT
1279/*
1280** Check to collation names to see if they are compatible.
1281*/
1282static int xferCompatibleCollation(const char *z1, const char *z2){
1283 if( z1==0 ){
1284 return z2==0;
1285 }
1286 if( z2==0 ){
1287 return 0;
1288 }
1289 return sqlite3StrICmp(z1, z2)==0;
1290}
1291
1292
1293/*
1294** Check to see if index pSrc is compatible as a source of data
1295** for index pDest in an insert transfer optimization. The rules
1296** for a compatible index:
1297**
1298** * The index is over the same set of columns
1299** * The same DESC and ASC markings occurs on all columns
1300** * The same onError processing (OE_Abort, OE_Ignore, etc)
1301** * The same collating sequence on each column
1302*/
1303static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1304 int i;
1305 assert( pDest && pSrc );
1306 assert( pDest->pTable!=pSrc->pTable );
1307 if( pDest->nColumn!=pSrc->nColumn ){
1308 return 0; /* Different number of columns */
1309 }
1310 if( pDest->onError!=pSrc->onError ){
1311 return 0; /* Different conflict resolution strategies */
1312 }
1313 for(i=0; i<pSrc->nColumn; i++){
1314 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1315 return 0; /* Different columns indexed */
1316 }
1317 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1318 return 0; /* Different sort orders */
1319 }
1320 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1321 return 0; /* Different sort orders */
1322 }
1323 }
1324
1325 /* If no test above fails then the indices must be compatible */
1326 return 1;
1327}
1328
1329/*
1330** Attempt the transfer optimization on INSERTs of the form
1331**
1332** INSERT INTO tab1 SELECT * FROM tab2;
1333**
1334** This optimization is only attempted if
1335**
1336** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001337** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001338**
1339** (2) tab1 and tab2 are different tables
1340**
1341** (3) There must be no triggers on tab1
1342**
1343** (4) The result set of the SELECT statement is "*"
1344**
1345** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1346** or LIMIT clause.
1347**
1348** (6) The SELECT statement is a simple (not a compound) select that
1349** contains only tab2 in its FROM clause
1350**
1351** This method for implementing the INSERT transfers raw records from
1352** tab2 over to tab1. The columns are not decoded. Raw records from
1353** the indices of tab2 are transfered to tab1 as well. In so doing,
1354** the resulting tab1 has much less fragmentation.
1355**
1356** This routine returns TRUE if the optimization is attempted. If any
1357** of the conditions above fail so that the optimization should not
1358** be attempted, then this routine returns FALSE.
1359*/
1360static int xferOptimization(
1361 Parse *pParse, /* Parser context */
1362 Table *pDest, /* The table we are inserting into */
1363 Select *pSelect, /* A SELECT statement to use as the data source */
1364 int onError, /* How to handle constraint errors */
1365 int iDbDest /* The database of pDest */
1366){
1367 ExprList *pEList; /* The result set of the SELECT */
1368 Table *pSrc; /* The table in the FROM clause of SELECT */
1369 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1370 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1371 int i; /* Loop counter */
1372 int iDbSrc; /* The database of pSrc */
1373 int iSrc, iDest; /* Cursors from source and destination */
1374 int addr1, addr2; /* Loop addresses */
1375 int emptyDestTest; /* Address of test for empty pDest */
1376 int emptySrcTest; /* Address of test for empty pSrc */
1377 int memRowid; /* A memcell containing a rowid from pSrc */
1378 Vdbe *v; /* The VDBE we are building */
1379 KeyInfo *pKey; /* Key information for an index */
1380 int counterMem; /* Memory register used by AUTOINC */
1381
1382 if( pSelect==0 ){
1383 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1384 }
1385 if( pDest->pTrigger ){
1386 return 0; /* tab1 must not have triggers */
1387 }
1388#ifndef SQLITE_OMIT_VIRTUALTABLE
1389 if( pDest->isVirtual ){
1390 return 0; /* tab1 must not be a virtual table */
1391 }
1392#endif
1393 if( onError==OE_Default ){
1394 onError = OE_Abort;
1395 }
1396 if( onError!=OE_Abort && onError!=OE_Rollback ){
1397 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1398 }
1399 if( pSelect->pSrc==0 ){
1400 return 0; /* SELECT must have a FROM clause */
1401 }
1402 if( pSelect->pSrc->nSrc!=1 ){
1403 return 0; /* FROM clause must have exactly one term */
1404 }
1405 if( pSelect->pSrc->a[0].pSelect ){
1406 return 0; /* FROM clause cannot contain a subquery */
1407 }
1408 if( pSelect->pWhere ){
1409 return 0; /* SELECT may not have a WHERE clause */
1410 }
1411 if( pSelect->pOrderBy ){
1412 return 0; /* SELECT may not have an ORDER BY clause */
1413 }
drh8103b7d2007-02-24 13:23:51 +00001414 /* Do not need to test for a HAVING clause. If HAVING is present but
1415 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001416 if( pSelect->pGroupBy ){
1417 return 0; /* SELECT may not have a GROUP BY clause */
1418 }
1419 if( pSelect->pLimit ){
1420 return 0; /* SELECT may not have a LIMIT clause */
1421 }
drh8103b7d2007-02-24 13:23:51 +00001422 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001423 if( pSelect->pPrior ){
1424 return 0; /* SELECT may not be a compound query */
1425 }
1426 if( pSelect->isDistinct ){
1427 return 0; /* SELECT may not be DISTINCT */
1428 }
1429 pEList = pSelect->pEList;
1430 assert( pEList!=0 );
1431 if( pEList->nExpr!=1 ){
1432 return 0; /* The result set must have exactly one column */
1433 }
1434 assert( pEList->a[0].pExpr );
1435 if( pEList->a[0].pExpr->op!=TK_ALL ){
1436 return 0; /* The result set must be the special operator "*" */
1437 }
1438
1439 /* At this point we have established that the statement is of the
1440 ** correct syntactic form to participate in this optimization. Now
1441 ** we have to check the semantics.
1442 */
1443 pItem = pSelect->pSrc->a;
1444 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1445 if( pSrc==0 ){
1446 return 0; /* FROM clause does not contain a real table */
1447 }
1448 if( pSrc==pDest ){
1449 return 0; /* tab1 and tab2 may not be the same table */
1450 }
1451#ifndef SQLITE_OMIT_VIRTUALTABLE
1452 if( pSrc->isVirtual ){
1453 return 0; /* tab2 must not be a virtual table */
1454 }
1455#endif
1456 if( pSrc->pSelect ){
1457 return 0; /* tab2 may not be a view */
1458 }
1459 if( pDest->nCol!=pSrc->nCol ){
1460 return 0; /* Number of columns must be the same in tab1 and tab2 */
1461 }
1462 if( pDest->iPKey!=pSrc->iPKey ){
1463 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1464 }
1465 for(i=0; i<pDest->nCol; i++){
1466 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1467 return 0; /* Affinity must be the same on all columns */
1468 }
1469 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1470 return 0; /* Collating sequence must be the same on all columns */
1471 }
1472 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1473 return 0; /* tab2 must be NOT NULL if tab1 is */
1474 }
1475 }
1476 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1477 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1478 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1479 }
1480 if( pSrcIdx==0 ){
1481 return 0; /* pDestIdx has no corresponding index in pSrc */
1482 }
1483 }
drh7fc2f412007-03-29 00:08:24 +00001484#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001485 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001486 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1487 }
drh7fc2f412007-03-29 00:08:24 +00001488#endif
drh9d9cf222007-02-13 15:01:11 +00001489
1490 /* If we get this far, it means either:
1491 **
1492 ** * We can always do the transfer if the table contains an
1493 ** an integer primary key
1494 **
1495 ** * We can conditionally do the transfer if the destination
1496 ** table is empty.
1497 */
drhdd735212007-02-24 13:53:05 +00001498#ifdef SQLITE_TEST
1499 sqlite3_xferopt_count++;
1500#endif
drh9d9cf222007-02-13 15:01:11 +00001501 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1502 v = sqlite3GetVdbe(pParse);
1503 iSrc = pParse->nTab++;
1504 iDest = pParse->nTab++;
1505 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1506 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1507 if( pDest->iPKey<0 ){
1508 /* The tables do not have an INTEGER PRIMARY KEY so that
1509 ** transfer optimization is only allowed if the destination
1510 ** table is initially empty
1511 */
1512 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1513 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1514 sqlite3VdbeJumpHere(v, addr1);
1515 }else{
1516 emptyDestTest = 0;
1517 }
1518 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1519 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001520 if( pDest->pIndex!=0 ){
drh95bad4c2007-03-28 18:04:10 +00001521 sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001522 memRowid = pParse->nMem++;
1523 sqlite3VdbeAddOp(v, OP_MemStore, memRowid, pDest->iPKey>=0);
1524 }
1525 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
1526 if( pDest->iPKey>=0 ){
drh95bad4c2007-03-28 18:04:10 +00001527 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1528 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1529 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1530 "PRIMARY KEY must be unique", P3_STATIC);
1531 sqlite3VdbeJumpHere(v, addr2);
1532 autoIncStep(pParse, counterMem);
1533 }else{
drh42242de2007-03-29 13:35:35 +00001534 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001535 }
drh9d9cf222007-02-13 15:01:11 +00001536 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001537 sqlite3VdbeOp3(v, OP_Insert, iDest,
1538 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
drh9d9cf222007-02-13 15:01:11 +00001539 pDest->zName, 0);
1540 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1541 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1542 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1543 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1544 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1545 }
1546 assert( pSrcIdx );
1547 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1548 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1549 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1550 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1551 VdbeComment((v, "# %s", pSrcIdx->zName));
1552 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1553 (char*)pKey, P3_KEYINFO_HANDOFF);
1554 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1555 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1556 VdbeComment((v, "# %s", pDestIdx->zName));
1557 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1558 (char*)pKey, P3_KEYINFO_HANDOFF);
1559 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1560 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
1561 if( pDestIdx->onError!=OE_None ){
1562 sqlite3VdbeAddOp(v, OP_MemLoad, memRowid, 0);
1563 addr2 = sqlite3VdbeAddOp(v, OP_IsUnique, iDest, 0);
1564 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1565 "UNIQUE constraint failed", P3_STATIC);
1566 sqlite3VdbeJumpHere(v, addr2);
1567 }
drhe4d90812007-03-29 05:51:49 +00001568 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
drh9d9cf222007-02-13 15:01:11 +00001569 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1570 sqlite3VdbeJumpHere(v, addr1);
1571 }
1572 sqlite3VdbeJumpHere(v, emptySrcTest);
1573 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1574 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1575 if( emptyDestTest ){
1576 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1577 sqlite3VdbeJumpHere(v, emptyDestTest);
1578 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1579 return 0;
1580 }else{
1581 return 1;
1582 }
1583}
1584#endif /* SQLITE_OMIT_XFER_OPT */