blob: 3334c3661612f8758deab3a70735e3e61452877e [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**
danielk1977997a9042007-12-12 17:42:53 +000015** $Id: insert.c,v 1.195 2007/12/12 17:42:53 danielk1977 Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
19/*
danielk19773d1bfea2004-05-14 11:00:53 +000020** Set P3 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000021** string for index pIdx. A column affinity string has one character
danielk19773d1bfea2004-05-14 11:00:53 +000022** for each column in the table, according to the affinity of the column:
23**
24** Character Column affinity
25** ------------------------------
drh3eda0402005-11-24 13:15:32 +000026** 'a' TEXT
27** 'b' NONE
28** 'c' NUMERIC
29** 'd' INTEGER
30** 'e' REAL
danielk19773d1bfea2004-05-14 11:00:53 +000031*/
danielk1977a37cdde2004-05-16 11:15:36 +000032void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
33 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000034 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000035 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000036 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000037 **
38 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000039 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000040 ** up.
41 */
42 int n;
43 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000044 sqlite3 *db = sqlite3VdbeDb(v);
drh17435752007-08-16 04:30:38 +000045 pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
danielk1977a37cdde2004-05-16 11:15:36 +000046 if( !pIdx->zColAff ){
47 return;
48 }
49 for(n=0; n<pIdx->nColumn; n++){
50 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
51 }
52 pIdx->zColAff[pIdx->nColumn] = '\0';
53 }
danielk19773d1bfea2004-05-14 11:00:53 +000054
drh956bc922004-07-24 17:38:29 +000055 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000056}
57
58/*
59** Set P3 of the most recently inserted opcode to a column affinity
60** string for table pTab. A column affinity string has one character
61** for each column indexed by the index, according to the affinity of the
62** column:
63**
64** Character Column affinity
65** ------------------------------
drh3eda0402005-11-24 13:15:32 +000066** 'a' TEXT
67** 'b' NONE
68** 'c' NUMERIC
69** 'd' INTEGER
70** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000071*/
72void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000073 /* The first time a column affinity string for a particular table
74 ** is required, it is allocated and populated here. It is then
75 ** stored as a member of the Table structure for subsequent use.
76 **
77 ** The column affinity string will eventually be deleted by
78 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
79 */
80 if( !pTab->zColAff ){
81 char *zColAff;
82 int i;
drhabb6fca2007-08-16 12:24:01 +000083 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +000084
drh17435752007-08-16 04:30:38 +000085 zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000086 if( !zColAff ){
danielk1977a37cdde2004-05-16 11:15:36 +000087 return;
danielk19773d1bfea2004-05-14 11:00:53 +000088 }
89
90 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000091 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000092 }
93 zColAff[pTab->nCol] = '\0';
94
95 pTab->zColAff = zColAff;
96 }
97
drh956bc922004-07-24 17:38:29 +000098 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +000099}
100
danielk19774d887782005-02-08 08:42:27 +0000101/*
drh48d11782007-11-23 15:02:19 +0000102** Return non-zero if the table pTab in database iDb or any of its indices
103** have been opened at any point in the VDBE program beginning at location
104** iStartAddr throught the end of the program. This is used to see if
105** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
106** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000107*/
drh48d11782007-11-23 15:02:19 +0000108static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000109 int i;
drh48d11782007-11-23 15:02:19 +0000110 int iEnd = sqlite3VdbeCurrentAddr(v);
111 for(i=iStartAddr; i<iEnd; i++){
112 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
113 if( pOp->opcode==OP_OpenRead ){
114 VdbeOp *pPrior = &pOp[-1];
115 int tnum = pOp->p2;
116 assert( i>iStartAddr );
117 assert( pPrior->opcode==OP_Integer );
118 if( pPrior->p1==iDb ){
119 Index *pIndex;
120 if( tnum==pTab->tnum ){
121 return 1;
122 }
123 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
124 if( tnum==pIndex->tnum ){
125 return 1;
126 }
127 }
128 }
129 }
drh543165e2007-11-27 14:46:41 +0000130#ifndef SQLITE_OMIT_VIRTUALTABLE
drh48d11782007-11-23 15:02:19 +0000131 if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){
132 assert( pOp->p3!=0 );
133 assert( pOp->p3type==P3_VTAB );
134 return 1;
danielk19774d887782005-02-08 08:42:27 +0000135 }
drh543165e2007-11-27 14:46:41 +0000136#endif
danielk19774d887782005-02-08 08:42:27 +0000137 }
138 return 0;
139}
danielk19773d1bfea2004-05-14 11:00:53 +0000140
drh9d9cf222007-02-13 15:01:11 +0000141#ifndef SQLITE_OMIT_AUTOINCREMENT
142/*
143** Write out code to initialize the autoincrement logic. This code
144** looks up the current autoincrement value in the sqlite_sequence
145** table and stores that value in a memory cell. Code generated by
146** autoIncStep() will keep that memory cell holding the largest
147** rowid value. Code generated by autoIncEnd() will write the new
148** largest value of the counter back into the sqlite_sequence table.
149**
150** This routine returns the index of the mem[] cell that contains
151** the maximum rowid counter.
152**
153** Two memory cells are allocated. The next memory cell after the
154** one returned holds the rowid in sqlite_sequence where we will
155** write back the revised maximum rowid.
156*/
157static int autoIncBegin(
158 Parse *pParse, /* Parsing context */
159 int iDb, /* Index of the database holding pTab */
160 Table *pTab /* The table we are writing to */
161){
162 int memId = 0;
163 if( pTab->autoInc ){
164 Vdbe *v = pParse->pVdbe;
165 Db *pDb = &pParse->db->aDb[iDb];
166 int iCur = pParse->nTab;
167 int addr;
168 assert( v );
169 addr = sqlite3VdbeCurrentAddr(v);
170 memId = pParse->nMem+1;
171 pParse->nMem += 2;
172 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
173 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
174 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
175 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
176 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
177 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
178 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
179 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
180 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
181 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
182 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
183 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
184 }
185 return memId;
186}
187
188/*
189** Update the maximum rowid for an autoincrement calculation.
190**
191** This routine should be called when the top of the stack holds a
192** new rowid that is about to be inserted. If that new rowid is
193** larger than the maximum rowid in the memId memory cell, then the
194** memory cell is updated. The stack is unchanged.
195*/
196static void autoIncStep(Parse *pParse, int memId){
197 if( memId>0 ){
198 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
199 }
200}
201
202/*
203** After doing one or more inserts, the maximum rowid is stored
204** in mem[memId]. Generate code to write this value back into the
205** the sqlite_sequence table.
206*/
207static void autoIncEnd(
208 Parse *pParse, /* The parsing context */
209 int iDb, /* Index of the database holding pTab */
210 Table *pTab, /* Table we are inserting into */
211 int memId /* Memory cell holding the maximum rowid */
212){
213 if( pTab->autoInc ){
214 int iCur = pParse->nTab;
215 Vdbe *v = pParse->pVdbe;
216 Db *pDb = &pParse->db->aDb[iDb];
217 int addr;
218 assert( v );
219 addr = sqlite3VdbeCurrentAddr(v);
220 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
221 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
222 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
223 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
224 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
225 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
226 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
227 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
drhe4d90812007-03-29 05:51:49 +0000228 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
drh9d9cf222007-02-13 15:01:11 +0000229 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
230 }
231}
232#else
233/*
234** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
235** above are all no-ops
236*/
237# define autoIncBegin(A,B,C) (0)
238# define autoIncStep(A,B)
239# define autoIncEnd(A,B,C,D)
240#endif /* SQLITE_OMIT_AUTOINCREMENT */
241
242
243/* Forward declaration */
244static int xferOptimization(
245 Parse *pParse, /* Parser context */
246 Table *pDest, /* The table we are inserting into */
247 Select *pSelect, /* A SELECT statement to use as the data source */
248 int onError, /* How to handle constraint errors */
249 int iDbDest /* The database of pDest */
250);
251
danielk19773d1bfea2004-05-14 11:00:53 +0000252/*
drh1ccde152000-06-17 13:12:39 +0000253** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000254**
255** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000256** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000257**
drh1ccde152000-06-17 13:12:39 +0000258** The IDLIST following the table name is always optional. If omitted,
259** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000260** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000261**
262** The pList parameter holds EXPRLIST in the first form of the INSERT
263** statement above, and pSelect is NULL. For the second form, pList is
264** NULL and pSelect is a pointer to the select statement used to generate
265** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000266**
drh9d9cf222007-02-13 15:01:11 +0000267** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000268** select with data coming from a VALUES clause, the code executes
269** once straight down through. The template looks like this:
270**
271** open write cursor to <table> and its indices
272** puts VALUES clause expressions onto the stack
273** write the resulting record into <table>
274** cleanup
275**
drh9d9cf222007-02-13 15:01:11 +0000276** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000277**
278** INSERT INTO <table> SELECT ...
279**
drh9d9cf222007-02-13 15:01:11 +0000280** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
281** in other words if the SELECT pulls all columns from a single table
282** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
283** if <table2> and <table1> are distinct tables but have identical
284** schemas, including all the same indices, then a special optimization
285** is invoked that copies raw records from <table2> over to <table1>.
286** See the xferOptimization() function for the implementation of this
287** template. This is the second template.
288**
289** open a write cursor to <table>
290** open read cursor on <table2>
291** transfer all records in <table2> over to <table>
292** close cursors
293** foreach index on <table>
294** open a write cursor on the <table> index
295** open a read cursor on the corresponding <table2> index
296** transfer all records from the read to the write cursors
297** close cursors
298** end foreach
299**
300** The third template is for when the second template does not apply
301** and the SELECT clause does not read from <table> at any time.
302** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000303**
304** goto B
305** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000306** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000307** gosub C
308** end loop
309** cleanup after the SELECT
310** goto D
311** B: open write cursor to <table> and its indices
312** goto A
313** C: insert the select result into <table>
314** return
315** D: cleanup
316**
drh9d9cf222007-02-13 15:01:11 +0000317** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000318** values from a SELECT but the data is being inserted into a table
319** that is also read as part of the SELECT. In the third form,
320** we have to use a intermediate table to store the results of
321** the select. The template is like this:
322**
323** goto B
324** A: setup for the SELECT
325** loop over the tables in the SELECT
326** gosub C
327** end loop
328** cleanup after the SELECT
329** goto D
330** C: insert the select result into the intermediate table
331** return
332** B: open a cursor to an intermediate table
333** goto A
334** D: open write cursor to <table> and its indices
335** loop over the intermediate table
336** transfer values form intermediate table into <table>
337** end the loop
338** cleanup
drhcce7d172000-05-31 15:34:51 +0000339*/
danielk19774adee202004-05-08 08:23:19 +0000340void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000341 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000342 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000343 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000344 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000345 IdList *pColumn, /* Column names corresponding to IDLIST. */
346 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000347){
drh5974a302000-06-07 14:42:26 +0000348 Table *pTab; /* The table to insert into */
drh113088e2003-03-20 01:16:58 +0000349 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000350 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000351 int i, j, idx; /* Loop counters */
352 Vdbe *v; /* Generate code into this virtual machine */
353 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000354 int nColumn; /* Number of columns in the data */
danielk1977cfe9a692004-06-16 12:00:29 +0000355 int base = 0; /* VDBE Cursor number for pTab */
356 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
drh9bb575f2004-09-06 17:24:11 +0000357 sqlite3 *db; /* The main database structure */
drh4a324312001-12-21 14:30:42 +0000358 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000359 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000360 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000361 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
362 int iSelectLoop = 0; /* Address of code that implements the SELECT */
363 int iCleanup = 0; /* Address of the cleanup code */
364 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
365 int iCntMem = 0; /* Memory cell used for the row counter */
drh798da522004-11-04 04:42:28 +0000366 int newIdx = -1; /* Cursor for the NEW table */
drh2958a4e2004-11-12 03:56:15 +0000367 Db *pDb; /* The database containing table being inserted into */
368 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
drhe4d90812007-03-29 05:51:49 +0000369 int appendFlag = 0; /* True if the insert is likely to be an append */
danielk1977da184232006-01-05 11:34:32 +0000370 int iDb;
drhcce7d172000-05-31 15:34:51 +0000371
danielk1977034ca142007-06-26 10:38:54 +0000372 int nHidden = 0;
373
drh798da522004-11-04 04:42:28 +0000374#ifndef SQLITE_OMIT_TRIGGER
375 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000376 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000377#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000378
drh17435752007-08-16 04:30:38 +0000379 db = pParse->db;
380 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000381 goto insert_cleanup;
382 }
drhdaffd0e2001-04-11 14:28:42 +0000383
drh1ccde152000-06-17 13:12:39 +0000384 /* Locate the table into which we will be inserting new information.
385 */
drh113088e2003-03-20 01:16:58 +0000386 assert( pTabList->nSrc==1 );
387 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000388 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000389 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000390 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000391 goto insert_cleanup;
392 }
danielk1977da184232006-01-05 11:34:32 +0000393 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
394 assert( iDb<db->nDb );
395 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000396 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000397 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000398 goto insert_cleanup;
399 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000400
drhb7f91642004-10-31 02:22:47 +0000401 /* Figure out if we have any triggers and if the table being
402 ** inserted into is a view
403 */
404#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000405 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000406 isView = pTab->pSelect!=0;
407#else
drhdca76842004-12-07 14:06:13 +0000408# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000409# define isView 0
410#endif
411#ifdef SQLITE_OMIT_VIEW
412# undef isView
413# define isView 0
414#endif
415
danielk1977c3f9bad2002-05-15 08:30:12 +0000416 /* Ensure that:
417 * (a) the table is not read-only,
418 * (b) that if it is a view then ON INSERT triggers exist
419 */
drhdca76842004-12-07 14:06:13 +0000420 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000421 goto insert_cleanup;
422 }
drh43617e92006-03-06 20:55:46 +0000423 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000424
drhf573c992002-07-31 00:32:50 +0000425 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000426 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
427 ** module table).
drhf573c992002-07-31 00:32:50 +0000428 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000429 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000430 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000431 }
432
drh1ccde152000-06-17 13:12:39 +0000433 /* Allocate a VDBE
434 */
danielk19774adee202004-05-08 08:23:19 +0000435 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000436 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000437 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000438 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000439
danielk1977c3f9bad2002-05-15 08:30:12 +0000440 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000441 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000442 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000443 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000444
drh9d9cf222007-02-13 15:01:11 +0000445#ifndef SQLITE_OMIT_XFER_OPT
446 /* If the statement is of the form
447 **
448 ** INSERT INTO <table1> SELECT * FROM <table2>;
449 **
450 ** Then special optimizations can be applied that make the transfer
451 ** very fast and which reduce fragmentation of indices.
452 */
453 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
454 assert( !triggers_exist );
455 assert( pList==0 );
456 goto insert_cleanup;
457 }
458#endif /* SQLITE_OMIT_XFER_OPT */
459
drh2958a4e2004-11-12 03:56:15 +0000460 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000461 ** sqlite_sequence table and store it in memory cell counterMem. Also
462 ** remember the rowid of the sqlite_sequence table entry in memory cell
463 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000464 */
drh9d9cf222007-02-13 15:01:11 +0000465 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000466
drh1ccde152000-06-17 13:12:39 +0000467 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000468 ** is coming from a SELECT statement, then this step also generates
469 ** all the code to implement the SELECT statement and invoke a subroutine
470 ** to process each row of the result. (Template 2.) If the SELECT
471 ** statement uses the the table that is being inserted into, then the
472 ** subroutine is also coded here. That subroutine stores the SELECT
473 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000474 */
drh5974a302000-06-07 14:42:26 +0000475 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000476 /* Data is coming from a SELECT. Generate code to implement that SELECT
477 */
478 int rc, iInitCode;
danielk19774adee202004-05-08 08:23:19 +0000479 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
480 iSelectLoop = sqlite3VdbeCurrentAddr(v);
481 iInsertBlock = sqlite3VdbeMakeLabel(v);
danielk1977b3bce662005-01-29 08:32:43 +0000482
483 /* Resolve the expressions in the SELECT statement and execute it. */
484 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
drh17435752007-08-16 04:30:38 +0000485 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000486 goto insert_cleanup;
487 }
danielk1977b3bce662005-01-29 08:32:43 +0000488
danielk19774adee202004-05-08 08:23:19 +0000489 iCleanup = sqlite3VdbeMakeLabel(v);
490 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000491 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000492 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000493
494 /* Set useTempTable to TRUE if the result of the SELECT statement
495 ** should be written into a temporary table. Set to FALSE if each
496 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000497 **
498 ** A temp table must be used if the table being updated is also one
499 ** of the tables being read by the SELECT statement. Also use a
500 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000501 */
drh48d11782007-11-23 15:02:19 +0000502 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000503 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000504 }
drh142e30d2002-08-28 03:00:58 +0000505
506 if( useTempTable ){
507 /* Generate the subroutine that SELECT calls to process each row of
508 ** the result. Store the result in a temporary table
509 */
510 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000511 sqlite3VdbeResolveLabel(v, iInsertBlock);
danielk1977997a9042007-12-12 17:42:53 +0000512 sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000513 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf0863fe2005-06-12 21:35:51 +0000514 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
danielk19774adee202004-05-08 08:23:19 +0000515 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhe4d90812007-03-29 05:51:49 +0000516 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
danielk19774adee202004-05-08 08:23:19 +0000517 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000518
519 /* The following code runs first because the GOTO at the very top
520 ** of the program jumps to it. Create the temporary table, then jump
521 ** back up and execute the SELECT code above.
522 */
drhd654be82005-09-20 17:42:23 +0000523 sqlite3VdbeJumpHere(v, iInitCode);
drhb9bb7c12006-06-11 23:41:55 +0000524 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
drhb6f54522004-05-20 02:42:16 +0000525 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
danielk19774adee202004-05-08 08:23:19 +0000526 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
527 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000528 }else{
drhd654be82005-09-20 17:42:23 +0000529 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000530 }
drh5974a302000-06-07 14:42:26 +0000531 }else{
drh142e30d2002-08-28 03:00:58 +0000532 /* This is the case if the data for the INSERT is coming from a VALUES
533 ** clause
534 */
danielk1977b3bce662005-01-29 08:32:43 +0000535 NameContext sNC;
536 memset(&sNC, 0, sizeof(sNC));
537 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000538 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000539 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000540 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000541 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000542 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000543 goto insert_cleanup;
544 }
drhe64e7b22002-02-18 13:56:36 +0000545 }
drh5974a302000-06-07 14:42:26 +0000546 }
drh1ccde152000-06-17 13:12:39 +0000547
548 /* Make sure the number of columns in the source data matches the number
549 ** of columns to be inserted into the table.
550 */
danielk1977034ca142007-06-26 10:38:54 +0000551 if( IsVirtual(pTab) ){
552 for(i=0; i<pTab->nCol; i++){
553 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
554 }
555 }
556 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000557 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000558 "table %S has %d columns but %d values were supplied",
559 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000560 goto insert_cleanup;
561 }
drh967e8b72000-06-21 13:59:10 +0000562 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000563 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000564 goto insert_cleanup;
565 }
drh1ccde152000-06-17 13:12:39 +0000566
567 /* If the INSERT statement included an IDLIST term, then make sure
568 ** all elements of the IDLIST really are columns of the table and
569 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000570 **
571 ** If the table has an INTEGER PRIMARY KEY column and that column
572 ** is named in the IDLIST, then record in the keyColumn variable
573 ** the index into IDLIST of the primary key column. keyColumn is
574 ** the index of the primary key as it appears in IDLIST, not as
575 ** is appears in the original table. (The index of the primary
576 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000577 */
drh967e8b72000-06-21 13:59:10 +0000578 if( pColumn ){
579 for(i=0; i<pColumn->nId; i++){
580 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000581 }
drh967e8b72000-06-21 13:59:10 +0000582 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000583 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000584 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000585 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000586 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000587 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000588 }
drhcce7d172000-05-31 15:34:51 +0000589 break;
590 }
591 }
592 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000593 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000594 keyColumn = i;
595 }else{
danielk19774adee202004-05-08 08:23:19 +0000596 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000597 pTabList, 0, pColumn->a[i].zName);
598 pParse->nErr++;
599 goto insert_cleanup;
600 }
drhcce7d172000-05-31 15:34:51 +0000601 }
602 }
603 }
drh1ccde152000-06-17 13:12:39 +0000604
drhaacc5432002-01-06 17:07:40 +0000605 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000606 ** key, the set the keyColumn variable to the primary key column index
607 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000608 */
drh147d0cc2006-08-25 23:42:53 +0000609 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000610 keyColumn = pTab->iPKey;
611 }
612
drh142e30d2002-08-28 03:00:58 +0000613 /* Open the temp table for FOR EACH ROW triggers
614 */
drhdca76842004-12-07 14:06:13 +0000615 if( triggers_exist ){
danielk19774adee202004-05-08 08:23:19 +0000616 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
danielk197784ac9d02004-05-18 09:58:06 +0000617 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000618 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000619
drhfeeb1392002-04-09 03:28:01 +0000620 /* Initialize the count of rows to be inserted
621 */
drh142e30d2002-08-28 03:00:58 +0000622 if( db->flags & SQLITE_CountRows ){
623 iCntMem = pParse->nMem++;
drhd654be82005-09-20 17:42:23 +0000624 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000625 }
626
danielk1977c3f9bad2002-05-15 08:30:12 +0000627 /* Open tables and indices if there are no row triggers */
drhdca76842004-12-07 14:06:13 +0000628 if( !triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000629 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000630 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000631 }
632
drh142e30d2002-08-28 03:00:58 +0000633 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000634 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000635 ** source is a subroutine call from the SELECT statement, then we need
636 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000637 */
drh142e30d2002-08-28 03:00:58 +0000638 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000639 iBreak = sqlite3VdbeMakeLabel(v);
640 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
641 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000642 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000643 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
644 sqlite3VdbeResolveLabel(v, iInsertBlock);
danielk1977997a9042007-12-12 17:42:53 +0000645 sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000646 }
drh1ccde152000-06-17 13:12:39 +0000647
drh5cf590c2003-04-24 01:45:04 +0000648 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000649 */
danielk19774adee202004-05-08 08:23:19 +0000650 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000651 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000652
drh70ce3f02003-04-15 19:22:22 +0000653 /* build the NEW.* reference row. Note that if there is an INTEGER
654 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
655 ** translated into a unique ID for the row. But on a BEFORE trigger,
656 ** we do not know what the unique ID will be (because the insert has
657 ** not happened yet) so we substitute a rowid of -1
658 */
659 if( keyColumn<0 ){
danielk19774adee202004-05-08 08:23:19 +0000660 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000661 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000662 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000663 }else{
drhd6fe9612005-01-14 01:22:00 +0000664 assert( pSelect==0 ); /* Otherwise useTempTable is true */
danielk19774adee202004-05-08 08:23:19 +0000665 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
666 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
667 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
668 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
669 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000670 }
671
danielk1977034ca142007-06-26 10:38:54 +0000672 /* Cannot have triggers on a virtual table. If it were possible,
673 ** this block would have to account for hidden column.
674 */
675 assert(!IsVirtual(pTab));
676
drh70ce3f02003-04-15 19:22:22 +0000677 /* Create the new column data
678 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000679 for(i=0; i<pTab->nCol; i++){
680 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000681 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000682 }else{
drh9adf9ac2002-05-15 11:44:13 +0000683 for(j=0; j<pColumn->nId; j++){
684 if( pColumn->a[j].idx==i ) break;
685 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000686 }
687 if( pColumn && j>=pColumn->nId ){
danielk19777977a172004-11-09 12:44:37 +0000688 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000689 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000690 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000691 }else{
drhd6fe9612005-01-14 01:22:00 +0000692 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000693 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000694 }
695 }
danielk19774adee202004-05-08 08:23:19 +0000696 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000697
698 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
699 ** do not attempt any conversions before assembling the record.
700 ** If this is a real table, attempt conversions as required by the
701 ** table column affinities.
702 */
703 if( !isView ){
704 sqlite3TableAffinityStr(v, pTab);
705 }
drhf0863fe2005-06-12 21:35:51 +0000706 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000707
drh5cf590c2003-04-24 01:45:04 +0000708 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000709 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
drhb2fe7d82003-04-20 17:29:23 +0000710 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000711 goto insert_cleanup;
712 }
drh70ce3f02003-04-15 19:22:22 +0000713 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000714
drh70ce3f02003-04-15 19:22:22 +0000715 /* If any triggers exists, the opening of tables and indices is deferred
716 ** until now.
717 */
drhdca76842004-12-07 14:06:13 +0000718 if( triggers_exist && !isView ){
drh5cf590c2003-04-24 01:45:04 +0000719 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000720 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000721 }
722
drh4a324312001-12-21 14:30:42 +0000723 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000724 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000725 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000726 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000727 */
drh5cf590c2003-04-24 01:45:04 +0000728 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000729 if( IsVirtual(pTab) ){
730 /* The row that the VUpdate opcode will delete: none */
731 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
732 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000733 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000734 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000735 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
drh142e30d2002-08-28 03:00:58 +0000736 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000737 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000738 }else{
drhe4d90812007-03-29 05:51:49 +0000739 VdbeOp *pOp;
danielk19774adee202004-05-08 08:23:19 +0000740 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
drhe4d90812007-03-29 05:51:49 +0000741 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000742 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000743 appendFlag = 1;
744 pOp->opcode = OP_NewRowid;
745 pOp->p1 = base;
746 pOp->p2 = counterMem;
747 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000748 }
drhf0863fe2005-06-12 21:35:51 +0000749 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000750 ** to generate a unique primary key value.
751 */
drhe4d90812007-03-29 05:51:49 +0000752 if( !appendFlag ){
753 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
754 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
755 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
756 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
757 }
drh4cbdda92006-06-14 19:00:20 +0000758 }else if( IsVirtual(pTab) ){
759 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000760 }else{
drhf0863fe2005-06-12 21:35:51 +0000761 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
drhe4d90812007-03-29 05:51:49 +0000762 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000763 }
drh9d9cf222007-02-13 15:01:11 +0000764 autoIncStep(pParse, counterMem);
drh4a324312001-12-21 14:30:42 +0000765
danielk1977c3f9bad2002-05-15 08:30:12 +0000766 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000767 ** with the first column.
768 */
danielk1977034ca142007-06-26 10:38:54 +0000769 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000770 for(i=0; i<pTab->nCol; i++){
771 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000772 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000773 ** Whenever this column is read, the record number will be substituted
774 ** in its place. So will fill this column with a NULL to avoid
775 ** taking up data space with information that will never be used. */
drhf0863fe2005-06-12 21:35:51 +0000776 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh9adf9ac2002-05-15 11:44:13 +0000777 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000778 }
779 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000780 if( IsHiddenColumn(&pTab->aCol[i]) ){
781 assert( IsVirtual(pTab) );
782 j = -1;
783 nHidden++;
784 }else{
785 j = i - nHidden;
786 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000787 }else{
drh9adf9ac2002-05-15 11:44:13 +0000788 for(j=0; j<pColumn->nId; j++){
789 if( pColumn->a[j].idx==i ) break;
790 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000791 }
danielk1977034ca142007-06-26 10:38:54 +0000792 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk19777977a172004-11-09 12:44:37 +0000793 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
drh142e30d2002-08-28 03:00:58 +0000794 }else if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000795 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
drh142e30d2002-08-28 03:00:58 +0000796 }else if( pSelect ){
drh16ed8a62006-08-29 18:46:14 +0000797 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
danielk1977c3f9bad2002-05-15 08:30:12 +0000798 }else{
danielk19774adee202004-05-08 08:23:19 +0000799 sqlite3ExprCode(pParse, pList->a[j].pExpr);
drh5974a302000-06-07 14:42:26 +0000800 }
drhbed86902000-06-02 13:27:59 +0000801 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000802
803 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000804 ** do the insertion.
805 */
drh4cbdda92006-06-14 19:00:20 +0000806#ifndef SQLITE_OMIT_VIRTUALTABLE
807 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000808 pParse->pVirtualLock = pTab;
danielk19771f6eec52006-06-16 06:17:47 +0000809 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
drh4cbdda92006-06-14 19:00:20 +0000810 (const char*)pTab->pVtab, P3_VTAB);
811 }else
812#endif
813 {
814 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
815 0, onError, endOfLoop);
816 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000817 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
818 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000819 }
drh5cf590c2003-04-24 01:45:04 +0000820 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000821
drh5cf590c2003-04-24 01:45:04 +0000822 /* Update the count of rows that are inserted
823 */
824 if( (db->flags & SQLITE_CountRows)!=0 ){
drh15007a92006-01-08 18:10:17 +0000825 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
drh5974a302000-06-07 14:42:26 +0000826 }
drh1ccde152000-06-17 13:12:39 +0000827
drhdca76842004-12-07 14:06:13 +0000828 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000829 /* Close all tables opened */
drh5cf590c2003-04-24 01:45:04 +0000830 if( !isView ){
danielk19774adee202004-05-08 08:23:19 +0000831 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000832 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000833 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000834 }
835 }
drh1bee3d72001-10-15 00:44:35 +0000836
danielk1977c3f9bad2002-05-15 08:30:12 +0000837 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000838 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
839 newIdx, -1, onError, endOfLoop) ){
danielk1977f29ce552002-05-19 23:43:12 +0000840 goto insert_cleanup;
841 }
drh1bee3d72001-10-15 00:44:35 +0000842 }
843
drh1ccde152000-06-17 13:12:39 +0000844 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000845 */
danielk19774adee202004-05-08 08:23:19 +0000846 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000847 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000848 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
849 sqlite3VdbeResolveLabel(v, iBreak);
850 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000851 }else if( pSelect ){
danielk19774adee202004-05-08 08:23:19 +0000852 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
853 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
854 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000855 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000856
drh4cbdda92006-06-14 19:00:20 +0000857 if( !triggers_exist && !IsVirtual(pTab) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000858 /* Close all tables opened */
danielk19774adee202004-05-08 08:23:19 +0000859 sqlite3VdbeAddOp(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000860 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
danielk19774adee202004-05-08 08:23:19 +0000861 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000862 }
drhcce7d172000-05-31 15:34:51 +0000863 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000864
drhf3388142004-11-13 03:48:06 +0000865 /* Update the sqlite_sequence table by storing the content of the
866 ** counter value in memory counterMem back into the sqlite_sequence
867 ** table.
drh2958a4e2004-11-12 03:56:15 +0000868 */
drh9d9cf222007-02-13 15:01:11 +0000869 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000870
drh1bee3d72001-10-15 00:44:35 +0000871 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000872 ** Return the number of rows inserted. If this routine is
873 ** generating code because of a call to sqlite3NestedParse(), do not
874 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000875 */
danielk1977cc6bd382005-01-10 02:48:49 +0000876 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +0000877 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
878 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
danielk197722322fd2004-05-25 23:35:17 +0000879 sqlite3VdbeSetNumCols(v, 1);
danielk1977955de522006-02-10 02:27:42 +0000880 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000881 }
drhcce7d172000-05-31 15:34:51 +0000882
883insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000884 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000885 sqlite3ExprListDelete(pList);
886 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000887 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000888}
drh9cfcf5d2002-01-29 18:41:24 +0000889
drh9cfcf5d2002-01-29 18:41:24 +0000890/*
891** Generate code to do a constraint check prior to an INSERT or an UPDATE.
892**
893** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000894** the following values:
895**
drhf0863fe2005-06-12 21:35:51 +0000896** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000897** value is omitted unless we are doing an UPDATE that involves a
898** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000899**
drhf0863fe2005-06-12 21:35:51 +0000900** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000901**
902** 3. The data in the first column of the entry after the update.
903**
904** i. Data from middle columns...
905**
906** N. The data in the last column of the entry after the update.
907**
drhf0863fe2005-06-12 21:35:51 +0000908** The old rowid shown as entry (1) above is omitted unless both isUpdate
909** and rowidChng are 1. isUpdate is true for UPDATEs and false for
910** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000911**
912** The code generated by this routine pushes additional entries onto
913** the stack which are the keys for new index entries for the new record.
914** The order of index keys is the same as the order of the indices on
915** the pTable->pIndex list. A key is only created for index i if
916** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000917**
918** This routine also generates code to check constraints. NOT NULL,
919** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000920** then the appropriate action is performed. There are five possible
921** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000922**
923** Constraint type Action What Happens
924** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000925** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000926** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000927** return code of SQLITE_CONSTRAINT.
928**
drh1c928532002-01-31 15:54:21 +0000929** any ABORT Back out changes from the current command
930** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000931** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000932** with SQLITE_CONSTRAINT.
933**
934** any FAIL Sqlite_exec() returns immediately with a
935** return code of SQLITE_CONSTRAINT. The
936** transaction is not rolled back and any
937** prior changes are retained.
938**
drh9cfcf5d2002-01-29 18:41:24 +0000939** any IGNORE The record number and data is popped from
940** the stack and there is an immediate jump
941** to label ignoreDest.
942**
943** NOT NULL REPLACE The NULL value is replace by the default
944** value for that column. If the default value
945** is NULL, the action is the same as ABORT.
946**
947** UNIQUE REPLACE The other row that conflicts with the row
948** being inserted is removed.
949**
950** CHECK REPLACE Illegal. The results in an exception.
951**
drh1c928532002-01-31 15:54:21 +0000952** Which action to take is determined by the overrideError parameter.
953** Or if overrideError==OE_Default, then the pParse->onError parameter
954** is used. Or if pParse->onError==OE_Default then the onError value
955** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000956**
drhaaab5722002-02-19 13:39:21 +0000957** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000958** cursor number "base". All indices of pTab must also have open
959** read/write cursors with cursor number base+i for the i-th cursor.
960** Except, if there is no possibility of a REPLACE action then
961** cursors do not need to be open for indices where aIdxUsed[i]==0.
962**
963** If the isUpdate flag is true, it means that the "base" cursor is
964** initially pointing to an entry that is being updated. The isUpdate
965** flag causes extra code to be generated so that the "base" cursor
966** is still pointing at the same entry after the routine returns.
967** Without the isUpdate flag, the "base" cursor might be moved.
968*/
danielk19774adee202004-05-08 08:23:19 +0000969void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000970 Parse *pParse, /* The parser context */
971 Table *pTab, /* the table into which we are inserting */
972 int base, /* Index of a read/write cursor pointing at pTab */
973 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000974 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000975 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000976 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000977 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000978){
979 int i;
980 Vdbe *v;
981 int nCol;
982 int onError;
983 int addr;
984 int extra;
drh0ca3e242002-01-29 23:07:02 +0000985 int iCur;
986 Index *pIdx;
987 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000988 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000989 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000990
danielk19774adee202004-05-08 08:23:19 +0000991 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000992 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000993 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000994 nCol = pTab->nCol;
995
996 /* Test all NOT NULL constraints.
997 */
998 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000999 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001000 continue;
1001 }
drh9cfcf5d2002-01-29 18:41:24 +00001002 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001003 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001004 if( overrideError!=OE_Default ){
1005 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001006 }else if( onError==OE_Default ){
1007 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001008 }
danielk19777977a172004-11-09 12:44:37 +00001009 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001010 onError = OE_Abort;
1011 }
danielk19774adee202004-05-08 08:23:19 +00001012 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
1013 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +00001014 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1015 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001016 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001017 case OE_Rollback:
1018 case OE_Abort:
1019 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001020 char *zMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00001021 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1022 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001023 " may not be NULL", (char*)0);
danielk19774adee202004-05-08 08:23:19 +00001024 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001025 break;
1026 }
1027 case OE_Ignore: {
drhf0863fe2005-06-12 21:35:51 +00001028 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001029 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001030 break;
1031 }
1032 case OE_Replace: {
danielk19777977a172004-11-09 12:44:37 +00001033 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
danielk19774adee202004-05-08 08:23:19 +00001034 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001035 break;
1036 }
drh9cfcf5d2002-01-29 18:41:24 +00001037 }
drhd654be82005-09-20 17:42:23 +00001038 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001039 }
1040
1041 /* Test all CHECK constraints
1042 */
drhffe07b22005-11-03 00:41:17 +00001043#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001044 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001045 int allOk = sqlite3VdbeMakeLabel(v);
1046 assert( pParse->ckOffset==0 );
1047 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001048 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001049 assert( pParse->ckOffset==nCol );
1050 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001051 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001052 if( onError==OE_Ignore ){
drhaa01c7e2006-03-15 16:26:10 +00001053 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1054 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1055 }else{
1056 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1057 }
drhffe07b22005-11-03 00:41:17 +00001058 sqlite3VdbeResolveLabel(v, allOk);
1059 }
1060#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001061
drh0bd1f4e2002-06-06 18:54:39 +00001062 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1063 ** of the new record does not previously exist. Except, if this
1064 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001065 */
drhf0863fe2005-06-12 21:35:51 +00001066 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001067 onError = pTab->keyConf;
1068 if( overrideError!=OE_Default ){
1069 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001070 }else if( onError==OE_Default ){
1071 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001072 }
drha0217ba2003-06-01 01:10:33 +00001073
drh5383ae52003-06-04 12:23:30 +00001074 if( isUpdate ){
danielk19774adee202004-05-08 08:23:19 +00001075 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1076 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1077 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001078 }
danielk19774adee202004-05-08 08:23:19 +00001079 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1080 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001081 switch( onError ){
1082 default: {
1083 onError = OE_Abort;
1084 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001085 }
drh5383ae52003-06-04 12:23:30 +00001086 case OE_Rollback:
1087 case OE_Abort:
1088 case OE_Fail: {
danielk19774adee202004-05-08 08:23:19 +00001089 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
drh701a0ae2004-02-22 20:05:00 +00001090 "PRIMARY KEY must be unique", P3_STATIC);
drh5383ae52003-06-04 12:23:30 +00001091 break;
drh0ca3e242002-01-29 23:07:02 +00001092 }
drh5383ae52003-06-04 12:23:30 +00001093 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001094 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001095 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001096 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001097 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001098 }
1099 seenReplace = 1;
1100 break;
drh0ca3e242002-01-29 23:07:02 +00001101 }
drh5383ae52003-06-04 12:23:30 +00001102 case OE_Ignore: {
1103 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001104 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001105 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001106 break;
1107 }
1108 }
drhd654be82005-09-20 17:42:23 +00001109 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001110 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001111 sqlite3VdbeJumpHere(v, jumpInst1);
danielk19774adee202004-05-08 08:23:19 +00001112 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001113 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001114 }
1115 }
drh0bd1f4e2002-06-06 18:54:39 +00001116
1117 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1118 ** index and making sure that duplicate entries do not already exist.
1119 ** Add the new records to the indices as we go.
1120 */
drhb2fe7d82003-04-20 17:29:23 +00001121 extra = -1;
1122 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1123 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1124 extra++;
1125
1126 /* Create a key for accessing the index entry */
danielk19774adee202004-05-08 08:23:19 +00001127 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001128 for(i=0; i<pIdx->nColumn; i++){
1129 int idx = pIdx->aiColumn[i];
1130 if( idx==pTab->iPKey ){
danielk19774adee202004-05-08 08:23:19 +00001131 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001132 }else{
danielk19774adee202004-05-08 08:23:19 +00001133 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
drh9cfcf5d2002-01-29 18:41:24 +00001134 }
1135 }
drh7f057c92005-06-24 03:53:06 +00001136 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001137 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001138
1139 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001140 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001141 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001142 if( overrideError!=OE_Default ){
1143 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001144 }else if( onError==OE_Default ){
1145 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001146 }
drh5383ae52003-06-04 12:23:30 +00001147 if( seenReplace ){
1148 if( onError==OE_Ignore ) onError = OE_Replace;
1149 else if( onError==OE_Fail ) onError = OE_Abort;
1150 }
1151
drhb2fe7d82003-04-20 17:29:23 +00001152
1153 /* Check to see if the new index entry will be unique */
drhf0863fe2005-06-12 21:35:51 +00001154 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
danielk19774adee202004-05-08 08:23:19 +00001155 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001156
1157 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001158 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1159 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001160 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001161 case OE_Rollback:
1162 case OE_Abort:
1163 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001164 int j, n1, n2;
1165 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001166 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1167 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001168 n1 = strlen(zErrMsg);
1169 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1170 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1171 n2 = strlen(zCol);
1172 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001173 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001174 n1 += 2;
1175 }
1176 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001177 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001178 n1 += 3;
1179 break;
1180 }else{
drh5bb3eb92007-05-04 13:15:55 +00001181 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001182 n1 += n2;
1183 }
1184 }
drh5bb3eb92007-05-04 13:15:55 +00001185 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001186 pIdx->nColumn>1 ? " are not unique" : " is not unique");
danielk19774adee202004-05-08 08:23:19 +00001187 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001188 break;
1189 }
1190 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001191 assert( seenReplace==0 );
drhf0863fe2005-06-12 21:35:51 +00001192 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
danielk19774adee202004-05-08 08:23:19 +00001193 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001194 break;
1195 }
1196 case OE_Replace: {
danielk19774adee202004-05-08 08:23:19 +00001197 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001198 if( isUpdate ){
drhf0863fe2005-06-12 21:35:51 +00001199 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
drh7cf6e4d2004-05-19 14:56:55 +00001200 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001201 }
drh0ca3e242002-01-29 23:07:02 +00001202 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001203 break;
1204 }
drh9cfcf5d2002-01-29 18:41:24 +00001205 }
drh0bd1f4e2002-06-06 18:54:39 +00001206#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001207 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001208#endif
drhd654be82005-09-20 17:42:23 +00001209 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001210 }
1211}
drh0ca3e242002-01-29 23:07:02 +00001212
1213/*
1214** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001215** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001216** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001217** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001218** entries in all indices and in the main table.
1219**
drhb419a922002-01-30 16:17:23 +00001220** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001221** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001222*/
danielk19774adee202004-05-08 08:23:19 +00001223void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001224 Parse *pParse, /* The parser context */
1225 Table *pTab, /* the table into which we are inserting */
1226 int base, /* Index of a read/write cursor pointing at pTab */
1227 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001228 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001229 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001230 int newIdx, /* Index of NEW table for triggers. -1 if none */
1231 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001232){
1233 int i;
1234 Vdbe *v;
1235 int nIdx;
1236 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001237 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001238
danielk19774adee202004-05-08 08:23:19 +00001239 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001240 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001241 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001242 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1243 for(i=nIdx-1; i>=0; i--){
1244 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drhf0863fe2005-06-12 21:35:51 +00001245 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001246 }
danielk19774adee202004-05-08 08:23:19 +00001247 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001248 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001249#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001250 if( newIdx>=0 ){
danielk19774adee202004-05-08 08:23:19 +00001251 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1252 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhf0863fe2005-06-12 21:35:51 +00001253 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001254 }
danielk1977b84f96f2005-01-20 11:32:23 +00001255#endif
drh4794f732004-11-05 17:17:50 +00001256 if( pParse->nested ){
1257 pik_flags = 0;
1258 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001259 pik_flags = OPFLAG_NCHANGE;
1260 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001261 }
drhe4d90812007-03-29 05:51:49 +00001262 if( appendBias ){
1263 pik_flags |= OPFLAG_APPEND;
1264 }
drhf0863fe2005-06-12 21:35:51 +00001265 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001266 if( !pParse->nested ){
1267 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1268 }
danielk1977b28af712004-06-21 06:50:26 +00001269
drhf0863fe2005-06-12 21:35:51 +00001270 if( isUpdate && rowidChng ){
danielk19774adee202004-05-08 08:23:19 +00001271 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001272 }
1273}
drhcd446902004-02-24 01:05:31 +00001274
1275/*
drh290c1942004-08-21 17:54:45 +00001276** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001277** indices of that table. The "base" parameter is the cursor number used
1278** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001279*/
drh290c1942004-08-21 17:54:45 +00001280void sqlite3OpenTableAndIndices(
1281 Parse *pParse, /* Parsing context */
1282 Table *pTab, /* Table to be opened */
1283 int base, /* Cursor number assigned to the table */
1284 int op /* OP_OpenRead or OP_OpenWrite */
1285){
drhcd446902004-02-24 01:05:31 +00001286 int i;
drh4cbdda92006-06-14 19:00:20 +00001287 int iDb;
drhcd446902004-02-24 01:05:31 +00001288 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001289 Vdbe *v;
1290
1291 if( IsVirtual(pTab) ) return;
1292 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1293 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001294 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001295 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001296 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001297 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001298 assert( pIdx->pSchema==pTab->pSchema );
1299 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drh29dda4a2005-07-21 18:23:20 +00001300 VdbeComment((v, "# %s", pIdx->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00001301 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
drhcd446902004-02-24 01:05:31 +00001302 }
drh290c1942004-08-21 17:54:45 +00001303 if( pParse->nTab<=base+i ){
1304 pParse->nTab = base+i;
1305 }
drhcd446902004-02-24 01:05:31 +00001306}
drh9d9cf222007-02-13 15:01:11 +00001307
drh91c58e22007-03-27 12:04:04 +00001308
1309#ifdef SQLITE_TEST
1310/*
1311** The following global variable is incremented whenever the
1312** transfer optimization is used. This is used for testing
1313** purposes only - to make sure the transfer optimization really
1314** is happening when it is suppose to.
1315*/
1316int sqlite3_xferopt_count;
1317#endif /* SQLITE_TEST */
1318
1319
drh9d9cf222007-02-13 15:01:11 +00001320#ifndef SQLITE_OMIT_XFER_OPT
1321/*
1322** Check to collation names to see if they are compatible.
1323*/
1324static int xferCompatibleCollation(const char *z1, const char *z2){
1325 if( z1==0 ){
1326 return z2==0;
1327 }
1328 if( z2==0 ){
1329 return 0;
1330 }
1331 return sqlite3StrICmp(z1, z2)==0;
1332}
1333
1334
1335/*
1336** Check to see if index pSrc is compatible as a source of data
1337** for index pDest in an insert transfer optimization. The rules
1338** for a compatible index:
1339**
1340** * The index is over the same set of columns
1341** * The same DESC and ASC markings occurs on all columns
1342** * The same onError processing (OE_Abort, OE_Ignore, etc)
1343** * The same collating sequence on each column
1344*/
1345static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1346 int i;
1347 assert( pDest && pSrc );
1348 assert( pDest->pTable!=pSrc->pTable );
1349 if( pDest->nColumn!=pSrc->nColumn ){
1350 return 0; /* Different number of columns */
1351 }
1352 if( pDest->onError!=pSrc->onError ){
1353 return 0; /* Different conflict resolution strategies */
1354 }
1355 for(i=0; i<pSrc->nColumn; i++){
1356 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1357 return 0; /* Different columns indexed */
1358 }
1359 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1360 return 0; /* Different sort orders */
1361 }
1362 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1363 return 0; /* Different sort orders */
1364 }
1365 }
1366
1367 /* If no test above fails then the indices must be compatible */
1368 return 1;
1369}
1370
1371/*
1372** Attempt the transfer optimization on INSERTs of the form
1373**
1374** INSERT INTO tab1 SELECT * FROM tab2;
1375**
1376** This optimization is only attempted if
1377**
1378** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001379** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001380**
1381** (2) tab1 and tab2 are different tables
1382**
1383** (3) There must be no triggers on tab1
1384**
1385** (4) The result set of the SELECT statement is "*"
1386**
1387** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1388** or LIMIT clause.
1389**
1390** (6) The SELECT statement is a simple (not a compound) select that
1391** contains only tab2 in its FROM clause
1392**
1393** This method for implementing the INSERT transfers raw records from
1394** tab2 over to tab1. The columns are not decoded. Raw records from
1395** the indices of tab2 are transfered to tab1 as well. In so doing,
1396** the resulting tab1 has much less fragmentation.
1397**
1398** This routine returns TRUE if the optimization is attempted. If any
1399** of the conditions above fail so that the optimization should not
1400** be attempted, then this routine returns FALSE.
1401*/
1402static int xferOptimization(
1403 Parse *pParse, /* Parser context */
1404 Table *pDest, /* The table we are inserting into */
1405 Select *pSelect, /* A SELECT statement to use as the data source */
1406 int onError, /* How to handle constraint errors */
1407 int iDbDest /* The database of pDest */
1408){
1409 ExprList *pEList; /* The result set of the SELECT */
1410 Table *pSrc; /* The table in the FROM clause of SELECT */
1411 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1412 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1413 int i; /* Loop counter */
1414 int iDbSrc; /* The database of pSrc */
1415 int iSrc, iDest; /* Cursors from source and destination */
1416 int addr1, addr2; /* Loop addresses */
1417 int emptyDestTest; /* Address of test for empty pDest */
1418 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001419 Vdbe *v; /* The VDBE we are building */
1420 KeyInfo *pKey; /* Key information for an index */
1421 int counterMem; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001422 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001423
1424 if( pSelect==0 ){
1425 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1426 }
1427 if( pDest->pTrigger ){
1428 return 0; /* tab1 must not have triggers */
1429 }
1430#ifndef SQLITE_OMIT_VIRTUALTABLE
1431 if( pDest->isVirtual ){
1432 return 0; /* tab1 must not be a virtual table */
1433 }
1434#endif
1435 if( onError==OE_Default ){
1436 onError = OE_Abort;
1437 }
1438 if( onError!=OE_Abort && onError!=OE_Rollback ){
1439 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1440 }
danielk19775ce240a2007-09-03 17:30:06 +00001441 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001442 if( pSelect->pSrc->nSrc!=1 ){
1443 return 0; /* FROM clause must have exactly one term */
1444 }
1445 if( pSelect->pSrc->a[0].pSelect ){
1446 return 0; /* FROM clause cannot contain a subquery */
1447 }
1448 if( pSelect->pWhere ){
1449 return 0; /* SELECT may not have a WHERE clause */
1450 }
1451 if( pSelect->pOrderBy ){
1452 return 0; /* SELECT may not have an ORDER BY clause */
1453 }
drh8103b7d2007-02-24 13:23:51 +00001454 /* Do not need to test for a HAVING clause. If HAVING is present but
1455 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001456 if( pSelect->pGroupBy ){
1457 return 0; /* SELECT may not have a GROUP BY clause */
1458 }
1459 if( pSelect->pLimit ){
1460 return 0; /* SELECT may not have a LIMIT clause */
1461 }
drh8103b7d2007-02-24 13:23:51 +00001462 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001463 if( pSelect->pPrior ){
1464 return 0; /* SELECT may not be a compound query */
1465 }
1466 if( pSelect->isDistinct ){
1467 return 0; /* SELECT may not be DISTINCT */
1468 }
1469 pEList = pSelect->pEList;
1470 assert( pEList!=0 );
1471 if( pEList->nExpr!=1 ){
1472 return 0; /* The result set must have exactly one column */
1473 }
1474 assert( pEList->a[0].pExpr );
1475 if( pEList->a[0].pExpr->op!=TK_ALL ){
1476 return 0; /* The result set must be the special operator "*" */
1477 }
1478
1479 /* At this point we have established that the statement is of the
1480 ** correct syntactic form to participate in this optimization. Now
1481 ** we have to check the semantics.
1482 */
1483 pItem = pSelect->pSrc->a;
1484 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1485 if( pSrc==0 ){
1486 return 0; /* FROM clause does not contain a real table */
1487 }
1488 if( pSrc==pDest ){
1489 return 0; /* tab1 and tab2 may not be the same table */
1490 }
1491#ifndef SQLITE_OMIT_VIRTUALTABLE
1492 if( pSrc->isVirtual ){
1493 return 0; /* tab2 must not be a virtual table */
1494 }
1495#endif
1496 if( pSrc->pSelect ){
1497 return 0; /* tab2 may not be a view */
1498 }
1499 if( pDest->nCol!=pSrc->nCol ){
1500 return 0; /* Number of columns must be the same in tab1 and tab2 */
1501 }
1502 if( pDest->iPKey!=pSrc->iPKey ){
1503 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1504 }
1505 for(i=0; i<pDest->nCol; i++){
1506 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1507 return 0; /* Affinity must be the same on all columns */
1508 }
1509 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1510 return 0; /* Collating sequence must be the same on all columns */
1511 }
1512 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1513 return 0; /* tab2 must be NOT NULL if tab1 is */
1514 }
1515 }
1516 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001517 if( pDestIdx->onError!=OE_None ){
1518 destHasUniqueIdx = 1;
1519 }
drh9d9cf222007-02-13 15:01:11 +00001520 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1521 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1522 }
1523 if( pSrcIdx==0 ){
1524 return 0; /* pDestIdx has no corresponding index in pSrc */
1525 }
1526 }
drh7fc2f412007-03-29 00:08:24 +00001527#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001528 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001529 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1530 }
drh7fc2f412007-03-29 00:08:24 +00001531#endif
drh9d9cf222007-02-13 15:01:11 +00001532
1533 /* If we get this far, it means either:
1534 **
1535 ** * We can always do the transfer if the table contains an
1536 ** an integer primary key
1537 **
1538 ** * We can conditionally do the transfer if the destination
1539 ** table is empty.
1540 */
drhdd735212007-02-24 13:53:05 +00001541#ifdef SQLITE_TEST
1542 sqlite3_xferopt_count++;
1543#endif
drh9d9cf222007-02-13 15:01:11 +00001544 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1545 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001546 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001547 iSrc = pParse->nTab++;
1548 iDest = pParse->nTab++;
1549 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1550 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001551 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001552 /* If tables do not have an INTEGER PRIMARY KEY and there
1553 ** are indices to be copied and the destination is not empty,
1554 ** we have to disallow the transfer optimization because the
1555 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001556 **
1557 ** Or if the destination has a UNIQUE index and is not empty,
1558 ** we also disallow the transfer optimization because we cannot
1559 ** insure that all entries in the union of DEST and SRC will be
1560 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001561 */
1562 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1563 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1564 sqlite3VdbeJumpHere(v, addr1);
1565 }else{
1566 emptyDestTest = 0;
1567 }
1568 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1569 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001570 if( pDest->iPKey>=0 ){
drhbd36ba62007-03-31 13:00:26 +00001571 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh95bad4c2007-03-28 18:04:10 +00001572 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1573 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1574 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1575 "PRIMARY KEY must be unique", P3_STATIC);
1576 sqlite3VdbeJumpHere(v, addr2);
1577 autoIncStep(pParse, counterMem);
drhbd36ba62007-03-31 13:00:26 +00001578 }else if( pDest->pIndex==0 ){
1579 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
drh95bad4c2007-03-28 18:04:10 +00001580 }else{
drhbd36ba62007-03-31 13:00:26 +00001581 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001582 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001583 }
drh9d9cf222007-02-13 15:01:11 +00001584 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001585 sqlite3VdbeOp3(v, OP_Insert, iDest,
1586 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
drh9d9cf222007-02-13 15:01:11 +00001587 pDest->zName, 0);
1588 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1589 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1590 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1591 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1592 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1593 }
1594 assert( pSrcIdx );
1595 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1596 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1597 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1598 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1599 VdbeComment((v, "# %s", pSrcIdx->zName));
1600 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1601 (char*)pKey, P3_KEYINFO_HANDOFF);
1602 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1603 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1604 VdbeComment((v, "# %s", pDestIdx->zName));
1605 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1606 (char*)pKey, P3_KEYINFO_HANDOFF);
1607 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1608 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
drhe4d90812007-03-29 05:51:49 +00001609 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
drh9d9cf222007-02-13 15:01:11 +00001610 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1611 sqlite3VdbeJumpHere(v, addr1);
1612 }
1613 sqlite3VdbeJumpHere(v, emptySrcTest);
1614 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1615 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1616 if( emptyDestTest ){
1617 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1618 sqlite3VdbeJumpHere(v, emptyDestTest);
1619 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1620 return 0;
1621 }else{
1622 return 1;
1623 }
1624}
1625#endif /* SQLITE_OMIT_XFER_OPT */