blob: 26f5408e6af80626ee8722bcbdd1feccafb32cc0 [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**
drh04adf412008-01-08 18:57:50 +000015** $Id: insert.c,v 1.217 2008/01/08 18:57:50 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
19/*
drh66a51672008-01-03 00:01:23 +000020** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000021** string for index pIdx. A column affinity string has one character
danielk19773d1bfea2004-05-14 11:00:53 +000022** for each column in the table, according to the affinity of the column:
23**
24** Character Column affinity
25** ------------------------------
drh3eda0402005-11-24 13:15:32 +000026** 'a' TEXT
27** 'b' NONE
28** 'c' NUMERIC
29** 'd' INTEGER
30** 'e' REAL
danielk19773d1bfea2004-05-14 11:00:53 +000031*/
danielk1977a37cdde2004-05-16 11:15:36 +000032void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
33 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000034 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000035 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000036 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000037 **
38 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000039 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000040 ** up.
41 */
42 int n;
43 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000044 sqlite3 *db = sqlite3VdbeDb(v);
drh17435752007-08-16 04:30:38 +000045 pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
danielk1977a37cdde2004-05-16 11:15:36 +000046 if( !pIdx->zColAff ){
47 return;
48 }
49 for(n=0; n<pIdx->nColumn; n++){
50 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
51 }
52 pIdx->zColAff[pIdx->nColumn] = '\0';
53 }
danielk19773d1bfea2004-05-14 11:00:53 +000054
drh66a51672008-01-03 00:01:23 +000055 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000056}
57
58/*
drh66a51672008-01-03 00:01:23 +000059** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000060** string for table pTab. A column affinity string has one character
61** for each column indexed by the index, according to the affinity of the
62** column:
63**
64** Character Column affinity
65** ------------------------------
drh3eda0402005-11-24 13:15:32 +000066** 'a' TEXT
67** 'b' NONE
68** 'c' NUMERIC
69** 'd' INTEGER
70** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000071*/
72void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000073 /* The first time a column affinity string for a particular table
74 ** is required, it is allocated and populated here. It is then
75 ** stored as a member of the Table structure for subsequent use.
76 **
77 ** The column affinity string will eventually be deleted by
78 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
79 */
80 if( !pTab->zColAff ){
81 char *zColAff;
82 int i;
drhabb6fca2007-08-16 12:24:01 +000083 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +000084
drh17435752007-08-16 04:30:38 +000085 zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000086 if( !zColAff ){
danielk1977a37cdde2004-05-16 11:15:36 +000087 return;
danielk19773d1bfea2004-05-14 11:00:53 +000088 }
89
90 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000091 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000092 }
93 zColAff[pTab->nCol] = '\0';
94
95 pTab->zColAff = zColAff;
96 }
97
drh66a51672008-01-03 00:01:23 +000098 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +000099}
100
danielk19774d887782005-02-08 08:42:27 +0000101/*
drh48d11782007-11-23 15:02:19 +0000102** Return non-zero if the table pTab in database iDb or any of its indices
103** have been opened at any point in the VDBE program beginning at location
104** iStartAddr throught the end of the program. This is used to see if
105** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
106** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000107*/
drh48d11782007-11-23 15:02:19 +0000108static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000109 int i;
drh48d11782007-11-23 15:02:19 +0000110 int iEnd = sqlite3VdbeCurrentAddr(v);
111 for(i=iStartAddr; i<iEnd; i++){
112 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000113 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000114 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
115 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000116 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000117 if( tnum==pTab->tnum ){
118 return 1;
119 }
120 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
121 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000122 return 1;
123 }
drh48d11782007-11-23 15:02:19 +0000124 }
125 }
drh543165e2007-11-27 14:46:41 +0000126#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19772dca4ac2008-01-03 11:50:29 +0000127 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
128 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000129 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000130 return 1;
danielk19774d887782005-02-08 08:42:27 +0000131 }
drh543165e2007-11-27 14:46:41 +0000132#endif
danielk19774d887782005-02-08 08:42:27 +0000133 }
134 return 0;
135}
danielk19773d1bfea2004-05-14 11:00:53 +0000136
drh9d9cf222007-02-13 15:01:11 +0000137#ifndef SQLITE_OMIT_AUTOINCREMENT
138/*
139** Write out code to initialize the autoincrement logic. This code
140** looks up the current autoincrement value in the sqlite_sequence
drh6a288a32008-01-07 19:20:24 +0000141** table and stores that value in a register. Code generated by
142** autoIncStep() will keep that register holding the largest
drh9d9cf222007-02-13 15:01:11 +0000143** rowid value. Code generated by autoIncEnd() will write the new
144** largest value of the counter back into the sqlite_sequence table.
145**
146** This routine returns the index of the mem[] cell that contains
147** the maximum rowid counter.
148**
drh6a288a32008-01-07 19:20:24 +0000149** Three consecutive registers are allocated by this routine. The
150** first two hold the name of the target table and the maximum rowid
151** inserted into the target table, respectively.
152** The third holds the rowid in sqlite_sequence where we will
153** write back the revised maximum rowid. This routine returns the
154** index of the second of these three registers.
drh9d9cf222007-02-13 15:01:11 +0000155*/
156static int autoIncBegin(
157 Parse *pParse, /* Parsing context */
158 int iDb, /* Index of the database holding pTab */
159 Table *pTab /* The table we are writing to */
160){
drh6a288a32008-01-07 19:20:24 +0000161 int memId = 0; /* Register holding maximum rowid */
drh9d9cf222007-02-13 15:01:11 +0000162 if( pTab->autoInc ){
163 Vdbe *v = pParse->pVdbe;
164 Db *pDb = &pParse->db->aDb[iDb];
165 int iCur = pParse->nTab;
drh6a288a32008-01-07 19:20:24 +0000166 int addr; /* Address of the top of the loop */
drh9d9cf222007-02-13 15:01:11 +0000167 assert( v );
drh6a288a32008-01-07 19:20:24 +0000168 pParse->nMem++; /* Holds name of table */
169 memId = ++pParse->nMem;
170 pParse->nMem++;
drh9d9cf222007-02-13 15:01:11 +0000171 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh6a288a32008-01-07 19:20:24 +0000172 addr = sqlite3VdbeCurrentAddr(v);
173 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8);
drh66a51672008-01-03 00:01:23 +0000174 sqlite3VdbeAddOp2(v, OP_Column, iCur, 0);
175 sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
drh6a288a32008-01-07 19:20:24 +0000176 sqlite3VdbeAddOp2(v, OP_Ne, 0x100, addr+7);
177 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
178 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
179 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
180 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1);
drh66a51672008-01-03 00:01:23 +0000181 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000182 }
183 return memId;
184}
185
186/*
187** Update the maximum rowid for an autoincrement calculation.
188**
189** This routine should be called when the top of the stack holds a
190** new rowid that is about to be inserted. If that new rowid is
191** larger than the maximum rowid in the memId memory cell, then the
192** memory cell is updated. The stack is unchanged.
193*/
drh6a288a32008-01-07 19:20:24 +0000194static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000195 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000196 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000197 }
198}
199
200/*
201** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000202** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000203** the sqlite_sequence table.
204*/
205static void autoIncEnd(
206 Parse *pParse, /* The parsing context */
207 int iDb, /* Index of the database holding pTab */
208 Table *pTab, /* Table we are inserting into */
209 int memId /* Memory cell holding the maximum rowid */
210){
211 if( pTab->autoInc ){
212 int iCur = pParse->nTab;
213 Vdbe *v = pParse->pVdbe;
214 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000215 int j1;
216
drh9d9cf222007-02-13 15:01:11 +0000217 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000218 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000219 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
220 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
221 sqlite3VdbeJumpHere(v, j1);
222 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
223 sqlite3VdbeAddOp3(v, OP_RegMakeRec, memId-1, 2, memId-1);
224 sqlite3VdbeAddOp3(v, OP_Insert, iCur, memId-1, memId+1);
225 sqlite3VdbeChangeP5(v, -1, OPFLAG_APPEND);
226 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000227 }
228}
229#else
230/*
231** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
232** above are all no-ops
233*/
234# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000235# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000236# define autoIncEnd(A,B,C,D)
237#endif /* SQLITE_OMIT_AUTOINCREMENT */
238
239
240/* Forward declaration */
241static int xferOptimization(
242 Parse *pParse, /* Parser context */
243 Table *pDest, /* The table we are inserting into */
244 Select *pSelect, /* A SELECT statement to use as the data source */
245 int onError, /* How to handle constraint errors */
246 int iDbDest /* The database of pDest */
247);
248
danielk19773d1bfea2004-05-14 11:00:53 +0000249/*
drh1ccde152000-06-17 13:12:39 +0000250** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000251**
252** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000253** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000254**
drh1ccde152000-06-17 13:12:39 +0000255** The IDLIST following the table name is always optional. If omitted,
256** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000257** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000258**
259** The pList parameter holds EXPRLIST in the first form of the INSERT
260** statement above, and pSelect is NULL. For the second form, pList is
261** NULL and pSelect is a pointer to the select statement used to generate
262** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000263**
drh9d9cf222007-02-13 15:01:11 +0000264** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000265** select with data coming from a VALUES clause, the code executes
266** once straight down through. The template looks like this:
267**
268** open write cursor to <table> and its indices
269** puts VALUES clause expressions onto the stack
270** write the resulting record into <table>
271** cleanup
272**
drh9d9cf222007-02-13 15:01:11 +0000273** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000274**
275** INSERT INTO <table> SELECT ...
276**
drh9d9cf222007-02-13 15:01:11 +0000277** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
278** in other words if the SELECT pulls all columns from a single table
279** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
280** if <table2> and <table1> are distinct tables but have identical
281** schemas, including all the same indices, then a special optimization
282** is invoked that copies raw records from <table2> over to <table1>.
283** See the xferOptimization() function for the implementation of this
284** template. This is the second template.
285**
286** open a write cursor to <table>
287** open read cursor on <table2>
288** transfer all records in <table2> over to <table>
289** close cursors
290** foreach index on <table>
291** open a write cursor on the <table> index
292** open a read cursor on the corresponding <table2> index
293** transfer all records from the read to the write cursors
294** close cursors
295** end foreach
296**
297** The third template is for when the second template does not apply
298** and the SELECT clause does not read from <table> at any time.
299** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000300**
301** goto B
302** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000303** loop over the rows in the SELECT
drh142e30d2002-08-28 03:00:58 +0000304** gosub C
305** end loop
306** cleanup after the SELECT
307** goto D
308** B: open write cursor to <table> and its indices
309** goto A
310** C: insert the select result into <table>
311** return
312** D: cleanup
313**
drh9d9cf222007-02-13 15:01:11 +0000314** The fourth template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000315** values from a SELECT but the data is being inserted into a table
316** that is also read as part of the SELECT. In the third form,
317** we have to use a intermediate table to store the results of
318** the select. The template is like this:
319**
320** goto B
321** A: setup for the SELECT
322** loop over the tables in the SELECT
323** gosub C
324** end loop
325** cleanup after the SELECT
326** goto D
327** C: insert the select result into the intermediate table
328** return
329** B: open a cursor to an intermediate table
330** goto A
331** D: open write cursor to <table> and its indices
332** loop over the intermediate table
333** transfer values form intermediate table into <table>
334** end the loop
335** cleanup
drhcce7d172000-05-31 15:34:51 +0000336*/
danielk19774adee202004-05-08 08:23:19 +0000337void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000338 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000339 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000340 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000341 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000342 IdList *pColumn, /* Column names corresponding to IDLIST. */
343 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000344){
drh6a288a32008-01-07 19:20:24 +0000345 sqlite3 *db; /* The main database structure */
346 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000347 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000348 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000349 int i, j, idx; /* Loop counters */
350 Vdbe *v; /* Generate code into this virtual machine */
351 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000352 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000353 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000354 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000355 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000356 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000357 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000358 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drh6a288a32008-01-07 19:20:24 +0000359 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
danielk1977cfe9a692004-06-16 12:00:29 +0000360 int iSelectLoop = 0; /* Address of code that implements the SELECT */
361 int iCleanup = 0; /* Address of the cleanup code */
362 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
drh6a288a32008-01-07 19:20:24 +0000363 int newIdx = -1; /* Cursor for the NEW pseudo-table */
364 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000365 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000366 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000367
drh6a288a32008-01-07 19:20:24 +0000368 /* Register allocations */
369 int regFromSelect; /* Base register for data coming from SELECT */
370 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
371 int regRowCount = 0; /* Memory cell used for the row counter */
372 int regIns; /* Block of regs holding rowid+data being inserted */
373 int regRowid; /* registers holding insert rowid */
374 int regData; /* register holding first column to insert */
375 int regRecord; /* Holds the assemblied row record */
drhaa9b8962008-01-08 02:57:55 +0000376 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000377
danielk1977034ca142007-06-26 10:38:54 +0000378
drh798da522004-11-04 04:42:28 +0000379#ifndef SQLITE_OMIT_TRIGGER
380 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000381 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000382#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000383
drh17435752007-08-16 04:30:38 +0000384 db = pParse->db;
385 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000386 goto insert_cleanup;
387 }
drhdaffd0e2001-04-11 14:28:42 +0000388
drh1ccde152000-06-17 13:12:39 +0000389 /* Locate the table into which we will be inserting new information.
390 */
drh113088e2003-03-20 01:16:58 +0000391 assert( pTabList->nSrc==1 );
392 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000393 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000394 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000395 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000396 goto insert_cleanup;
397 }
danielk1977da184232006-01-05 11:34:32 +0000398 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
399 assert( iDb<db->nDb );
400 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000401 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000402 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000403 goto insert_cleanup;
404 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000405
drhb7f91642004-10-31 02:22:47 +0000406 /* Figure out if we have any triggers and if the table being
407 ** inserted into is a view
408 */
409#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000410 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000411 isView = pTab->pSelect!=0;
412#else
drhdca76842004-12-07 14:06:13 +0000413# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000414# define isView 0
415#endif
416#ifdef SQLITE_OMIT_VIEW
417# undef isView
418# define isView 0
419#endif
420
danielk1977c3f9bad2002-05-15 08:30:12 +0000421 /* Ensure that:
422 * (a) the table is not read-only,
423 * (b) that if it is a view then ON INSERT triggers exist
424 */
drhdca76842004-12-07 14:06:13 +0000425 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000426 goto insert_cleanup;
427 }
drh43617e92006-03-06 20:55:46 +0000428 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000429
drhf573c992002-07-31 00:32:50 +0000430 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000431 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
432 ** module table).
drhf573c992002-07-31 00:32:50 +0000433 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000434 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000435 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000436 }
437
drh1ccde152000-06-17 13:12:39 +0000438 /* Allocate a VDBE
439 */
danielk19774adee202004-05-08 08:23:19 +0000440 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000441 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000442 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000443 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000444
danielk1977c3f9bad2002-05-15 08:30:12 +0000445 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000446 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000447 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000448 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000449
drh9d9cf222007-02-13 15:01:11 +0000450#ifndef SQLITE_OMIT_XFER_OPT
451 /* If the statement is of the form
452 **
453 ** INSERT INTO <table1> SELECT * FROM <table2>;
454 **
455 ** Then special optimizations can be applied that make the transfer
456 ** very fast and which reduce fragmentation of indices.
457 */
458 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
459 assert( !triggers_exist );
460 assert( pList==0 );
461 goto insert_cleanup;
462 }
463#endif /* SQLITE_OMIT_XFER_OPT */
464
drh2958a4e2004-11-12 03:56:15 +0000465 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000466 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000467 */
drh6a288a32008-01-07 19:20:24 +0000468 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000469
drh1ccde152000-06-17 13:12:39 +0000470 /* Figure out how many columns of data are supplied. If the data
drh142e30d2002-08-28 03:00:58 +0000471 ** is coming from a SELECT statement, then this step also generates
472 ** all the code to implement the SELECT statement and invoke a subroutine
473 ** to process each row of the result. (Template 2.) If the SELECT
474 ** statement uses the the table that is being inserted into, then the
475 ** subroutine is also coded here. That subroutine stores the SELECT
476 ** results in a temporary table. (Template 3.)
drh1ccde152000-06-17 13:12:39 +0000477 */
drh5974a302000-06-07 14:42:26 +0000478 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000479 /* Data is coming from a SELECT. Generate code to implement that SELECT
480 */
drh1013c932008-01-06 00:25:21 +0000481 SelectDest dest;
drh142e30d2002-08-28 03:00:58 +0000482 int rc, iInitCode;
drh1013c932008-01-06 00:25:21 +0000483
drh66a51672008-01-03 00:01:23 +0000484 iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000485 iSelectLoop = sqlite3VdbeCurrentAddr(v);
486 iInsertBlock = sqlite3VdbeMakeLabel(v);
drh1013c932008-01-06 00:25:21 +0000487 sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
danielk1977b3bce662005-01-29 08:32:43 +0000488
489 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000490 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
drh17435752007-08-16 04:30:38 +0000491 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000492 goto insert_cleanup;
493 }
danielk1977b3bce662005-01-29 08:32:43 +0000494
drh6a288a32008-01-07 19:20:24 +0000495 regFromSelect = dest.iMem;
danielk19774adee202004-05-08 08:23:19 +0000496 iCleanup = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000497 sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
drh5974a302000-06-07 14:42:26 +0000498 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000499 nColumn = pSelect->pEList->nExpr;
drh142e30d2002-08-28 03:00:58 +0000500
501 /* Set useTempTable to TRUE if the result of the SELECT statement
502 ** should be written into a temporary table. Set to FALSE if each
503 ** row of the SELECT can be written directly into the result table.
drh048c5302003-04-03 01:50:44 +0000504 **
505 ** A temp table must be used if the table being updated is also one
506 ** of the tables being read by the SELECT statement. Also use a
507 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000508 */
drh48d11782007-11-23 15:02:19 +0000509 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000510 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000511 }
drh142e30d2002-08-28 03:00:58 +0000512
513 if( useTempTable ){
514 /* Generate the subroutine that SELECT calls to process each row of
515 ** the result. Store the result in a temporary table
516 */
517 srcTab = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +0000518 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000519 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regFromSelect, nColumn);
drh4c583122008-01-04 22:01:03 +0000520 sqlite3VdbeAddOp1(v, OP_NewRowid, srcTab);
drh66a51672008-01-03 00:01:23 +0000521 sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
danielk19771f4aa332008-01-03 09:51:55 +0000522 sqlite3CodeInsert(pParse, srcTab, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000523 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
drh142e30d2002-08-28 03:00:58 +0000524
525 /* The following code runs first because the GOTO at the very top
526 ** of the program jumps to it. Create the temporary table, then jump
527 ** back up and execute the SELECT code above.
528 */
drhd654be82005-09-20 17:42:23 +0000529 sqlite3VdbeJumpHere(v, iInitCode);
drh66a51672008-01-03 00:01:23 +0000530 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
531 sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
532 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000533 sqlite3VdbeResolveLabel(v, iCleanup);
drh142e30d2002-08-28 03:00:58 +0000534 }else{
drhd654be82005-09-20 17:42:23 +0000535 sqlite3VdbeJumpHere(v, iInitCode);
drh142e30d2002-08-28 03:00:58 +0000536 }
drh5974a302000-06-07 14:42:26 +0000537 }else{
drh142e30d2002-08-28 03:00:58 +0000538 /* This is the case if the data for the INSERT is coming from a VALUES
539 ** clause
540 */
danielk1977b3bce662005-01-29 08:32:43 +0000541 NameContext sNC;
542 memset(&sNC, 0, sizeof(sNC));
543 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000544 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000545 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000546 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000547 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000548 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000549 goto insert_cleanup;
550 }
drhe64e7b22002-02-18 13:56:36 +0000551 }
drh5974a302000-06-07 14:42:26 +0000552 }
drh1ccde152000-06-17 13:12:39 +0000553
554 /* Make sure the number of columns in the source data matches the number
555 ** of columns to be inserted into the table.
556 */
danielk1977034ca142007-06-26 10:38:54 +0000557 if( IsVirtual(pTab) ){
558 for(i=0; i<pTab->nCol; i++){
559 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
560 }
561 }
562 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000563 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000564 "table %S has %d columns but %d values were supplied",
565 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000566 goto insert_cleanup;
567 }
drh967e8b72000-06-21 13:59:10 +0000568 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000569 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000570 goto insert_cleanup;
571 }
drh1ccde152000-06-17 13:12:39 +0000572
573 /* If the INSERT statement included an IDLIST term, then make sure
574 ** all elements of the IDLIST really are columns of the table and
575 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000576 **
577 ** If the table has an INTEGER PRIMARY KEY column and that column
578 ** is named in the IDLIST, then record in the keyColumn variable
579 ** the index into IDLIST of the primary key column. keyColumn is
580 ** the index of the primary key as it appears in IDLIST, not as
581 ** is appears in the original table. (The index of the primary
582 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000583 */
drh967e8b72000-06-21 13:59:10 +0000584 if( pColumn ){
585 for(i=0; i<pColumn->nId; i++){
586 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000587 }
drh967e8b72000-06-21 13:59:10 +0000588 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000589 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000590 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000591 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000592 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000593 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000594 }
drhcce7d172000-05-31 15:34:51 +0000595 break;
596 }
597 }
598 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000599 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000600 keyColumn = i;
601 }else{
danielk19774adee202004-05-08 08:23:19 +0000602 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000603 pTabList, 0, pColumn->a[i].zName);
604 pParse->nErr++;
605 goto insert_cleanup;
606 }
drhcce7d172000-05-31 15:34:51 +0000607 }
608 }
609 }
drh1ccde152000-06-17 13:12:39 +0000610
drhaacc5432002-01-06 17:07:40 +0000611 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000612 ** key, the set the keyColumn variable to the primary key column index
613 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000614 */
drh147d0cc2006-08-25 23:42:53 +0000615 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000616 keyColumn = pTab->iPKey;
617 }
618
drh142e30d2002-08-28 03:00:58 +0000619 /* Open the temp table for FOR EACH ROW triggers
620 */
drhdca76842004-12-07 14:06:13 +0000621 if( triggers_exist ){
drh66a51672008-01-03 00:01:23 +0000622 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
623 sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000624 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000625
drhfeeb1392002-04-09 03:28:01 +0000626 /* Initialize the count of rows to be inserted
627 */
drh142e30d2002-08-28 03:00:58 +0000628 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000629 regRowCount = ++pParse->nMem;
630 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000631 }
632
danielk1977e448dc42008-01-02 11:50:51 +0000633 /* If this is not a view, open the table and and all indices */
634 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000635 int nIdx;
636 int i;
637
drh04adf412008-01-08 18:57:50 +0000638 baseCur = pParse->nTab;
639 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drhaa9b8962008-01-08 02:57:55 +0000640 aRegIdx = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1));
641 if( aRegIdx==0 ){
642 goto insert_cleanup;
643 }
644 for(i=0; i<nIdx; i++){
645 aRegIdx[i] = ++pParse->nMem;
646 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000647 }
648
drh142e30d2002-08-28 03:00:58 +0000649 /* If the data source is a temporary table, then we have to create
drh1ccde152000-06-17 13:12:39 +0000650 ** a loop because there might be multiple rows of data. If the data
drh142e30d2002-08-28 03:00:58 +0000651 ** source is a subroutine call from the SELECT statement, then we need
652 ** to launch the SELECT statement processing.
drh1ccde152000-06-17 13:12:39 +0000653 */
drh142e30d2002-08-28 03:00:58 +0000654 if( useTempTable ){
danielk19774adee202004-05-08 08:23:19 +0000655 iBreak = sqlite3VdbeMakeLabel(v);
drh66a51672008-01-03 00:01:23 +0000656 sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +0000657 iCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000658 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000659 sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
danielk19774adee202004-05-08 08:23:19 +0000660 sqlite3VdbeResolveLabel(v, iInsertBlock);
drh6a288a32008-01-07 19:20:24 +0000661 sqlite3RegToStack(pParse, regFromSelect, nColumn);
drh66a51672008-01-03 00:01:23 +0000662 sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
drh5974a302000-06-07 14:42:26 +0000663 }
drh1ccde152000-06-17 13:12:39 +0000664
drh6a288a32008-01-07 19:20:24 +0000665 /* Allocate registers for holding the rowid of the new row,
666 ** the content of the new row, and the assemblied row record.
667 */
668 regRecord = ++pParse->nMem;
669 regRowid = regIns = pParse->nMem+1;
670 pParse->nMem += pTab->nCol + 1;
671 if( IsVirtual(pTab) ){
672 regRowid++;
673 pParse->nMem++;
674 }
675 regData = regRowid+1;
676
drh5cf590c2003-04-24 01:45:04 +0000677 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000678 */
danielk19774adee202004-05-08 08:23:19 +0000679 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000680 if( triggers_exist & TRIGGER_BEFORE ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000681
drh70ce3f02003-04-15 19:22:22 +0000682 /* build the NEW.* reference row. Note that if there is an INTEGER
683 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
684 ** translated into a unique ID for the row. But on a BEFORE trigger,
685 ** we do not know what the unique ID will be (because the insert has
686 ** not happened yet) so we substitute a rowid of -1
687 */
688 if( keyColumn<0 ){
drh66a51672008-01-03 00:01:23 +0000689 sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
drh70ce3f02003-04-15 19:22:22 +0000690 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000691 sqlite3VdbeAddOp2(v, OP_Column, srcTab, keyColumn);
drh70ce3f02003-04-15 19:22:22 +0000692 }else{
drh6a288a32008-01-07 19:20:24 +0000693 int j1;
drhd6fe9612005-01-14 01:22:00 +0000694 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh389a1ad2008-01-03 23:44:53 +0000695 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drh6a288a32008-01-07 19:20:24 +0000696 sqlite3VdbeAddOp0(v, OP_SCopy);
697 j1 = sqlite3VdbeAddOp0(v, OP_NotNull);
698 sqlite3VdbeAddOp1(v, OP_Pop, 1);
699 sqlite3VdbeAddOp1(v, OP_Integer, -1);
700 sqlite3VdbeJumpHere(v, j1);
701 sqlite3VdbeAddOp0(v, OP_MustBeInt);
drh70ce3f02003-04-15 19:22:22 +0000702 }
703
danielk1977034ca142007-06-26 10:38:54 +0000704 /* Cannot have triggers on a virtual table. If it were possible,
705 ** this block would have to account for hidden column.
706 */
707 assert(!IsVirtual(pTab));
708
drh70ce3f02003-04-15 19:22:22 +0000709 /* Create the new column data
710 */
danielk1977c3f9bad2002-05-15 08:30:12 +0000711 for(i=0; i<pTab->nCol; i++){
712 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000713 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000714 }else{
drh9adf9ac2002-05-15 11:44:13 +0000715 for(j=0; j<pColumn->nId; j++){
716 if( pColumn->a[j].idx==i ) break;
717 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000718 }
719 if( pColumn && j>=pColumn->nId ){
drh389a1ad2008-01-03 23:44:53 +0000720 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
drh142e30d2002-08-28 03:00:58 +0000721 }else if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000722 sqlite3VdbeAddOp2(v, OP_Column, srcTab, j);
danielk1977c3f9bad2002-05-15 08:30:12 +0000723 }else{
drhd6fe9612005-01-14 01:22:00 +0000724 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh25303782004-12-07 15:41:48 +0000725 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
danielk1977c3f9bad2002-05-15 08:30:12 +0000726 }
727 }
drh66a51672008-01-03 00:01:23 +0000728 sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
danielk1977a37cdde2004-05-16 11:15:36 +0000729
730 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
731 ** do not attempt any conversions before assembling the record.
732 ** If this is a real table, attempt conversions as required by the
733 ** table column affinities.
734 */
735 if( !isView ){
736 sqlite3TableAffinityStr(v, pTab);
737 }
danielk19771f4aa332008-01-03 09:51:55 +0000738 sqlite3CodeInsert(pParse, newIdx, OPFLAG_APPEND);
danielk1977c3f9bad2002-05-15 08:30:12 +0000739
drh5cf590c2003-04-24 01:45:04 +0000740 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000741 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000742 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000743 goto insert_cleanup;
744 }
drh70ce3f02003-04-15 19:22:22 +0000745 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000746
drh4a324312001-12-21 14:30:42 +0000747 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000748 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000749 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000750 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000751 */
drh5cf590c2003-04-24 01:45:04 +0000752 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000753 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000754 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000755 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000756 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000757 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000758 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000759 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000760 }else if( pSelect ){
drh6a288a32008-01-07 19:20:24 +0000761 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn - keyColumn - 1), regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000762 }else{
drhe4d90812007-03-29 05:51:49 +0000763 VdbeOp *pOp;
drh389a1ad2008-01-03 23:44:53 +0000764 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
drhe4d90812007-03-29 05:51:49 +0000765 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk197701256832007-04-18 14:24:32 +0000766 if( pOp && pOp->opcode==OP_Null ){
drhe4d90812007-03-29 05:51:49 +0000767 appendFlag = 1;
768 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000769 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000770 pOp->p2 = regRowid;
771 pOp->p3 = regAutoinc;
danielk1977287fb612008-01-04 19:10:28 +0000772 }else{
773 /* TODO: Avoid this use of the stack. */
drh6a288a32008-01-07 19:20:24 +0000774 sqlite3VdbeAddOp2(v, OP_Move, 0, regRowid);
drhe4d90812007-03-29 05:51:49 +0000775 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000776 }
drhf0863fe2005-06-12 21:35:51 +0000777 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000778 ** to generate a unique primary key value.
779 */
drhe4d90812007-03-29 05:51:49 +0000780 if( !appendFlag ){
drh6a288a32008-01-07 19:20:24 +0000781 sqlite3VdbeAddOp2(v, OP_IfMemNull, regRowid, sqlite3VdbeCurrentAddr(v)+2);
danielk1977287fb612008-01-04 19:10:28 +0000782 sqlite3VdbeAddOp2(v, OP_Goto, -1, sqlite3VdbeCurrentAddr(v)+2);
drh04adf412008-01-08 18:57:50 +0000783 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drh6a288a32008-01-07 19:20:24 +0000784 sqlite3VdbeAddOp3(v, OP_MustBeInt, 0, 0, regRowid);
drhe4d90812007-03-29 05:51:49 +0000785 }
drh4cbdda92006-06-14 19:00:20 +0000786 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000787 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000788 }else{
drh04adf412008-01-08 18:57:50 +0000789 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000790 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000791 }
drh6a288a32008-01-07 19:20:24 +0000792 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000793
danielk1977c3f9bad2002-05-15 08:30:12 +0000794 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000795 ** with the first column.
796 */
danielk1977034ca142007-06-26 10:38:54 +0000797 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000798 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000799 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000800 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000801 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000802 ** Whenever this column is read, the record number will be substituted
803 ** in its place. So will fill this column with a NULL to avoid
804 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000805 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000806 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000807 }
808 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000809 if( IsHiddenColumn(&pTab->aCol[i]) ){
810 assert( IsVirtual(pTab) );
811 j = -1;
812 nHidden++;
813 }else{
814 j = i - nHidden;
815 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000816 }else{
drh9adf9ac2002-05-15 11:44:13 +0000817 for(j=0; j<pColumn->nId; j++){
818 if( pColumn->a[j].idx==i ) break;
819 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000820 }
danielk1977034ca142007-06-26 10:38:54 +0000821 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000822 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000823 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000824 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000825 }else if( pSelect ){
drhb1fdb2a2008-01-05 04:06:03 +0000826 sqlite3VdbeAddOp2(v, OP_SCopy, -(nColumn-j-1), iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000827 }else{
danielk1977287fb612008-01-04 19:10:28 +0000828 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000829 }
drhbed86902000-06-02 13:27:59 +0000830 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000831
832 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000833 ** do the insertion.
834 */
drh4cbdda92006-06-14 19:00:20 +0000835#ifndef SQLITE_OMIT_VIRTUALTABLE
836 if( IsVirtual(pTab) ){
danielk1977f9e7dda2006-06-16 16:08:53 +0000837 pParse->pVirtualLock = pTab;
drh6a288a32008-01-07 19:20:24 +0000838 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000839 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000840 }else
841#endif
842 {
drh04adf412008-01-08 18:57:50 +0000843 sqlite3GenerateConstraintChecks(
844 pParse,
845 pTab,
846 baseCur,
847 regIns,
848 aRegIdx,
849 keyColumn>=0,
850 0,
851 onError,
852 endOfLoop
853 );
854 sqlite3CompleteInsertion(
855 pParse,
856 pTab,
857 baseCur,
858 regIns,
859 aRegIdx,
860 0,
861 0,
862 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
863 appendFlag
864 );
drh4cbdda92006-06-14 19:00:20 +0000865 }
drh5cf590c2003-04-24 01:45:04 +0000866 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000867
drh5cf590c2003-04-24 01:45:04 +0000868 /* Update the count of rows that are inserted
869 */
870 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000871 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000872 }
drh1ccde152000-06-17 13:12:39 +0000873
drhdca76842004-12-07 14:06:13 +0000874 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000875 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000876 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000877 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000878 goto insert_cleanup;
879 }
drh1bee3d72001-10-15 00:44:35 +0000880 }
881
drh1ccde152000-06-17 13:12:39 +0000882 /* The bottom of the loop, if the data source is a SELECT statement
danielk1977f29ce552002-05-19 23:43:12 +0000883 */
danielk19774adee202004-05-08 08:23:19 +0000884 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000885 if( useTempTable ){
drh66a51672008-01-03 00:01:23 +0000886 sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
danielk19774adee202004-05-08 08:23:19 +0000887 sqlite3VdbeResolveLabel(v, iBreak);
drh66a51672008-01-03 00:01:23 +0000888 sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
drh142e30d2002-08-28 03:00:58 +0000889 }else if( pSelect ){
drh66a51672008-01-03 00:01:23 +0000890 sqlite3VdbeAddOp2(v, OP_Pop, nColumn, 0);
891 sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000892 sqlite3VdbeResolveLabel(v, iCleanup);
drh6b563442001-11-07 16:48:26 +0000893 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000894
danielk1977e448dc42008-01-02 11:50:51 +0000895 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000896 /* Close all tables opened */
drh04adf412008-01-08 18:57:50 +0000897 sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000898 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh04adf412008-01-08 18:57:50 +0000899 sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000900 }
drhcce7d172000-05-31 15:34:51 +0000901 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000902
drhf3388142004-11-13 03:48:06 +0000903 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000904 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000905 ** table.
drh2958a4e2004-11-12 03:56:15 +0000906 */
drh6a288a32008-01-07 19:20:24 +0000907 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000908
drh1bee3d72001-10-15 00:44:35 +0000909 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000910 ** Return the number of rows inserted. If this routine is
911 ** generating code because of a call to sqlite3NestedParse(), do not
912 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000913 */
danielk1977cc6bd382005-01-10 02:48:49 +0000914 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +0000915 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +0000916 sqlite3VdbeSetNumCols(v, 1);
drh66a51672008-01-03 00:01:23 +0000917 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000918 }
drhcce7d172000-05-31 15:34:51 +0000919
920insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000921 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000922 sqlite3ExprListDelete(pList);
923 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +0000924 sqlite3IdListDelete(pColumn);
drhaa9b8962008-01-08 02:57:55 +0000925 sqlite3_free(aRegIdx);
drhcce7d172000-05-31 15:34:51 +0000926}
drh9cfcf5d2002-01-29 18:41:24 +0000927
drh9cfcf5d2002-01-29 18:41:24 +0000928/*
drh6a288a32008-01-07 19:20:24 +0000929** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +0000930**
drh04adf412008-01-08 18:57:50 +0000931** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +0000932**
drhf0863fe2005-06-12 21:35:51 +0000933** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +0000934** value is omitted unless we are doing an UPDATE that involves a
drh6a288a32008-01-07 19:20:24 +0000935** change to the record number. (Or writing to a virtual table.)
drh0ca3e242002-01-29 23:07:02 +0000936**
drhf0863fe2005-06-12 21:35:51 +0000937** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +0000938**
939** 3. The data in the first column of the entry after the update.
940**
941** i. Data from middle columns...
942**
943** N. The data in the last column of the entry after the update.
944**
drh04adf412008-01-08 18:57:50 +0000945** The regRowid parameter is the index of the register containing (2).
946**
drhf0863fe2005-06-12 21:35:51 +0000947** The old rowid shown as entry (1) above is omitted unless both isUpdate
948** and rowidChng are 1. isUpdate is true for UPDATEs and false for
949** INSERTs and rowidChng is true if the record number is being changed.
drh0ca3e242002-01-29 23:07:02 +0000950**
drhaa9b8962008-01-08 02:57:55 +0000951** The code generated by this routine store new index entries into
952** registers identified by aRegIdx[]. No index entry is created for
953** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
954** the same as the order of indices on the linked list of indices
955** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +0000956**
957** This routine also generates code to check constraints. NOT NULL,
958** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +0000959** then the appropriate action is performed. There are five possible
960** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +0000961**
962** Constraint type Action What Happens
963** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +0000964** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +0000965** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +0000966** return code of SQLITE_CONSTRAINT.
967**
drh1c928532002-01-31 15:54:21 +0000968** any ABORT Back out changes from the current command
969** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +0000970** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +0000971** with SQLITE_CONSTRAINT.
972**
973** any FAIL Sqlite_exec() returns immediately with a
974** return code of SQLITE_CONSTRAINT. The
975** transaction is not rolled back and any
976** prior changes are retained.
977**
drh9cfcf5d2002-01-29 18:41:24 +0000978** any IGNORE The record number and data is popped from
979** the stack and there is an immediate jump
980** to label ignoreDest.
981**
982** NOT NULL REPLACE The NULL value is replace by the default
983** value for that column. If the default value
984** is NULL, the action is the same as ABORT.
985**
986** UNIQUE REPLACE The other row that conflicts with the row
987** being inserted is removed.
988**
989** CHECK REPLACE Illegal. The results in an exception.
990**
drh1c928532002-01-31 15:54:21 +0000991** Which action to take is determined by the overrideError parameter.
992** Or if overrideError==OE_Default, then the pParse->onError parameter
993** is used. Or if pParse->onError==OE_Default then the onError value
994** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +0000995**
drhaaab5722002-02-19 13:39:21 +0000996** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +0000997** cursor number "baseCur". All indices of pTab must also have open
998** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +0000999** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001000** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001001**
drh04adf412008-01-08 18:57:50 +00001002** If the isUpdate flag is true, it means that the "baseCur" cursor is
drh9cfcf5d2002-01-29 18:41:24 +00001003** initially pointing to an entry that is being updated. The isUpdate
drh04adf412008-01-08 18:57:50 +00001004** flag causes extra code to be generated so that the "baseCur" cursor
drh9cfcf5d2002-01-29 18:41:24 +00001005** is still pointing at the same entry after the routine returns.
drh04adf412008-01-08 18:57:50 +00001006** Without the isUpdate flag, the "baseCur" cursor might be moved.
drh9cfcf5d2002-01-29 18:41:24 +00001007*/
danielk19774adee202004-05-08 08:23:19 +00001008void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001009 Parse *pParse, /* The parser context */
1010 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001011 int baseCur, /* Index of a read/write cursor pointing at pTab */
1012 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001013 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh04adf412008-01-08 18:57:50 +00001014 int rowidChng, /* True if the rowid will change */
drhb419a922002-01-30 16:17:23 +00001015 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001016 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +00001017 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +00001018){
1019 int i;
1020 Vdbe *v;
1021 int nCol;
1022 int onError;
drhaa9b8962008-01-08 02:57:55 +00001023 int j1, j2, j3; /* Address of jump instructions */
drh04adf412008-01-08 18:57:50 +00001024 int regData; /* Register containing first data column */
drh0ca3e242002-01-29 23:07:02 +00001025 int iCur;
1026 Index *pIdx;
1027 int seenReplace = 0;
drhf0863fe2005-06-12 21:35:51 +00001028 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001029
danielk19774adee202004-05-08 08:23:19 +00001030 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001031 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001032 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001033 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001034 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001035
drhaa9b8962008-01-08 02:57:55 +00001036
drh9cfcf5d2002-01-29 18:41:24 +00001037 /* Test all NOT NULL constraints.
1038 */
1039 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001040 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001041 continue;
1042 }
drh9cfcf5d2002-01-29 18:41:24 +00001043 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001044 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001045 if( overrideError!=OE_Default ){
1046 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001047 }else if( onError==OE_Default ){
1048 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001049 }
danielk19777977a172004-11-09 12:44:37 +00001050 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001051 onError = OE_Abort;
1052 }
drhaa9b8962008-01-08 02:57:55 +00001053 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
danielk1977b84f96f2005-01-20 11:32:23 +00001054 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1055 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001056 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001057 case OE_Rollback:
1058 case OE_Abort:
1059 case OE_Fail: {
drh483750b2003-01-29 18:46:51 +00001060 char *zMsg = 0;
drh66a51672008-01-03 00:01:23 +00001061 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
danielk19774adee202004-05-08 08:23:19 +00001062 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
drh41743982003-12-06 21:43:55 +00001063 " may not be NULL", (char*)0);
drh66a51672008-01-03 00:01:23 +00001064 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001065 break;
1066 }
1067 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001068 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001069 break;
1070 }
1071 case OE_Replace: {
drh04adf412008-01-08 18:57:50 +00001072 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh9cfcf5d2002-01-29 18:41:24 +00001073 break;
1074 }
drh9cfcf5d2002-01-29 18:41:24 +00001075 }
drhaa9b8962008-01-08 02:57:55 +00001076 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001077 }
1078
1079 /* Test all CHECK constraints
1080 */
drhffe07b22005-11-03 00:41:17 +00001081#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001082 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001083 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001084 pParse->ckBase = regData;
drh6275b882005-11-03 01:22:30 +00001085 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
drhaa01c7e2006-03-15 16:26:10 +00001086 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001087 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001088 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001089 }else{
drh66a51672008-01-03 00:01:23 +00001090 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001091 }
drhffe07b22005-11-03 00:41:17 +00001092 sqlite3VdbeResolveLabel(v, allOk);
1093 }
1094#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001095
drh0bd1f4e2002-06-06 18:54:39 +00001096 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1097 ** of the new record does not previously exist. Except, if this
1098 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001099 */
drhf0863fe2005-06-12 21:35:51 +00001100 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001101 onError = pTab->keyConf;
1102 if( overrideError!=OE_Default ){
1103 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001104 }else if( onError==OE_Default ){
1105 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001106 }
drha0217ba2003-06-01 01:10:33 +00001107
drh5383ae52003-06-04 12:23:30 +00001108 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001109 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-1);
1110 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1111 j2 = sqlite3VdbeAddOp2(v, OP_Eq, 0, 0);
drh5383ae52003-06-04 12:23:30 +00001112 }
drh04adf412008-01-08 18:57:50 +00001113 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
drh5383ae52003-06-04 12:23:30 +00001114 switch( onError ){
1115 default: {
1116 onError = OE_Abort;
1117 /* Fall thru into the next case */
drh79b0c952002-05-21 12:56:43 +00001118 }
drh5383ae52003-06-04 12:23:30 +00001119 case OE_Rollback:
1120 case OE_Abort:
1121 case OE_Fail: {
drh66a51672008-01-03 00:01:23 +00001122 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1123 "PRIMARY KEY must be unique", P4_STATIC);
drh5383ae52003-06-04 12:23:30 +00001124 break;
drh0ca3e242002-01-29 23:07:02 +00001125 }
drh5383ae52003-06-04 12:23:30 +00001126 case OE_Replace: {
drh04adf412008-01-08 18:57:50 +00001127 sqlite3GenerateRowIndexDelete(v, pTab, baseCur, 0);
drh5383ae52003-06-04 12:23:30 +00001128 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001129 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-hasTwoRowids);
drh04adf412008-01-08 18:57:50 +00001130 sqlite3VdbeAddOp2(v, OP_MoveGe, baseCur, 0);
drh5383ae52003-06-04 12:23:30 +00001131 }
1132 seenReplace = 1;
1133 break;
drh0ca3e242002-01-29 23:07:02 +00001134 }
drh5383ae52003-06-04 12:23:30 +00001135 case OE_Ignore: {
1136 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001137 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh5383ae52003-06-04 12:23:30 +00001138 break;
1139 }
1140 }
drhaa9b8962008-01-08 02:57:55 +00001141 sqlite3VdbeJumpHere(v, j3);
drh5383ae52003-06-04 12:23:30 +00001142 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001143 sqlite3VdbeJumpHere(v, j2);
1144 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-1);
drh04adf412008-01-08 18:57:50 +00001145 sqlite3VdbeAddOp2(v, OP_MoveGe, baseCur, 0);
drh0ca3e242002-01-29 23:07:02 +00001146 }
1147 }
drh0bd1f4e2002-06-06 18:54:39 +00001148
1149 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1150 ** index and making sure that duplicate entries do not already exist.
1151 ** Add the new records to the indices as we go.
1152 */
drhb2fe7d82003-04-20 17:29:23 +00001153 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drhaa9b8962008-01-08 02:57:55 +00001154 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001155
1156 /* Create a key for accessing the index entry */
drhaa9b8962008-01-08 02:57:55 +00001157 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
drh9cfcf5d2002-01-29 18:41:24 +00001158 for(i=0; i<pIdx->nColumn; i++){
1159 int idx = pIdx->aiColumn[i];
1160 if( idx==pTab->iPKey ){
drhaa9b8962008-01-08 02:57:55 +00001161 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
drh9cfcf5d2002-01-29 18:41:24 +00001162 }else{
drhaa9b8962008-01-08 02:57:55 +00001163 sqlite3VdbeAddOp1(v, OP_SCopy, regData+idx);
drh9cfcf5d2002-01-29 18:41:24 +00001164 }
1165 }
drhaa9b8962008-01-08 02:57:55 +00001166 j2 = sqlite3VdbeAddOp3(v, OP_MakeIdxRec, pIdx->nColumn, 0, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001167 sqlite3IndexAffinityStr(v, pIdx);
drhb2fe7d82003-04-20 17:29:23 +00001168
1169 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001170 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001171 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001172 if( overrideError!=OE_Default ){
1173 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001174 }else if( onError==OE_Default ){
1175 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001176 }
drh5383ae52003-06-04 12:23:30 +00001177 if( seenReplace ){
1178 if( onError==OE_Ignore ) onError = OE_Replace;
1179 else if( onError==OE_Fail ) onError = OE_Abort;
1180 }
1181
drhb2fe7d82003-04-20 17:29:23 +00001182
1183 /* Check to see if the new index entry will be unique */
drhaa9b8962008-01-08 02:57:55 +00001184 sqlite3VdbeAddOp1(v, OP_SCopy, aRegIdx[iCur]);
1185 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-hasTwoRowids);
drh04adf412008-01-08 18:57:50 +00001186 j3 = sqlite3VdbeAddOp2(v, OP_IsUnique, baseCur+iCur+1, 0);
drhb2fe7d82003-04-20 17:29:23 +00001187
1188 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001189 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1190 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001191 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001192 case OE_Rollback:
1193 case OE_Abort:
1194 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001195 int j, n1, n2;
1196 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001197 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1198 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001199 n1 = strlen(zErrMsg);
1200 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1201 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1202 n2 = strlen(zCol);
1203 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001204 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001205 n1 += 2;
1206 }
1207 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001208 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001209 n1 += 3;
1210 break;
1211 }else{
drh5bb3eb92007-05-04 13:15:55 +00001212 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001213 n1 += n2;
1214 }
1215 }
drh5bb3eb92007-05-04 13:15:55 +00001216 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001217 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001218 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001219 break;
1220 }
1221 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001222 assert( seenReplace==0 );
drh04adf412008-01-08 18:57:50 +00001223 sqlite3VdbeAddOp1(v, OP_Pop, 2+hasTwoRowids);
drh66a51672008-01-03 00:01:23 +00001224 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001225 break;
1226 }
1227 case OE_Replace: {
danielk197796cb76f2008-01-04 13:24:28 +00001228 int iRowid = sqlite3StackToReg(pParse, 1);
drh04adf412008-01-08 18:57:50 +00001229 sqlite3GenerateRowDelete(pParse->db, v, pTab, baseCur, iRowid, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001230 if( isUpdate ){
drhaa9b8962008-01-08 02:57:55 +00001231 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid-hasTwoRowids);
drh04adf412008-01-08 18:57:50 +00001232 sqlite3VdbeAddOp2(v, OP_MoveGe, baseCur, 0);
drh9cfcf5d2002-01-29 18:41:24 +00001233 }
drh0ca3e242002-01-29 23:07:02 +00001234 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001235 break;
1236 }
drh9cfcf5d2002-01-29 18:41:24 +00001237 }
drhaa9b8962008-01-08 02:57:55 +00001238 sqlite3VdbeJumpHere(v, j3);
1239 sqlite3VdbeAddOp1(v, OP_Pop, 1);
drh0bd1f4e2002-06-06 18:54:39 +00001240#if NULL_DISTINCT_FOR_UNIQUE
drhaa9b8962008-01-08 02:57:55 +00001241 sqlite3VdbeJumpHere(v, j2);
drh0bd1f4e2002-06-06 18:54:39 +00001242#endif
drh9cfcf5d2002-01-29 18:41:24 +00001243 }
1244}
drh0ca3e242002-01-29 23:07:02 +00001245
1246/*
1247** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001248** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001249** A consecutive range of registers starting at regRowid contains the
1250** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001251**
drhb419a922002-01-30 16:17:23 +00001252** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001253** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001254*/
danielk19774adee202004-05-08 08:23:19 +00001255void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001256 Parse *pParse, /* The parser context */
1257 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001258 int baseCur, /* Index of a read/write cursor pointing at pTab */
1259 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001260 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drhf0863fe2005-06-12 21:35:51 +00001261 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001262 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001263 int newIdx, /* Index of NEW table for triggers. -1 if none */
1264 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001265){
1266 int i;
1267 Vdbe *v;
1268 int nIdx;
1269 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001270 int pik_flags;
drh04adf412008-01-08 18:57:50 +00001271 int regData;
drh0ca3e242002-01-29 23:07:02 +00001272
danielk19774adee202004-05-08 08:23:19 +00001273 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001274 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001275 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001276 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1277 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001278 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001279 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
drh0ca3e242002-01-29 23:07:02 +00001280 }
drh04adf412008-01-08 18:57:50 +00001281 regData = regRowid + 1;
1282 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1283 sqlite3VdbeAddOp2(v, OP_RegMakeRec, regData, pTab->nCol);
danielk1977a37cdde2004-05-16 11:15:36 +00001284 sqlite3TableAffinityStr(v, pTab);
danielk1977b84f96f2005-01-20 11:32:23 +00001285#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001286 if( newIdx>=0 ){
drh04adf412008-01-08 18:57:50 +00001287 sqlite3VdbeAddOp1(v, OP_SCopy, regRowid);
1288 sqlite3VdbeAddOp1(v, OP_SCopy, -1);
danielk19771f4aa332008-01-03 09:51:55 +00001289 sqlite3CodeInsert(pParse, newIdx, 0);
drh70ce3f02003-04-15 19:22:22 +00001290 }
danielk1977b84f96f2005-01-20 11:32:23 +00001291#endif
drh4794f732004-11-05 17:17:50 +00001292 if( pParse->nested ){
1293 pik_flags = 0;
1294 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001295 pik_flags = OPFLAG_NCHANGE;
1296 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001297 }
drhe4d90812007-03-29 05:51:49 +00001298 if( appendBias ){
1299 pik_flags |= OPFLAG_APPEND;
1300 }
drh04adf412008-01-08 18:57:50 +00001301 sqlite3CodeInsert(pParse, baseCur, pik_flags);
danielk197794eb6a12005-12-15 15:22:08 +00001302 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001303 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001304 }
drh0ca3e242002-01-29 23:07:02 +00001305}
drhcd446902004-02-24 01:05:31 +00001306
1307/*
drh290c1942004-08-21 17:54:45 +00001308** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001309** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001310** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001311**
1312** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001313*/
drhaa9b8962008-01-08 02:57:55 +00001314int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001315 Parse *pParse, /* Parsing context */
1316 Table *pTab, /* Table to be opened */
drh04adf412008-01-08 18:57:50 +00001317 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001318 int op /* OP_OpenRead or OP_OpenWrite */
1319){
drhcd446902004-02-24 01:05:31 +00001320 int i;
drh4cbdda92006-06-14 19:00:20 +00001321 int iDb;
drhcd446902004-02-24 01:05:31 +00001322 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001323 Vdbe *v;
1324
drhaa9b8962008-01-08 02:57:55 +00001325 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001326 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1327 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001328 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001329 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001330 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001331 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001332 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001333 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001334 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001335 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001336 }
drh04adf412008-01-08 18:57:50 +00001337 if( pParse->nTab<=baseCur+i ){
1338 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001339 }
drhaa9b8962008-01-08 02:57:55 +00001340 return i-1;
drhcd446902004-02-24 01:05:31 +00001341}
drh9d9cf222007-02-13 15:01:11 +00001342
drh91c58e22007-03-27 12:04:04 +00001343
1344#ifdef SQLITE_TEST
1345/*
1346** The following global variable is incremented whenever the
1347** transfer optimization is used. This is used for testing
1348** purposes only - to make sure the transfer optimization really
1349** is happening when it is suppose to.
1350*/
1351int sqlite3_xferopt_count;
1352#endif /* SQLITE_TEST */
1353
1354
drh9d9cf222007-02-13 15:01:11 +00001355#ifndef SQLITE_OMIT_XFER_OPT
1356/*
1357** Check to collation names to see if they are compatible.
1358*/
1359static int xferCompatibleCollation(const char *z1, const char *z2){
1360 if( z1==0 ){
1361 return z2==0;
1362 }
1363 if( z2==0 ){
1364 return 0;
1365 }
1366 return sqlite3StrICmp(z1, z2)==0;
1367}
1368
1369
1370/*
1371** Check to see if index pSrc is compatible as a source of data
1372** for index pDest in an insert transfer optimization. The rules
1373** for a compatible index:
1374**
1375** * The index is over the same set of columns
1376** * The same DESC and ASC markings occurs on all columns
1377** * The same onError processing (OE_Abort, OE_Ignore, etc)
1378** * The same collating sequence on each column
1379*/
1380static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1381 int i;
1382 assert( pDest && pSrc );
1383 assert( pDest->pTable!=pSrc->pTable );
1384 if( pDest->nColumn!=pSrc->nColumn ){
1385 return 0; /* Different number of columns */
1386 }
1387 if( pDest->onError!=pSrc->onError ){
1388 return 0; /* Different conflict resolution strategies */
1389 }
1390 for(i=0; i<pSrc->nColumn; i++){
1391 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1392 return 0; /* Different columns indexed */
1393 }
1394 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1395 return 0; /* Different sort orders */
1396 }
1397 if( pSrc->azColl[i]!=pDest->azColl[i] ){
1398 return 0; /* Different sort orders */
1399 }
1400 }
1401
1402 /* If no test above fails then the indices must be compatible */
1403 return 1;
1404}
1405
1406/*
1407** Attempt the transfer optimization on INSERTs of the form
1408**
1409** INSERT INTO tab1 SELECT * FROM tab2;
1410**
1411** This optimization is only attempted if
1412**
1413** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001414** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001415**
1416** (2) tab1 and tab2 are different tables
1417**
1418** (3) There must be no triggers on tab1
1419**
1420** (4) The result set of the SELECT statement is "*"
1421**
1422** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1423** or LIMIT clause.
1424**
1425** (6) The SELECT statement is a simple (not a compound) select that
1426** contains only tab2 in its FROM clause
1427**
1428** This method for implementing the INSERT transfers raw records from
1429** tab2 over to tab1. The columns are not decoded. Raw records from
1430** the indices of tab2 are transfered to tab1 as well. In so doing,
1431** the resulting tab1 has much less fragmentation.
1432**
1433** This routine returns TRUE if the optimization is attempted. If any
1434** of the conditions above fail so that the optimization should not
1435** be attempted, then this routine returns FALSE.
1436*/
1437static int xferOptimization(
1438 Parse *pParse, /* Parser context */
1439 Table *pDest, /* The table we are inserting into */
1440 Select *pSelect, /* A SELECT statement to use as the data source */
1441 int onError, /* How to handle constraint errors */
1442 int iDbDest /* The database of pDest */
1443){
1444 ExprList *pEList; /* The result set of the SELECT */
1445 Table *pSrc; /* The table in the FROM clause of SELECT */
1446 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1447 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1448 int i; /* Loop counter */
1449 int iDbSrc; /* The database of pSrc */
1450 int iSrc, iDest; /* Cursors from source and destination */
1451 int addr1, addr2; /* Loop addresses */
1452 int emptyDestTest; /* Address of test for empty pDest */
1453 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001454 Vdbe *v; /* The VDBE we are building */
1455 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001456 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001457 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drh9d9cf222007-02-13 15:01:11 +00001458
1459 if( pSelect==0 ){
1460 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1461 }
1462 if( pDest->pTrigger ){
1463 return 0; /* tab1 must not have triggers */
1464 }
1465#ifndef SQLITE_OMIT_VIRTUALTABLE
1466 if( pDest->isVirtual ){
1467 return 0; /* tab1 must not be a virtual table */
1468 }
1469#endif
1470 if( onError==OE_Default ){
1471 onError = OE_Abort;
1472 }
1473 if( onError!=OE_Abort && onError!=OE_Rollback ){
1474 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1475 }
danielk19775ce240a2007-09-03 17:30:06 +00001476 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001477 if( pSelect->pSrc->nSrc!=1 ){
1478 return 0; /* FROM clause must have exactly one term */
1479 }
1480 if( pSelect->pSrc->a[0].pSelect ){
1481 return 0; /* FROM clause cannot contain a subquery */
1482 }
1483 if( pSelect->pWhere ){
1484 return 0; /* SELECT may not have a WHERE clause */
1485 }
1486 if( pSelect->pOrderBy ){
1487 return 0; /* SELECT may not have an ORDER BY clause */
1488 }
drh8103b7d2007-02-24 13:23:51 +00001489 /* Do not need to test for a HAVING clause. If HAVING is present but
1490 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001491 if( pSelect->pGroupBy ){
1492 return 0; /* SELECT may not have a GROUP BY clause */
1493 }
1494 if( pSelect->pLimit ){
1495 return 0; /* SELECT may not have a LIMIT clause */
1496 }
drh8103b7d2007-02-24 13:23:51 +00001497 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001498 if( pSelect->pPrior ){
1499 return 0; /* SELECT may not be a compound query */
1500 }
1501 if( pSelect->isDistinct ){
1502 return 0; /* SELECT may not be DISTINCT */
1503 }
1504 pEList = pSelect->pEList;
1505 assert( pEList!=0 );
1506 if( pEList->nExpr!=1 ){
1507 return 0; /* The result set must have exactly one column */
1508 }
1509 assert( pEList->a[0].pExpr );
1510 if( pEList->a[0].pExpr->op!=TK_ALL ){
1511 return 0; /* The result set must be the special operator "*" */
1512 }
1513
1514 /* At this point we have established that the statement is of the
1515 ** correct syntactic form to participate in this optimization. Now
1516 ** we have to check the semantics.
1517 */
1518 pItem = pSelect->pSrc->a;
1519 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1520 if( pSrc==0 ){
1521 return 0; /* FROM clause does not contain a real table */
1522 }
1523 if( pSrc==pDest ){
1524 return 0; /* tab1 and tab2 may not be the same table */
1525 }
1526#ifndef SQLITE_OMIT_VIRTUALTABLE
1527 if( pSrc->isVirtual ){
1528 return 0; /* tab2 must not be a virtual table */
1529 }
1530#endif
1531 if( pSrc->pSelect ){
1532 return 0; /* tab2 may not be a view */
1533 }
1534 if( pDest->nCol!=pSrc->nCol ){
1535 return 0; /* Number of columns must be the same in tab1 and tab2 */
1536 }
1537 if( pDest->iPKey!=pSrc->iPKey ){
1538 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1539 }
1540 for(i=0; i<pDest->nCol; i++){
1541 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1542 return 0; /* Affinity must be the same on all columns */
1543 }
1544 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1545 return 0; /* Collating sequence must be the same on all columns */
1546 }
1547 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1548 return 0; /* tab2 must be NOT NULL if tab1 is */
1549 }
1550 }
1551 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001552 if( pDestIdx->onError!=OE_None ){
1553 destHasUniqueIdx = 1;
1554 }
drh9d9cf222007-02-13 15:01:11 +00001555 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1556 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1557 }
1558 if( pSrcIdx==0 ){
1559 return 0; /* pDestIdx has no corresponding index in pSrc */
1560 }
1561 }
drh7fc2f412007-03-29 00:08:24 +00001562#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001563 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001564 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1565 }
drh7fc2f412007-03-29 00:08:24 +00001566#endif
drh9d9cf222007-02-13 15:01:11 +00001567
1568 /* If we get this far, it means either:
1569 **
1570 ** * We can always do the transfer if the table contains an
1571 ** an integer primary key
1572 **
1573 ** * We can conditionally do the transfer if the destination
1574 ** table is empty.
1575 */
drhdd735212007-02-24 13:53:05 +00001576#ifdef SQLITE_TEST
1577 sqlite3_xferopt_count++;
1578#endif
drh9d9cf222007-02-13 15:01:11 +00001579 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1580 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001581 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001582 iSrc = pParse->nTab++;
1583 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001584 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001585 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001586 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001587 /* If tables do not have an INTEGER PRIMARY KEY and there
1588 ** are indices to be copied and the destination is not empty,
1589 ** we have to disallow the transfer optimization because the
1590 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001591 **
1592 ** Or if the destination has a UNIQUE index and is not empty,
1593 ** we also disallow the transfer optimization because we cannot
1594 ** insure that all entries in the union of DEST and SRC will be
1595 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001596 */
drh66a51672008-01-03 00:01:23 +00001597 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1598 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001599 sqlite3VdbeJumpHere(v, addr1);
1600 }else{
1601 emptyDestTest = 0;
1602 }
1603 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001604 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001605 if( pDest->iPKey>=0 ){
drh66a51672008-01-03 00:01:23 +00001606 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drhb1fdb2a2008-01-05 04:06:03 +00001607 sqlite3VdbeAddOp0(v, OP_Copy);
drh66a51672008-01-03 00:01:23 +00001608 addr2 = sqlite3VdbeAddOp2(v, OP_NotExists, iDest, 0);
1609 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1610 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001611 sqlite3VdbeJumpHere(v, addr2);
drh6a288a32008-01-07 19:20:24 +00001612 autoIncStep(pParse, regAutoinc, 0);
drhbd36ba62007-03-31 13:00:26 +00001613 }else if( pDest->pIndex==0 ){
drh4c583122008-01-04 22:01:03 +00001614 addr1 = sqlite3VdbeAddOp1(v, OP_NewRowid, iDest);
drh95bad4c2007-03-28 18:04:10 +00001615 }else{
drh66a51672008-01-03 00:01:23 +00001616 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
drh42242de2007-03-29 13:35:35 +00001617 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001618 }
drh66a51672008-01-03 00:01:23 +00001619 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, 0);
danielk19771f4aa332008-01-03 09:51:55 +00001620 sqlite3CodeInsert(pParse,iDest,OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1621 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001622 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001623 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001624 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1625 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1626 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1627 }
1628 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001629 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1630 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001631 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001632 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1633 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001634 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001635 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001636 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001637 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001638 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001639 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1640 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, 0);
drhaa9b8962008-01-08 02:57:55 +00001641 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, 0, 1);
drh66a51672008-01-03 00:01:23 +00001642 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001643 sqlite3VdbeJumpHere(v, addr1);
1644 }
1645 sqlite3VdbeJumpHere(v, emptySrcTest);
drh66a51672008-01-03 00:01:23 +00001646 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1647 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001648 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001649 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001650 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001651 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001652 return 0;
1653 }else{
1654 return 1;
1655 }
1656}
1657#endif /* SQLITE_OMIT_XFER_OPT */