blob: ea1e7c5c56d27994e4a69bfd3806d71b63c7c032 [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**
drh3c84ddf2008-01-09 02:15:38 +000015** $Id: insert.c,v 1.219 2008/01/09 02:15:39 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);
drh35573352008-01-08 23:54:25 +0000176 sqlite3VdbeAddOp2(v, OP_Ne, 0, addr+7);
177 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh6a288a32008-01-07 19:20:24 +0000178 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
179 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
180 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
181 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1);
drh66a51672008-01-03 00:01:23 +0000182 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000183 }
184 return memId;
185}
186
187/*
188** Update the maximum rowid for an autoincrement calculation.
189**
190** This routine should be called when the top of the stack holds a
191** new rowid that is about to be inserted. If that new rowid is
192** larger than the maximum rowid in the memId memory cell, then the
193** memory cell is updated. The stack is unchanged.
194*/
drh6a288a32008-01-07 19:20:24 +0000195static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000196 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000197 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000198 }
199}
200
201/*
202** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000203** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000204** the sqlite_sequence table.
205*/
206static void autoIncEnd(
207 Parse *pParse, /* The parsing context */
208 int iDb, /* Index of the database holding pTab */
209 Table *pTab, /* Table we are inserting into */
210 int memId /* Memory cell holding the maximum rowid */
211){
212 if( pTab->autoInc ){
213 int iCur = pParse->nTab;
214 Vdbe *v = pParse->pVdbe;
215 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000216 int j1;
217
drh9d9cf222007-02-13 15:01:11 +0000218 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000219 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000220 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
221 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
222 sqlite3VdbeJumpHere(v, j1);
223 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
224 sqlite3VdbeAddOp3(v, OP_RegMakeRec, memId-1, 2, memId-1);
225 sqlite3VdbeAddOp3(v, OP_Insert, iCur, memId-1, memId+1);
drh35573352008-01-08 23:54:25 +0000226 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh6a288a32008-01-07 19:20:24 +0000227 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000228 }
229}
230#else
231/*
232** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
233** above are all no-ops
234*/
235# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000236# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000237# define autoIncEnd(A,B,C,D)
238#endif /* SQLITE_OMIT_AUTOINCREMENT */
239
240
241/* Forward declaration */
242static int xferOptimization(
243 Parse *pParse, /* Parser context */
244 Table *pDest, /* The table we are inserting into */
245 Select *pSelect, /* A SELECT statement to use as the data source */
246 int onError, /* How to handle constraint errors */
247 int iDbDest /* The database of pDest */
248);
249
danielk19773d1bfea2004-05-14 11:00:53 +0000250/*
drh1ccde152000-06-17 13:12:39 +0000251** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000252**
253** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000254** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000255**
drh1ccde152000-06-17 13:12:39 +0000256** The IDLIST following the table name is always optional. If omitted,
257** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000258** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000259**
260** The pList parameter holds EXPRLIST in the first form of the INSERT
261** statement above, and pSelect is NULL. For the second form, pList is
262** NULL and pSelect is a pointer to the select statement used to generate
263** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000264**
drh9d9cf222007-02-13 15:01:11 +0000265** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000266** select with data coming from a VALUES clause, the code executes
267** once straight down through. The template looks like this:
268**
269** open write cursor to <table> and its indices
270** puts VALUES clause expressions onto the stack
271** write the resulting record into <table>
272** cleanup
273**
drh9d9cf222007-02-13 15:01:11 +0000274** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000275**
276** INSERT INTO <table> SELECT ...
277**
drh9d9cf222007-02-13 15:01:11 +0000278** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
279** in other words if the SELECT pulls all columns from a single table
280** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
281** if <table2> and <table1> are distinct tables but have identical
282** schemas, including all the same indices, then a special optimization
283** is invoked that copies raw records from <table2> over to <table1>.
284** See the xferOptimization() function for the implementation of this
285** template. This is the second template.
286**
287** open a write cursor to <table>
288** open read cursor on <table2>
289** transfer all records in <table2> over to <table>
290** close cursors
291** foreach index on <table>
292** open a write cursor on the <table> index
293** open a read cursor on the corresponding <table2> index
294** transfer all records from the read to the write cursors
295** close cursors
296** end foreach
297**
298** The third template is for when the second template does not apply
299** and the SELECT clause does not read from <table> at any time.
300** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000301**
302** goto B
303** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000304** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000305** gosub C
306** end loop
307** cleanup after the SELECT
308** goto D
309** B: open write cursor to <table> and its indices
310** goto A
311** C: insert the select result into <table>
312** return
313** D: cleanup
314**
drh9d9cf222007-02-13 15:01:11 +0000315** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000316** values from a SELECT but the data is being inserted into a table
317** that is also read as part of the SELECT. In the third form,
318** we have to use a intermediate table to store the results of
319** the select. The template is like this:
320**
321** goto B
322** A: setup for the SELECT
323** loop over the tables in the SELECT
324** gosub C
325** end loop
326** cleanup after the SELECT
327** goto D
328** C: insert the select result into the intermediate table
329** return
330** B: open a cursor to an intermediate table
331** goto A
332** D: open write cursor to <table> and its indices
333** loop over the intermediate table
334** transfer values form intermediate table into <table>
335** end the loop
336** cleanup
drhcce7d172000-05-31 15:34:51 +0000337*/
danielk19774adee202004-05-08 08:23:19 +0000338void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000339 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000340 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000341 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000342 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000343 IdList *pColumn, /* Column names corresponding to IDLIST. */
344 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000345){
drh6a288a32008-01-07 19:20:24 +0000346 sqlite3 *db; /* The main database structure */
347 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000348 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000349 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000350 int i, j, idx; /* Loop counters */
351 Vdbe *v; /* Generate code into this virtual machine */
352 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000353 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000354 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000355 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000356 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000357 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000358 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000359 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drh6a288a32008-01-07 19:20:24 +0000360 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
danielk1977cfe9a692004-06-16 12:00:29 +0000361 int iSelectLoop = 0; /* Address of code that implements the SELECT */
362 int iCleanup = 0; /* Address of the cleanup code */
363 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
drh6a288a32008-01-07 19:20:24 +0000364 int newIdx = -1; /* Cursor for the NEW pseudo-table */
365 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000366 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000367 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000368
drh6a288a32008-01-07 19:20:24 +0000369 /* Register allocations */
370 int regFromSelect; /* Base register for data coming from SELECT */
371 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
372 int regRowCount = 0; /* Memory cell used for the row counter */
373 int regIns; /* Block of regs holding rowid+data being inserted */
374 int regRowid; /* registers holding insert rowid */
375 int regData; /* register holding first column to insert */
376 int regRecord; /* Holds the assemblied row record */
drhaa9b8962008-01-08 02:57:55 +0000377 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000378
danielk1977034ca142007-06-26 10:38:54 +0000379
drh798da522004-11-04 04:42:28 +0000380#ifndef SQLITE_OMIT_TRIGGER
381 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000382 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000383#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000384
drh17435752007-08-16 04:30:38 +0000385 db = pParse->db;
386 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000387 goto insert_cleanup;
388 }
drhdaffd0e2001-04-11 14:28:42 +0000389
drh1ccde152000-06-17 13:12:39 +0000390 /* Locate the table into which we will be inserting new information.
391 */
drh113088e2003-03-20 01:16:58 +0000392 assert( pTabList->nSrc==1 );
393 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000394 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000395 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000396 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000397 goto insert_cleanup;
398 }
danielk1977da184232006-01-05 11:34:32 +0000399 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
400 assert( iDb<db->nDb );
401 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000402 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000403 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000404 goto insert_cleanup;
405 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000406
drhb7f91642004-10-31 02:22:47 +0000407 /* Figure out if we have any triggers and if the table being
408 ** inserted into is a view
409 */
410#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000411 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000412 isView = pTab->pSelect!=0;
413#else
drhdca76842004-12-07 14:06:13 +0000414# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000415# define isView 0
416#endif
417#ifdef SQLITE_OMIT_VIEW
418# undef isView
419# define isView 0
420#endif
421
danielk1977c3f9bad2002-05-15 08:30:12 +0000422 /* Ensure that:
423 * (a) the table is not read-only,
424 * (b) that if it is a view then ON INSERT triggers exist
425 */
drhdca76842004-12-07 14:06:13 +0000426 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000427 goto insert_cleanup;
428 }
drh43617e92006-03-06 20:55:46 +0000429 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000430
drhf573c992002-07-31 00:32:50 +0000431 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000432 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
433 ** module table).
drhf573c992002-07-31 00:32:50 +0000434 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000435 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000436 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000437 }
438
drh1ccde152000-06-17 13:12:39 +0000439 /* Allocate a VDBE
440 */
danielk19774adee202004-05-08 08:23:19 +0000441 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000442 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000443 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000444 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000445
danielk1977c3f9bad2002-05-15 08:30:12 +0000446 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000447 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000448 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000449 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000450
drh9d9cf222007-02-13 15:01:11 +0000451#ifndef SQLITE_OMIT_XFER_OPT
452 /* If the statement is of the form
453 **
454 ** INSERT INTO <table1> SELECT * FROM <table2>;
455 **
456 ** Then special optimizations can be applied that make the transfer
457 ** very fast and which reduce fragmentation of indices.
458 */
459 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
460 assert( !triggers_exist );
461 assert( pList==0 );
462 goto insert_cleanup;
463 }
464#endif /* SQLITE_OMIT_XFER_OPT */
465
drh2958a4e2004-11-12 03:56:15 +0000466 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000467 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000468 */
drh6a288a32008-01-07 19:20:24 +0000469 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000470
drh1ccde152000-06-17 13:12:39 +0000471 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000472 ** is coming from a SELECT statement, then this step also generates
473 ** all the code to implement the SELECT statement and invoke a subroutine
474 ** to process each row of the result. (Template 2.) If the SELECT
475 ** statement uses the the table that is being inserted into, then the
476 ** subroutine is also coded here. That subroutine stores the SELECT
477 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000478 */
drh5974a302000-06-07 14:42:26 +0000479 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000480 /* Data is coming from a SELECT. Generate code to implement that SELECT
481 */
drh1013c932008-01-06 00:25:21 +0000482 SelectDest dest;
drh142e30d2002-08-28 03:00:58 +0000483 int rc, iInitCode;
drh1013c932008-01-06 00:25:21 +0000484
drh66a51672008-01-03 00:01:23 +0000485 iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000486 iSelectLoop = sqlite3VdbeCurrentAddr(v);
487 iInsertBlock = sqlite3VdbeMakeLabel(v);
drh1013c932008-01-06 00:25:21 +0000488 sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
danielk1977b3bce662005-01-29 08:32:43 +0000489
490 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000491 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
drh17435752007-08-16 04:30:38 +0000492 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000493 goto insert_cleanup;
494 }
danielk1977b3bce662005-01-29 08:32:43 +0000495
drh6a288a32008-01-07 19:20:24 +0000496 regFromSelect = dest.iMem;
danielk19774adee202004-05-08 08:23:19 +0000497 iCleanup = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000498 sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000499 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000500 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000501
502 /* Set useTempTable to TRUE if the result of the SELECT statement
503 ** should be written into a temporary table. Set to FALSE if each
504 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000505 **
506 ** A temp table must be used if the table being updated is also one
507 ** of the tables being read by the SELECT statement. Also use a
508 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000509 */
drh48d11782007-11-23 15:02:19 +0000510 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000511 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000512 }
drh142e30d2002-08-28 03:00:58 +0000513
514 if( useTempTable ){
515 /* Generate the subroutine that SELECT calls to process each row of
516 ** the result. Store the result in a temporary table
517 */
518 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000519 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000520 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regFromSelect, nColumn);
drh4c583122008-01-04 22:01:03 +0000521 sqlite3VdbeAddOp1(v, OP_NewRowid, srcTab);
drh66a51672008-01-03 00:01:23 +0000522 sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
danielk19771f4aa332008-01-03 09:51:55 +0000523 sqlite3CodeInsert(pParse, srcTab, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000524 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000525
526 /* The following code runs first because the GOTO at the very top
527 ** of the program jumps to it. Create the temporary table, then jump
528 ** back up and execute the SELECT code above.
529 */
drhd654be82005-09-20 17:42:23 +0000530 sqlite3VdbeJumpHere(v, iInitCode);
drh66a51672008-01-03 00:01:23 +0000531 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
532 sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
533 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000534 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000535 }else{
drhd654be82005-09-20 17:42:23 +0000536 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000537 }
drh5974a302000-06-07 14:42:26 +0000538 }else{
drh142e30d2002-08-28 03:00:58 +0000539 /* This is the case if the data for the INSERT is coming from a VALUES
540 ** clause
541 */
danielk1977b3bce662005-01-29 08:32:43 +0000542 NameContext sNC;
543 memset(&sNC, 0, sizeof(sNC));
544 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000545 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000546 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000547 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000548 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000549 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000550 goto insert_cleanup;
551 }
drhe64e7b22002-02-18 13:56:36 +0000552 }
drh5974a302000-06-07 14:42:26 +0000553 }
drh1ccde152000-06-17 13:12:39 +0000554
555 /* Make sure the number of columns in the source data matches the number
556 ** of columns to be inserted into the table.
557 */
danielk1977034ca142007-06-26 10:38:54 +0000558 if( IsVirtual(pTab) ){
559 for(i=0; i<pTab->nCol; i++){
560 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
561 }
562 }
563 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000564 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000565 "table %S has %d columns but %d values were supplied",
566 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000567 goto insert_cleanup;
568 }
drh967e8b72000-06-21 13:59:10 +0000569 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000570 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000571 goto insert_cleanup;
572 }
drh1ccde152000-06-17 13:12:39 +0000573
574 /* If the INSERT statement included an IDLIST term, then make sure
575 ** all elements of the IDLIST really are columns of the table and
576 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000577 **
578 ** If the table has an INTEGER PRIMARY KEY column and that column
579 ** is named in the IDLIST, then record in the keyColumn variable
580 ** the index into IDLIST of the primary key column. keyColumn is
581 ** the index of the primary key as it appears in IDLIST, not as
582 ** is appears in the original table. (The index of the primary
583 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000584 */
drh967e8b72000-06-21 13:59:10 +0000585 if( pColumn ){
586 for(i=0; i<pColumn->nId; i++){
587 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000588 }
drh967e8b72000-06-21 13:59:10 +0000589 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000590 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000591 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000592 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000593 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000594 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000595 }
drhcce7d172000-05-31 15:34:51 +0000596 break;
597 }
598 }
599 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000600 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000601 keyColumn = i;
602 }else{
danielk19774adee202004-05-08 08:23:19 +0000603 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000604 pTabList, 0, pColumn->a[i].zName);
605 pParse->nErr++;
606 goto insert_cleanup;
607 }
drhcce7d172000-05-31 15:34:51 +0000608 }
609 }
610 }
drh1ccde152000-06-17 13:12:39 +0000611
drhaacc5432002-01-06 17:07:40 +0000612 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000613 ** key, the set the keyColumn variable to the primary key column index
614 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000615 */
drh147d0cc2006-08-25 23:42:53 +0000616 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000617 keyColumn = pTab->iPKey;
618 }
619
drh142e30d2002-08-28 03:00:58 +0000620 /* Open the temp table for FOR EACH ROW triggers
621 */
drhdca76842004-12-07 14:06:13 +0000622 if( triggers_exist ){
drh66a51672008-01-03 00:01:23 +0000623 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
624 sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000625 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000626
drhfeeb1392002-04-09 03:28:01 +0000627 /* Initialize the count of rows to be inserted
628 */
drh142e30d2002-08-28 03:00:58 +0000629 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000630 regRowCount = ++pParse->nMem;
631 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000632 }
633
danielk1977e448dc42008-01-02 11:50:51 +0000634 /* If this is not a view, open the table and and all indices */
635 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000636 int nIdx;
637 int i;
638
drh04adf412008-01-08 18:57:50 +0000639 baseCur = pParse->nTab;
640 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drhaa9b8962008-01-08 02:57:55 +0000641 aRegIdx = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1));
642 if( aRegIdx==0 ){
643 goto insert_cleanup;
644 }
645 for(i=0; i<nIdx; i++){
646 aRegIdx[i] = ++pParse->nMem;
647 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000648 }
649
drh142e30d2002-08-28 03:00:58 +0000650 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000651 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000652 ** source is a subroutine call from the SELECT statement, then we need
653 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000654 */
drh142e30d2002-08-28 03:00:58 +0000655 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000656 iBreak = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000657 sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +0000658 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000659 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000660 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000661 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000662 sqlite3RegToStack(pParse, regFromSelect, nColumn);
drh66a51672008-01-03 00:01:23 +0000663 sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000664 }
drh1ccde152000-06-17 13:12:39 +0000665
drh6a288a32008-01-07 19:20:24 +0000666 /* Allocate registers for holding the rowid of the new row,
667 ** the content of the new row, and the assemblied row record.
668 */
669 regRecord = ++pParse->nMem;
670 regRowid = regIns = pParse->nMem+1;
671 pParse->nMem += pTab->nCol + 1;
672 if( IsVirtual(pTab) ){
673 regRowid++;
674 pParse->nMem++;
675 }
676 regData = regRowid+1;
677
drh5cf590c2003-04-24 01:45:04 +0000678 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000679 */
danielk19774adee202004-05-08 08:23:19 +0000680 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000681 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000682
drh70ce3f02003-04-15 19:22:22 +0000683 /* build the NEW.* reference row. Note that if there is an INTEGER
684 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
685 ** translated into a unique ID for the row. But on a BEFORE trigger,
686 ** we do not know what the unique ID will be (because the insert has
687 ** not happened yet) so we substitute a rowid of -1
688 */
689 if( keyColumn<0 ){
drh66a51672008-01-03 00:01:23 +0000690 sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000691 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000692 sqlite3VdbeAddOp2(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000693 }else{
drh6a288a32008-01-07 19:20:24 +0000694 int j1;
drhd6fe9612005-01-14 01:22:00 +0000695 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh389a1ad2008-01-03 23:44:53 +0000696 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drh6a288a32008-01-07 19:20:24 +0000697 sqlite3VdbeAddOp0(v, OP_SCopy);
698 j1 = sqlite3VdbeAddOp0(v, OP_NotNull);
699 sqlite3VdbeAddOp1(v, OP_Pop, 1);
700 sqlite3VdbeAddOp1(v, OP_Integer, -1);
701 sqlite3VdbeJumpHere(v, j1);
702 sqlite3VdbeAddOp0(v, OP_MustBeInt);
drh70ce3f02003-04-15 19:22:22 +0000703 }
704
danielk1977034ca142007-06-26 10:38:54 +0000705 /* Cannot have triggers on a virtual table. If it were possible,
706 ** this block would have to account for hidden column.
707 */
708 assert(!IsVirtual(pTab));
709
drh70ce3f02003-04-15 19:22:22 +0000710 /* Create the new column data
711 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000712 for(i=0; i<pTab->nCol; i++){
713 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000714 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000715 }else{
drh9adf9ac2002-05-15 11:44:13 +0000716 for(j=0; j<pColumn->nId; j++){
717 if( pColumn->a[j].idx==i ) break;
718 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000719 }
720 if( pColumn && j>=pColumn->nId ){
drh389a1ad2008-01-03 23:44:53 +0000721 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
drh142e30d2002-08-28 03:00:58 +0000722 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000723 sqlite3VdbeAddOp2(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000724 }else{
drhd6fe9612005-01-14 01:22:00 +0000725 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000726 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000727 }
728 }
drh66a51672008-01-03 00:01:23 +0000729 sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000730
731 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
732 ** do not attempt any conversions before assembling the record.
733 ** If this is a real table, attempt conversions as required by the
734 ** table column affinities.
735 */
736 if( !isView ){
737 sqlite3TableAffinityStr(v, pTab);
738 }
danielk19771f4aa332008-01-03 09:51:55 +0000739 sqlite3CodeInsert(pParse, newIdx, OPFLAG_APPEND);
danielk1977c3f9bad2002-05-15 08:30:12 +0000740
drh5cf590c2003-04-24 01:45:04 +0000741 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000742 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000743 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000744 goto insert_cleanup;
745 }
drh70ce3f02003-04-15 19:22:22 +0000746 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000747
drh4a324312001-12-21 14:30:42 +0000748 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000749 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000750 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000751 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000752 */
drh5cf590c2003-04-24 01:45:04 +0000753 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000754 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000755 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000756 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000757 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000758 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000759 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000760 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000761 }else if( pSelect ){
drh6a288a32008-01-07 19:20:24 +0000762 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn - keyColumn - 1), regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000763 }else{
drhe4d90812007-03-29 05:51:49 +0000764 VdbeOp *pOp;
drh389a1ad2008-01-03 23:44:53 +0000765 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drhe4d90812007-03-29 05:51:49 +0000766 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000767 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000768 appendFlag = 1;
769 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000770 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000771 pOp->p2 = regRowid;
772 pOp->p3 = regAutoinc;
danielk1977287fb612008-01-04 19:10:28 +0000773 }else{
774 /* TODO: Avoid this use of the stack. */
drh6a288a32008-01-07 19:20:24 +0000775 sqlite3VdbeAddOp2(v, OP_Move, 0, regRowid);
drhe4d90812007-03-29 05:51:49 +0000776 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000777 }
drhf0863fe2005-06-12 21:35:51 +0000778 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000779 ** to generate a unique primary key value.
780 */
drhe4d90812007-03-29 05:51:49 +0000781 if( !appendFlag ){
drh3c84ddf2008-01-09 02:15:38 +0000782 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, sqlite3VdbeCurrentAddr(v)+2);
danielk1977287fb612008-01-04 19:10:28 +0000783 sqlite3VdbeAddOp2(v, OP_Goto, -1, sqlite3VdbeCurrentAddr(v)+2);
drh04adf412008-01-08 18:57:50 +0000784 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drh3c84ddf2008-01-09 02:15:38 +0000785 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000786 }
drh4cbdda92006-06-14 19:00:20 +0000787 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000788 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000789 }else{
drh04adf412008-01-08 18:57:50 +0000790 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000791 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000792 }
drh6a288a32008-01-07 19:20:24 +0000793 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000794
danielk1977c3f9bad2002-05-15 08:30:12 +0000795 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000796 ** with the first column.
797 */
danielk1977034ca142007-06-26 10:38:54 +0000798 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000799 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000800 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000801 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000802 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000803 ** Whenever this column is read, the record number will be substituted
804 ** in its place. So will fill this column with a NULL to avoid
805 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000806 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000807 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000808 }
809 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000810 if( IsHiddenColumn(&pTab->aCol[i]) ){
811 assert( IsVirtual(pTab) );
812 j = -1;
813 nHidden++;
814 }else{
815 j = i - nHidden;
816 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000817 }else{
drh9adf9ac2002-05-15 11:44:13 +0000818 for(j=0; j<pColumn->nId; j++){
819 if( pColumn->a[j].idx==i ) break;
820 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000821 }
danielk1977034ca142007-06-26 10:38:54 +0000822 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000823 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000824 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000825 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000826 }else if( pSelect ){
drhb1fdb2a2008-01-05 04:06:03 +0000827 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn-j-1), iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000828 }else{
danielk1977287fb612008-01-04 19:10:28 +0000829 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000830 }
drhbed86902000-06-02 13:27:59 +0000831 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000832
833 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000834 ** do the insertion.
835 */
drh4cbdda92006-06-14 19:00:20 +0000836#ifndef SQLITE_OMIT_VIRTUALTABLE
837 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000838 pParse->pVirtualLock = pTab;
drh6a288a32008-01-07 19:20:24 +0000839 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000840 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000841 }else
842#endif
843 {
drh04adf412008-01-08 18:57:50 +0000844 sqlite3GenerateConstraintChecks(
845 pParse,
846 pTab,
847 baseCur,
848 regIns,
849 aRegIdx,
850 keyColumn>=0,
851 0,
852 onError,
853 endOfLoop
854 );
855 sqlite3CompleteInsertion(
856 pParse,
857 pTab,
858 baseCur,
859 regIns,
860 aRegIdx,
861 0,
862 0,
863 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
864 appendFlag
865 );
drh4cbdda92006-06-14 19:00:20 +0000866 }
drh5cf590c2003-04-24 01:45:04 +0000867 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000868
drh5cf590c2003-04-24 01:45:04 +0000869 /* Update the count of rows that are inserted
870 */
871 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000872 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000873 }
drh1ccde152000-06-17 13:12:39 +0000874
drhdca76842004-12-07 14:06:13 +0000875 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000876 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000877 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000878 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000879 goto insert_cleanup;
880 }
drh1bee3d72001-10-15 00:44:35 +0000881 }
882
drh1ccde152000-06-17 13:12:39 +0000883 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000884 */
danielk19774adee202004-05-08 08:23:19 +0000885 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000886 if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000887 sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
danielk19774adee202004-05-08 08:23:19 +0000888 sqlite3VdbeResolveLabel(v, iBreak);
drh66a51672008-01-03 00:01:23 +0000889 sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000890 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000891 sqlite3VdbeAddOp2(v, OP_Pop, nColumn, 0);
892 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000893 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000894 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000895
danielk1977e448dc42008-01-02 11:50:51 +0000896 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000897 /* Close all tables opened */
drh04adf412008-01-08 18:57:50 +0000898 sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000899 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh04adf412008-01-08 18:57:50 +0000900 sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000901 }
drhcce7d172000-05-31 15:34:51 +0000902 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000903
drhf3388142004-11-13 03:48:06 +0000904 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000905 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000906 ** table.
drh2958a4e2004-11-12 03:56:15 +0000907 */
drh6a288a32008-01-07 19:20:24 +0000908 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000909
drh1bee3d72001-10-15 00:44:35 +0000910 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000911 ** Return the number of rows inserted. If this routine is
912 ** generating code because of a call to sqlite3NestedParse(), do not
913 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000914 */
danielk1977cc6bd382005-01-10 02:48:49 +0000915 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +0000916 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +0000917 sqlite3VdbeSetNumCols(v, 1);
drh66a51672008-01-03 00:01:23 +0000918 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000919 }
drhcce7d172000-05-31 15:34:51 +0000920
921insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000922 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000923 sqlite3ExprListDelete(pList);
924 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000925 sqlite3IdListDelete(pColumn);
drhaa9b8962008-01-08 02:57:55 +0000926 sqlite3_free(aRegIdx);
drhcce7d172000-05-31 15:34:51 +0000927}
drh9cfcf5d2002-01-29 18:41:24 +0000928
drh9cfcf5d2002-01-29 18:41:24 +0000929/*
drh6a288a32008-01-07 19:20:24 +0000930** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +0000931**
drh04adf412008-01-08 18:57:50 +0000932** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +0000933**
drhf0863fe2005-06-12 21:35:51 +0000934** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000935** value is omitted unless we are doing an UPDATE that involves a
drh6a288a32008-01-07 19:20:24 +0000936** change to the record number. (Or writing to a virtual table.)
drh0ca3e242002-01-29 23:07:02 +0000937**
drhf0863fe2005-06-12 21:35:51 +0000938** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000939**
940** 3. The data in the first column of the entry after the update.
941**
942** i. Data from middle columns...
943**
944** N. The data in the last column of the entry after the update.
945**
drh04adf412008-01-08 18:57:50 +0000946** The regRowid parameter is the index of the register containing (2).
947**
drhf0863fe2005-06-12 21:35:51 +0000948** The old rowid shown as entry (1) above is omitted unless both isUpdate
949** and rowidChng are 1. isUpdate is true for UPDATEs and false for
950** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000951**
drhaa9b8962008-01-08 02:57:55 +0000952** The code generated by this routine store new index entries into
953** registers identified by aRegIdx[]. No index entry is created for
954** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
955** the same as the order of indices on the linked list of indices
956** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +0000957**
958** This routine also generates code to check constraints. NOT NULL,
959** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000960** then the appropriate action is performed. There are five possible
961** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000962**
963** Constraint type Action What Happens
964** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000965** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000966** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000967** return code of SQLITE_CONSTRAINT.
968**
drh1c928532002-01-31 15:54:21 +0000969** any ABORT Back out changes from the current command
970** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000971** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000972** with SQLITE_CONSTRAINT.
973**
974** any FAIL Sqlite_exec() returns immediately with a
975** return code of SQLITE_CONSTRAINT. The
976** transaction is not rolled back and any
977** prior changes are retained.
978**
drh9cfcf5d2002-01-29 18:41:24 +0000979** any IGNORE The record number and data is popped from
980** the stack and there is an immediate jump
981** to label ignoreDest.
982**
983** NOT NULL REPLACE The NULL value is replace by the default
984** value for that column. If the default value
985** is NULL, the action is the same as ABORT.
986**
987** UNIQUE REPLACE The other row that conflicts with the row
988** being inserted is removed.
989**
990** CHECK REPLACE Illegal. The results in an exception.
991**
drh1c928532002-01-31 15:54:21 +0000992** Which action to take is determined by the overrideError parameter.
993** Or if overrideError==OE_Default, then the pParse->onError parameter
994** is used. Or if pParse->onError==OE_Default then the onError value
995** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000996**
drhaaab5722002-02-19 13:39:21 +0000997** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +0000998** cursor number "baseCur". All indices of pTab must also have open
999** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001000** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001001** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001002**
drh04adf412008-01-08 18:57:50 +00001003** If the isUpdate flag is true, it means that the "baseCur" cursor is
drh9cfcf5d2002-01-29 18:41:24 +00001004** initially pointing to an entry that is being updated. The isUpdate
drh04adf412008-01-08 18:57:50 +00001005** flag causes extra code to be generated so that the "baseCur" cursor
drh9cfcf5d2002-01-29 18:41:24 +00001006** is still pointing at the same entry after the routine returns.
drh04adf412008-01-08 18:57:50 +00001007** Without the isUpdate flag, the "baseCur" cursor might be moved.
drh9cfcf5d2002-01-29 18:41:24 +00001008*/
danielk19774adee202004-05-08 08:23:19 +00001009void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001010 Parse *pParse, /* The parser context */
1011 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001012 int baseCur, /* Index of a read/write cursor pointing at pTab */
1013 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001014 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh04adf412008-01-08 18:57:50 +00001015 int rowidChng, /* True if the rowid will change */
drhb419a922002-01-30 16:17:23 +00001016 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001017 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +00001018 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +00001019){
1020 int i;
1021 Vdbe *v;
1022 int nCol;
1023 int onError;
drhaa9b8962008-01-08 02:57:55 +00001024 int j1, j2, j3; /* Address of jump instructions */
drh04adf412008-01-08 18:57:50 +00001025 int regData; /* Register containing first data column */
drh0ca3e242002-01-29 23:07:02 +00001026 int iCur;
1027 Index *pIdx;
1028 int seenReplace = 0;
drhf0863fe2005-06-12 21:35:51 +00001029 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001030
danielk19774adee202004-05-08 08:23:19 +00001031 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001032 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001033 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001034 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001035 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001036
drhaa9b8962008-01-08 02:57:55 +00001037
drh9cfcf5d2002-01-29 18:41:24 +00001038 /* Test all NOT NULL constraints.
1039 */
1040 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001041 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001042 continue;
1043 }
drh9cfcf5d2002-01-29 18:41:24 +00001044 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001045 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001046 if( overrideError!=OE_Default ){
1047 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001048 }else if( onError==OE_Default ){
1049 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001050 }
danielk19777977a172004-11-09 12:44:37 +00001051 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001052 onError = OE_Abort;
1053 }
drhaa9b8962008-01-08 02:57:55 +00001054 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
danielk1977b84f96f2005-01-20 11:32:23 +00001055 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1056 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001057 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001058 case OE_Rollback:
1059 case OE_Abort:
1060 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001061 char *zMsg = 0;
drh66a51672008-01-03 00:01:23 +00001062 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
danielk19774adee202004-05-08 08:23:19 +00001063 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001064 " may not be NULL", (char*)0);
drh66a51672008-01-03 00:01:23 +00001065 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001066 break;
1067 }
1068 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001069 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001070 break;
1071 }
1072 case OE_Replace: {
drh04adf412008-01-08 18:57:50 +00001073 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh9cfcf5d2002-01-29 18:41:24 +00001074 break;
1075 }
drh9cfcf5d2002-01-29 18:41:24 +00001076 }
drhaa9b8962008-01-08 02:57:55 +00001077 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001078 }
1079
1080 /* Test all CHECK constraints
1081 */
drhffe07b22005-11-03 00:41:17 +00001082#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001083 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001084 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001085 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001086 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001087 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001088 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001089 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001090 }else{
drh66a51672008-01-03 00:01:23 +00001091 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001092 }
drhffe07b22005-11-03 00:41:17 +00001093 sqlite3VdbeResolveLabel(v, allOk);
1094 }
1095#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001096
drh0bd1f4e2002-06-06 18:54:39 +00001097 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1098 ** of the new record does not previously exist. Except, if this
1099 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001100 */
drhf0863fe2005-06-12 21:35:51 +00001101 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001102 onError = pTab->keyConf;
1103 if( overrideError!=OE_Default ){
1104 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001105 }else if( onError==OE_Default ){
1106 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001107 }
drha0217ba2003-06-01 01:10:33 +00001108
drh5383ae52003-06-04 12:23:30 +00001109 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001110 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-1);
1111 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1112 j2 = sqlite3VdbeAddOp2(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001113 }
drh04adf412008-01-08 18:57:50 +00001114 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
drh5383ae52003-06-04 12:23:30 +00001115 switch( onError ){
1116 default: {
1117 onError = OE_Abort;
1118 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001119 }
drh5383ae52003-06-04 12:23:30 +00001120 case OE_Rollback:
1121 case OE_Abort:
1122 case OE_Fail: {
drh66a51672008-01-03 00:01:23 +00001123 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1124 "PRIMARY KEY must be unique", P4_STATIC);
drh5383ae52003-06-04 12:23:30 +00001125 break;
drh0ca3e242002-01-29 23:07:02 +00001126 }
drh5383ae52003-06-04 12:23:30 +00001127 case OE_Replace: {
drh04adf412008-01-08 18:57:50 +00001128 sqlite3GenerateRowIndexDelete(v, pTab, baseCur, 0);
drh5383ae52003-06-04 12:23:30 +00001129 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001130 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-hasTwoRowids);
drh04adf412008-01-08 18:57:50 +00001131 sqlite3VdbeAddOp2(v, OP_MoveGe, baseCur, 0);
drh5383ae52003-06-04 12:23:30 +00001132 }
1133 seenReplace = 1;
1134 break;
drh0ca3e242002-01-29 23:07:02 +00001135 }
drh5383ae52003-06-04 12:23:30 +00001136 case OE_Ignore: {
1137 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001138 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001139 break;
1140 }
1141 }
drhaa9b8962008-01-08 02:57:55 +00001142 sqlite3VdbeJumpHere(v, j3);
drh5383ae52003-06-04 12:23:30 +00001143 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001144 sqlite3VdbeJumpHere(v, j2);
1145 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-1);
drh04adf412008-01-08 18:57:50 +00001146 sqlite3VdbeAddOp2(v, OP_MoveGe, baseCur, 0);
drh0ca3e242002-01-29 23:07:02 +00001147 }
1148 }
drh0bd1f4e2002-06-06 18:54:39 +00001149
1150 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1151 ** index and making sure that duplicate entries do not already exist.
1152 ** Add the new records to the indices as we go.
1153 */
drhb2fe7d82003-04-20 17:29:23 +00001154 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drhaa9b8962008-01-08 02:57:55 +00001155 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001156
1157 /* Create a key for accessing the index entry */
drhaa9b8962008-01-08 02:57:55 +00001158 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
drh9cfcf5d2002-01-29 18:41:24 +00001159 for(i=0; i<pIdx->nColumn; i++){
1160 int idx = pIdx->aiColumn[i];
1161 if( idx==pTab->iPKey ){
drhaa9b8962008-01-08 02:57:55 +00001162 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
drh9cfcf5d2002-01-29 18:41:24 +00001163 }else{
drhaa9b8962008-01-08 02:57:55 +00001164 sqlite3VdbeAddOp1(v, OP_SCopy, regData+idx);
drh9cfcf5d2002-01-29 18:41:24 +00001165 }
1166 }
drhaa9b8962008-01-08 02:57:55 +00001167 j2 = sqlite3VdbeAddOp3(v, OP_MakeIdxRec, pIdx->nColumn, 0, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001168 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001169
1170 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001171 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001172 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001173 if( overrideError!=OE_Default ){
1174 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001175 }else if( onError==OE_Default ){
1176 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001177 }
drh5383ae52003-06-04 12:23:30 +00001178 if( seenReplace ){
1179 if( onError==OE_Ignore ) onError = OE_Replace;
1180 else if( onError==OE_Fail ) onError = OE_Abort;
1181 }
1182
drhb2fe7d82003-04-20 17:29:23 +00001183
1184 /* Check to see if the new index entry will be unique */
drhaa9b8962008-01-08 02:57:55 +00001185 sqlite3VdbeAddOp1(v, OP_SCopy, aRegIdx[iCur]);
1186 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-hasTwoRowids);
drh04adf412008-01-08 18:57:50 +00001187 j3 = sqlite3VdbeAddOp2(v, OP_IsUnique, baseCur+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001188
1189 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001190 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1191 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001192 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001193 case OE_Rollback:
1194 case OE_Abort:
1195 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001196 int j, n1, n2;
1197 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001198 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1199 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001200 n1 = strlen(zErrMsg);
1201 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1202 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1203 n2 = strlen(zCol);
1204 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001205 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001206 n1 += 2;
1207 }
1208 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001209 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001210 n1 += 3;
1211 break;
1212 }else{
drh5bb3eb92007-05-04 13:15:55 +00001213 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001214 n1 += n2;
1215 }
1216 }
drh5bb3eb92007-05-04 13:15:55 +00001217 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001218 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001219 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001220 break;
1221 }
1222 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001223 assert( seenReplace==0 );
drh04adf412008-01-08 18:57:50 +00001224 sqlite3VdbeAddOp1(v, OP_Pop, 2+hasTwoRowids);
drh66a51672008-01-03 00:01:23 +00001225 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001226 break;
1227 }
1228 case OE_Replace: {
danielk197796cb76f2008-01-04 13:24:28 +00001229 int iRowid = sqlite3StackToReg(pParse, 1);
drh04adf412008-01-08 18:57:50 +00001230 sqlite3GenerateRowDelete(pParse->db, v, pTab, baseCur, iRowid, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001231 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001232 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-hasTwoRowids);
drh04adf412008-01-08 18:57:50 +00001233 sqlite3VdbeAddOp2(v, OP_MoveGe, baseCur, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001234 }
drh0ca3e242002-01-29 23:07:02 +00001235 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001236 break;
1237 }
drh9cfcf5d2002-01-29 18:41:24 +00001238 }
drhaa9b8962008-01-08 02:57:55 +00001239 sqlite3VdbeJumpHere(v, j3);
1240 sqlite3VdbeAddOp1(v, OP_Pop, 1);
drh0bd1f4e2002-06-06 18:54:39 +00001241#if NULL_DISTINCT_FOR_UNIQUE
drhaa9b8962008-01-08 02:57:55 +00001242 sqlite3VdbeJumpHere(v, j2);
drh0bd1f4e2002-06-06 18:54:39 +00001243#endif
drh9cfcf5d2002-01-29 18:41:24 +00001244 }
1245}
drh0ca3e242002-01-29 23:07:02 +00001246
1247/*
1248** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001249** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001250** A consecutive range of registers starting at regRowid contains the
1251** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001252**
drhb419a922002-01-30 16:17:23 +00001253** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001254** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001255*/
danielk19774adee202004-05-08 08:23:19 +00001256void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001257 Parse *pParse, /* The parser context */
1258 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001259 int baseCur, /* Index of a read/write cursor pointing at pTab */
1260 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001261 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drhf0863fe2005-06-12 21:35:51 +00001262 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001263 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001264 int newIdx, /* Index of NEW table for triggers. -1 if none */
1265 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001266){
1267 int i;
1268 Vdbe *v;
1269 int nIdx;
1270 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001271 int pik_flags;
drh04adf412008-01-08 18:57:50 +00001272 int regData;
drh0ca3e242002-01-29 23:07:02 +00001273
danielk19774adee202004-05-08 08:23:19 +00001274 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001275 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001276 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001277 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1278 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001279 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001280 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
drh0ca3e242002-01-29 23:07:02 +00001281 }
drh04adf412008-01-08 18:57:50 +00001282 regData = regRowid + 1;
1283 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1284 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regData, pTab->nCol);
danielk1977a37cdde2004-05-16 11:15:36 +00001285 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001286#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001287 if( newIdx>=0 ){
drh04adf412008-01-08 18:57:50 +00001288 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1289 sqlite3VdbeAddOp1(v, OP_SCopy, -1);
danielk19771f4aa332008-01-03 09:51:55 +00001290 sqlite3CodeInsert(pParse, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001291 }
danielk1977b84f96f2005-01-20 11:32:23 +00001292#endif
drh4794f732004-11-05 17:17:50 +00001293 if( pParse->nested ){
1294 pik_flags = 0;
1295 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001296 pik_flags = OPFLAG_NCHANGE;
1297 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001298 }
drhe4d90812007-03-29 05:51:49 +00001299 if( appendBias ){
1300 pik_flags |= OPFLAG_APPEND;
1301 }
drh04adf412008-01-08 18:57:50 +00001302 sqlite3CodeInsert(pParse, baseCur, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001303 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001304 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001305 }
drh0ca3e242002-01-29 23:07:02 +00001306}
drhcd446902004-02-24 01:05:31 +00001307
1308/*
drh290c1942004-08-21 17:54:45 +00001309** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001310** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001311** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001312**
1313** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001314*/
drhaa9b8962008-01-08 02:57:55 +00001315int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001316 Parse *pParse, /* Parsing context */
1317 Table *pTab, /* Table to be opened */
drh04adf412008-01-08 18:57:50 +00001318 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001319 int op /* OP_OpenRead or OP_OpenWrite */
1320){
drhcd446902004-02-24 01:05:31 +00001321 int i;
drh4cbdda92006-06-14 19:00:20 +00001322 int iDb;
drhcd446902004-02-24 01:05:31 +00001323 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001324 Vdbe *v;
1325
drhaa9b8962008-01-08 02:57:55 +00001326 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001327 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1328 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001329 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001330 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001331 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001332 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001333 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001334 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001335 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001336 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001337 }
drh04adf412008-01-08 18:57:50 +00001338 if( pParse->nTab<=baseCur+i ){
1339 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001340 }
drhaa9b8962008-01-08 02:57:55 +00001341 return i-1;
drhcd446902004-02-24 01:05:31 +00001342}
drh9d9cf222007-02-13 15:01:11 +00001343
drh91c58e22007-03-27 12:04:04 +00001344
1345#ifdef SQLITE_TEST
1346/*
1347** The following global variable is incremented whenever the
1348** transfer optimization is used. This is used for testing
1349** purposes only - to make sure the transfer optimization really
1350** is happening when it is suppose to.
1351*/
1352int sqlite3_xferopt_count;
1353#endif /* SQLITE_TEST */
1354
1355
drh9d9cf222007-02-13 15:01:11 +00001356#ifndef SQLITE_OMIT_XFER_OPT
1357/*
1358** Check to collation names to see if they are compatible.
1359*/
1360static int xferCompatibleCollation(const char *z1, const char *z2){
1361 if( z1==0 ){
1362 return z2==0;
1363 }
1364 if( z2==0 ){
1365 return 0;
1366 }
1367 return sqlite3StrICmp(z1, z2)==0;
1368}
1369
1370
1371/*
1372** Check to see if index pSrc is compatible as a source of data
1373** for index pDest in an insert transfer optimization. The rules
1374** for a compatible index:
1375**
1376** * The index is over the same set of columns
1377** * The same DESC and ASC markings occurs on all columns
1378** * The same onError processing (OE_Abort, OE_Ignore, etc)
1379** * The same collating sequence on each column
1380*/
1381static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1382 int i;
1383 assert( pDest && pSrc );
1384 assert( pDest->pTable!=pSrc->pTable );
1385 if( pDest->nColumn!=pSrc->nColumn ){
1386 return 0; /* Different number of columns */
1387 }
1388 if( pDest->onError!=pSrc->onError ){
1389 return 0; /* Different conflict resolution strategies */
1390 }
1391 for(i=0; i<pSrc->nColumn; i++){
1392 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1393 return 0; /* Different columns indexed */
1394 }
1395 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1396 return 0; /* Different sort orders */
1397 }
1398 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1399 return 0; /* Different sort orders */
1400 }
1401 }
1402
1403 /* If no test above fails then the indices must be compatible */
1404 return 1;
1405}
1406
1407/*
1408** Attempt the transfer optimization on INSERTs of the form
1409**
1410** INSERT INTO tab1 SELECT * FROM tab2;
1411**
1412** This optimization is only attempted if
1413**
1414** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001415** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001416**
1417** (2) tab1 and tab2 are different tables
1418**
1419** (3) There must be no triggers on tab1
1420**
1421** (4) The result set of the SELECT statement is "*"
1422**
1423** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1424** or LIMIT clause.
1425**
1426** (6) The SELECT statement is a simple (not a compound) select that
1427** contains only tab2 in its FROM clause
1428**
1429** This method for implementing the INSERT transfers raw records from
1430** tab2 over to tab1. The columns are not decoded. Raw records from
1431** the indices of tab2 are transfered to tab1 as well. In so doing,
1432** the resulting tab1 has much less fragmentation.
1433**
1434** This routine returns TRUE if the optimization is attempted. If any
1435** of the conditions above fail so that the optimization should not
1436** be attempted, then this routine returns FALSE.
1437*/
1438static int xferOptimization(
1439 Parse *pParse, /* Parser context */
1440 Table *pDest, /* The table we are inserting into */
1441 Select *pSelect, /* A SELECT statement to use as the data source */
1442 int onError, /* How to handle constraint errors */
1443 int iDbDest /* The database of pDest */
1444){
1445 ExprList *pEList; /* The result set of the SELECT */
1446 Table *pSrc; /* The table in the FROM clause of SELECT */
1447 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1448 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1449 int i; /* Loop counter */
1450 int iDbSrc; /* The database of pSrc */
1451 int iSrc, iDest; /* Cursors from source and destination */
1452 int addr1, addr2; /* Loop addresses */
1453 int emptyDestTest; /* Address of test for empty pDest */
1454 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001455 Vdbe *v; /* The VDBE we are building */
1456 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001457 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001458 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001459
1460 if( pSelect==0 ){
1461 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1462 }
1463 if( pDest->pTrigger ){
1464 return 0; /* tab1 must not have triggers */
1465 }
1466#ifndef SQLITE_OMIT_VIRTUALTABLE
1467 if( pDest->isVirtual ){
1468 return 0; /* tab1 must not be a virtual table */
1469 }
1470#endif
1471 if( onError==OE_Default ){
1472 onError = OE_Abort;
1473 }
1474 if( onError!=OE_Abort && onError!=OE_Rollback ){
1475 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1476 }
danielk19775ce240a2007-09-03 17:30:06 +00001477 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001478 if( pSelect->pSrc->nSrc!=1 ){
1479 return 0; /* FROM clause must have exactly one term */
1480 }
1481 if( pSelect->pSrc->a[0].pSelect ){
1482 return 0; /* FROM clause cannot contain a subquery */
1483 }
1484 if( pSelect->pWhere ){
1485 return 0; /* SELECT may not have a WHERE clause */
1486 }
1487 if( pSelect->pOrderBy ){
1488 return 0; /* SELECT may not have an ORDER BY clause */
1489 }
drh8103b7d2007-02-24 13:23:51 +00001490 /* Do not need to test for a HAVING clause. If HAVING is present but
1491 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001492 if( pSelect->pGroupBy ){
1493 return 0; /* SELECT may not have a GROUP BY clause */
1494 }
1495 if( pSelect->pLimit ){
1496 return 0; /* SELECT may not have a LIMIT clause */
1497 }
drh8103b7d2007-02-24 13:23:51 +00001498 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001499 if( pSelect->pPrior ){
1500 return 0; /* SELECT may not be a compound query */
1501 }
1502 if( pSelect->isDistinct ){
1503 return 0; /* SELECT may not be DISTINCT */
1504 }
1505 pEList = pSelect->pEList;
1506 assert( pEList!=0 );
1507 if( pEList->nExpr!=1 ){
1508 return 0; /* The result set must have exactly one column */
1509 }
1510 assert( pEList->a[0].pExpr );
1511 if( pEList->a[0].pExpr->op!=TK_ALL ){
1512 return 0; /* The result set must be the special operator "*" */
1513 }
1514
1515 /* At this point we have established that the statement is of the
1516 ** correct syntactic form to participate in this optimization. Now
1517 ** we have to check the semantics.
1518 */
1519 pItem = pSelect->pSrc->a;
1520 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1521 if( pSrc==0 ){
1522 return 0; /* FROM clause does not contain a real table */
1523 }
1524 if( pSrc==pDest ){
1525 return 0; /* tab1 and tab2 may not be the same table */
1526 }
1527#ifndef SQLITE_OMIT_VIRTUALTABLE
1528 if( pSrc->isVirtual ){
1529 return 0; /* tab2 must not be a virtual table */
1530 }
1531#endif
1532 if( pSrc->pSelect ){
1533 return 0; /* tab2 may not be a view */
1534 }
1535 if( pDest->nCol!=pSrc->nCol ){
1536 return 0; /* Number of columns must be the same in tab1 and tab2 */
1537 }
1538 if( pDest->iPKey!=pSrc->iPKey ){
1539 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1540 }
1541 for(i=0; i<pDest->nCol; i++){
1542 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1543 return 0; /* Affinity must be the same on all columns */
1544 }
1545 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1546 return 0; /* Collating sequence must be the same on all columns */
1547 }
1548 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1549 return 0; /* tab2 must be NOT NULL if tab1 is */
1550 }
1551 }
1552 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001553 if( pDestIdx->onError!=OE_None ){
1554 destHasUniqueIdx = 1;
1555 }
drh9d9cf222007-02-13 15:01:11 +00001556 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1557 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1558 }
1559 if( pSrcIdx==0 ){
1560 return 0; /* pDestIdx has no corresponding index in pSrc */
1561 }
1562 }
drh7fc2f412007-03-29 00:08:24 +00001563#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001564 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001565 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1566 }
drh7fc2f412007-03-29 00:08:24 +00001567#endif
drh9d9cf222007-02-13 15:01:11 +00001568
1569 /* If we get this far, it means either:
1570 **
1571 ** * We can always do the transfer if the table contains an
1572 ** an integer primary key
1573 **
1574 ** * We can conditionally do the transfer if the destination
1575 ** table is empty.
1576 */
drhdd735212007-02-24 13:53:05 +00001577#ifdef SQLITE_TEST
1578 sqlite3_xferopt_count++;
1579#endif
drh9d9cf222007-02-13 15:01:11 +00001580 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1581 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001582 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001583 iSrc = pParse->nTab++;
1584 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001585 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001586 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001587 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001588 /* If tables do not have an INTEGER PRIMARY KEY and there
1589 ** are indices to be copied and the destination is not empty,
1590 ** we have to disallow the transfer optimization because the
1591 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001592 **
1593 ** Or if the destination has a UNIQUE index and is not empty,
1594 ** we also disallow the transfer optimization because we cannot
1595 ** insure that all entries in the union of DEST and SRC will be
1596 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001597 */
drh66a51672008-01-03 00:01:23 +00001598 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1599 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001600 sqlite3VdbeJumpHere(v, addr1);
1601 }else{
1602 emptyDestTest = 0;
1603 }
1604 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001605 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001606 if( pDest->iPKey>=0 ){
drh66a51672008-01-03 00:01:23 +00001607 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001608 sqlite3VdbeAddOp0(v, OP_Copy);
drh66a51672008-01-03 00:01:23 +00001609 addr2 = sqlite3VdbeAddOp2(v, OP_NotExists, iDest, 0);
1610 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1611 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001612 sqlite3VdbeJumpHere(v, addr2);
drh6a288a32008-01-07 19:20:24 +00001613 autoIncStep(pParse, regAutoinc, 0);
drhbd36ba62007-03-31 13:00:26 +00001614 }else if( pDest->pIndex==0 ){
drh4c583122008-01-04 22:01:03 +00001615 addr1 = sqlite3VdbeAddOp1(v, OP_NewRowid, iDest);
drh95bad4c2007-03-28 18:04:10 +00001616 }else{
drh66a51672008-01-03 00:01:23 +00001617 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001618 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001619 }
drh66a51672008-01-03 00:01:23 +00001620 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, 0);
danielk19771f4aa332008-01-03 09:51:55 +00001621 sqlite3CodeInsert(pParse,iDest,OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1622 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001623 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001624 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001625 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1626 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1627 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1628 }
1629 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001630 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1631 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001632 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001633 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1634 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001635 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001636 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001637 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001638 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001639 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001640 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1641 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, 0);
drhaa9b8962008-01-08 02:57:55 +00001642 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, 0, 1);
drh66a51672008-01-03 00:01:23 +00001643 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001644 sqlite3VdbeJumpHere(v, addr1);
1645 }
1646 sqlite3VdbeJumpHere(v, emptySrcTest);
drh66a51672008-01-03 00:01:23 +00001647 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1648 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001649 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001650 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001651 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001652 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001653 return 0;
1654 }else{
1655 return 1;
1656 }
1657}
1658#endif /* SQLITE_OMIT_XFER_OPT */