blob: 7577f46774e237cc5ea4a397fe1b53313b6a792c [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**
drh2d401ab2008-01-10 23:50:11 +000015** $Id: insert.c,v 1.222 2008/01/10 23:50:11 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
drh2d401ab2008-01-10 23:50:11 +000031**
32** An extra 'b' is appended to the end of the string to cover the
33** rowid that appears as the last column in every index.
danielk19773d1bfea2004-05-14 11:00:53 +000034*/
danielk1977a37cdde2004-05-16 11:15:36 +000035void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
36 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000037 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000038 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000039 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000040 **
41 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000042 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000043 ** up.
44 */
45 int n;
46 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000047 sqlite3 *db = sqlite3VdbeDb(v);
drh2d401ab2008-01-10 23:50:11 +000048 pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+2);
danielk1977a37cdde2004-05-16 11:15:36 +000049 if( !pIdx->zColAff ){
50 return;
51 }
52 for(n=0; n<pIdx->nColumn; n++){
53 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
54 }
drh2d401ab2008-01-10 23:50:11 +000055 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
56 pIdx->zColAff[n] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +000057 }
danielk19773d1bfea2004-05-14 11:00:53 +000058
drh66a51672008-01-03 00:01:23 +000059 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000060}
61
62/*
drh66a51672008-01-03 00:01:23 +000063** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000064** string for table pTab. A column affinity string has one character
65** for each column indexed by the index, according to the affinity of the
66** column:
67**
68** Character Column affinity
69** ------------------------------
drh3eda0402005-11-24 13:15:32 +000070** 'a' TEXT
71** 'b' NONE
72** 'c' NUMERIC
73** 'd' INTEGER
74** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000075*/
76void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000077 /* The first time a column affinity string for a particular table
78 ** is required, it is allocated and populated here. It is then
79 ** stored as a member of the Table structure for subsequent use.
80 **
81 ** The column affinity string will eventually be deleted by
82 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
83 */
84 if( !pTab->zColAff ){
85 char *zColAff;
86 int i;
drhabb6fca2007-08-16 12:24:01 +000087 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +000088
drh17435752007-08-16 04:30:38 +000089 zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000090 if( !zColAff ){
danielk1977a37cdde2004-05-16 11:15:36 +000091 return;
danielk19773d1bfea2004-05-14 11:00:53 +000092 }
93
94 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000095 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000096 }
97 zColAff[pTab->nCol] = '\0';
98
99 pTab->zColAff = zColAff;
100 }
101
drh66a51672008-01-03 00:01:23 +0000102 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +0000103}
104
danielk19774d887782005-02-08 08:42:27 +0000105/*
drh48d11782007-11-23 15:02:19 +0000106** Return non-zero if the table pTab in database iDb or any of its indices
107** have been opened at any point in the VDBE program beginning at location
108** iStartAddr throught the end of the program. This is used to see if
109** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
110** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000111*/
drh48d11782007-11-23 15:02:19 +0000112static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000113 int i;
drh48d11782007-11-23 15:02:19 +0000114 int iEnd = sqlite3VdbeCurrentAddr(v);
115 for(i=iStartAddr; i<iEnd; i++){
116 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000117 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000118 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
119 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000120 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000121 if( tnum==pTab->tnum ){
122 return 1;
123 }
124 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
125 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000126 return 1;
127 }
drh48d11782007-11-23 15:02:19 +0000128 }
129 }
drh543165e2007-11-27 14:46:41 +0000130#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19772dca4ac2008-01-03 11:50:29 +0000131 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
132 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000133 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000134 return 1;
danielk19774d887782005-02-08 08:42:27 +0000135 }
drh543165e2007-11-27 14:46:41 +0000136#endif
danielk19774d887782005-02-08 08:42:27 +0000137 }
138 return 0;
139}
danielk19773d1bfea2004-05-14 11:00:53 +0000140
drh9d9cf222007-02-13 15:01:11 +0000141#ifndef SQLITE_OMIT_AUTOINCREMENT
142/*
143** Write out code to initialize the autoincrement logic. This code
144** looks up the current autoincrement value in the sqlite_sequence
drh6a288a32008-01-07 19:20:24 +0000145** table and stores that value in a register. Code generated by
146** autoIncStep() will keep that register holding the largest
drh9d9cf222007-02-13 15:01:11 +0000147** rowid value. Code generated by autoIncEnd() will write the new
148** largest value of the counter back into the sqlite_sequence table.
149**
150** This routine returns the index of the mem[] cell that contains
151** the maximum rowid counter.
152**
drh6a288a32008-01-07 19:20:24 +0000153** Three consecutive registers are allocated by this routine. The
154** first two hold the name of the target table and the maximum rowid
155** inserted into the target table, respectively.
156** The third holds the rowid in sqlite_sequence where we will
157** write back the revised maximum rowid. This routine returns the
158** index of the second of these three registers.
drh9d9cf222007-02-13 15:01:11 +0000159*/
160static int autoIncBegin(
161 Parse *pParse, /* Parsing context */
162 int iDb, /* Index of the database holding pTab */
163 Table *pTab /* The table we are writing to */
164){
drh6a288a32008-01-07 19:20:24 +0000165 int memId = 0; /* Register holding maximum rowid */
drh9d9cf222007-02-13 15:01:11 +0000166 if( pTab->autoInc ){
167 Vdbe *v = pParse->pVdbe;
168 Db *pDb = &pParse->db->aDb[iDb];
169 int iCur = pParse->nTab;
drh6a288a32008-01-07 19:20:24 +0000170 int addr; /* Address of the top of the loop */
drh9d9cf222007-02-13 15:01:11 +0000171 assert( v );
drh6a288a32008-01-07 19:20:24 +0000172 pParse->nMem++; /* Holds name of table */
173 memId = ++pParse->nMem;
174 pParse->nMem++;
drh9d9cf222007-02-13 15:01:11 +0000175 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh6a288a32008-01-07 19:20:24 +0000176 addr = sqlite3VdbeCurrentAddr(v);
177 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8);
drh66a51672008-01-03 00:01:23 +0000178 sqlite3VdbeAddOp2(v, OP_Column, iCur, 0);
179 sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
drh35573352008-01-08 23:54:25 +0000180 sqlite3VdbeAddOp2(v, OP_Ne, 0, addr+7);
181 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh6a288a32008-01-07 19:20:24 +0000182 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
183 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
184 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
185 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1);
drh66a51672008-01-03 00:01:23 +0000186 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000187 }
188 return memId;
189}
190
191/*
192** Update the maximum rowid for an autoincrement calculation.
193**
194** This routine should be called when the top of the stack holds a
195** new rowid that is about to be inserted. If that new rowid is
196** larger than the maximum rowid in the memId memory cell, then the
197** memory cell is updated. The stack is unchanged.
198*/
drh6a288a32008-01-07 19:20:24 +0000199static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000200 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000201 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000202 }
203}
204
205/*
206** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000207** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000208** the sqlite_sequence table.
209*/
210static void autoIncEnd(
211 Parse *pParse, /* The parsing context */
212 int iDb, /* Index of the database holding pTab */
213 Table *pTab, /* Table we are inserting into */
214 int memId /* Memory cell holding the maximum rowid */
215){
216 if( pTab->autoInc ){
217 int iCur = pParse->nTab;
218 Vdbe *v = pParse->pVdbe;
219 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000220 int j1;
221
drh9d9cf222007-02-13 15:01:11 +0000222 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000223 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000224 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
225 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
226 sqlite3VdbeJumpHere(v, j1);
227 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
228 sqlite3VdbeAddOp3(v, OP_RegMakeRec, memId-1, 2, memId-1);
229 sqlite3VdbeAddOp3(v, OP_Insert, iCur, memId-1, memId+1);
drh35573352008-01-08 23:54:25 +0000230 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh6a288a32008-01-07 19:20:24 +0000231 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000232 }
233}
234#else
235/*
236** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
237** above are all no-ops
238*/
239# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000240# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000241# define autoIncEnd(A,B,C,D)
242#endif /* SQLITE_OMIT_AUTOINCREMENT */
243
244
245/* Forward declaration */
246static int xferOptimization(
247 Parse *pParse, /* Parser context */
248 Table *pDest, /* The table we are inserting into */
249 Select *pSelect, /* A SELECT statement to use as the data source */
250 int onError, /* How to handle constraint errors */
251 int iDbDest /* The database of pDest */
252);
253
danielk19773d1bfea2004-05-14 11:00:53 +0000254/*
drh1ccde152000-06-17 13:12:39 +0000255** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000256**
257** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000258** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000259**
drh1ccde152000-06-17 13:12:39 +0000260** The IDLIST following the table name is always optional. If omitted,
261** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000262** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000263**
264** The pList parameter holds EXPRLIST in the first form of the INSERT
265** statement above, and pSelect is NULL. For the second form, pList is
266** NULL and pSelect is a pointer to the select statement used to generate
267** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000268**
drh9d9cf222007-02-13 15:01:11 +0000269** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000270** select with data coming from a VALUES clause, the code executes
271** once straight down through. The template looks like this:
272**
273** open write cursor to <table> and its indices
274** puts VALUES clause expressions onto the stack
275** write the resulting record into <table>
276** cleanup
277**
drh9d9cf222007-02-13 15:01:11 +0000278** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000279**
280** INSERT INTO <table> SELECT ...
281**
drh9d9cf222007-02-13 15:01:11 +0000282** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
283** in other words if the SELECT pulls all columns from a single table
284** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
285** if <table2> and <table1> are distinct tables but have identical
286** schemas, including all the same indices, then a special optimization
287** is invoked that copies raw records from <table2> over to <table1>.
288** See the xferOptimization() function for the implementation of this
289** template. This is the second template.
290**
291** open a write cursor to <table>
292** open read cursor on <table2>
293** transfer all records in <table2> over to <table>
294** close cursors
295** foreach index on <table>
296** open a write cursor on the <table> index
297** open a read cursor on the corresponding <table2> index
298** transfer all records from the read to the write cursors
299** close cursors
300** end foreach
301**
302** The third template is for when the second template does not apply
303** and the SELECT clause does not read from <table> at any time.
304** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000305**
306** goto B
307** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000308** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000309** gosub C
310** end loop
311** cleanup after the SELECT
312** goto D
313** B: open write cursor to <table> and its indices
314** goto A
315** C: insert the select result into <table>
316** return
317** D: cleanup
318**
drh9d9cf222007-02-13 15:01:11 +0000319** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000320** values from a SELECT but the data is being inserted into a table
321** that is also read as part of the SELECT. In the third form,
322** we have to use a intermediate table to store the results of
323** the select. The template is like this:
324**
325** goto B
326** A: setup for the SELECT
327** loop over the tables in the SELECT
328** gosub C
329** end loop
330** cleanup after the SELECT
331** goto D
332** C: insert the select result into the intermediate table
333** return
334** B: open a cursor to an intermediate table
335** goto A
336** D: open write cursor to <table> and its indices
337** loop over the intermediate table
338** transfer values form intermediate table into <table>
339** end the loop
340** cleanup
drhcce7d172000-05-31 15:34:51 +0000341*/
danielk19774adee202004-05-08 08:23:19 +0000342void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000343 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000344 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000345 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000346 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000347 IdList *pColumn, /* Column names corresponding to IDLIST. */
348 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000349){
drh6a288a32008-01-07 19:20:24 +0000350 sqlite3 *db; /* The main database structure */
351 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000352 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000353 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000354 int i, j, idx; /* Loop counters */
355 Vdbe *v; /* Generate code into this virtual machine */
356 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000357 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000358 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000359 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000360 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000361 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000362 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000363 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drh6a288a32008-01-07 19:20:24 +0000364 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
danielk1977cfe9a692004-06-16 12:00:29 +0000365 int iSelectLoop = 0; /* Address of code that implements the SELECT */
366 int iCleanup = 0; /* Address of the cleanup code */
367 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
drh6a288a32008-01-07 19:20:24 +0000368 int newIdx = -1; /* Cursor for the NEW pseudo-table */
369 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000370 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000371 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000372
drh6a288a32008-01-07 19:20:24 +0000373 /* Register allocations */
374 int regFromSelect; /* Base register for data coming from SELECT */
375 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
376 int regRowCount = 0; /* Memory cell used for the row counter */
377 int regIns; /* Block of regs holding rowid+data being inserted */
378 int regRowid; /* registers holding insert rowid */
379 int regData; /* register holding first column to insert */
380 int regRecord; /* Holds the assemblied row record */
drhaa9b8962008-01-08 02:57:55 +0000381 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000382
danielk1977034ca142007-06-26 10:38:54 +0000383
drh798da522004-11-04 04:42:28 +0000384#ifndef SQLITE_OMIT_TRIGGER
385 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000386 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000387#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000388
drh17435752007-08-16 04:30:38 +0000389 db = pParse->db;
390 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000391 goto insert_cleanup;
392 }
drhdaffd0e2001-04-11 14:28:42 +0000393
drh1ccde152000-06-17 13:12:39 +0000394 /* Locate the table into which we will be inserting new information.
395 */
drh113088e2003-03-20 01:16:58 +0000396 assert( pTabList->nSrc==1 );
397 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000398 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000399 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000400 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000401 goto insert_cleanup;
402 }
danielk1977da184232006-01-05 11:34:32 +0000403 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
404 assert( iDb<db->nDb );
405 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000406 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000407 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000408 goto insert_cleanup;
409 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000410
drhb7f91642004-10-31 02:22:47 +0000411 /* Figure out if we have any triggers and if the table being
412 ** inserted into is a view
413 */
414#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000415 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000416 isView = pTab->pSelect!=0;
417#else
drhdca76842004-12-07 14:06:13 +0000418# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000419# define isView 0
420#endif
421#ifdef SQLITE_OMIT_VIEW
422# undef isView
423# define isView 0
424#endif
425
danielk1977c3f9bad2002-05-15 08:30:12 +0000426 /* Ensure that:
427 * (a) the table is not read-only,
428 * (b) that if it is a view then ON INSERT triggers exist
429 */
drhdca76842004-12-07 14:06:13 +0000430 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000431 goto insert_cleanup;
432 }
drh43617e92006-03-06 20:55:46 +0000433 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000434
drhf573c992002-07-31 00:32:50 +0000435 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000436 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
437 ** module table).
drhf573c992002-07-31 00:32:50 +0000438 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000439 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000440 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000441 }
442
drh1ccde152000-06-17 13:12:39 +0000443 /* Allocate a VDBE
444 */
danielk19774adee202004-05-08 08:23:19 +0000445 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000446 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000447 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000448 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000449
danielk1977c3f9bad2002-05-15 08:30:12 +0000450 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000451 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000452 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000453 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000454
drh9d9cf222007-02-13 15:01:11 +0000455#ifndef SQLITE_OMIT_XFER_OPT
456 /* If the statement is of the form
457 **
458 ** INSERT INTO <table1> SELECT * FROM <table2>;
459 **
460 ** Then special optimizations can be applied that make the transfer
461 ** very fast and which reduce fragmentation of indices.
462 */
463 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
464 assert( !triggers_exist );
465 assert( pList==0 );
466 goto insert_cleanup;
467 }
468#endif /* SQLITE_OMIT_XFER_OPT */
469
drh2958a4e2004-11-12 03:56:15 +0000470 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000471 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000472 */
drh6a288a32008-01-07 19:20:24 +0000473 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000474
drh1ccde152000-06-17 13:12:39 +0000475 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000476 ** is coming from a SELECT statement, then this step also generates
477 ** all the code to implement the SELECT statement and invoke a subroutine
478 ** to process each row of the result. (Template 2.) If the SELECT
479 ** statement uses the the table that is being inserted into, then the
480 ** subroutine is also coded here. That subroutine stores the SELECT
481 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000482 */
drh5974a302000-06-07 14:42:26 +0000483 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000484 /* Data is coming from a SELECT. Generate code to implement that SELECT
485 */
drh1013c932008-01-06 00:25:21 +0000486 SelectDest dest;
drh142e30d2002-08-28 03:00:58 +0000487 int rc, iInitCode;
drh1013c932008-01-06 00:25:21 +0000488
drh66a51672008-01-03 00:01:23 +0000489 iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000490 iSelectLoop = sqlite3VdbeCurrentAddr(v);
491 iInsertBlock = sqlite3VdbeMakeLabel(v);
drh1013c932008-01-06 00:25:21 +0000492 sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
danielk1977b3bce662005-01-29 08:32:43 +0000493
494 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000495 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
drh17435752007-08-16 04:30:38 +0000496 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000497 goto insert_cleanup;
498 }
danielk1977b3bce662005-01-29 08:32:43 +0000499
drh6a288a32008-01-07 19:20:24 +0000500 regFromSelect = dest.iMem;
danielk19774adee202004-05-08 08:23:19 +0000501 iCleanup = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000502 sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000503 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000504 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000505
506 /* Set useTempTable to TRUE if the result of the SELECT statement
507 ** should be written into a temporary table. Set to FALSE if each
508 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000509 **
510 ** A temp table must be used if the table being updated is also one
511 ** of the tables being read by the SELECT statement. Also use a
512 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000513 */
drh48d11782007-11-23 15:02:19 +0000514 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000515 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000516 }
drh142e30d2002-08-28 03:00:58 +0000517
518 if( useTempTable ){
519 /* Generate the subroutine that SELECT calls to process each row of
520 ** the result. Store the result in a temporary table
521 */
522 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000523 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000524 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regFromSelect, nColumn);
drh4c583122008-01-04 22:01:03 +0000525 sqlite3VdbeAddOp1(v, OP_NewRowid, srcTab);
drh66a51672008-01-03 00:01:23 +0000526 sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
danielk19771f4aa332008-01-03 09:51:55 +0000527 sqlite3CodeInsert(pParse, srcTab, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000528 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000529
530 /* The following code runs first because the GOTO at the very top
531 ** of the program jumps to it. Create the temporary table, then jump
532 ** back up and execute the SELECT code above.
533 */
drhd654be82005-09-20 17:42:23 +0000534 sqlite3VdbeJumpHere(v, iInitCode);
drh66a51672008-01-03 00:01:23 +0000535 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
536 sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
537 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000538 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000539 }else{
drhd654be82005-09-20 17:42:23 +0000540 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000541 }
drh5974a302000-06-07 14:42:26 +0000542 }else{
drh142e30d2002-08-28 03:00:58 +0000543 /* This is the case if the data for the INSERT is coming from a VALUES
544 ** clause
545 */
danielk1977b3bce662005-01-29 08:32:43 +0000546 NameContext sNC;
547 memset(&sNC, 0, sizeof(sNC));
548 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000549 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000550 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000551 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000552 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000553 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000554 goto insert_cleanup;
555 }
drhe64e7b22002-02-18 13:56:36 +0000556 }
drh5974a302000-06-07 14:42:26 +0000557 }
drh1ccde152000-06-17 13:12:39 +0000558
559 /* Make sure the number of columns in the source data matches the number
560 ** of columns to be inserted into the table.
561 */
danielk1977034ca142007-06-26 10:38:54 +0000562 if( IsVirtual(pTab) ){
563 for(i=0; i<pTab->nCol; i++){
564 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
565 }
566 }
567 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000568 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000569 "table %S has %d columns but %d values were supplied",
570 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000571 goto insert_cleanup;
572 }
drh967e8b72000-06-21 13:59:10 +0000573 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000574 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000575 goto insert_cleanup;
576 }
drh1ccde152000-06-17 13:12:39 +0000577
578 /* If the INSERT statement included an IDLIST term, then make sure
579 ** all elements of the IDLIST really are columns of the table and
580 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000581 **
582 ** If the table has an INTEGER PRIMARY KEY column and that column
583 ** is named in the IDLIST, then record in the keyColumn variable
584 ** the index into IDLIST of the primary key column. keyColumn is
585 ** the index of the primary key as it appears in IDLIST, not as
586 ** is appears in the original table. (The index of the primary
587 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000588 */
drh967e8b72000-06-21 13:59:10 +0000589 if( pColumn ){
590 for(i=0; i<pColumn->nId; i++){
591 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000592 }
drh967e8b72000-06-21 13:59:10 +0000593 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000594 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000595 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000596 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000597 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000598 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000599 }
drhcce7d172000-05-31 15:34:51 +0000600 break;
601 }
602 }
603 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000604 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000605 keyColumn = i;
606 }else{
danielk19774adee202004-05-08 08:23:19 +0000607 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000608 pTabList, 0, pColumn->a[i].zName);
609 pParse->nErr++;
610 goto insert_cleanup;
611 }
drhcce7d172000-05-31 15:34:51 +0000612 }
613 }
614 }
drh1ccde152000-06-17 13:12:39 +0000615
drhaacc5432002-01-06 17:07:40 +0000616 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000617 ** key, the set the keyColumn variable to the primary key column index
618 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000619 */
drh147d0cc2006-08-25 23:42:53 +0000620 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000621 keyColumn = pTab->iPKey;
622 }
623
drh142e30d2002-08-28 03:00:58 +0000624 /* Open the temp table for FOR EACH ROW triggers
625 */
drhdca76842004-12-07 14:06:13 +0000626 if( triggers_exist ){
drh66a51672008-01-03 00:01:23 +0000627 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
628 sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000629 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000630
drhfeeb1392002-04-09 03:28:01 +0000631 /* Initialize the count of rows to be inserted
632 */
drh142e30d2002-08-28 03:00:58 +0000633 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000634 regRowCount = ++pParse->nMem;
635 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000636 }
637
danielk1977e448dc42008-01-02 11:50:51 +0000638 /* If this is not a view, open the table and and all indices */
639 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000640 int nIdx;
641 int i;
642
drh04adf412008-01-08 18:57:50 +0000643 baseCur = pParse->nTab;
644 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drhaa9b8962008-01-08 02:57:55 +0000645 aRegIdx = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1));
646 if( aRegIdx==0 ){
647 goto insert_cleanup;
648 }
649 for(i=0; i<nIdx; i++){
650 aRegIdx[i] = ++pParse->nMem;
651 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000652 }
653
drh142e30d2002-08-28 03:00:58 +0000654 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000655 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000656 ** source is a subroutine call from the SELECT statement, then we need
657 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000658 */
drh142e30d2002-08-28 03:00:58 +0000659 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000660 iBreak = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000661 sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +0000662 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000663 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000664 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000665 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000666 sqlite3RegToStack(pParse, regFromSelect, nColumn);
drh66a51672008-01-03 00:01:23 +0000667 sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000668 }
drh1ccde152000-06-17 13:12:39 +0000669
drh6a288a32008-01-07 19:20:24 +0000670 /* Allocate registers for holding the rowid of the new row,
671 ** the content of the new row, and the assemblied row record.
672 */
673 regRecord = ++pParse->nMem;
674 regRowid = regIns = pParse->nMem+1;
675 pParse->nMem += pTab->nCol + 1;
676 if( IsVirtual(pTab) ){
677 regRowid++;
678 pParse->nMem++;
679 }
680 regData = regRowid+1;
681
drh5cf590c2003-04-24 01:45:04 +0000682 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000683 */
danielk19774adee202004-05-08 08:23:19 +0000684 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000685 if( triggers_exist & TRIGGER_BEFORE ){
drh2d401ab2008-01-10 23:50:11 +0000686 int regRowid;
687 int regCols;
688 int regRec;
danielk1977c3f9bad2002-05-15 08:30:12 +0000689
drh70ce3f02003-04-15 19:22:22 +0000690 /* build the NEW.* reference row. Note that if there is an INTEGER
691 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
692 ** translated into a unique ID for the row. But on a BEFORE trigger,
693 ** we do not know what the unique ID will be (because the insert has
694 ** not happened yet) so we substitute a rowid of -1
695 */
drh2d401ab2008-01-10 23:50:11 +0000696 regRowid = sqlite3GetTempReg(pParse);
drh70ce3f02003-04-15 19:22:22 +0000697 if( keyColumn<0 ){
drh2d401ab2008-01-10 23:50:11 +0000698 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
drh70ce3f02003-04-15 19:22:22 +0000699 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000700 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh70ce3f02003-04-15 19:22:22 +0000701 }else{
drh6a288a32008-01-07 19:20:24 +0000702 int j1;
drhd6fe9612005-01-14 01:22:00 +0000703 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000704 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
705 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
706 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
drh6a288a32008-01-07 19:20:24 +0000707 sqlite3VdbeJumpHere(v, j1);
drh2d401ab2008-01-10 23:50:11 +0000708 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drh70ce3f02003-04-15 19:22:22 +0000709 }
710
danielk1977034ca142007-06-26 10:38:54 +0000711 /* Cannot have triggers on a virtual table. If it were possible,
712 ** this block would have to account for hidden column.
713 */
714 assert(!IsVirtual(pTab));
715
drh70ce3f02003-04-15 19:22:22 +0000716 /* Create the new column data
717 */
drh2d401ab2008-01-10 23:50:11 +0000718 regCols = sqlite3GetTempRange(pParse, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000719 for(i=0; i<pTab->nCol; i++){
720 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000721 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000722 }else{
drh9adf9ac2002-05-15 11:44:13 +0000723 for(j=0; j<pColumn->nId; j++){
724 if( pColumn->a[j].idx==i ) break;
725 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000726 }
727 if( pColumn && j>=pColumn->nId ){
drh2d401ab2008-01-10 23:50:11 +0000728 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
drh142e30d2002-08-28 03:00:58 +0000729 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000730 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000731 }else{
drhd6fe9612005-01-14 01:22:00 +0000732 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000733 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000734 }
735 }
drh2d401ab2008-01-10 23:50:11 +0000736 regRec = sqlite3GetTempReg(pParse);
737 sqlite3VdbeAddOp3(v, OP_RegMakeRec, regCols, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +0000738
739 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
740 ** do not attempt any conversions before assembling the record.
741 ** If this is a real table, attempt conversions as required by the
742 ** table column affinities.
743 */
744 if( !isView ){
745 sqlite3TableAffinityStr(v, pTab);
746 }
drh2d401ab2008-01-10 23:50:11 +0000747 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
748 sqlite3ReleaseTempReg(pParse, regRec);
749 sqlite3ReleaseTempReg(pParse, regRowid);
750 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000751
drh5cf590c2003-04-24 01:45:04 +0000752 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000753 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000754 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000755 goto insert_cleanup;
756 }
drh70ce3f02003-04-15 19:22:22 +0000757 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000758
drh4a324312001-12-21 14:30:42 +0000759 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000760 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000761 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000762 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000763 */
drh5cf590c2003-04-24 01:45:04 +0000764 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000765 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000766 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000767 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000768 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000769 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000770 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000771 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000772 }else if( pSelect ){
drh6a288a32008-01-07 19:20:24 +0000773 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn - keyColumn - 1), regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000774 }else{
drhe4d90812007-03-29 05:51:49 +0000775 VdbeOp *pOp;
drh389a1ad2008-01-03 23:44:53 +0000776 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drhe4d90812007-03-29 05:51:49 +0000777 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000778 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000779 appendFlag = 1;
780 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000781 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000782 pOp->p2 = regRowid;
783 pOp->p3 = regAutoinc;
danielk1977287fb612008-01-04 19:10:28 +0000784 }else{
785 /* TODO: Avoid this use of the stack. */
drh6a288a32008-01-07 19:20:24 +0000786 sqlite3VdbeAddOp2(v, OP_Move, 0, regRowid);
drhe4d90812007-03-29 05:51:49 +0000787 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000788 }
drhf0863fe2005-06-12 21:35:51 +0000789 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000790 ** to generate a unique primary key value.
791 */
drhe4d90812007-03-29 05:51:49 +0000792 if( !appendFlag ){
drh3c84ddf2008-01-09 02:15:38 +0000793 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, sqlite3VdbeCurrentAddr(v)+2);
danielk1977287fb612008-01-04 19:10:28 +0000794 sqlite3VdbeAddOp2(v, OP_Goto, -1, sqlite3VdbeCurrentAddr(v)+2);
drh04adf412008-01-08 18:57:50 +0000795 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drh3c84ddf2008-01-09 02:15:38 +0000796 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000797 }
drh4cbdda92006-06-14 19:00:20 +0000798 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000799 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000800 }else{
drh04adf412008-01-08 18:57:50 +0000801 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000802 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000803 }
drh6a288a32008-01-07 19:20:24 +0000804 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000805
danielk1977c3f9bad2002-05-15 08:30:12 +0000806 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000807 ** with the first column.
808 */
danielk1977034ca142007-06-26 10:38:54 +0000809 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000810 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000811 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000812 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000813 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000814 ** Whenever this column is read, the record number will be substituted
815 ** in its place. So will fill this column with a NULL to avoid
816 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000817 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000818 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000819 }
820 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000821 if( IsHiddenColumn(&pTab->aCol[i]) ){
822 assert( IsVirtual(pTab) );
823 j = -1;
824 nHidden++;
825 }else{
826 j = i - nHidden;
827 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000828 }else{
drh9adf9ac2002-05-15 11:44:13 +0000829 for(j=0; j<pColumn->nId; j++){
830 if( pColumn->a[j].idx==i ) break;
831 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000832 }
danielk1977034ca142007-06-26 10:38:54 +0000833 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000834 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000835 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000836 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000837 }else if( pSelect ){
drhb1fdb2a2008-01-05 04:06:03 +0000838 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn-j-1), iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000839 }else{
danielk1977287fb612008-01-04 19:10:28 +0000840 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000841 }
drhbed86902000-06-02 13:27:59 +0000842 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000843
844 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000845 ** do the insertion.
846 */
drh4cbdda92006-06-14 19:00:20 +0000847#ifndef SQLITE_OMIT_VIRTUALTABLE
848 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000849 pParse->pVirtualLock = pTab;
drh6a288a32008-01-07 19:20:24 +0000850 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000851 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000852 }else
853#endif
854 {
drh04adf412008-01-08 18:57:50 +0000855 sqlite3GenerateConstraintChecks(
856 pParse,
857 pTab,
858 baseCur,
859 regIns,
860 aRegIdx,
861 keyColumn>=0,
862 0,
863 onError,
864 endOfLoop
865 );
866 sqlite3CompleteInsertion(
867 pParse,
868 pTab,
869 baseCur,
870 regIns,
871 aRegIdx,
872 0,
873 0,
874 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
875 appendFlag
876 );
drh4cbdda92006-06-14 19:00:20 +0000877 }
drh5cf590c2003-04-24 01:45:04 +0000878 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000879
drh5cf590c2003-04-24 01:45:04 +0000880 /* Update the count of rows that are inserted
881 */
882 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000883 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000884 }
drh1ccde152000-06-17 13:12:39 +0000885
drhdca76842004-12-07 14:06:13 +0000886 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000887 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000888 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000889 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000890 goto insert_cleanup;
891 }
drh1bee3d72001-10-15 00:44:35 +0000892 }
893
drh1ccde152000-06-17 13:12:39 +0000894 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000895 */
danielk19774adee202004-05-08 08:23:19 +0000896 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000897 if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000898 sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
danielk19774adee202004-05-08 08:23:19 +0000899 sqlite3VdbeResolveLabel(v, iBreak);
drh66a51672008-01-03 00:01:23 +0000900 sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000901 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000902 sqlite3VdbeAddOp2(v, OP_Pop, nColumn, 0);
903 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000904 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000905 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000906
danielk1977e448dc42008-01-02 11:50:51 +0000907 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000908 /* Close all tables opened */
drh04adf412008-01-08 18:57:50 +0000909 sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000910 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh04adf412008-01-08 18:57:50 +0000911 sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000912 }
drhcce7d172000-05-31 15:34:51 +0000913 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000914
drhf3388142004-11-13 03:48:06 +0000915 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000916 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000917 ** table.
drh2958a4e2004-11-12 03:56:15 +0000918 */
drh6a288a32008-01-07 19:20:24 +0000919 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000920
drh1bee3d72001-10-15 00:44:35 +0000921 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000922 ** Return the number of rows inserted. If this routine is
923 ** generating code because of a call to sqlite3NestedParse(), do not
924 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000925 */
danielk1977cc6bd382005-01-10 02:48:49 +0000926 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +0000927 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +0000928 sqlite3VdbeSetNumCols(v, 1);
drh66a51672008-01-03 00:01:23 +0000929 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000930 }
drhcce7d172000-05-31 15:34:51 +0000931
932insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000933 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000934 sqlite3ExprListDelete(pList);
935 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000936 sqlite3IdListDelete(pColumn);
drhaa9b8962008-01-08 02:57:55 +0000937 sqlite3_free(aRegIdx);
drhcce7d172000-05-31 15:34:51 +0000938}
drh9cfcf5d2002-01-29 18:41:24 +0000939
drh9cfcf5d2002-01-29 18:41:24 +0000940/*
drh6a288a32008-01-07 19:20:24 +0000941** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +0000942**
drh04adf412008-01-08 18:57:50 +0000943** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +0000944**
drhf0863fe2005-06-12 21:35:51 +0000945** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000946** value is omitted unless we are doing an UPDATE that involves a
drh6a288a32008-01-07 19:20:24 +0000947** change to the record number. (Or writing to a virtual table.)
drh0ca3e242002-01-29 23:07:02 +0000948**
drhf0863fe2005-06-12 21:35:51 +0000949** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000950**
951** 3. The data in the first column of the entry after the update.
952**
953** i. Data from middle columns...
954**
955** N. The data in the last column of the entry after the update.
956**
drh04adf412008-01-08 18:57:50 +0000957** The regRowid parameter is the index of the register containing (2).
958**
drhf0863fe2005-06-12 21:35:51 +0000959** The old rowid shown as entry (1) above is omitted unless both isUpdate
960** and rowidChng are 1. isUpdate is true for UPDATEs and false for
961** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000962**
drhaa9b8962008-01-08 02:57:55 +0000963** The code generated by this routine store new index entries into
964** registers identified by aRegIdx[]. No index entry is created for
965** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
966** the same as the order of indices on the linked list of indices
967** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +0000968**
969** This routine also generates code to check constraints. NOT NULL,
970** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000971** then the appropriate action is performed. There are five possible
972** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000973**
974** Constraint type Action What Happens
975** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000976** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000977** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000978** return code of SQLITE_CONSTRAINT.
979**
drh1c928532002-01-31 15:54:21 +0000980** any ABORT Back out changes from the current command
981** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000982** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000983** with SQLITE_CONSTRAINT.
984**
985** any FAIL Sqlite_exec() returns immediately with a
986** return code of SQLITE_CONSTRAINT. The
987** transaction is not rolled back and any
988** prior changes are retained.
989**
drh9cfcf5d2002-01-29 18:41:24 +0000990** any IGNORE The record number and data is popped from
991** the stack and there is an immediate jump
992** to label ignoreDest.
993**
994** NOT NULL REPLACE The NULL value is replace by the default
995** value for that column. If the default value
996** is NULL, the action is the same as ABORT.
997**
998** UNIQUE REPLACE The other row that conflicts with the row
999** being inserted is removed.
1000**
1001** CHECK REPLACE Illegal. The results in an exception.
1002**
drh1c928532002-01-31 15:54:21 +00001003** Which action to take is determined by the overrideError parameter.
1004** Or if overrideError==OE_Default, then the pParse->onError parameter
1005** is used. Or if pParse->onError==OE_Default then the onError value
1006** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001007**
drhaaab5722002-02-19 13:39:21 +00001008** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +00001009** cursor number "baseCur". All indices of pTab must also have open
1010** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001011** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001012** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001013**
drh04adf412008-01-08 18:57:50 +00001014** If the isUpdate flag is true, it means that the "baseCur" cursor is
drh9cfcf5d2002-01-29 18:41:24 +00001015** initially pointing to an entry that is being updated. The isUpdate
drh04adf412008-01-08 18:57:50 +00001016** flag causes extra code to be generated so that the "baseCur" cursor
drh9cfcf5d2002-01-29 18:41:24 +00001017** is still pointing at the same entry after the routine returns.
drh04adf412008-01-08 18:57:50 +00001018** Without the isUpdate flag, the "baseCur" cursor might be moved.
drh9cfcf5d2002-01-29 18:41:24 +00001019*/
danielk19774adee202004-05-08 08:23:19 +00001020void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001021 Parse *pParse, /* The parser context */
1022 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001023 int baseCur, /* Index of a read/write cursor pointing at pTab */
1024 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001025 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh04adf412008-01-08 18:57:50 +00001026 int rowidChng, /* True if the rowid will change */
drhb419a922002-01-30 16:17:23 +00001027 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001028 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +00001029 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +00001030){
1031 int i;
1032 Vdbe *v;
1033 int nCol;
1034 int onError;
drhaa9b8962008-01-08 02:57:55 +00001035 int j1, j2, j3; /* Address of jump instructions */
drh04adf412008-01-08 18:57:50 +00001036 int regData; /* Register containing first data column */
drh0ca3e242002-01-29 23:07:02 +00001037 int iCur;
1038 Index *pIdx;
1039 int seenReplace = 0;
drhf0863fe2005-06-12 21:35:51 +00001040 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001041
danielk19774adee202004-05-08 08:23:19 +00001042 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001043 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001044 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001045 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001046 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001047
drhaa9b8962008-01-08 02:57:55 +00001048
drh9cfcf5d2002-01-29 18:41:24 +00001049 /* Test all NOT NULL constraints.
1050 */
1051 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001052 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001053 continue;
1054 }
drh9cfcf5d2002-01-29 18:41:24 +00001055 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001056 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001057 if( overrideError!=OE_Default ){
1058 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001059 }else if( onError==OE_Default ){
1060 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001061 }
danielk19777977a172004-11-09 12:44:37 +00001062 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001063 onError = OE_Abort;
1064 }
drhaa9b8962008-01-08 02:57:55 +00001065 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
danielk1977b84f96f2005-01-20 11:32:23 +00001066 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1067 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001068 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001069 case OE_Rollback:
1070 case OE_Abort:
1071 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001072 char *zMsg = 0;
drh66a51672008-01-03 00:01:23 +00001073 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
danielk19774adee202004-05-08 08:23:19 +00001074 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001075 " may not be NULL", (char*)0);
drh66a51672008-01-03 00:01:23 +00001076 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001077 break;
1078 }
1079 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001080 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001081 break;
1082 }
1083 case OE_Replace: {
drh04adf412008-01-08 18:57:50 +00001084 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh9cfcf5d2002-01-29 18:41:24 +00001085 break;
1086 }
drh9cfcf5d2002-01-29 18:41:24 +00001087 }
drhaa9b8962008-01-08 02:57:55 +00001088 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001089 }
1090
1091 /* Test all CHECK constraints
1092 */
drhffe07b22005-11-03 00:41:17 +00001093#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001094 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001095 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001096 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001097 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001098 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001099 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001100 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001101 }else{
drh66a51672008-01-03 00:01:23 +00001102 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001103 }
drhffe07b22005-11-03 00:41:17 +00001104 sqlite3VdbeResolveLabel(v, allOk);
1105 }
1106#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001107
drh0bd1f4e2002-06-06 18:54:39 +00001108 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1109 ** of the new record does not previously exist. Except, if this
1110 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001111 */
drhf0863fe2005-06-12 21:35:51 +00001112 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001113 onError = pTab->keyConf;
1114 if( overrideError!=OE_Default ){
1115 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001116 }else if( onError==OE_Default ){
1117 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001118 }
drha0217ba2003-06-01 01:10:33 +00001119
drh5383ae52003-06-04 12:23:30 +00001120 if( isUpdate ){
drh892d3172008-01-10 03:46:36 +00001121 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
drh5383ae52003-06-04 12:23:30 +00001122 }
drh04adf412008-01-08 18:57:50 +00001123 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
drh5383ae52003-06-04 12:23:30 +00001124 switch( onError ){
1125 default: {
1126 onError = OE_Abort;
1127 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001128 }
drh5383ae52003-06-04 12:23:30 +00001129 case OE_Rollback:
1130 case OE_Abort:
1131 case OE_Fail: {
drh66a51672008-01-03 00:01:23 +00001132 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1133 "PRIMARY KEY must be unique", P4_STATIC);
drh5383ae52003-06-04 12:23:30 +00001134 break;
drh0ca3e242002-01-29 23:07:02 +00001135 }
drh5383ae52003-06-04 12:23:30 +00001136 case OE_Replace: {
drh2d401ab2008-01-10 23:50:11 +00001137 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
drh5383ae52003-06-04 12:23:30 +00001138 if( isUpdate ){
drh892d3172008-01-10 03:46:36 +00001139 sqlite3VdbeAddOp3(v, OP_MoveGe, baseCur, 0, regRowid-hasTwoRowids);
drh5383ae52003-06-04 12:23:30 +00001140 }
1141 seenReplace = 1;
1142 break;
drh0ca3e242002-01-29 23:07:02 +00001143 }
drh5383ae52003-06-04 12:23:30 +00001144 case OE_Ignore: {
1145 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001146 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001147 break;
1148 }
1149 }
drhaa9b8962008-01-08 02:57:55 +00001150 sqlite3VdbeJumpHere(v, j3);
drh5383ae52003-06-04 12:23:30 +00001151 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001152 sqlite3VdbeJumpHere(v, j2);
drh892d3172008-01-10 03:46:36 +00001153 sqlite3VdbeAddOp3(v, OP_MoveGe, baseCur, 0, regRowid-1);
drh0ca3e242002-01-29 23:07:02 +00001154 }
1155 }
drh0bd1f4e2002-06-06 18:54:39 +00001156
1157 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1158 ** index and making sure that duplicate entries do not already exist.
1159 ** Add the new records to the indices as we go.
1160 */
drhb2fe7d82003-04-20 17:29:23 +00001161 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001162 int regIdx;
1163 int regR;
1164
drhaa9b8962008-01-08 02:57:55 +00001165 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001166
1167 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001168 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001169 for(i=0; i<pIdx->nColumn; i++){
1170 int idx = pIdx->aiColumn[i];
1171 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001172 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001173 }else{
drh2d401ab2008-01-10 23:50:11 +00001174 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001175 }
1176 }
drh2d401ab2008-01-10 23:50:11 +00001177 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
1178 sqlite3VdbeAddOp3(v, OP_RegMakeRec, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001179 sqlite3IndexAffinityStr(v, pIdx);
drh2d401ab2008-01-10 23:50:11 +00001180 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001181
1182 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001183 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001184 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001185 if( overrideError!=OE_Default ){
1186 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001187 }else if( onError==OE_Default ){
1188 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001189 }
drh5383ae52003-06-04 12:23:30 +00001190 if( seenReplace ){
1191 if( onError==OE_Ignore ) onError = OE_Replace;
1192 else if( onError==OE_Fail ) onError = OE_Abort;
1193 }
1194
drhb2fe7d82003-04-20 17:29:23 +00001195
1196 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001197 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
1198 regR = sqlite3GetTempReg(pParse);
1199 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
1200 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1201 regR, (char*)aRegIdx[iCur], P4_INT32);
drhb2fe7d82003-04-20 17:29:23 +00001202
1203 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001204 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1205 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001206 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001207 case OE_Rollback:
1208 case OE_Abort:
1209 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001210 int j, n1, n2;
1211 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001212 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1213 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001214 n1 = strlen(zErrMsg);
1215 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1216 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1217 n2 = strlen(zCol);
1218 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001219 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001220 n1 += 2;
1221 }
1222 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001223 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001224 n1 += 3;
1225 break;
1226 }else{
drh5bb3eb92007-05-04 13:15:55 +00001227 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001228 n1 += n2;
1229 }
1230 }
drh5bb3eb92007-05-04 13:15:55 +00001231 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001232 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001233 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001234 break;
1235 }
1236 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001237 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001238 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001239 break;
1240 }
1241 case OE_Replace: {
drh2d401ab2008-01-10 23:50:11 +00001242 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001243 if( isUpdate ){
drh2d401ab2008-01-10 23:50:11 +00001244 sqlite3VdbeAddOp3(v, OP_MoveGe, baseCur, 0, regRowid-hasTwoRowids);
drh9cfcf5d2002-01-29 18:41:24 +00001245 }
drh0ca3e242002-01-29 23:07:02 +00001246 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001247 break;
1248 }
drh9cfcf5d2002-01-29 18:41:24 +00001249 }
drhaa9b8962008-01-08 02:57:55 +00001250 sqlite3VdbeJumpHere(v, j2);
drh2d401ab2008-01-10 23:50:11 +00001251 sqlite3VdbeJumpHere(v, j3);
1252 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001253 }
1254}
drh0ca3e242002-01-29 23:07:02 +00001255
1256/*
1257** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001258** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001259** A consecutive range of registers starting at regRowid contains the
1260** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001261**
drhb419a922002-01-30 16:17:23 +00001262** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001263** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001264*/
danielk19774adee202004-05-08 08:23:19 +00001265void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001266 Parse *pParse, /* The parser context */
1267 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001268 int baseCur, /* Index of a read/write cursor pointing at pTab */
1269 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001270 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drhf0863fe2005-06-12 21:35:51 +00001271 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001272 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001273 int newIdx, /* Index of NEW table for triggers. -1 if none */
1274 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001275){
1276 int i;
1277 Vdbe *v;
1278 int nIdx;
1279 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001280 int pik_flags;
drh04adf412008-01-08 18:57:50 +00001281 int regData;
drh0ca3e242002-01-29 23:07:02 +00001282
danielk19774adee202004-05-08 08:23:19 +00001283 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001284 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001285 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001286 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1287 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001288 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001289 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
drh0ca3e242002-01-29 23:07:02 +00001290 }
drh04adf412008-01-08 18:57:50 +00001291 regData = regRowid + 1;
1292 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1293 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regData, pTab->nCol);
danielk1977a37cdde2004-05-16 11:15:36 +00001294 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001295#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001296 if( newIdx>=0 ){
drh04adf412008-01-08 18:57:50 +00001297 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1298 sqlite3VdbeAddOp1(v, OP_SCopy, -1);
danielk19771f4aa332008-01-03 09:51:55 +00001299 sqlite3CodeInsert(pParse, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001300 }
danielk1977b84f96f2005-01-20 11:32:23 +00001301#endif
drh4794f732004-11-05 17:17:50 +00001302 if( pParse->nested ){
1303 pik_flags = 0;
1304 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001305 pik_flags = OPFLAG_NCHANGE;
1306 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001307 }
drhe4d90812007-03-29 05:51:49 +00001308 if( appendBias ){
1309 pik_flags |= OPFLAG_APPEND;
1310 }
drh04adf412008-01-08 18:57:50 +00001311 sqlite3CodeInsert(pParse, baseCur, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001312 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001313 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001314 }
drh0ca3e242002-01-29 23:07:02 +00001315}
drhcd446902004-02-24 01:05:31 +00001316
1317/*
drh290c1942004-08-21 17:54:45 +00001318** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001319** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001320** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001321**
1322** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001323*/
drhaa9b8962008-01-08 02:57:55 +00001324int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001325 Parse *pParse, /* Parsing context */
1326 Table *pTab, /* Table to be opened */
drh04adf412008-01-08 18:57:50 +00001327 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001328 int op /* OP_OpenRead or OP_OpenWrite */
1329){
drhcd446902004-02-24 01:05:31 +00001330 int i;
drh4cbdda92006-06-14 19:00:20 +00001331 int iDb;
drhcd446902004-02-24 01:05:31 +00001332 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001333 Vdbe *v;
1334
drhaa9b8962008-01-08 02:57:55 +00001335 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001336 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1337 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001338 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001339 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001340 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001341 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001342 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001343 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001344 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001345 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001346 }
drh04adf412008-01-08 18:57:50 +00001347 if( pParse->nTab<=baseCur+i ){
1348 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001349 }
drhaa9b8962008-01-08 02:57:55 +00001350 return i-1;
drhcd446902004-02-24 01:05:31 +00001351}
drh9d9cf222007-02-13 15:01:11 +00001352
drh91c58e22007-03-27 12:04:04 +00001353
1354#ifdef SQLITE_TEST
1355/*
1356** The following global variable is incremented whenever the
1357** transfer optimization is used. This is used for testing
1358** purposes only - to make sure the transfer optimization really
1359** is happening when it is suppose to.
1360*/
1361int sqlite3_xferopt_count;
1362#endif /* SQLITE_TEST */
1363
1364
drh9d9cf222007-02-13 15:01:11 +00001365#ifndef SQLITE_OMIT_XFER_OPT
1366/*
1367** Check to collation names to see if they are compatible.
1368*/
1369static int xferCompatibleCollation(const char *z1, const char *z2){
1370 if( z1==0 ){
1371 return z2==0;
1372 }
1373 if( z2==0 ){
1374 return 0;
1375 }
1376 return sqlite3StrICmp(z1, z2)==0;
1377}
1378
1379
1380/*
1381** Check to see if index pSrc is compatible as a source of data
1382** for index pDest in an insert transfer optimization. The rules
1383** for a compatible index:
1384**
1385** * The index is over the same set of columns
1386** * The same DESC and ASC markings occurs on all columns
1387** * The same onError processing (OE_Abort, OE_Ignore, etc)
1388** * The same collating sequence on each column
1389*/
1390static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1391 int i;
1392 assert( pDest && pSrc );
1393 assert( pDest->pTable!=pSrc->pTable );
1394 if( pDest->nColumn!=pSrc->nColumn ){
1395 return 0; /* Different number of columns */
1396 }
1397 if( pDest->onError!=pSrc->onError ){
1398 return 0; /* Different conflict resolution strategies */
1399 }
1400 for(i=0; i<pSrc->nColumn; i++){
1401 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1402 return 0; /* Different columns indexed */
1403 }
1404 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1405 return 0; /* Different sort orders */
1406 }
1407 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1408 return 0; /* Different sort orders */
1409 }
1410 }
1411
1412 /* If no test above fails then the indices must be compatible */
1413 return 1;
1414}
1415
1416/*
1417** Attempt the transfer optimization on INSERTs of the form
1418**
1419** INSERT INTO tab1 SELECT * FROM tab2;
1420**
1421** This optimization is only attempted if
1422**
1423** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001424** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001425**
1426** (2) tab1 and tab2 are different tables
1427**
1428** (3) There must be no triggers on tab1
1429**
1430** (4) The result set of the SELECT statement is "*"
1431**
1432** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1433** or LIMIT clause.
1434**
1435** (6) The SELECT statement is a simple (not a compound) select that
1436** contains only tab2 in its FROM clause
1437**
1438** This method for implementing the INSERT transfers raw records from
1439** tab2 over to tab1. The columns are not decoded. Raw records from
1440** the indices of tab2 are transfered to tab1 as well. In so doing,
1441** the resulting tab1 has much less fragmentation.
1442**
1443** This routine returns TRUE if the optimization is attempted. If any
1444** of the conditions above fail so that the optimization should not
1445** be attempted, then this routine returns FALSE.
1446*/
1447static int xferOptimization(
1448 Parse *pParse, /* Parser context */
1449 Table *pDest, /* The table we are inserting into */
1450 Select *pSelect, /* A SELECT statement to use as the data source */
1451 int onError, /* How to handle constraint errors */
1452 int iDbDest /* The database of pDest */
1453){
1454 ExprList *pEList; /* The result set of the SELECT */
1455 Table *pSrc; /* The table in the FROM clause of SELECT */
1456 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1457 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1458 int i; /* Loop counter */
1459 int iDbSrc; /* The database of pSrc */
1460 int iSrc, iDest; /* Cursors from source and destination */
1461 int addr1, addr2; /* Loop addresses */
1462 int emptyDestTest; /* Address of test for empty pDest */
1463 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001464 Vdbe *v; /* The VDBE we are building */
1465 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001466 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001467 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001468
1469 if( pSelect==0 ){
1470 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1471 }
1472 if( pDest->pTrigger ){
1473 return 0; /* tab1 must not have triggers */
1474 }
1475#ifndef SQLITE_OMIT_VIRTUALTABLE
1476 if( pDest->isVirtual ){
1477 return 0; /* tab1 must not be a virtual table */
1478 }
1479#endif
1480 if( onError==OE_Default ){
1481 onError = OE_Abort;
1482 }
1483 if( onError!=OE_Abort && onError!=OE_Rollback ){
1484 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1485 }
danielk19775ce240a2007-09-03 17:30:06 +00001486 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001487 if( pSelect->pSrc->nSrc!=1 ){
1488 return 0; /* FROM clause must have exactly one term */
1489 }
1490 if( pSelect->pSrc->a[0].pSelect ){
1491 return 0; /* FROM clause cannot contain a subquery */
1492 }
1493 if( pSelect->pWhere ){
1494 return 0; /* SELECT may not have a WHERE clause */
1495 }
1496 if( pSelect->pOrderBy ){
1497 return 0; /* SELECT may not have an ORDER BY clause */
1498 }
drh8103b7d2007-02-24 13:23:51 +00001499 /* Do not need to test for a HAVING clause. If HAVING is present but
1500 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001501 if( pSelect->pGroupBy ){
1502 return 0; /* SELECT may not have a GROUP BY clause */
1503 }
1504 if( pSelect->pLimit ){
1505 return 0; /* SELECT may not have a LIMIT clause */
1506 }
drh8103b7d2007-02-24 13:23:51 +00001507 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001508 if( pSelect->pPrior ){
1509 return 0; /* SELECT may not be a compound query */
1510 }
1511 if( pSelect->isDistinct ){
1512 return 0; /* SELECT may not be DISTINCT */
1513 }
1514 pEList = pSelect->pEList;
1515 assert( pEList!=0 );
1516 if( pEList->nExpr!=1 ){
1517 return 0; /* The result set must have exactly one column */
1518 }
1519 assert( pEList->a[0].pExpr );
1520 if( pEList->a[0].pExpr->op!=TK_ALL ){
1521 return 0; /* The result set must be the special operator "*" */
1522 }
1523
1524 /* At this point we have established that the statement is of the
1525 ** correct syntactic form to participate in this optimization. Now
1526 ** we have to check the semantics.
1527 */
1528 pItem = pSelect->pSrc->a;
1529 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1530 if( pSrc==0 ){
1531 return 0; /* FROM clause does not contain a real table */
1532 }
1533 if( pSrc==pDest ){
1534 return 0; /* tab1 and tab2 may not be the same table */
1535 }
1536#ifndef SQLITE_OMIT_VIRTUALTABLE
1537 if( pSrc->isVirtual ){
1538 return 0; /* tab2 must not be a virtual table */
1539 }
1540#endif
1541 if( pSrc->pSelect ){
1542 return 0; /* tab2 may not be a view */
1543 }
1544 if( pDest->nCol!=pSrc->nCol ){
1545 return 0; /* Number of columns must be the same in tab1 and tab2 */
1546 }
1547 if( pDest->iPKey!=pSrc->iPKey ){
1548 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1549 }
1550 for(i=0; i<pDest->nCol; i++){
1551 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1552 return 0; /* Affinity must be the same on all columns */
1553 }
1554 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1555 return 0; /* Collating sequence must be the same on all columns */
1556 }
1557 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1558 return 0; /* tab2 must be NOT NULL if tab1 is */
1559 }
1560 }
1561 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001562 if( pDestIdx->onError!=OE_None ){
1563 destHasUniqueIdx = 1;
1564 }
drh9d9cf222007-02-13 15:01:11 +00001565 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1566 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1567 }
1568 if( pSrcIdx==0 ){
1569 return 0; /* pDestIdx has no corresponding index in pSrc */
1570 }
1571 }
drh7fc2f412007-03-29 00:08:24 +00001572#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001573 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001574 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1575 }
drh7fc2f412007-03-29 00:08:24 +00001576#endif
drh9d9cf222007-02-13 15:01:11 +00001577
1578 /* If we get this far, it means either:
1579 **
1580 ** * We can always do the transfer if the table contains an
1581 ** an integer primary key
1582 **
1583 ** * We can conditionally do the transfer if the destination
1584 ** table is empty.
1585 */
drhdd735212007-02-24 13:53:05 +00001586#ifdef SQLITE_TEST
1587 sqlite3_xferopt_count++;
1588#endif
drh9d9cf222007-02-13 15:01:11 +00001589 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1590 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001591 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001592 iSrc = pParse->nTab++;
1593 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001594 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001595 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001596 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001597 /* If tables do not have an INTEGER PRIMARY KEY and there
1598 ** are indices to be copied and the destination is not empty,
1599 ** we have to disallow the transfer optimization because the
1600 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001601 **
1602 ** Or if the destination has a UNIQUE index and is not empty,
1603 ** we also disallow the transfer optimization because we cannot
1604 ** insure that all entries in the union of DEST and SRC will be
1605 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001606 */
drh66a51672008-01-03 00:01:23 +00001607 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1608 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001609 sqlite3VdbeJumpHere(v, addr1);
1610 }else{
1611 emptyDestTest = 0;
1612 }
1613 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001614 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001615 if( pDest->iPKey>=0 ){
drh66a51672008-01-03 00:01:23 +00001616 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001617 sqlite3VdbeAddOp0(v, OP_Copy);
drh66a51672008-01-03 00:01:23 +00001618 addr2 = sqlite3VdbeAddOp2(v, OP_NotExists, iDest, 0);
1619 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1620 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001621 sqlite3VdbeJumpHere(v, addr2);
drh6a288a32008-01-07 19:20:24 +00001622 autoIncStep(pParse, regAutoinc, 0);
drhbd36ba62007-03-31 13:00:26 +00001623 }else if( pDest->pIndex==0 ){
drh4c583122008-01-04 22:01:03 +00001624 addr1 = sqlite3VdbeAddOp1(v, OP_NewRowid, iDest);
drh95bad4c2007-03-28 18:04:10 +00001625 }else{
drh66a51672008-01-03 00:01:23 +00001626 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001627 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001628 }
drh98757152008-01-09 23:04:12 +00001629 sqlite3VdbeAddOp1(v, OP_RowData, iSrc);
danielk19771f4aa332008-01-03 09:51:55 +00001630 sqlite3CodeInsert(pParse,iDest,OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1631 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001632 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001633 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001634 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1635 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1636 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1637 }
1638 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001639 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1640 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001641 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001642 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1643 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001644 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001645 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001646 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001647 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001648 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001649 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drh98757152008-01-09 23:04:12 +00001650 sqlite3VdbeAddOp1(v, OP_RowKey, iSrc);
drhaa9b8962008-01-08 02:57:55 +00001651 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, 0, 1);
drh66a51672008-01-03 00:01:23 +00001652 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001653 sqlite3VdbeJumpHere(v, addr1);
1654 }
1655 sqlite3VdbeJumpHere(v, emptySrcTest);
drh66a51672008-01-03 00:01:23 +00001656 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1657 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001658 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001659 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001660 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001661 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001662 return 0;
1663 }else{
1664 return 1;
1665 }
1666}
1667#endif /* SQLITE_OMIT_XFER_OPT */