blob: c0ef2aeef416ed8434e0909c7ef63c622eb3322b [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**
drh1013c932008-01-06 00:25:21 +000015** $Id: insert.c,v 1.214 2008/01/06 00:25:22 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
19/*
drh66a51672008-01-03 00:01:23 +000020** Set P4 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
drh66a51672008-01-03 00:01:23 +000055 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000056}
57
58/*
drh66a51672008-01-03 00:01:23 +000059** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000060** 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
drh66a51672008-01-03 00:01:23 +000098 sqlite3VdbeChangeP4(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);
drhef0bea92007-12-14 16:11:09 +0000113 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000114 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
115 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000116 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000117 if( tnum==pTab->tnum ){
118 return 1;
119 }
120 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
121 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000122 return 1;
123 }
drh48d11782007-11-23 15:02:19 +0000124 }
125 }
drh543165e2007-11-27 14:46:41 +0000126#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19772dca4ac2008-01-03 11:50:29 +0000127 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
128 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000129 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000130 return 1;
danielk19774d887782005-02-08 08:42:27 +0000131 }
drh543165e2007-11-27 14:46:41 +0000132#endif
danielk19774d887782005-02-08 08:42:27 +0000133 }
134 return 0;
135}
danielk19773d1bfea2004-05-14 11:00:53 +0000136
drh9d9cf222007-02-13 15:01:11 +0000137#ifndef SQLITE_OMIT_AUTOINCREMENT
138/*
139** Write out code to initialize the autoincrement logic. This code
140** looks up the current autoincrement value in the sqlite_sequence
141** table and stores that value in a memory cell. Code generated by
142** autoIncStep() will keep that memory cell holding the largest
143** rowid value. Code generated by autoIncEnd() will write the new
144** largest value of the counter back into the sqlite_sequence table.
145**
146** This routine returns the index of the mem[] cell that contains
147** the maximum rowid counter.
148**
drh0a07c102008-01-03 18:03:08 +0000149** Two memory cells are allocated. The next memory cell befor the
drh9d9cf222007-02-13 15:01:11 +0000150** one returned holds the rowid in sqlite_sequence where we will
151** write back the revised maximum rowid.
152*/
153static int autoIncBegin(
154 Parse *pParse, /* Parsing context */
155 int iDb, /* Index of the database holding pTab */
156 Table *pTab /* The table we are writing to */
157){
158 int memId = 0;
159 if( pTab->autoInc ){
160 Vdbe *v = pParse->pVdbe;
161 Db *pDb = &pParse->db->aDb[iDb];
162 int iCur = pParse->nTab;
163 int addr;
164 assert( v );
165 addr = sqlite3VdbeCurrentAddr(v);
drh9d9cf222007-02-13 15:01:11 +0000166 pParse->nMem += 2;
drh0a07c102008-01-03 18:03:08 +0000167 memId = pParse->nMem;
drh9d9cf222007-02-13 15:01:11 +0000168 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
danielk1977207872a2008-01-03 07:54:23 +0000169 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+12);
drh66a51672008-01-03 00:01:23 +0000170 sqlite3VdbeAddOp2(v, OP_Column, iCur, 0);
171 sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
danielk1977207872a2008-01-03 07:54:23 +0000172 sqlite3VdbeAddOp2(v, OP_Ne, 0x100, addr+11);
drh66a51672008-01-03 00:01:23 +0000173 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, 0);
drhb1fdb2a2008-01-05 04:06:03 +0000174 sqlite3VdbeAddOp2(v, OP_Move, 0, memId-1);
drh66a51672008-01-03 00:01:23 +0000175 sqlite3VdbeAddOp2(v, OP_Column, iCur, 1);
drhb1fdb2a2008-01-05 04:06:03 +0000176 sqlite3VdbeAddOp2(v, OP_Move, 0, memId);
danielk1977207872a2008-01-03 07:54:23 +0000177 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+12);
178 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+3);
drh66a51672008-01-03 00:01:23 +0000179 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000180 }
181 return memId;
182}
183
184/*
185** Update the maximum rowid for an autoincrement calculation.
186**
187** This routine should be called when the top of the stack holds a
188** new rowid that is about to be inserted. If that new rowid is
189** larger than the maximum rowid in the memId memory cell, then the
190** memory cell is updated. The stack is unchanged.
191*/
danielk1977287fb612008-01-04 19:10:28 +0000192static void autoIncStep(Parse *pParse, int memId, int iRowid){
drh9d9cf222007-02-13 15:01:11 +0000193 if( memId>0 ){
danielk1977287fb612008-01-04 19:10:28 +0000194 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, iRowid);
drh9d9cf222007-02-13 15:01:11 +0000195 }
196}
197
198/*
199** After doing one or more inserts, the maximum rowid is stored
200** in mem[memId]. Generate code to write this value back into the
201** the sqlite_sequence table.
202*/
203static void autoIncEnd(
204 Parse *pParse, /* The parsing context */
205 int iDb, /* Index of the database holding pTab */
206 Table *pTab, /* Table we are inserting into */
207 int memId /* Memory cell holding the maximum rowid */
208){
209 if( pTab->autoInc ){
210 int iCur = pParse->nTab;
211 Vdbe *v = pParse->pVdbe;
212 Db *pDb = &pParse->db->aDb[iDb];
213 int addr;
214 assert( v );
215 addr = sqlite3VdbeCurrentAddr(v);
216 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drhb1fdb2a2008-01-05 04:06:03 +0000217 sqlite3VdbeAddOp2(v, OP_SCopy, memId-1, 0);
danielk1977207872a2008-01-03 07:54:23 +0000218 sqlite3VdbeAddOp2(v, OP_NotNull, -1, addr+6);
drh66a51672008-01-03 00:01:23 +0000219 sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
drh4c583122008-01-04 22:01:03 +0000220 sqlite3VdbeAddOp1(v, OP_NewRowid, iCur);
drh66a51672008-01-03 00:01:23 +0000221 sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
drhb1fdb2a2008-01-05 04:06:03 +0000222 sqlite3VdbeAddOp2(v, OP_SCopy, memId, 0);
drh66a51672008-01-03 00:01:23 +0000223 sqlite3VdbeAddOp2(v, OP_MakeRecord, 2, 0);
danielk19771f4aa332008-01-03 09:51:55 +0000224 sqlite3CodeInsert(pParse, iCur, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000225 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000226 }
227}
228#else
229/*
230** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
231** above are all no-ops
232*/
233# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000234# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000235# define autoIncEnd(A,B,C,D)
236#endif /* SQLITE_OMIT_AUTOINCREMENT */
237
238
239/* Forward declaration */
240static int xferOptimization(
241 Parse *pParse, /* Parser context */
242 Table *pDest, /* The table we are inserting into */
243 Select *pSelect, /* A SELECT statement to use as the data source */
244 int onError, /* How to handle constraint errors */
245 int iDbDest /* The database of pDest */
246);
247
danielk19773d1bfea2004-05-14 11:00:53 +0000248/*
drh1ccde152000-06-17 13:12:39 +0000249** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000250**
251** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000252** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000253**
drh1ccde152000-06-17 13:12:39 +0000254** The IDLIST following the table name is always optional. If omitted,
255** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000256** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000257**
258** The pList parameter holds EXPRLIST in the first form of the INSERT
259** statement above, and pSelect is NULL. For the second form, pList is
260** NULL and pSelect is a pointer to the select statement used to generate
261** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000262**
drh9d9cf222007-02-13 15:01:11 +0000263** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000264** select with data coming from a VALUES clause, the code executes
265** once straight down through. The template looks like this:
266**
267** open write cursor to <table> and its indices
268** puts VALUES clause expressions onto the stack
269** write the resulting record into <table>
270** cleanup
271**
drh9d9cf222007-02-13 15:01:11 +0000272** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000273**
274** INSERT INTO <table> SELECT ...
275**
drh9d9cf222007-02-13 15:01:11 +0000276** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
277** in other words if the SELECT pulls all columns from a single table
278** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
279** if <table2> and <table1> are distinct tables but have identical
280** schemas, including all the same indices, then a special optimization
281** is invoked that copies raw records from <table2> over to <table1>.
282** See the xferOptimization() function for the implementation of this
283** template. This is the second template.
284**
285** open a write cursor to <table>
286** open read cursor on <table2>
287** transfer all records in <table2> over to <table>
288** close cursors
289** foreach index on <table>
290** open a write cursor on the <table> index
291** open a read cursor on the corresponding <table2> index
292** transfer all records from the read to the write cursors
293** close cursors
294** end foreach
295**
296** The third template is for when the second template does not apply
297** and the SELECT clause does not read from <table> at any time.
298** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000299**
300** goto B
301** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000302** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000303** gosub C
304** end loop
305** cleanup after the SELECT
306** goto D
307** B: open write cursor to <table> and its indices
308** goto A
309** C: insert the select result into <table>
310** return
311** D: cleanup
312**
drh9d9cf222007-02-13 15:01:11 +0000313** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000314** values from a SELECT but the data is being inserted into a table
315** that is also read as part of the SELECT. In the third form,
316** we have to use a intermediate table to store the results of
317** the select. The template is like this:
318**
319** goto B
320** A: setup for the SELECT
321** loop over the tables in the SELECT
322** gosub C
323** end loop
324** cleanup after the SELECT
325** goto D
326** C: insert the select result into the intermediate table
327** return
328** B: open a cursor to an intermediate table
329** goto A
330** D: open write cursor to <table> and its indices
331** loop over the intermediate table
332** transfer values form intermediate table into <table>
333** end the loop
334** cleanup
drhcce7d172000-05-31 15:34:51 +0000335*/
danielk19774adee202004-05-08 08:23:19 +0000336void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000337 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000338 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000339 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000340 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000341 IdList *pColumn, /* Column names corresponding to IDLIST. */
342 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000343){
drh5974a302000-06-07 14:42:26 +0000344 Table *pTab; /* The table to insert into */
drh113088e2003-03-20 01:16:58 +0000345 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000346 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000347 int i, j, idx; /* Loop counters */
348 Vdbe *v; /* Generate code into this virtual machine */
349 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000350 int nColumn; /* Number of columns in the data */
danielk1977cfe9a692004-06-16 12:00:29 +0000351 int base = 0; /* VDBE Cursor number for pTab */
352 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
drh9bb575f2004-09-06 17:24:11 +0000353 sqlite3 *db; /* The main database structure */
drh4a324312001-12-21 14:30:42 +0000354 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000355 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000356 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000357 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
358 int iSelectLoop = 0; /* Address of code that implements the SELECT */
359 int iCleanup = 0; /* Address of the cleanup code */
360 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
361 int iCntMem = 0; /* Memory cell used for the row counter */
drh1013c932008-01-06 00:25:21 +0000362 int iBaseReg; /* Base register for data */
drh798da522004-11-04 04:42:28 +0000363 int newIdx = -1; /* Cursor for the NEW table */
drh2958a4e2004-11-12 03:56:15 +0000364 Db *pDb; /* The database containing table being inserted into */
365 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
drhe4d90812007-03-29 05:51:49 +0000366 int appendFlag = 0; /* True if the insert is likely to be an append */
danielk1977da184232006-01-05 11:34:32 +0000367 int iDb;
drhcce7d172000-05-31 15:34:51 +0000368
danielk1977034ca142007-06-26 10:38:54 +0000369 int nHidden = 0;
370
drh798da522004-11-04 04:42:28 +0000371#ifndef SQLITE_OMIT_TRIGGER
372 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000373 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000374#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000375
drh17435752007-08-16 04:30:38 +0000376 db = pParse->db;
377 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000378 goto insert_cleanup;
379 }
drhdaffd0e2001-04-11 14:28:42 +0000380
drh1ccde152000-06-17 13:12:39 +0000381 /* Locate the table into which we will be inserting new information.
382 */
drh113088e2003-03-20 01:16:58 +0000383 assert( pTabList->nSrc==1 );
384 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000385 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000386 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000387 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000388 goto insert_cleanup;
389 }
danielk1977da184232006-01-05 11:34:32 +0000390 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
391 assert( iDb<db->nDb );
392 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000393 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000394 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000395 goto insert_cleanup;
396 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000397
drhb7f91642004-10-31 02:22:47 +0000398 /* Figure out if we have any triggers and if the table being
399 ** inserted into is a view
400 */
401#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000402 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000403 isView = pTab->pSelect!=0;
404#else
drhdca76842004-12-07 14:06:13 +0000405# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000406# define isView 0
407#endif
408#ifdef SQLITE_OMIT_VIEW
409# undef isView
410# define isView 0
411#endif
412
danielk1977c3f9bad2002-05-15 08:30:12 +0000413 /* Ensure that:
414 * (a) the table is not read-only,
415 * (b) that if it is a view then ON INSERT triggers exist
416 */
drhdca76842004-12-07 14:06:13 +0000417 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000418 goto insert_cleanup;
419 }
drh43617e92006-03-06 20:55:46 +0000420 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000421
drhf573c992002-07-31 00:32:50 +0000422 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000423 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
424 ** module table).
drhf573c992002-07-31 00:32:50 +0000425 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000426 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000427 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000428 }
429
drh1ccde152000-06-17 13:12:39 +0000430 /* Allocate a VDBE
431 */
danielk19774adee202004-05-08 08:23:19 +0000432 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000433 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000434 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000435 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000436
danielk1977c3f9bad2002-05-15 08:30:12 +0000437 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000438 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000439 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000440 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000441
drh9d9cf222007-02-13 15:01:11 +0000442#ifndef SQLITE_OMIT_XFER_OPT
443 /* If the statement is of the form
444 **
445 ** INSERT INTO <table1> SELECT * FROM <table2>;
446 **
447 ** Then special optimizations can be applied that make the transfer
448 ** very fast and which reduce fragmentation of indices.
449 */
450 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
451 assert( !triggers_exist );
452 assert( pList==0 );
453 goto insert_cleanup;
454 }
455#endif /* SQLITE_OMIT_XFER_OPT */
456
drh2958a4e2004-11-12 03:56:15 +0000457 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drhf3388142004-11-13 03:48:06 +0000458 ** sqlite_sequence table and store it in memory cell counterMem. Also
459 ** remember the rowid of the sqlite_sequence table entry in memory cell
460 ** counterRowid.
drh2958a4e2004-11-12 03:56:15 +0000461 */
drh9d9cf222007-02-13 15:01:11 +0000462 counterMem = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000463
drh1ccde152000-06-17 13:12:39 +0000464 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000465 ** is coming from a SELECT statement, then this step also generates
466 ** all the code to implement the SELECT statement and invoke a subroutine
467 ** to process each row of the result. (Template 2.) If the SELECT
468 ** statement uses the the table that is being inserted into, then the
469 ** subroutine is also coded here. That subroutine stores the SELECT
470 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000471 */
drh5974a302000-06-07 14:42:26 +0000472 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000473 /* Data is coming from a SELECT. Generate code to implement that SELECT
474 */
drh1013c932008-01-06 00:25:21 +0000475 SelectDest dest;
drh142e30d2002-08-28 03:00:58 +0000476 int rc, iInitCode;
drh1013c932008-01-06 00:25:21 +0000477
drh66a51672008-01-03 00:01:23 +0000478 iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000479 iSelectLoop = sqlite3VdbeCurrentAddr(v);
480 iInsertBlock = sqlite3VdbeMakeLabel(v);
drh1013c932008-01-06 00:25:21 +0000481 sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
danielk1977b3bce662005-01-29 08:32:43 +0000482
483 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000484 rc = sqlite3Select(pParse, pSelect, &dest, 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
drh1013c932008-01-06 00:25:21 +0000489 iBaseReg = dest.iMem;
danielk19774adee202004-05-08 08:23:19 +0000490 iCleanup = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000491 sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000492 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000493 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000494
495 /* Set useTempTable to TRUE if the result of the SELECT statement
496 ** should be written into a temporary table. Set to FALSE if each
497 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000498 **
499 ** A temp table must be used if the table being updated is also one
500 ** of the tables being read by the SELECT statement. Also use a
501 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000502 */
drh48d11782007-11-23 15:02:19 +0000503 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000504 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000505 }
drh142e30d2002-08-28 03:00:58 +0000506
507 if( useTempTable ){
508 /* Generate the subroutine that SELECT calls to process each row of
509 ** the result. Store the result in a temporary table
510 */
511 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000512 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh1013c932008-01-06 00:25:21 +0000513 sqlite3VdbeAddOp2(v, OP_RegMakeRec, iBaseReg, nColumn);
drh4c583122008-01-04 22:01:03 +0000514 sqlite3VdbeAddOp1(v, OP_NewRowid, srcTab);
drh66a51672008-01-03 00:01:23 +0000515 sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
danielk19771f4aa332008-01-03 09:51:55 +0000516 sqlite3CodeInsert(pParse, srcTab, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000517 sqlite3VdbeAddOp2(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);
drh66a51672008-01-03 00:01:23 +0000524 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
525 sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
526 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000527 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 ){
drh66a51672008-01-03 00:01:23 +0000616 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
617 sqlite3VdbeAddOp2(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 ){
drh0a07c102008-01-03 18:03:08 +0000623 iCntMem = ++pParse->nMem;
drh4c583122008-01-04 22:01:03 +0000624 sqlite3VdbeAddOp2(v, OP_Integer, 0, iCntMem);
drhfeeb1392002-04-09 03:28:01 +0000625 }
626
danielk1977e448dc42008-01-02 11:50:51 +0000627 /* If this is not a view, open the table and and all indices */
628 if( !isView ){
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);
drh66a51672008-01-03 00:01:23 +0000640 sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +0000641 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000642 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000643 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000644 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh1013c932008-01-06 00:25:21 +0000645 sqlite3RegToStack(pParse, iBaseReg, nColumn);
drh66a51672008-01-03 00:01:23 +0000646 sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000647 }
drh1ccde152000-06-17 13:12:39 +0000648
drh5cf590c2003-04-24 01:45:04 +0000649 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000650 */
danielk19774adee202004-05-08 08:23:19 +0000651 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000652 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000653
drh70ce3f02003-04-15 19:22:22 +0000654 /* build the NEW.* reference row. Note that if there is an INTEGER
655 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
656 ** translated into a unique ID for the row. But on a BEFORE trigger,
657 ** we do not know what the unique ID will be (because the insert has
658 ** not happened yet) so we substitute a rowid of -1
659 */
660 if( keyColumn<0 ){
drh66a51672008-01-03 00:01:23 +0000661 sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000662 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000663 sqlite3VdbeAddOp2(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000664 }else{
drhd6fe9612005-01-14 01:22:00 +0000665 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh389a1ad2008-01-03 23:44:53 +0000666 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drh66a51672008-01-03 00:01:23 +0000667 sqlite3VdbeAddOp2(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
668 sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
669 sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
670 sqlite3VdbeAddOp2(v, OP_MustBeInt, 0, 0);
drh70ce3f02003-04-15 19:22:22 +0000671 }
672
danielk1977034ca142007-06-26 10:38:54 +0000673 /* Cannot have triggers on a virtual table. If it were possible,
674 ** this block would have to account for hidden column.
675 */
676 assert(!IsVirtual(pTab));
677
drh70ce3f02003-04-15 19:22:22 +0000678 /* Create the new column data
679 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000680 for(i=0; i<pTab->nCol; i++){
681 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000682 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000683 }else{
drh9adf9ac2002-05-15 11:44:13 +0000684 for(j=0; j<pColumn->nId; j++){
685 if( pColumn->a[j].idx==i ) break;
686 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000687 }
688 if( pColumn && j>=pColumn->nId ){
drh389a1ad2008-01-03 23:44:53 +0000689 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
drh142e30d2002-08-28 03:00:58 +0000690 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000691 sqlite3VdbeAddOp2(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000692 }else{
drhd6fe9612005-01-14 01:22:00 +0000693 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000694 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000695 }
696 }
drh66a51672008-01-03 00:01:23 +0000697 sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000698
699 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
700 ** do not attempt any conversions before assembling the record.
701 ** If this is a real table, attempt conversions as required by the
702 ** table column affinities.
703 */
704 if( !isView ){
705 sqlite3TableAffinityStr(v, pTab);
706 }
danielk19771f4aa332008-01-03 09:51:55 +0000707 sqlite3CodeInsert(pParse, newIdx, OPFLAG_APPEND);
danielk1977c3f9bad2002-05-15 08:30:12 +0000708
drh5cf590c2003-04-24 01:45:04 +0000709 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000710 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000711 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000712 goto insert_cleanup;
713 }
drh70ce3f02003-04-15 19:22:22 +0000714 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000715
drh4a324312001-12-21 14:30:42 +0000716 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000717 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000718 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000719 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000720 */
drh5cf590c2003-04-24 01:45:04 +0000721 if( !isView ){
danielk1977287fb612008-01-04 19:10:28 +0000722 int iReg = pParse->nMem+1;
723 int iRowid = iReg+(IsVirtual(pTab)?1:0);
724 pParse->nMem += pTab->nCol + (IsVirtual(pTab)?2:1);
725
drh4cbdda92006-06-14 19:00:20 +0000726 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000727 /* The row that the VUpdate opcode will delete: none */
drh4c583122008-01-04 22:01:03 +0000728 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
drh4cbdda92006-06-14 19:00:20 +0000729 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000730 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000731 if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000732 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, iRowid);
drh142e30d2002-08-28 03:00:58 +0000733 }else if( pSelect ){
drhb1fdb2a2008-01-05 04:06:03 +0000734 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn - keyColumn - 1), iRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000735 }else{
drhe4d90812007-03-29 05:51:49 +0000736 VdbeOp *pOp;
drh389a1ad2008-01-03 23:44:53 +0000737 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drhe4d90812007-03-29 05:51:49 +0000738 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000739 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000740 appendFlag = 1;
741 pOp->opcode = OP_NewRowid;
742 pOp->p1 = base;
drh4c583122008-01-04 22:01:03 +0000743 pOp->p2 = iRowid;
744 pOp->p3 = counterMem;
danielk1977287fb612008-01-04 19:10:28 +0000745 }else{
746 /* TODO: Avoid this use of the stack. */
drhb1fdb2a2008-01-05 04:06:03 +0000747 sqlite3VdbeAddOp2(v, OP_Move, 0, iRowid);
drhe4d90812007-03-29 05:51:49 +0000748 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000749 }
drhf0863fe2005-06-12 21:35:51 +0000750 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000751 ** to generate a unique primary key value.
752 */
drhe4d90812007-03-29 05:51:49 +0000753 if( !appendFlag ){
danielk1977287fb612008-01-04 19:10:28 +0000754 sqlite3VdbeAddOp2(v, OP_IfMemNull, iRowid, sqlite3VdbeCurrentAddr(v)+2);
755 sqlite3VdbeAddOp2(v, OP_Goto, -1, sqlite3VdbeCurrentAddr(v)+2);
drh4c583122008-01-04 22:01:03 +0000756 sqlite3VdbeAddOp3(v, OP_NewRowid, base, iRowid, counterMem);
danielk1977287fb612008-01-04 19:10:28 +0000757 sqlite3VdbeAddOp3(v, OP_MustBeInt, 0, 0, iRowid);
drhe4d90812007-03-29 05:51:49 +0000758 }
drh4cbdda92006-06-14 19:00:20 +0000759 }else if( IsVirtual(pTab) ){
drh4c583122008-01-04 22:01:03 +0000760 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000761 }else{
drhb1fdb2a2008-01-05 04:06:03 +0000762 sqlite3VdbeAddOp3(v, OP_NewRowid, base, iRowid, counterMem);
drhe4d90812007-03-29 05:51:49 +0000763 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000764 }
danielk1977287fb612008-01-04 19:10:28 +0000765 autoIncStep(pParse, counterMem, iRowid);
drh4a324312001-12-21 14:30:42 +0000766
danielk1977c3f9bad2002-05-15 08:30:12 +0000767 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000768 ** with the first column.
769 */
danielk1977034ca142007-06-26 10:38:54 +0000770 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000771 for(i=0; i<pTab->nCol; i++){
danielk1977287fb612008-01-04 19:10:28 +0000772 int iRegStore = iRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000773 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000774 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000775 ** Whenever this column is read, the record number will be substituted
776 ** in its place. So will fill this column with a NULL to avoid
777 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000778 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000779 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000780 }
781 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000782 if( IsHiddenColumn(&pTab->aCol[i]) ){
783 assert( IsVirtual(pTab) );
784 j = -1;
785 nHidden++;
786 }else{
787 j = i - nHidden;
788 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000789 }else{
drh9adf9ac2002-05-15 11:44:13 +0000790 for(j=0; j<pColumn->nId; j++){
791 if( pColumn->a[j].idx==i ) break;
792 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000793 }
danielk1977034ca142007-06-26 10:38:54 +0000794 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000795 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000796 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000797 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000798 }else if( pSelect ){
drhb1fdb2a2008-01-05 04:06:03 +0000799 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn-j-1), iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000800 }else{
danielk1977287fb612008-01-04 19:10:28 +0000801 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000802 }
drhbed86902000-06-02 13:27:59 +0000803 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000804
805 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000806 ** do the insertion.
807 */
drh4cbdda92006-06-14 19:00:20 +0000808#ifndef SQLITE_OMIT_VIRTUALTABLE
809 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000810 pParse->pVirtualLock = pTab;
danielk19772a339ff2008-01-03 17:31:44 +0000811 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, iReg,
drh66a51672008-01-03 00:01:23 +0000812 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000813 }else
814#endif
815 {
danielk1977287fb612008-01-04 19:10:28 +0000816 sqlite3RegToStack(pParse, iReg, pTab->nCol+1);
drh4cbdda92006-06-14 19:00:20 +0000817 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
818 0, onError, endOfLoop);
819 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000820 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
821 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000822 }
drh5cf590c2003-04-24 01:45:04 +0000823 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000824
drh5cf590c2003-04-24 01:45:04 +0000825 /* Update the count of rows that are inserted
826 */
827 if( (db->flags & SQLITE_CountRows)!=0 ){
drh8558cde2008-01-05 05:20:10 +0000828 sqlite3VdbeAddOp2(v, OP_AddImm, iCntMem, 1);
drh5974a302000-06-07 14:42:26 +0000829 }
drh1ccde152000-06-17 13:12:39 +0000830
drhdca76842004-12-07 14:06:13 +0000831 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000832 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000833 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000834 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000835 goto insert_cleanup;
836 }
drh1bee3d72001-10-15 00:44:35 +0000837 }
838
drh1ccde152000-06-17 13:12:39 +0000839 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000840 */
danielk19774adee202004-05-08 08:23:19 +0000841 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000842 if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000843 sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
danielk19774adee202004-05-08 08:23:19 +0000844 sqlite3VdbeResolveLabel(v, iBreak);
drh66a51672008-01-03 00:01:23 +0000845 sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000846 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000847 sqlite3VdbeAddOp2(v, OP_Pop, nColumn, 0);
848 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000849 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000850 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000851
danielk1977e448dc42008-01-02 11:50:51 +0000852 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000853 /* Close all tables opened */
drh66a51672008-01-03 00:01:23 +0000854 sqlite3VdbeAddOp2(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000855 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh66a51672008-01-03 00:01:23 +0000856 sqlite3VdbeAddOp2(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000857 }
drhcce7d172000-05-31 15:34:51 +0000858 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000859
drhf3388142004-11-13 03:48:06 +0000860 /* Update the sqlite_sequence table by storing the content of the
861 ** counter value in memory counterMem back into the sqlite_sequence
862 ** table.
drh2958a4e2004-11-12 03:56:15 +0000863 */
drh9d9cf222007-02-13 15:01:11 +0000864 autoIncEnd(pParse, iDb, pTab, counterMem);
drh2958a4e2004-11-12 03:56:15 +0000865
drh1bee3d72001-10-15 00:44:35 +0000866 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000867 ** Return the number of rows inserted. If this routine is
868 ** generating code because of a call to sqlite3NestedParse(), do not
869 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000870 */
danielk1977cc6bd382005-01-10 02:48:49 +0000871 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh66a51672008-01-03 00:01:23 +0000872 sqlite3VdbeAddOp2(v, OP_ResultRow, iCntMem, 1);
danielk197722322fd2004-05-25 23:35:17 +0000873 sqlite3VdbeSetNumCols(v, 1);
drh66a51672008-01-03 00:01:23 +0000874 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000875 }
drhcce7d172000-05-31 15:34:51 +0000876
877insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000878 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000879 sqlite3ExprListDelete(pList);
880 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000881 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000882}
drh9cfcf5d2002-01-29 18:41:24 +0000883
drh9cfcf5d2002-01-29 18:41:24 +0000884/*
885** Generate code to do a constraint check prior to an INSERT or an UPDATE.
886**
887** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000888** the following values:
889**
drhf0863fe2005-06-12 21:35:51 +0000890** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000891** value is omitted unless we are doing an UPDATE that involves a
892** change to the record number.
drh0ca3e242002-01-29 23:07:02 +0000893**
drhf0863fe2005-06-12 21:35:51 +0000894** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000895**
896** 3. The data in the first column of the entry after the update.
897**
898** i. Data from middle columns...
899**
900** N. The data in the last column of the entry after the update.
901**
drhf0863fe2005-06-12 21:35:51 +0000902** The old rowid shown as entry (1) above is omitted unless both isUpdate
903** and rowidChng are 1. isUpdate is true for UPDATEs and false for
904** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000905**
906** The code generated by this routine pushes additional entries onto
907** the stack which are the keys for new index entries for the new record.
908** The order of index keys is the same as the order of the indices on
909** the pTable->pIndex list. A key is only created for index i if
910** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000911**
912** This routine also generates code to check constraints. NOT NULL,
913** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000914** then the appropriate action is performed. There are five possible
915** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000916**
917** Constraint type Action What Happens
918** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000919** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000920** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000921** return code of SQLITE_CONSTRAINT.
922**
drh1c928532002-01-31 15:54:21 +0000923** any ABORT Back out changes from the current command
924** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000925** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000926** with SQLITE_CONSTRAINT.
927**
928** any FAIL Sqlite_exec() returns immediately with a
929** return code of SQLITE_CONSTRAINT. The
930** transaction is not rolled back and any
931** prior changes are retained.
932**
drh9cfcf5d2002-01-29 18:41:24 +0000933** any IGNORE The record number and data is popped from
934** the stack and there is an immediate jump
935** to label ignoreDest.
936**
937** NOT NULL REPLACE The NULL value is replace by the default
938** value for that column. If the default value
939** is NULL, the action is the same as ABORT.
940**
941** UNIQUE REPLACE The other row that conflicts with the row
942** being inserted is removed.
943**
944** CHECK REPLACE Illegal. The results in an exception.
945**
drh1c928532002-01-31 15:54:21 +0000946** Which action to take is determined by the overrideError parameter.
947** Or if overrideError==OE_Default, then the pParse->onError parameter
948** is used. Or if pParse->onError==OE_Default then the onError value
949** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000950**
drhaaab5722002-02-19 13:39:21 +0000951** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000952** cursor number "base". All indices of pTab must also have open
953** read/write cursors with cursor number base+i for the i-th cursor.
954** Except, if there is no possibility of a REPLACE action then
955** cursors do not need to be open for indices where aIdxUsed[i]==0.
956**
957** If the isUpdate flag is true, it means that the "base" cursor is
958** initially pointing to an entry that is being updated. The isUpdate
959** flag causes extra code to be generated so that the "base" cursor
960** is still pointing at the same entry after the routine returns.
961** Without the isUpdate flag, the "base" cursor might be moved.
962*/
danielk19774adee202004-05-08 08:23:19 +0000963void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000964 Parse *pParse, /* The parser context */
965 Table *pTab, /* the table into which we are inserting */
966 int base, /* Index of a read/write cursor pointing at pTab */
967 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000968 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000969 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000970 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000971 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000972){
973 int i;
974 Vdbe *v;
975 int nCol;
976 int onError;
977 int addr;
978 int extra;
drh0ca3e242002-01-29 23:07:02 +0000979 int iCur;
980 Index *pIdx;
981 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000982 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000983 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +0000984
danielk19774adee202004-05-08 08:23:19 +0000985 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +0000986 assert( v!=0 );
drh417be792002-03-03 18:59:40 +0000987 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +0000988 nCol = pTab->nCol;
989
990 /* Test all NOT NULL constraints.
991 */
992 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +0000993 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +0000994 continue;
995 }
drh9cfcf5d2002-01-29 18:41:24 +0000996 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +0000997 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +0000998 if( overrideError!=OE_Default ){
999 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001000 }else if( onError==OE_Default ){
1001 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001002 }
danielk19777977a172004-11-09 12:44:37 +00001003 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001004 onError = OE_Abort;
1005 }
drhb1fdb2a2008-01-05 04:06:03 +00001006 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol-1-i));
drh66a51672008-01-03 00:01:23 +00001007 addr = sqlite3VdbeAddOp2(v, OP_NotNull, 1, 0);
danielk1977b84f96f2005-01-20 11:32:23 +00001008 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1009 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001010 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001011 case OE_Rollback:
1012 case OE_Abort:
1013 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001014 char *zMsg = 0;
drh66a51672008-01-03 00:01:23 +00001015 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
danielk19774adee202004-05-08 08:23:19 +00001016 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001017 " may not be NULL", (char*)0);
drh66a51672008-01-03 00:01:23 +00001018 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001019 break;
1020 }
1021 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001022 sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1023 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001024 break;
1025 }
1026 case OE_Replace: {
drh389a1ad2008-01-03 23:44:53 +00001027 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001028 sqlite3VdbeAddOp1(v, OP_Push, nCol-i);
drh9cfcf5d2002-01-29 18:41:24 +00001029 break;
1030 }
drh9cfcf5d2002-01-29 18:41:24 +00001031 }
drhd654be82005-09-20 17:42:23 +00001032 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001033 }
1034
1035 /* Test all CHECK constraints
1036 */
drhffe07b22005-11-03 00:41:17 +00001037#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001038 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001039 int allOk = sqlite3VdbeMakeLabel(v);
1040 assert( pParse->ckOffset==0 );
1041 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001042 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001043 assert( pParse->ckOffset==nCol );
1044 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001045 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001046 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001047 sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1048 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001049 }else{
drh66a51672008-01-03 00:01:23 +00001050 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001051 }
drhffe07b22005-11-03 00:41:17 +00001052 sqlite3VdbeResolveLabel(v, allOk);
1053 }
1054#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001055
drh0bd1f4e2002-06-06 18:54:39 +00001056 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1057 ** of the new record does not previously exist. Except, if this
1058 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001059 */
drhf0863fe2005-06-12 21:35:51 +00001060 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001061 onError = pTab->keyConf;
1062 if( overrideError!=OE_Default ){
1063 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001064 }else if( onError==OE_Default ){
1065 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001066 }
drha0217ba2003-06-01 01:10:33 +00001067
drh5383ae52003-06-04 12:23:30 +00001068 if( isUpdate ){
drhb1fdb2a2008-01-05 04:06:03 +00001069 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+1));
1070 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+1));
drh66a51672008-01-03 00:01:23 +00001071 jumpInst1 = sqlite3VdbeAddOp2(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001072 }
drhb1fdb2a2008-01-05 04:06:03 +00001073 sqlite3VdbeAddOp1(v, OP_SCopy, -nCol);
drh66a51672008-01-03 00:01:23 +00001074 jumpInst2 = sqlite3VdbeAddOp2(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001075 switch( onError ){
1076 default: {
1077 onError = OE_Abort;
1078 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001079 }
drh5383ae52003-06-04 12:23:30 +00001080 case OE_Rollback:
1081 case OE_Abort:
1082 case OE_Fail: {
drh66a51672008-01-03 00:01:23 +00001083 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1084 "PRIMARY KEY must be unique", P4_STATIC);
drh5383ae52003-06-04 12:23:30 +00001085 break;
drh0ca3e242002-01-29 23:07:02 +00001086 }
drh5383ae52003-06-04 12:23:30 +00001087 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001088 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001089 if( isUpdate ){
drhb1fdb2a2008-01-05 04:06:03 +00001090 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+hasTwoRowids));
drh66a51672008-01-03 00:01:23 +00001091 sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001092 }
1093 seenReplace = 1;
1094 break;
drh0ca3e242002-01-29 23:07:02 +00001095 }
drh5383ae52003-06-04 12:23:30 +00001096 case OE_Ignore: {
1097 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001098 sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1099 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001100 break;
1101 }
1102 }
drhd654be82005-09-20 17:42:23 +00001103 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001104 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001105 sqlite3VdbeJumpHere(v, jumpInst1);
drhb1fdb2a2008-01-05 04:06:03 +00001106 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+1));
drh66a51672008-01-03 00:01:23 +00001107 sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001108 }
1109 }
drh0bd1f4e2002-06-06 18:54:39 +00001110
1111 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1112 ** index and making sure that duplicate entries do not already exist.
1113 ** Add the new records to the indices as we go.
1114 */
drhb2fe7d82003-04-20 17:29:23 +00001115 extra = -1;
1116 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1117 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1118 extra++;
1119
1120 /* Create a key for accessing the index entry */
drhb1fdb2a2008-01-05 04:06:03 +00001121 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+extra));
drh9cfcf5d2002-01-29 18:41:24 +00001122 for(i=0; i<pIdx->nColumn; i++){
1123 int idx = pIdx->aiColumn[i];
1124 if( idx==pTab->iPKey ){
drhb1fdb2a2008-01-05 04:06:03 +00001125 sqlite3VdbeAddOp1(v, OP_SCopy, -(i+extra+nCol+1));
drh9cfcf5d2002-01-29 18:41:24 +00001126 }else{
drhb1fdb2a2008-01-05 04:06:03 +00001127 sqlite3VdbeAddOp1(v, OP_SCopy, -(i+extra+nCol-idx));
drh9cfcf5d2002-01-29 18:41:24 +00001128 }
1129 }
drh66a51672008-01-03 00:01:23 +00001130 jumpInst1 = sqlite3VdbeAddOp2(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001131 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001132
1133 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001134 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001135 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001136 if( overrideError!=OE_Default ){
1137 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001138 }else if( onError==OE_Default ){
1139 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001140 }
drh5383ae52003-06-04 12:23:30 +00001141 if( seenReplace ){
1142 if( onError==OE_Ignore ) onError = OE_Replace;
1143 else if( onError==OE_Fail ) onError = OE_Abort;
1144 }
1145
drhb2fe7d82003-04-20 17:29:23 +00001146
1147 /* Check to see if the new index entry will be unique */
drhb1fdb2a2008-01-05 04:06:03 +00001148 sqlite3VdbeAddOp1(v, OP_SCopy, -(extra+nCol+1+hasTwoRowids));
drh66a51672008-01-03 00:01:23 +00001149 jumpInst2 = sqlite3VdbeAddOp2(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001150
1151 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001152 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1153 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001154 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001155 case OE_Rollback:
1156 case OE_Abort:
1157 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001158 int j, n1, n2;
1159 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001160 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1161 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001162 n1 = strlen(zErrMsg);
1163 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1164 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1165 n2 = strlen(zCol);
1166 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001167 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001168 n1 += 2;
1169 }
1170 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001171 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001172 n1 += 3;
1173 break;
1174 }else{
drh5bb3eb92007-05-04 13:15:55 +00001175 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001176 n1 += n2;
1177 }
1178 }
drh5bb3eb92007-05-04 13:15:55 +00001179 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001180 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001181 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001182 break;
1183 }
1184 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001185 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001186 sqlite3VdbeAddOp2(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
1187 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001188 break;
1189 }
1190 case OE_Replace: {
danielk197796cb76f2008-01-04 13:24:28 +00001191 int iRowid = sqlite3StackToReg(pParse, 1);
1192 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, iRowid, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001193 if( isUpdate ){
drhb1fdb2a2008-01-05 04:06:03 +00001194 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+extra+1+hasTwoRowids));
drh66a51672008-01-03 00:01:23 +00001195 sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001196 }
drh0ca3e242002-01-29 23:07:02 +00001197 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001198 break;
1199 }
drh9cfcf5d2002-01-29 18:41:24 +00001200 }
drh0bd1f4e2002-06-06 18:54:39 +00001201#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001202 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001203#endif
drhd654be82005-09-20 17:42:23 +00001204 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001205 }
1206}
drh0ca3e242002-01-29 23:07:02 +00001207
1208/*
1209** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001210** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001211** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001212** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001213** entries in all indices and in the main table.
1214**
drhb419a922002-01-30 16:17:23 +00001215** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001216** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001217*/
danielk19774adee202004-05-08 08:23:19 +00001218void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001219 Parse *pParse, /* The parser context */
1220 Table *pTab, /* the table into which we are inserting */
1221 int base, /* Index of a read/write cursor pointing at pTab */
1222 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001223 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001224 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001225 int newIdx, /* Index of NEW table for triggers. -1 if none */
1226 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001227){
1228 int i;
1229 Vdbe *v;
1230 int nIdx;
1231 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001232 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001233
danielk19774adee202004-05-08 08:23:19 +00001234 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001235 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001236 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001237 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1238 for(i=nIdx-1; i>=0; i--){
1239 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drh66a51672008-01-03 00:01:23 +00001240 sqlite3VdbeAddOp2(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001241 }
drh66a51672008-01-03 00:01:23 +00001242 sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001243 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001244#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001245 if( newIdx>=0 ){
drhb1fdb2a2008-01-05 04:06:03 +00001246 sqlite3VdbeAddOp1(v, OP_Copy, -1);
1247 sqlite3VdbeAddOp1(v, OP_Copy, -1);
danielk19771f4aa332008-01-03 09:51:55 +00001248 sqlite3CodeInsert(pParse, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001249 }
danielk1977b84f96f2005-01-20 11:32:23 +00001250#endif
drh4794f732004-11-05 17:17:50 +00001251 if( pParse->nested ){
1252 pik_flags = 0;
1253 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001254 pik_flags = OPFLAG_NCHANGE;
1255 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001256 }
drhe4d90812007-03-29 05:51:49 +00001257 if( appendBias ){
1258 pik_flags |= OPFLAG_APPEND;
1259 }
danielk19771f4aa332008-01-03 09:51:55 +00001260 sqlite3CodeInsert(pParse, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001261 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001262 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001263 }
danielk1977b28af712004-06-21 06:50:26 +00001264
drhf0863fe2005-06-12 21:35:51 +00001265 if( isUpdate && rowidChng ){
drh66a51672008-01-03 00:01:23 +00001266 sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001267 }
1268}
drhcd446902004-02-24 01:05:31 +00001269
1270/*
drh290c1942004-08-21 17:54:45 +00001271** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001272** indices of that table. The "base" parameter is the cursor number used
1273** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001274*/
drh290c1942004-08-21 17:54:45 +00001275void sqlite3OpenTableAndIndices(
1276 Parse *pParse, /* Parsing context */
1277 Table *pTab, /* Table to be opened */
1278 int base, /* Cursor number assigned to the table */
1279 int op /* OP_OpenRead or OP_OpenWrite */
1280){
drhcd446902004-02-24 01:05:31 +00001281 int i;
drh4cbdda92006-06-14 19:00:20 +00001282 int iDb;
drhcd446902004-02-24 01:05:31 +00001283 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001284 Vdbe *v;
1285
1286 if( IsVirtual(pTab) ) return;
1287 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1288 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001289 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001290 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001291 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001292 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001293 assert( pIdx->pSchema==pTab->pSchema );
danielk1977207872a2008-01-03 07:54:23 +00001294 sqlite3VdbeAddOp4(v, op, i+base, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001295 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001296 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001297 }
drh290c1942004-08-21 17:54:45 +00001298 if( pParse->nTab<=base+i ){
1299 pParse->nTab = base+i;
1300 }
drhcd446902004-02-24 01:05:31 +00001301}
drh9d9cf222007-02-13 15:01:11 +00001302
drh91c58e22007-03-27 12:04:04 +00001303
1304#ifdef SQLITE_TEST
1305/*
1306** The following global variable is incremented whenever the
1307** transfer optimization is used. This is used for testing
1308** purposes only - to make sure the transfer optimization really
1309** is happening when it is suppose to.
1310*/
1311int sqlite3_xferopt_count;
1312#endif /* SQLITE_TEST */
1313
1314
drh9d9cf222007-02-13 15:01:11 +00001315#ifndef SQLITE_OMIT_XFER_OPT
1316/*
1317** Check to collation names to see if they are compatible.
1318*/
1319static int xferCompatibleCollation(const char *z1, const char *z2){
1320 if( z1==0 ){
1321 return z2==0;
1322 }
1323 if( z2==0 ){
1324 return 0;
1325 }
1326 return sqlite3StrICmp(z1, z2)==0;
1327}
1328
1329
1330/*
1331** Check to see if index pSrc is compatible as a source of data
1332** for index pDest in an insert transfer optimization. The rules
1333** for a compatible index:
1334**
1335** * The index is over the same set of columns
1336** * The same DESC and ASC markings occurs on all columns
1337** * The same onError processing (OE_Abort, OE_Ignore, etc)
1338** * The same collating sequence on each column
1339*/
1340static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1341 int i;
1342 assert( pDest && pSrc );
1343 assert( pDest->pTable!=pSrc->pTable );
1344 if( pDest->nColumn!=pSrc->nColumn ){
1345 return 0; /* Different number of columns */
1346 }
1347 if( pDest->onError!=pSrc->onError ){
1348 return 0; /* Different conflict resolution strategies */
1349 }
1350 for(i=0; i<pSrc->nColumn; i++){
1351 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1352 return 0; /* Different columns indexed */
1353 }
1354 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1355 return 0; /* Different sort orders */
1356 }
1357 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1358 return 0; /* Different sort orders */
1359 }
1360 }
1361
1362 /* If no test above fails then the indices must be compatible */
1363 return 1;
1364}
1365
1366/*
1367** Attempt the transfer optimization on INSERTs of the form
1368**
1369** INSERT INTO tab1 SELECT * FROM tab2;
1370**
1371** This optimization is only attempted if
1372**
1373** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001374** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001375**
1376** (2) tab1 and tab2 are different tables
1377**
1378** (3) There must be no triggers on tab1
1379**
1380** (4) The result set of the SELECT statement is "*"
1381**
1382** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1383** or LIMIT clause.
1384**
1385** (6) The SELECT statement is a simple (not a compound) select that
1386** contains only tab2 in its FROM clause
1387**
1388** This method for implementing the INSERT transfers raw records from
1389** tab2 over to tab1. The columns are not decoded. Raw records from
1390** the indices of tab2 are transfered to tab1 as well. In so doing,
1391** the resulting tab1 has much less fragmentation.
1392**
1393** This routine returns TRUE if the optimization is attempted. If any
1394** of the conditions above fail so that the optimization should not
1395** be attempted, then this routine returns FALSE.
1396*/
1397static int xferOptimization(
1398 Parse *pParse, /* Parser context */
1399 Table *pDest, /* The table we are inserting into */
1400 Select *pSelect, /* A SELECT statement to use as the data source */
1401 int onError, /* How to handle constraint errors */
1402 int iDbDest /* The database of pDest */
1403){
1404 ExprList *pEList; /* The result set of the SELECT */
1405 Table *pSrc; /* The table in the FROM clause of SELECT */
1406 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1407 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1408 int i; /* Loop counter */
1409 int iDbSrc; /* The database of pSrc */
1410 int iSrc, iDest; /* Cursors from source and destination */
1411 int addr1, addr2; /* Loop addresses */
1412 int emptyDestTest; /* Address of test for empty pDest */
1413 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001414 Vdbe *v; /* The VDBE we are building */
1415 KeyInfo *pKey; /* Key information for an index */
1416 int counterMem; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001417 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001418
1419 if( pSelect==0 ){
1420 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1421 }
1422 if( pDest->pTrigger ){
1423 return 0; /* tab1 must not have triggers */
1424 }
1425#ifndef SQLITE_OMIT_VIRTUALTABLE
1426 if( pDest->isVirtual ){
1427 return 0; /* tab1 must not be a virtual table */
1428 }
1429#endif
1430 if( onError==OE_Default ){
1431 onError = OE_Abort;
1432 }
1433 if( onError!=OE_Abort && onError!=OE_Rollback ){
1434 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1435 }
danielk19775ce240a2007-09-03 17:30:06 +00001436 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001437 if( pSelect->pSrc->nSrc!=1 ){
1438 return 0; /* FROM clause must have exactly one term */
1439 }
1440 if( pSelect->pSrc->a[0].pSelect ){
1441 return 0; /* FROM clause cannot contain a subquery */
1442 }
1443 if( pSelect->pWhere ){
1444 return 0; /* SELECT may not have a WHERE clause */
1445 }
1446 if( pSelect->pOrderBy ){
1447 return 0; /* SELECT may not have an ORDER BY clause */
1448 }
drh8103b7d2007-02-24 13:23:51 +00001449 /* Do not need to test for a HAVING clause. If HAVING is present but
1450 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001451 if( pSelect->pGroupBy ){
1452 return 0; /* SELECT may not have a GROUP BY clause */
1453 }
1454 if( pSelect->pLimit ){
1455 return 0; /* SELECT may not have a LIMIT clause */
1456 }
drh8103b7d2007-02-24 13:23:51 +00001457 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001458 if( pSelect->pPrior ){
1459 return 0; /* SELECT may not be a compound query */
1460 }
1461 if( pSelect->isDistinct ){
1462 return 0; /* SELECT may not be DISTINCT */
1463 }
1464 pEList = pSelect->pEList;
1465 assert( pEList!=0 );
1466 if( pEList->nExpr!=1 ){
1467 return 0; /* The result set must have exactly one column */
1468 }
1469 assert( pEList->a[0].pExpr );
1470 if( pEList->a[0].pExpr->op!=TK_ALL ){
1471 return 0; /* The result set must be the special operator "*" */
1472 }
1473
1474 /* At this point we have established that the statement is of the
1475 ** correct syntactic form to participate in this optimization. Now
1476 ** we have to check the semantics.
1477 */
1478 pItem = pSelect->pSrc->a;
1479 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1480 if( pSrc==0 ){
1481 return 0; /* FROM clause does not contain a real table */
1482 }
1483 if( pSrc==pDest ){
1484 return 0; /* tab1 and tab2 may not be the same table */
1485 }
1486#ifndef SQLITE_OMIT_VIRTUALTABLE
1487 if( pSrc->isVirtual ){
1488 return 0; /* tab2 must not be a virtual table */
1489 }
1490#endif
1491 if( pSrc->pSelect ){
1492 return 0; /* tab2 may not be a view */
1493 }
1494 if( pDest->nCol!=pSrc->nCol ){
1495 return 0; /* Number of columns must be the same in tab1 and tab2 */
1496 }
1497 if( pDest->iPKey!=pSrc->iPKey ){
1498 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1499 }
1500 for(i=0; i<pDest->nCol; i++){
1501 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1502 return 0; /* Affinity must be the same on all columns */
1503 }
1504 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1505 return 0; /* Collating sequence must be the same on all columns */
1506 }
1507 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1508 return 0; /* tab2 must be NOT NULL if tab1 is */
1509 }
1510 }
1511 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001512 if( pDestIdx->onError!=OE_None ){
1513 destHasUniqueIdx = 1;
1514 }
drh9d9cf222007-02-13 15:01:11 +00001515 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1516 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1517 }
1518 if( pSrcIdx==0 ){
1519 return 0; /* pDestIdx has no corresponding index in pSrc */
1520 }
1521 }
drh7fc2f412007-03-29 00:08:24 +00001522#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001523 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001524 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1525 }
drh7fc2f412007-03-29 00:08:24 +00001526#endif
drh9d9cf222007-02-13 15:01:11 +00001527
1528 /* If we get this far, it means either:
1529 **
1530 ** * We can always do the transfer if the table contains an
1531 ** an integer primary key
1532 **
1533 ** * We can conditionally do the transfer if the destination
1534 ** table is empty.
1535 */
drhdd735212007-02-24 13:53:05 +00001536#ifdef SQLITE_TEST
1537 sqlite3_xferopt_count++;
1538#endif
drh9d9cf222007-02-13 15:01:11 +00001539 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1540 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001541 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001542 iSrc = pParse->nTab++;
1543 iDest = pParse->nTab++;
1544 counterMem = autoIncBegin(pParse, iDbDest, pDest);
1545 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001546 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001547 /* If tables do not have an INTEGER PRIMARY KEY and there
1548 ** are indices to be copied and the destination is not empty,
1549 ** we have to disallow the transfer optimization because the
1550 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001551 **
1552 ** Or if the destination has a UNIQUE index and is not empty,
1553 ** we also disallow the transfer optimization because we cannot
1554 ** insure that all entries in the union of DEST and SRC will be
1555 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001556 */
drh66a51672008-01-03 00:01:23 +00001557 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1558 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001559 sqlite3VdbeJumpHere(v, addr1);
1560 }else{
1561 emptyDestTest = 0;
1562 }
1563 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001564 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001565 if( pDest->iPKey>=0 ){
drh66a51672008-01-03 00:01:23 +00001566 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001567 sqlite3VdbeAddOp0(v, OP_Copy);
drh66a51672008-01-03 00:01:23 +00001568 addr2 = sqlite3VdbeAddOp2(v, OP_NotExists, iDest, 0);
1569 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1570 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001571 sqlite3VdbeJumpHere(v, addr2);
danielk1977287fb612008-01-04 19:10:28 +00001572 autoIncStep(pParse, counterMem, 0);
drhbd36ba62007-03-31 13:00:26 +00001573 }else if( pDest->pIndex==0 ){
drh4c583122008-01-04 22:01:03 +00001574 addr1 = sqlite3VdbeAddOp1(v, OP_NewRowid, iDest);
drh95bad4c2007-03-28 18:04:10 +00001575 }else{
drh66a51672008-01-03 00:01:23 +00001576 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001577 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001578 }
drh66a51672008-01-03 00:01:23 +00001579 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, 0);
danielk19771f4aa332008-01-03 09:51:55 +00001580 sqlite3CodeInsert(pParse,iDest,OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1581 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001582 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh9d9cf222007-02-13 15:01:11 +00001583 autoIncEnd(pParse, iDbDest, pDest, counterMem);
1584 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1585 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1586 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1587 }
1588 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001589 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1590 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001591 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001592 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1593 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001594 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001595 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001596 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001597 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001598 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001599 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1600 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, 0);
1601 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, 1);
1602 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001603 sqlite3VdbeJumpHere(v, addr1);
1604 }
1605 sqlite3VdbeJumpHere(v, emptySrcTest);
drh66a51672008-01-03 00:01:23 +00001606 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1607 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001608 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001609 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001610 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001611 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001612 return 0;
1613 }else{
1614 return 1;
1615 }
1616}
1617#endif /* SQLITE_OMIT_XFER_OPT */