blob: c4fe10717c4ef4b7c06b03d8837d24c304007614 [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**
drh6a288a32008-01-07 19:20:24 +000015** $Id: insert.c,v 1.215 2008/01/07 19:20:25 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
drh6a288a32008-01-07 19:20:24 +0000141** table and stores that value in a register. Code generated by
142** autoIncStep() will keep that register holding the largest
drh9d9cf222007-02-13 15:01:11 +0000143** 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**
drh6a288a32008-01-07 19:20:24 +0000149** Three consecutive registers are allocated by this routine. The
150** first two hold the name of the target table and the maximum rowid
151** inserted into the target table, respectively.
152** The third holds the rowid in sqlite_sequence where we will
153** write back the revised maximum rowid. This routine returns the
154** index of the second of these three registers.
drh9d9cf222007-02-13 15:01:11 +0000155*/
156static int autoIncBegin(
157 Parse *pParse, /* Parsing context */
158 int iDb, /* Index of the database holding pTab */
159 Table *pTab /* The table we are writing to */
160){
drh6a288a32008-01-07 19:20:24 +0000161 int memId = 0; /* Register holding maximum rowid */
drh9d9cf222007-02-13 15:01:11 +0000162 if( pTab->autoInc ){
163 Vdbe *v = pParse->pVdbe;
164 Db *pDb = &pParse->db->aDb[iDb];
165 int iCur = pParse->nTab;
drh6a288a32008-01-07 19:20:24 +0000166 int addr; /* Address of the top of the loop */
drh9d9cf222007-02-13 15:01:11 +0000167 assert( v );
drh6a288a32008-01-07 19:20:24 +0000168 pParse->nMem++; /* Holds name of table */
169 memId = ++pParse->nMem;
170 pParse->nMem++;
drh9d9cf222007-02-13 15:01:11 +0000171 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh6a288a32008-01-07 19:20:24 +0000172 addr = sqlite3VdbeCurrentAddr(v);
173 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8);
drh66a51672008-01-03 00:01:23 +0000174 sqlite3VdbeAddOp2(v, OP_Column, iCur, 0);
175 sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
drh6a288a32008-01-07 19:20:24 +0000176 sqlite3VdbeAddOp2(v, OP_Ne, 0x100, addr+7);
177 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
178 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
179 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
180 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1);
drh66a51672008-01-03 00:01:23 +0000181 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000182 }
183 return memId;
184}
185
186/*
187** Update the maximum rowid for an autoincrement calculation.
188**
189** This routine should be called when the top of the stack holds a
190** new rowid that is about to be inserted. If that new rowid is
191** larger than the maximum rowid in the memId memory cell, then the
192** memory cell is updated. The stack is unchanged.
193*/
drh6a288a32008-01-07 19:20:24 +0000194static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000195 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000196 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000197 }
198}
199
200/*
201** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000202** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000203** the sqlite_sequence table.
204*/
205static void autoIncEnd(
206 Parse *pParse, /* The parsing context */
207 int iDb, /* Index of the database holding pTab */
208 Table *pTab, /* Table we are inserting into */
209 int memId /* Memory cell holding the maximum rowid */
210){
211 if( pTab->autoInc ){
212 int iCur = pParse->nTab;
213 Vdbe *v = pParse->pVdbe;
214 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000215 int j1;
216
drh9d9cf222007-02-13 15:01:11 +0000217 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000218 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000219 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
220 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
221 sqlite3VdbeJumpHere(v, j1);
222 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
223 sqlite3VdbeAddOp3(v, OP_RegMakeRec, memId-1, 2, memId-1);
224 sqlite3VdbeAddOp3(v, OP_Insert, iCur, memId-1, memId+1);
225 sqlite3VdbeChangeP5(v, -1, OPFLAG_APPEND);
226 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000227 }
228}
229#else
230/*
231** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
232** above are all no-ops
233*/
234# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000235# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000236# define autoIncEnd(A,B,C,D)
237#endif /* SQLITE_OMIT_AUTOINCREMENT */
238
239
240/* Forward declaration */
241static int xferOptimization(
242 Parse *pParse, /* Parser context */
243 Table *pDest, /* The table we are inserting into */
244 Select *pSelect, /* A SELECT statement to use as the data source */
245 int onError, /* How to handle constraint errors */
246 int iDbDest /* The database of pDest */
247);
248
danielk19773d1bfea2004-05-14 11:00:53 +0000249/*
drh1ccde152000-06-17 13:12:39 +0000250** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000251**
252** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000253** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000254**
drh1ccde152000-06-17 13:12:39 +0000255** The IDLIST following the table name is always optional. If omitted,
256** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000257** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000258**
259** The pList parameter holds EXPRLIST in the first form of the INSERT
260** statement above, and pSelect is NULL. For the second form, pList is
261** NULL and pSelect is a pointer to the select statement used to generate
262** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000263**
drh9d9cf222007-02-13 15:01:11 +0000264** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000265** select with data coming from a VALUES clause, the code executes
266** once straight down through. The template looks like this:
267**
268** open write cursor to <table> and its indices
269** puts VALUES clause expressions onto the stack
270** write the resulting record into <table>
271** cleanup
272**
drh9d9cf222007-02-13 15:01:11 +0000273** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000274**
275** INSERT INTO <table> SELECT ...
276**
drh9d9cf222007-02-13 15:01:11 +0000277** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
278** in other words if the SELECT pulls all columns from a single table
279** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
280** if <table2> and <table1> are distinct tables but have identical
281** schemas, including all the same indices, then a special optimization
282** is invoked that copies raw records from <table2> over to <table1>.
283** See the xferOptimization() function for the implementation of this
284** template. This is the second template.
285**
286** open a write cursor to <table>
287** open read cursor on <table2>
288** transfer all records in <table2> over to <table>
289** close cursors
290** foreach index on <table>
291** open a write cursor on the <table> index
292** open a read cursor on the corresponding <table2> index
293** transfer all records from the read to the write cursors
294** close cursors
295** end foreach
296**
297** The third template is for when the second template does not apply
298** and the SELECT clause does not read from <table> at any time.
299** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000300**
301** goto B
302** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000303** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000304** gosub C
305** end loop
306** cleanup after the SELECT
307** goto D
308** B: open write cursor to <table> and its indices
309** goto A
310** C: insert the select result into <table>
311** return
312** D: cleanup
313**
drh9d9cf222007-02-13 15:01:11 +0000314** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000315** values from a SELECT but the data is being inserted into a table
316** that is also read as part of the SELECT. In the third form,
317** we have to use a intermediate table to store the results of
318** the select. The template is like this:
319**
320** goto B
321** A: setup for the SELECT
322** loop over the tables in the SELECT
323** gosub C
324** end loop
325** cleanup after the SELECT
326** goto D
327** C: insert the select result into the intermediate table
328** return
329** B: open a cursor to an intermediate table
330** goto A
331** D: open write cursor to <table> and its indices
332** loop over the intermediate table
333** transfer values form intermediate table into <table>
334** end the loop
335** cleanup
drhcce7d172000-05-31 15:34:51 +0000336*/
danielk19774adee202004-05-08 08:23:19 +0000337void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000338 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000339 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000340 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000341 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000342 IdList *pColumn, /* Column names corresponding to IDLIST. */
343 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000344){
drh6a288a32008-01-07 19:20:24 +0000345 sqlite3 *db; /* The main database structure */
346 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000347 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000348 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000349 int i, j, idx; /* Loop counters */
350 Vdbe *v; /* Generate code into this virtual machine */
351 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000352 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000353 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
danielk1977cfe9a692004-06-16 12:00:29 +0000354 int base = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000355 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000356 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000357 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000358 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drh6a288a32008-01-07 19:20:24 +0000359 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
danielk1977cfe9a692004-06-16 12:00:29 +0000360 int iSelectLoop = 0; /* Address of code that implements the SELECT */
361 int iCleanup = 0; /* Address of the cleanup code */
362 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
drh6a288a32008-01-07 19:20:24 +0000363 int newIdx = -1; /* Cursor for the NEW pseudo-table */
364 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000365 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000366 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000367
drh6a288a32008-01-07 19:20:24 +0000368 /* Register allocations */
369 int regFromSelect; /* Base register for data coming from SELECT */
370 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
371 int regRowCount = 0; /* Memory cell used for the row counter */
372 int regIns; /* Block of regs holding rowid+data being inserted */
373 int regRowid; /* registers holding insert rowid */
374 int regData; /* register holding first column to insert */
375 int regRecord; /* Holds the assemblied row record */
376
danielk1977034ca142007-06-26 10:38:54 +0000377
drh798da522004-11-04 04:42:28 +0000378#ifndef SQLITE_OMIT_TRIGGER
379 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000380 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000381#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000382
drh17435752007-08-16 04:30:38 +0000383 db = pParse->db;
384 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000385 goto insert_cleanup;
386 }
drhdaffd0e2001-04-11 14:28:42 +0000387
drh1ccde152000-06-17 13:12:39 +0000388 /* Locate the table into which we will be inserting new information.
389 */
drh113088e2003-03-20 01:16:58 +0000390 assert( pTabList->nSrc==1 );
391 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000392 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000393 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000394 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000395 goto insert_cleanup;
396 }
danielk1977da184232006-01-05 11:34:32 +0000397 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
398 assert( iDb<db->nDb );
399 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000400 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000401 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000402 goto insert_cleanup;
403 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000404
drhb7f91642004-10-31 02:22:47 +0000405 /* Figure out if we have any triggers and if the table being
406 ** inserted into is a view
407 */
408#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000409 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000410 isView = pTab->pSelect!=0;
411#else
drhdca76842004-12-07 14:06:13 +0000412# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000413# define isView 0
414#endif
415#ifdef SQLITE_OMIT_VIEW
416# undef isView
417# define isView 0
418#endif
419
danielk1977c3f9bad2002-05-15 08:30:12 +0000420 /* Ensure that:
421 * (a) the table is not read-only,
422 * (b) that if it is a view then ON INSERT triggers exist
423 */
drhdca76842004-12-07 14:06:13 +0000424 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000425 goto insert_cleanup;
426 }
drh43617e92006-03-06 20:55:46 +0000427 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000428
drhf573c992002-07-31 00:32:50 +0000429 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000430 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
431 ** module table).
drhf573c992002-07-31 00:32:50 +0000432 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000433 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000434 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000435 }
436
drh1ccde152000-06-17 13:12:39 +0000437 /* Allocate a VDBE
438 */
danielk19774adee202004-05-08 08:23:19 +0000439 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000440 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000441 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000442 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000443
danielk1977c3f9bad2002-05-15 08:30:12 +0000444 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000445 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000446 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000447 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000448
drh9d9cf222007-02-13 15:01:11 +0000449#ifndef SQLITE_OMIT_XFER_OPT
450 /* If the statement is of the form
451 **
452 ** INSERT INTO <table1> SELECT * FROM <table2>;
453 **
454 ** Then special optimizations can be applied that make the transfer
455 ** very fast and which reduce fragmentation of indices.
456 */
457 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
458 assert( !triggers_exist );
459 assert( pList==0 );
460 goto insert_cleanup;
461 }
462#endif /* SQLITE_OMIT_XFER_OPT */
463
drh2958a4e2004-11-12 03:56:15 +0000464 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000465 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000466 */
drh6a288a32008-01-07 19:20:24 +0000467 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000468
drh1ccde152000-06-17 13:12:39 +0000469 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000470 ** is coming from a SELECT statement, then this step also generates
471 ** all the code to implement the SELECT statement and invoke a subroutine
472 ** to process each row of the result. (Template 2.) If the SELECT
473 ** statement uses the the table that is being inserted into, then the
474 ** subroutine is also coded here. That subroutine stores the SELECT
475 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000476 */
drh5974a302000-06-07 14:42:26 +0000477 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000478 /* Data is coming from a SELECT. Generate code to implement that SELECT
479 */
drh1013c932008-01-06 00:25:21 +0000480 SelectDest dest;
drh142e30d2002-08-28 03:00:58 +0000481 int rc, iInitCode;
drh1013c932008-01-06 00:25:21 +0000482
drh66a51672008-01-03 00:01:23 +0000483 iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000484 iSelectLoop = sqlite3VdbeCurrentAddr(v);
485 iInsertBlock = sqlite3VdbeMakeLabel(v);
drh1013c932008-01-06 00:25:21 +0000486 sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
danielk1977b3bce662005-01-29 08:32:43 +0000487
488 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000489 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
drh17435752007-08-16 04:30:38 +0000490 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000491 goto insert_cleanup;
492 }
danielk1977b3bce662005-01-29 08:32:43 +0000493
drh6a288a32008-01-07 19:20:24 +0000494 regFromSelect = dest.iMem;
danielk19774adee202004-05-08 08:23:19 +0000495 iCleanup = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000496 sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000497 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000498 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000499
500 /* Set useTempTable to TRUE if the result of the SELECT statement
501 ** should be written into a temporary table. Set to FALSE if each
502 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000503 **
504 ** A temp table must be used if the table being updated is also one
505 ** of the tables being read by the SELECT statement. Also use a
506 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000507 */
drh48d11782007-11-23 15:02:19 +0000508 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000509 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000510 }
drh142e30d2002-08-28 03:00:58 +0000511
512 if( useTempTable ){
513 /* Generate the subroutine that SELECT calls to process each row of
514 ** the result. Store the result in a temporary table
515 */
516 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000517 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000518 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regFromSelect, nColumn);
drh4c583122008-01-04 22:01:03 +0000519 sqlite3VdbeAddOp1(v, OP_NewRowid, srcTab);
drh66a51672008-01-03 00:01:23 +0000520 sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
danielk19771f4aa332008-01-03 09:51:55 +0000521 sqlite3CodeInsert(pParse, srcTab, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000522 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000523
524 /* The following code runs first because the GOTO at the very top
525 ** of the program jumps to it. Create the temporary table, then jump
526 ** back up and execute the SELECT code above.
527 */
drhd654be82005-09-20 17:42:23 +0000528 sqlite3VdbeJumpHere(v, iInitCode);
drh66a51672008-01-03 00:01:23 +0000529 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
530 sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
531 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000532 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000533 }else{
drhd654be82005-09-20 17:42:23 +0000534 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000535 }
drh5974a302000-06-07 14:42:26 +0000536 }else{
drh142e30d2002-08-28 03:00:58 +0000537 /* This is the case if the data for the INSERT is coming from a VALUES
538 ** clause
539 */
danielk1977b3bce662005-01-29 08:32:43 +0000540 NameContext sNC;
541 memset(&sNC, 0, sizeof(sNC));
542 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000543 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000544 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000545 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000546 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000547 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000548 goto insert_cleanup;
549 }
drhe64e7b22002-02-18 13:56:36 +0000550 }
drh5974a302000-06-07 14:42:26 +0000551 }
drh1ccde152000-06-17 13:12:39 +0000552
553 /* Make sure the number of columns in the source data matches the number
554 ** of columns to be inserted into the table.
555 */
danielk1977034ca142007-06-26 10:38:54 +0000556 if( IsVirtual(pTab) ){
557 for(i=0; i<pTab->nCol; i++){
558 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
559 }
560 }
561 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000562 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000563 "table %S has %d columns but %d values were supplied",
564 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000565 goto insert_cleanup;
566 }
drh967e8b72000-06-21 13:59:10 +0000567 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000568 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000569 goto insert_cleanup;
570 }
drh1ccde152000-06-17 13:12:39 +0000571
572 /* If the INSERT statement included an IDLIST term, then make sure
573 ** all elements of the IDLIST really are columns of the table and
574 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000575 **
576 ** If the table has an INTEGER PRIMARY KEY column and that column
577 ** is named in the IDLIST, then record in the keyColumn variable
578 ** the index into IDLIST of the primary key column. keyColumn is
579 ** the index of the primary key as it appears in IDLIST, not as
580 ** is appears in the original table. (The index of the primary
581 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000582 */
drh967e8b72000-06-21 13:59:10 +0000583 if( pColumn ){
584 for(i=0; i<pColumn->nId; i++){
585 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000586 }
drh967e8b72000-06-21 13:59:10 +0000587 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000588 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000589 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000590 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000591 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000592 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000593 }
drhcce7d172000-05-31 15:34:51 +0000594 break;
595 }
596 }
597 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000598 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000599 keyColumn = i;
600 }else{
danielk19774adee202004-05-08 08:23:19 +0000601 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000602 pTabList, 0, pColumn->a[i].zName);
603 pParse->nErr++;
604 goto insert_cleanup;
605 }
drhcce7d172000-05-31 15:34:51 +0000606 }
607 }
608 }
drh1ccde152000-06-17 13:12:39 +0000609
drhaacc5432002-01-06 17:07:40 +0000610 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000611 ** key, the set the keyColumn variable to the primary key column index
612 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000613 */
drh147d0cc2006-08-25 23:42:53 +0000614 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000615 keyColumn = pTab->iPKey;
616 }
617
drh142e30d2002-08-28 03:00:58 +0000618 /* Open the temp table for FOR EACH ROW triggers
619 */
drhdca76842004-12-07 14:06:13 +0000620 if( triggers_exist ){
drh66a51672008-01-03 00:01:23 +0000621 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
622 sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000623 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000624
drhfeeb1392002-04-09 03:28:01 +0000625 /* Initialize the count of rows to be inserted
626 */
drh142e30d2002-08-28 03:00:58 +0000627 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000628 regRowCount = ++pParse->nMem;
629 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000630 }
631
danielk1977e448dc42008-01-02 11:50:51 +0000632 /* If this is not a view, open the table and and all indices */
633 if( !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000634 base = pParse->nTab;
drh290c1942004-08-21 17:54:45 +0000635 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
danielk1977c3f9bad2002-05-15 08:30:12 +0000636 }
637
drh142e30d2002-08-28 03:00:58 +0000638 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000639 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000640 ** source is a subroutine call from the SELECT statement, then we need
641 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000642 */
drh142e30d2002-08-28 03:00:58 +0000643 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000644 iBreak = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000645 sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +0000646 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000647 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000648 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000649 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000650 sqlite3RegToStack(pParse, regFromSelect, nColumn);
drh66a51672008-01-03 00:01:23 +0000651 sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000652 }
drh1ccde152000-06-17 13:12:39 +0000653
drh6a288a32008-01-07 19:20:24 +0000654 /* Allocate registers for holding the rowid of the new row,
655 ** the content of the new row, and the assemblied row record.
656 */
657 regRecord = ++pParse->nMem;
658 regRowid = regIns = pParse->nMem+1;
659 pParse->nMem += pTab->nCol + 1;
660 if( IsVirtual(pTab) ){
661 regRowid++;
662 pParse->nMem++;
663 }
664 regData = regRowid+1;
665
drh5cf590c2003-04-24 01:45:04 +0000666 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000667 */
danielk19774adee202004-05-08 08:23:19 +0000668 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000669 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000670
drh70ce3f02003-04-15 19:22:22 +0000671 /* build the NEW.* reference row. Note that if there is an INTEGER
672 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
673 ** translated into a unique ID for the row. But on a BEFORE trigger,
674 ** we do not know what the unique ID will be (because the insert has
675 ** not happened yet) so we substitute a rowid of -1
676 */
677 if( keyColumn<0 ){
drh66a51672008-01-03 00:01:23 +0000678 sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000679 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000680 sqlite3VdbeAddOp2(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000681 }else{
drh6a288a32008-01-07 19:20:24 +0000682 int j1;
drhd6fe9612005-01-14 01:22:00 +0000683 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh389a1ad2008-01-03 23:44:53 +0000684 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drh6a288a32008-01-07 19:20:24 +0000685 sqlite3VdbeAddOp0(v, OP_SCopy);
686 j1 = sqlite3VdbeAddOp0(v, OP_NotNull);
687 sqlite3VdbeAddOp1(v, OP_Pop, 1);
688 sqlite3VdbeAddOp1(v, OP_Integer, -1);
689 sqlite3VdbeJumpHere(v, j1);
690 sqlite3VdbeAddOp0(v, OP_MustBeInt);
drh70ce3f02003-04-15 19:22:22 +0000691 }
692
danielk1977034ca142007-06-26 10:38:54 +0000693 /* Cannot have triggers on a virtual table. If it were possible,
694 ** this block would have to account for hidden column.
695 */
696 assert(!IsVirtual(pTab));
697
drh70ce3f02003-04-15 19:22:22 +0000698 /* Create the new column data
699 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000700 for(i=0; i<pTab->nCol; i++){
701 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000702 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000703 }else{
drh9adf9ac2002-05-15 11:44:13 +0000704 for(j=0; j<pColumn->nId; j++){
705 if( pColumn->a[j].idx==i ) break;
706 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000707 }
708 if( pColumn && j>=pColumn->nId ){
drh389a1ad2008-01-03 23:44:53 +0000709 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
drh142e30d2002-08-28 03:00:58 +0000710 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000711 sqlite3VdbeAddOp2(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000712 }else{
drhd6fe9612005-01-14 01:22:00 +0000713 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000714 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000715 }
716 }
drh66a51672008-01-03 00:01:23 +0000717 sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000718
719 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
720 ** do not attempt any conversions before assembling the record.
721 ** If this is a real table, attempt conversions as required by the
722 ** table column affinities.
723 */
724 if( !isView ){
725 sqlite3TableAffinityStr(v, pTab);
726 }
danielk19771f4aa332008-01-03 09:51:55 +0000727 sqlite3CodeInsert(pParse, newIdx, OPFLAG_APPEND);
danielk1977c3f9bad2002-05-15 08:30:12 +0000728
drh5cf590c2003-04-24 01:45:04 +0000729 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000730 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000731 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000732 goto insert_cleanup;
733 }
drh70ce3f02003-04-15 19:22:22 +0000734 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000735
drh4a324312001-12-21 14:30:42 +0000736 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000737 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000738 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000739 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000740 */
drh5cf590c2003-04-24 01:45:04 +0000741 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000742 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000743 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000744 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000745 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000746 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000747 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000748 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000749 }else if( pSelect ){
drh6a288a32008-01-07 19:20:24 +0000750 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn - keyColumn - 1), regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000751 }else{
drhe4d90812007-03-29 05:51:49 +0000752 VdbeOp *pOp;
drh389a1ad2008-01-03 23:44:53 +0000753 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drhe4d90812007-03-29 05:51:49 +0000754 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000755 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000756 appendFlag = 1;
757 pOp->opcode = OP_NewRowid;
758 pOp->p1 = base;
drh6a288a32008-01-07 19:20:24 +0000759 pOp->p2 = regRowid;
760 pOp->p3 = regAutoinc;
danielk1977287fb612008-01-04 19:10:28 +0000761 }else{
762 /* TODO: Avoid this use of the stack. */
drh6a288a32008-01-07 19:20:24 +0000763 sqlite3VdbeAddOp2(v, OP_Move, 0, regRowid);
drhe4d90812007-03-29 05:51:49 +0000764 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000765 }
drhf0863fe2005-06-12 21:35:51 +0000766 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000767 ** to generate a unique primary key value.
768 */
drhe4d90812007-03-29 05:51:49 +0000769 if( !appendFlag ){
drh6a288a32008-01-07 19:20:24 +0000770 sqlite3VdbeAddOp2(v, OP_IfMemNull, regRowid, sqlite3VdbeCurrentAddr(v)+2);
danielk1977287fb612008-01-04 19:10:28 +0000771 sqlite3VdbeAddOp2(v, OP_Goto, -1, sqlite3VdbeCurrentAddr(v)+2);
drh6a288a32008-01-07 19:20:24 +0000772 sqlite3VdbeAddOp3(v, OP_NewRowid, base, regRowid, regAutoinc);
773 sqlite3VdbeAddOp3(v, OP_MustBeInt, 0, 0, regRowid);
drhe4d90812007-03-29 05:51:49 +0000774 }
drh4cbdda92006-06-14 19:00:20 +0000775 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000776 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000777 }else{
drh6a288a32008-01-07 19:20:24 +0000778 sqlite3VdbeAddOp3(v, OP_NewRowid, base, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000779 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000780 }
drh6a288a32008-01-07 19:20:24 +0000781 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000782
danielk1977c3f9bad2002-05-15 08:30:12 +0000783 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000784 ** with the first column.
785 */
danielk1977034ca142007-06-26 10:38:54 +0000786 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000787 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000788 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000789 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000790 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000791 ** Whenever this column is read, the record number will be substituted
792 ** in its place. So will fill this column with a NULL to avoid
793 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000794 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000795 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000796 }
797 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000798 if( IsHiddenColumn(&pTab->aCol[i]) ){
799 assert( IsVirtual(pTab) );
800 j = -1;
801 nHidden++;
802 }else{
803 j = i - nHidden;
804 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000805 }else{
drh9adf9ac2002-05-15 11:44:13 +0000806 for(j=0; j<pColumn->nId; j++){
807 if( pColumn->a[j].idx==i ) break;
808 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000809 }
danielk1977034ca142007-06-26 10:38:54 +0000810 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000811 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000812 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000813 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000814 }else if( pSelect ){
drhb1fdb2a2008-01-05 04:06:03 +0000815 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn-j-1), iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000816 }else{
danielk1977287fb612008-01-04 19:10:28 +0000817 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000818 }
drhbed86902000-06-02 13:27:59 +0000819 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000820
821 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000822 ** do the insertion.
823 */
drh4cbdda92006-06-14 19:00:20 +0000824#ifndef SQLITE_OMIT_VIRTUALTABLE
825 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000826 pParse->pVirtualLock = pTab;
drh6a288a32008-01-07 19:20:24 +0000827 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000828 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000829 }else
830#endif
831 {
drh6a288a32008-01-07 19:20:24 +0000832 sqlite3RegToStack(pParse, regIns, pTab->nCol+1);
drh4cbdda92006-06-14 19:00:20 +0000833 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
834 0, onError, endOfLoop);
835 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
drhe4d90812007-03-29 05:51:49 +0000836 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
837 appendFlag);
drh4cbdda92006-06-14 19:00:20 +0000838 }
drh5cf590c2003-04-24 01:45:04 +0000839 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000840
drh5cf590c2003-04-24 01:45:04 +0000841 /* Update the count of rows that are inserted
842 */
843 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000844 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000845 }
drh1ccde152000-06-17 13:12:39 +0000846
drhdca76842004-12-07 14:06:13 +0000847 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000848 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000849 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000850 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000851 goto insert_cleanup;
852 }
drh1bee3d72001-10-15 00:44:35 +0000853 }
854
drh1ccde152000-06-17 13:12:39 +0000855 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000856 */
danielk19774adee202004-05-08 08:23:19 +0000857 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000858 if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000859 sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
danielk19774adee202004-05-08 08:23:19 +0000860 sqlite3VdbeResolveLabel(v, iBreak);
drh66a51672008-01-03 00:01:23 +0000861 sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000862 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000863 sqlite3VdbeAddOp2(v, OP_Pop, nColumn, 0);
864 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000865 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000866 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000867
danielk1977e448dc42008-01-02 11:50:51 +0000868 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000869 /* Close all tables opened */
drh66a51672008-01-03 00:01:23 +0000870 sqlite3VdbeAddOp2(v, OP_Close, base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000871 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh66a51672008-01-03 00:01:23 +0000872 sqlite3VdbeAddOp2(v, OP_Close, idx+base, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000873 }
drhcce7d172000-05-31 15:34:51 +0000874 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000875
drhf3388142004-11-13 03:48:06 +0000876 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000877 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000878 ** table.
drh2958a4e2004-11-12 03:56:15 +0000879 */
drh6a288a32008-01-07 19:20:24 +0000880 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000881
drh1bee3d72001-10-15 00:44:35 +0000882 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000883 ** Return the number of rows inserted. If this routine is
884 ** generating code because of a call to sqlite3NestedParse(), do not
885 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000886 */
danielk1977cc6bd382005-01-10 02:48:49 +0000887 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +0000888 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +0000889 sqlite3VdbeSetNumCols(v, 1);
drh66a51672008-01-03 00:01:23 +0000890 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000891 }
drhcce7d172000-05-31 15:34:51 +0000892
893insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000894 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000895 sqlite3ExprListDelete(pList);
896 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000897 sqlite3IdListDelete(pColumn);
drhcce7d172000-05-31 15:34:51 +0000898}
drh9cfcf5d2002-01-29 18:41:24 +0000899
drh9cfcf5d2002-01-29 18:41:24 +0000900/*
drh6a288a32008-01-07 19:20:24 +0000901** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +0000902**
903** When this routine is called, the stack contains (from bottom to top)
drh0ca3e242002-01-29 23:07:02 +0000904** the following values:
905**
drhf0863fe2005-06-12 21:35:51 +0000906** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000907** value is omitted unless we are doing an UPDATE that involves a
drh6a288a32008-01-07 19:20:24 +0000908** change to the record number. (Or writing to a virtual table.)
drh0ca3e242002-01-29 23:07:02 +0000909**
drhf0863fe2005-06-12 21:35:51 +0000910** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000911**
912** 3. The data in the first column of the entry after the update.
913**
914** i. Data from middle columns...
915**
916** N. The data in the last column of the entry after the update.
917**
drhf0863fe2005-06-12 21:35:51 +0000918** The old rowid shown as entry (1) above is omitted unless both isUpdate
919** and rowidChng are 1. isUpdate is true for UPDATEs and false for
920** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000921**
922** The code generated by this routine pushes additional entries onto
923** the stack which are the keys for new index entries for the new record.
924** The order of index keys is the same as the order of the indices on
925** the pTable->pIndex list. A key is only created for index i if
926** aIdxUsed!=0 and aIdxUsed[i]!=0.
drh9cfcf5d2002-01-29 18:41:24 +0000927**
928** This routine also generates code to check constraints. NOT NULL,
929** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000930** then the appropriate action is performed. There are five possible
931** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000932**
933** Constraint type Action What Happens
934** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000935** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000936** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000937** return code of SQLITE_CONSTRAINT.
938**
drh1c928532002-01-31 15:54:21 +0000939** any ABORT Back out changes from the current command
940** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000941** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000942** with SQLITE_CONSTRAINT.
943**
944** any FAIL Sqlite_exec() returns immediately with a
945** return code of SQLITE_CONSTRAINT. The
946** transaction is not rolled back and any
947** prior changes are retained.
948**
drh9cfcf5d2002-01-29 18:41:24 +0000949** any IGNORE The record number and data is popped from
950** the stack and there is an immediate jump
951** to label ignoreDest.
952**
953** NOT NULL REPLACE The NULL value is replace by the default
954** value for that column. If the default value
955** is NULL, the action is the same as ABORT.
956**
957** UNIQUE REPLACE The other row that conflicts with the row
958** being inserted is removed.
959**
960** CHECK REPLACE Illegal. The results in an exception.
961**
drh1c928532002-01-31 15:54:21 +0000962** Which action to take is determined by the overrideError parameter.
963** Or if overrideError==OE_Default, then the pParse->onError parameter
964** is used. Or if pParse->onError==OE_Default then the onError value
965** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000966**
drhaaab5722002-02-19 13:39:21 +0000967** The calling routine must open a read/write cursor for pTab with
drh9cfcf5d2002-01-29 18:41:24 +0000968** cursor number "base". All indices of pTab must also have open
969** read/write cursors with cursor number base+i for the i-th cursor.
970** Except, if there is no possibility of a REPLACE action then
971** cursors do not need to be open for indices where aIdxUsed[i]==0.
972**
973** If the isUpdate flag is true, it means that the "base" cursor is
974** initially pointing to an entry that is being updated. The isUpdate
975** flag causes extra code to be generated so that the "base" cursor
976** is still pointing at the same entry after the routine returns.
977** Without the isUpdate flag, the "base" cursor might be moved.
978*/
danielk19774adee202004-05-08 08:23:19 +0000979void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +0000980 Parse *pParse, /* The parser context */
981 Table *pTab, /* the table into which we are inserting */
982 int base, /* Index of a read/write cursor pointing at pTab */
983 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +0000984 int rowidChng, /* True if the record number will change */
drhb419a922002-01-30 16:17:23 +0000985 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +0000986 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +0000987 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +0000988){
989 int i;
990 Vdbe *v;
991 int nCol;
992 int onError;
993 int addr;
994 int extra;
drh0ca3e242002-01-29 23:07:02 +0000995 int iCur;
996 Index *pIdx;
997 int seenReplace = 0;
danielk1977cfe9a692004-06-16 12:00:29 +0000998 int jumpInst1=0, jumpInst2;
drhf0863fe2005-06-12 21:35:51 +0000999 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001000
danielk19774adee202004-05-08 08:23:19 +00001001 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001002 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001003 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001004 nCol = pTab->nCol;
1005
1006 /* Test all NOT NULL constraints.
1007 */
1008 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001009 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001010 continue;
1011 }
drh9cfcf5d2002-01-29 18:41:24 +00001012 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001013 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001014 if( overrideError!=OE_Default ){
1015 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001016 }else if( onError==OE_Default ){
1017 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001018 }
danielk19777977a172004-11-09 12:44:37 +00001019 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001020 onError = OE_Abort;
1021 }
drhb1fdb2a2008-01-05 04:06:03 +00001022 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol-1-i));
drh6a288a32008-01-07 19:20:24 +00001023 addr = sqlite3VdbeAddOp0(v, OP_NotNull);
danielk1977b84f96f2005-01-20 11:32:23 +00001024 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1025 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001026 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001027 case OE_Rollback:
1028 case OE_Abort:
1029 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001030 char *zMsg = 0;
drh66a51672008-01-03 00:01:23 +00001031 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
danielk19774adee202004-05-08 08:23:19 +00001032 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001033 " may not be NULL", (char*)0);
drh66a51672008-01-03 00:01:23 +00001034 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001035 break;
1036 }
1037 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001038 sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1039 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001040 break;
1041 }
1042 case OE_Replace: {
drh389a1ad2008-01-03 23:44:53 +00001043 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001044 sqlite3VdbeAddOp1(v, OP_Push, nCol-i);
drh9cfcf5d2002-01-29 18:41:24 +00001045 break;
1046 }
drh9cfcf5d2002-01-29 18:41:24 +00001047 }
drhd654be82005-09-20 17:42:23 +00001048 sqlite3VdbeJumpHere(v, addr);
drh9cfcf5d2002-01-29 18:41:24 +00001049 }
1050
1051 /* Test all CHECK constraints
1052 */
drhffe07b22005-11-03 00:41:17 +00001053#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001054 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001055 int allOk = sqlite3VdbeMakeLabel(v);
1056 assert( pParse->ckOffset==0 );
1057 pParse->ckOffset = nCol;
drh6275b882005-11-03 01:22:30 +00001058 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhffe07b22005-11-03 00:41:17 +00001059 assert( pParse->ckOffset==nCol );
1060 pParse->ckOffset = 0;
drhaa01c7e2006-03-15 16:26:10 +00001061 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001062 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001063 sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1064 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001065 }else{
drh66a51672008-01-03 00:01:23 +00001066 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001067 }
drhffe07b22005-11-03 00:41:17 +00001068 sqlite3VdbeResolveLabel(v, allOk);
1069 }
1070#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001071
drh0bd1f4e2002-06-06 18:54:39 +00001072 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1073 ** of the new record does not previously exist. Except, if this
1074 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001075 */
drhf0863fe2005-06-12 21:35:51 +00001076 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001077 onError = pTab->keyConf;
1078 if( overrideError!=OE_Default ){
1079 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001080 }else if( onError==OE_Default ){
1081 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001082 }
drha0217ba2003-06-01 01:10:33 +00001083
drh5383ae52003-06-04 12:23:30 +00001084 if( isUpdate ){
drhb1fdb2a2008-01-05 04:06:03 +00001085 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+1));
1086 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+1));
drh66a51672008-01-03 00:01:23 +00001087 jumpInst1 = sqlite3VdbeAddOp2(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001088 }
drhb1fdb2a2008-01-05 04:06:03 +00001089 sqlite3VdbeAddOp1(v, OP_SCopy, -nCol);
drh66a51672008-01-03 00:01:23 +00001090 jumpInst2 = sqlite3VdbeAddOp2(v, OP_NotExists, base, 0);
drh5383ae52003-06-04 12:23:30 +00001091 switch( onError ){
1092 default: {
1093 onError = OE_Abort;
1094 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001095 }
drh5383ae52003-06-04 12:23:30 +00001096 case OE_Rollback:
1097 case OE_Abort:
1098 case OE_Fail: {
drh66a51672008-01-03 00:01:23 +00001099 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1100 "PRIMARY KEY must be unique", P4_STATIC);
drh5383ae52003-06-04 12:23:30 +00001101 break;
drh0ca3e242002-01-29 23:07:02 +00001102 }
drh5383ae52003-06-04 12:23:30 +00001103 case OE_Replace: {
drh74161702006-02-24 02:53:49 +00001104 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
drh5383ae52003-06-04 12:23:30 +00001105 if( isUpdate ){
drhb1fdb2a2008-01-05 04:06:03 +00001106 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+hasTwoRowids));
drh66a51672008-01-03 00:01:23 +00001107 sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
drh5383ae52003-06-04 12:23:30 +00001108 }
1109 seenReplace = 1;
1110 break;
drh0ca3e242002-01-29 23:07:02 +00001111 }
drh5383ae52003-06-04 12:23:30 +00001112 case OE_Ignore: {
1113 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001114 sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1115 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001116 break;
1117 }
1118 }
drhd654be82005-09-20 17:42:23 +00001119 sqlite3VdbeJumpHere(v, jumpInst2);
drh5383ae52003-06-04 12:23:30 +00001120 if( isUpdate ){
drhd654be82005-09-20 17:42:23 +00001121 sqlite3VdbeJumpHere(v, jumpInst1);
drhb1fdb2a2008-01-05 04:06:03 +00001122 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+1));
drh66a51672008-01-03 00:01:23 +00001123 sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
drh0ca3e242002-01-29 23:07:02 +00001124 }
1125 }
drh0bd1f4e2002-06-06 18:54:39 +00001126
1127 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1128 ** index and making sure that duplicate entries do not already exist.
1129 ** Add the new records to the indices as we go.
1130 */
drhb2fe7d82003-04-20 17:29:23 +00001131 extra = -1;
1132 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1133 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1134 extra++;
1135
1136 /* Create a key for accessing the index entry */
drhb1fdb2a2008-01-05 04:06:03 +00001137 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+extra));
drh9cfcf5d2002-01-29 18:41:24 +00001138 for(i=0; i<pIdx->nColumn; i++){
1139 int idx = pIdx->aiColumn[i];
1140 if( idx==pTab->iPKey ){
drhb1fdb2a2008-01-05 04:06:03 +00001141 sqlite3VdbeAddOp1(v, OP_SCopy, -(i+extra+nCol+1));
drh9cfcf5d2002-01-29 18:41:24 +00001142 }else{
drhb1fdb2a2008-01-05 04:06:03 +00001143 sqlite3VdbeAddOp1(v, OP_SCopy, -(i+extra+nCol-idx));
drh9cfcf5d2002-01-29 18:41:24 +00001144 }
1145 }
drh66a51672008-01-03 00:01:23 +00001146 jumpInst1 = sqlite3VdbeAddOp2(v, OP_MakeIdxRec, pIdx->nColumn, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001147 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001148
1149 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001150 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001151 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001152 if( overrideError!=OE_Default ){
1153 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001154 }else if( onError==OE_Default ){
1155 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001156 }
drh5383ae52003-06-04 12:23:30 +00001157 if( seenReplace ){
1158 if( onError==OE_Ignore ) onError = OE_Replace;
1159 else if( onError==OE_Fail ) onError = OE_Abort;
1160 }
1161
drhb2fe7d82003-04-20 17:29:23 +00001162
1163 /* Check to see if the new index entry will be unique */
drhb1fdb2a2008-01-05 04:06:03 +00001164 sqlite3VdbeAddOp1(v, OP_SCopy, -(extra+nCol+1+hasTwoRowids));
drh66a51672008-01-03 00:01:23 +00001165 jumpInst2 = sqlite3VdbeAddOp2(v, OP_IsUnique, base+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001166
1167 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001168 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1169 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001170 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001171 case OE_Rollback:
1172 case OE_Abort:
1173 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001174 int j, n1, n2;
1175 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001176 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1177 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001178 n1 = strlen(zErrMsg);
1179 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1180 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1181 n2 = strlen(zCol);
1182 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001183 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001184 n1 += 2;
1185 }
1186 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001187 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001188 n1 += 3;
1189 break;
1190 }else{
drh5bb3eb92007-05-04 13:15:55 +00001191 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001192 n1 += n2;
1193 }
1194 }
drh5bb3eb92007-05-04 13:15:55 +00001195 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001196 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001197 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001198 break;
1199 }
1200 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001201 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001202 sqlite3VdbeAddOp2(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
1203 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001204 break;
1205 }
1206 case OE_Replace: {
danielk197796cb76f2008-01-04 13:24:28 +00001207 int iRowid = sqlite3StackToReg(pParse, 1);
1208 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, iRowid, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001209 if( isUpdate ){
drhb1fdb2a2008-01-05 04:06:03 +00001210 sqlite3VdbeAddOp1(v, OP_SCopy, -(nCol+extra+1+hasTwoRowids));
drh66a51672008-01-03 00:01:23 +00001211 sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001212 }
drh0ca3e242002-01-29 23:07:02 +00001213 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001214 break;
1215 }
drh9cfcf5d2002-01-29 18:41:24 +00001216 }
drh0bd1f4e2002-06-06 18:54:39 +00001217#if NULL_DISTINCT_FOR_UNIQUE
drhd654be82005-09-20 17:42:23 +00001218 sqlite3VdbeJumpHere(v, jumpInst1);
drh0bd1f4e2002-06-06 18:54:39 +00001219#endif
drhd654be82005-09-20 17:42:23 +00001220 sqlite3VdbeJumpHere(v, jumpInst2);
drh9cfcf5d2002-01-29 18:41:24 +00001221 }
1222}
drh0ca3e242002-01-29 23:07:02 +00001223
1224/*
1225** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001226** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001227** The stack must contain keys for all active indices followed by data
drhf0863fe2005-06-12 21:35:51 +00001228** and the rowid for the new entry. This routine creates the new
drh0ca3e242002-01-29 23:07:02 +00001229** entries in all indices and in the main table.
1230**
drhb419a922002-01-30 16:17:23 +00001231** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001232** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001233*/
danielk19774adee202004-05-08 08:23:19 +00001234void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001235 Parse *pParse, /* The parser context */
1236 Table *pTab, /* the table into which we are inserting */
1237 int base, /* Index of a read/write cursor pointing at pTab */
1238 char *aIdxUsed, /* Which indices are used. NULL means all are used */
drhf0863fe2005-06-12 21:35:51 +00001239 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001240 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001241 int newIdx, /* Index of NEW table for triggers. -1 if none */
1242 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001243){
1244 int i;
1245 Vdbe *v;
1246 int nIdx;
1247 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001248 int pik_flags;
drh0ca3e242002-01-29 23:07:02 +00001249
danielk19774adee202004-05-08 08:23:19 +00001250 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001251 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001252 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001253 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1254 for(i=nIdx-1; i>=0; i--){
1255 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
drh66a51672008-01-03 00:01:23 +00001256 sqlite3VdbeAddOp2(v, OP_IdxInsert, base+i+1, 0);
drh0ca3e242002-01-29 23:07:02 +00001257 }
drh66a51672008-01-03 00:01:23 +00001258 sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +00001259 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001260#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001261 if( newIdx>=0 ){
drhb1fdb2a2008-01-05 04:06:03 +00001262 sqlite3VdbeAddOp1(v, OP_Copy, -1);
1263 sqlite3VdbeAddOp1(v, OP_Copy, -1);
danielk19771f4aa332008-01-03 09:51:55 +00001264 sqlite3CodeInsert(pParse, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001265 }
danielk1977b84f96f2005-01-20 11:32:23 +00001266#endif
drh4794f732004-11-05 17:17:50 +00001267 if( pParse->nested ){
1268 pik_flags = 0;
1269 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001270 pik_flags = OPFLAG_NCHANGE;
1271 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001272 }
drhe4d90812007-03-29 05:51:49 +00001273 if( appendBias ){
1274 pik_flags |= OPFLAG_APPEND;
1275 }
danielk19771f4aa332008-01-03 09:51:55 +00001276 sqlite3CodeInsert(pParse, base, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001277 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001278 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001279 }
danielk1977b28af712004-06-21 06:50:26 +00001280
drhf0863fe2005-06-12 21:35:51 +00001281 if( isUpdate && rowidChng ){
drh66a51672008-01-03 00:01:23 +00001282 sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
drh0ca3e242002-01-29 23:07:02 +00001283 }
1284}
drhcd446902004-02-24 01:05:31 +00001285
1286/*
drh290c1942004-08-21 17:54:45 +00001287** Generate code that will open cursors for a table and for all
drhcd446902004-02-24 01:05:31 +00001288** indices of that table. The "base" parameter is the cursor number used
1289** for the table. Indices are opened on subsequent cursors.
drhcd446902004-02-24 01:05:31 +00001290*/
drh290c1942004-08-21 17:54:45 +00001291void sqlite3OpenTableAndIndices(
1292 Parse *pParse, /* Parsing context */
1293 Table *pTab, /* Table to be opened */
1294 int base, /* Cursor number assigned to the table */
1295 int op /* OP_OpenRead or OP_OpenWrite */
1296){
drhcd446902004-02-24 01:05:31 +00001297 int i;
drh4cbdda92006-06-14 19:00:20 +00001298 int iDb;
drhcd446902004-02-24 01:05:31 +00001299 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001300 Vdbe *v;
1301
1302 if( IsVirtual(pTab) ) return;
1303 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1304 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001305 assert( v!=0 );
danielk1977c00da102006-01-07 13:21:04 +00001306 sqlite3OpenTable(pParse, base, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001307 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001308 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001309 assert( pIdx->pSchema==pTab->pSchema );
danielk1977207872a2008-01-03 07:54:23 +00001310 sqlite3VdbeAddOp4(v, op, i+base, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001311 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001312 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001313 }
drh290c1942004-08-21 17:54:45 +00001314 if( pParse->nTab<=base+i ){
1315 pParse->nTab = base+i;
1316 }
drhcd446902004-02-24 01:05:31 +00001317}
drh9d9cf222007-02-13 15:01:11 +00001318
drh91c58e22007-03-27 12:04:04 +00001319
1320#ifdef SQLITE_TEST
1321/*
1322** The following global variable is incremented whenever the
1323** transfer optimization is used. This is used for testing
1324** purposes only - to make sure the transfer optimization really
1325** is happening when it is suppose to.
1326*/
1327int sqlite3_xferopt_count;
1328#endif /* SQLITE_TEST */
1329
1330
drh9d9cf222007-02-13 15:01:11 +00001331#ifndef SQLITE_OMIT_XFER_OPT
1332/*
1333** Check to collation names to see if they are compatible.
1334*/
1335static int xferCompatibleCollation(const char *z1, const char *z2){
1336 if( z1==0 ){
1337 return z2==0;
1338 }
1339 if( z2==0 ){
1340 return 0;
1341 }
1342 return sqlite3StrICmp(z1, z2)==0;
1343}
1344
1345
1346/*
1347** Check to see if index pSrc is compatible as a source of data
1348** for index pDest in an insert transfer optimization. The rules
1349** for a compatible index:
1350**
1351** * The index is over the same set of columns
1352** * The same DESC and ASC markings occurs on all columns
1353** * The same onError processing (OE_Abort, OE_Ignore, etc)
1354** * The same collating sequence on each column
1355*/
1356static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1357 int i;
1358 assert( pDest && pSrc );
1359 assert( pDest->pTable!=pSrc->pTable );
1360 if( pDest->nColumn!=pSrc->nColumn ){
1361 return 0; /* Different number of columns */
1362 }
1363 if( pDest->onError!=pSrc->onError ){
1364 return 0; /* Different conflict resolution strategies */
1365 }
1366 for(i=0; i<pSrc->nColumn; i++){
1367 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1368 return 0; /* Different columns indexed */
1369 }
1370 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1371 return 0; /* Different sort orders */
1372 }
1373 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1374 return 0; /* Different sort orders */
1375 }
1376 }
1377
1378 /* If no test above fails then the indices must be compatible */
1379 return 1;
1380}
1381
1382/*
1383** Attempt the transfer optimization on INSERTs of the form
1384**
1385** INSERT INTO tab1 SELECT * FROM tab2;
1386**
1387** This optimization is only attempted if
1388**
1389** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001390** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001391**
1392** (2) tab1 and tab2 are different tables
1393**
1394** (3) There must be no triggers on tab1
1395**
1396** (4) The result set of the SELECT statement is "*"
1397**
1398** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1399** or LIMIT clause.
1400**
1401** (6) The SELECT statement is a simple (not a compound) select that
1402** contains only tab2 in its FROM clause
1403**
1404** This method for implementing the INSERT transfers raw records from
1405** tab2 over to tab1. The columns are not decoded. Raw records from
1406** the indices of tab2 are transfered to tab1 as well. In so doing,
1407** the resulting tab1 has much less fragmentation.
1408**
1409** This routine returns TRUE if the optimization is attempted. If any
1410** of the conditions above fail so that the optimization should not
1411** be attempted, then this routine returns FALSE.
1412*/
1413static int xferOptimization(
1414 Parse *pParse, /* Parser context */
1415 Table *pDest, /* The table we are inserting into */
1416 Select *pSelect, /* A SELECT statement to use as the data source */
1417 int onError, /* How to handle constraint errors */
1418 int iDbDest /* The database of pDest */
1419){
1420 ExprList *pEList; /* The result set of the SELECT */
1421 Table *pSrc; /* The table in the FROM clause of SELECT */
1422 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1423 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1424 int i; /* Loop counter */
1425 int iDbSrc; /* The database of pSrc */
1426 int iSrc, iDest; /* Cursors from source and destination */
1427 int addr1, addr2; /* Loop addresses */
1428 int emptyDestTest; /* Address of test for empty pDest */
1429 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001430 Vdbe *v; /* The VDBE we are building */
1431 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001432 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001433 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001434
1435 if( pSelect==0 ){
1436 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1437 }
1438 if( pDest->pTrigger ){
1439 return 0; /* tab1 must not have triggers */
1440 }
1441#ifndef SQLITE_OMIT_VIRTUALTABLE
1442 if( pDest->isVirtual ){
1443 return 0; /* tab1 must not be a virtual table */
1444 }
1445#endif
1446 if( onError==OE_Default ){
1447 onError = OE_Abort;
1448 }
1449 if( onError!=OE_Abort && onError!=OE_Rollback ){
1450 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1451 }
danielk19775ce240a2007-09-03 17:30:06 +00001452 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001453 if( pSelect->pSrc->nSrc!=1 ){
1454 return 0; /* FROM clause must have exactly one term */
1455 }
1456 if( pSelect->pSrc->a[0].pSelect ){
1457 return 0; /* FROM clause cannot contain a subquery */
1458 }
1459 if( pSelect->pWhere ){
1460 return 0; /* SELECT may not have a WHERE clause */
1461 }
1462 if( pSelect->pOrderBy ){
1463 return 0; /* SELECT may not have an ORDER BY clause */
1464 }
drh8103b7d2007-02-24 13:23:51 +00001465 /* Do not need to test for a HAVING clause. If HAVING is present but
1466 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001467 if( pSelect->pGroupBy ){
1468 return 0; /* SELECT may not have a GROUP BY clause */
1469 }
1470 if( pSelect->pLimit ){
1471 return 0; /* SELECT may not have a LIMIT clause */
1472 }
drh8103b7d2007-02-24 13:23:51 +00001473 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001474 if( pSelect->pPrior ){
1475 return 0; /* SELECT may not be a compound query */
1476 }
1477 if( pSelect->isDistinct ){
1478 return 0; /* SELECT may not be DISTINCT */
1479 }
1480 pEList = pSelect->pEList;
1481 assert( pEList!=0 );
1482 if( pEList->nExpr!=1 ){
1483 return 0; /* The result set must have exactly one column */
1484 }
1485 assert( pEList->a[0].pExpr );
1486 if( pEList->a[0].pExpr->op!=TK_ALL ){
1487 return 0; /* The result set must be the special operator "*" */
1488 }
1489
1490 /* At this point we have established that the statement is of the
1491 ** correct syntactic form to participate in this optimization. Now
1492 ** we have to check the semantics.
1493 */
1494 pItem = pSelect->pSrc->a;
1495 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1496 if( pSrc==0 ){
1497 return 0; /* FROM clause does not contain a real table */
1498 }
1499 if( pSrc==pDest ){
1500 return 0; /* tab1 and tab2 may not be the same table */
1501 }
1502#ifndef SQLITE_OMIT_VIRTUALTABLE
1503 if( pSrc->isVirtual ){
1504 return 0; /* tab2 must not be a virtual table */
1505 }
1506#endif
1507 if( pSrc->pSelect ){
1508 return 0; /* tab2 may not be a view */
1509 }
1510 if( pDest->nCol!=pSrc->nCol ){
1511 return 0; /* Number of columns must be the same in tab1 and tab2 */
1512 }
1513 if( pDest->iPKey!=pSrc->iPKey ){
1514 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1515 }
1516 for(i=0; i<pDest->nCol; i++){
1517 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1518 return 0; /* Affinity must be the same on all columns */
1519 }
1520 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1521 return 0; /* Collating sequence must be the same on all columns */
1522 }
1523 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1524 return 0; /* tab2 must be NOT NULL if tab1 is */
1525 }
1526 }
1527 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001528 if( pDestIdx->onError!=OE_None ){
1529 destHasUniqueIdx = 1;
1530 }
drh9d9cf222007-02-13 15:01:11 +00001531 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1532 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1533 }
1534 if( pSrcIdx==0 ){
1535 return 0; /* pDestIdx has no corresponding index in pSrc */
1536 }
1537 }
drh7fc2f412007-03-29 00:08:24 +00001538#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001539 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001540 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1541 }
drh7fc2f412007-03-29 00:08:24 +00001542#endif
drh9d9cf222007-02-13 15:01:11 +00001543
1544 /* If we get this far, it means either:
1545 **
1546 ** * We can always do the transfer if the table contains an
1547 ** an integer primary key
1548 **
1549 ** * We can conditionally do the transfer if the destination
1550 ** table is empty.
1551 */
drhdd735212007-02-24 13:53:05 +00001552#ifdef SQLITE_TEST
1553 sqlite3_xferopt_count++;
1554#endif
drh9d9cf222007-02-13 15:01:11 +00001555 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1556 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001557 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001558 iSrc = pParse->nTab++;
1559 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001560 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001561 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001562 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001563 /* If tables do not have an INTEGER PRIMARY KEY and there
1564 ** are indices to be copied and the destination is not empty,
1565 ** we have to disallow the transfer optimization because the
1566 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001567 **
1568 ** Or if the destination has a UNIQUE index and is not empty,
1569 ** we also disallow the transfer optimization because we cannot
1570 ** insure that all entries in the union of DEST and SRC will be
1571 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001572 */
drh66a51672008-01-03 00:01:23 +00001573 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1574 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001575 sqlite3VdbeJumpHere(v, addr1);
1576 }else{
1577 emptyDestTest = 0;
1578 }
1579 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001580 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001581 if( pDest->iPKey>=0 ){
drh66a51672008-01-03 00:01:23 +00001582 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001583 sqlite3VdbeAddOp0(v, OP_Copy);
drh66a51672008-01-03 00:01:23 +00001584 addr2 = sqlite3VdbeAddOp2(v, OP_NotExists, iDest, 0);
1585 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1586 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001587 sqlite3VdbeJumpHere(v, addr2);
drh6a288a32008-01-07 19:20:24 +00001588 autoIncStep(pParse, regAutoinc, 0);
drhbd36ba62007-03-31 13:00:26 +00001589 }else if( pDest->pIndex==0 ){
drh4c583122008-01-04 22:01:03 +00001590 addr1 = sqlite3VdbeAddOp1(v, OP_NewRowid, iDest);
drh95bad4c2007-03-28 18:04:10 +00001591 }else{
drh66a51672008-01-03 00:01:23 +00001592 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001593 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001594 }
drh66a51672008-01-03 00:01:23 +00001595 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, 0);
danielk19771f4aa332008-01-03 09:51:55 +00001596 sqlite3CodeInsert(pParse,iDest,OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1597 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001598 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001599 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001600 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1601 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1602 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1603 }
1604 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001605 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1606 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001607 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001608 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1609 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001610 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001611 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001612 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001613 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001614 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001615 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1616 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, 0);
1617 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, 1);
1618 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001619 sqlite3VdbeJumpHere(v, addr1);
1620 }
1621 sqlite3VdbeJumpHere(v, emptySrcTest);
drh66a51672008-01-03 00:01:23 +00001622 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1623 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001624 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001625 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001626 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001627 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001628 return 0;
1629 }else{
1630 return 1;
1631 }
1632}
1633#endif /* SQLITE_OMIT_XFER_OPT */