blob: 27549f0018d29397685c1f9a9359e4b7a5f2777b [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**
drh20411ea2009-05-29 19:00:12 +000015** $Id: insert.c,v 1.268 2009/05/29 19:00:13 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
19/*
drhbbb5e4e2009-04-30 00:11:09 +000020** Generate code that will open a table for reading.
21*/
22void sqlite3OpenTable(
23 Parse *p, /* Generate code into this VDBE */
24 int iCur, /* The cursor number of the table */
25 int iDb, /* The database index in sqlite3.aDb[] */
26 Table *pTab, /* The table to be opened */
27 int opcode /* OP_OpenRead or OP_OpenWrite */
28){
29 Vdbe *v;
30 if( IsVirtual(pTab) ) return;
31 v = sqlite3GetVdbe(p);
32 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
33 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
34 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
35 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
36 VdbeComment((v, "%s", pTab->zName));
37}
38
39/*
drh66a51672008-01-03 00:01:23 +000040** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000041** string for index pIdx. A column affinity string has one character
danielk19773d1bfea2004-05-14 11:00:53 +000042** for each column in the table, according to the affinity of the column:
43**
44** Character Column affinity
45** ------------------------------
drh3eda0402005-11-24 13:15:32 +000046** 'a' TEXT
47** 'b' NONE
48** 'c' NUMERIC
49** 'd' INTEGER
50** 'e' REAL
drh2d401ab2008-01-10 23:50:11 +000051**
52** An extra 'b' is appended to the end of the string to cover the
53** rowid that appears as the last column in every index.
danielk19773d1bfea2004-05-14 11:00:53 +000054*/
danielk1977a37cdde2004-05-16 11:15:36 +000055void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
56 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000057 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000058 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000059 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000060 **
61 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000062 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000063 ** up.
64 */
65 int n;
66 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000067 sqlite3 *db = sqlite3VdbeDb(v);
drh633e6d52008-07-28 19:34:53 +000068 pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
danielk1977a37cdde2004-05-16 11:15:36 +000069 if( !pIdx->zColAff ){
drh633e6d52008-07-28 19:34:53 +000070 db->mallocFailed = 1;
danielk1977a37cdde2004-05-16 11:15:36 +000071 return;
72 }
73 for(n=0; n<pIdx->nColumn; n++){
74 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
75 }
drh2d401ab2008-01-10 23:50:11 +000076 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
77 pIdx->zColAff[n] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +000078 }
danielk19773d1bfea2004-05-14 11:00:53 +000079
drh66a51672008-01-03 00:01:23 +000080 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000081}
82
83/*
drh66a51672008-01-03 00:01:23 +000084** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000085** string for table pTab. A column affinity string has one character
86** for each column indexed by the index, according to the affinity of the
87** column:
88**
89** Character Column affinity
90** ------------------------------
drh3eda0402005-11-24 13:15:32 +000091** 'a' TEXT
92** 'b' NONE
93** 'c' NUMERIC
94** 'd' INTEGER
95** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000096*/
97void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000098 /* The first time a column affinity string for a particular table
99 ** is required, it is allocated and populated here. It is then
100 ** stored as a member of the Table structure for subsequent use.
101 **
102 ** The column affinity string will eventually be deleted by
103 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
104 */
105 if( !pTab->zColAff ){
106 char *zColAff;
107 int i;
drhabb6fca2007-08-16 12:24:01 +0000108 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +0000109
drh633e6d52008-07-28 19:34:53 +0000110 zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +0000111 if( !zColAff ){
drh633e6d52008-07-28 19:34:53 +0000112 db->mallocFailed = 1;
danielk1977a37cdde2004-05-16 11:15:36 +0000113 return;
danielk19773d1bfea2004-05-14 11:00:53 +0000114 }
115
116 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +0000117 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +0000118 }
119 zColAff[pTab->nCol] = '\0';
120
121 pTab->zColAff = zColAff;
122 }
123
drh66a51672008-01-03 00:01:23 +0000124 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +0000125}
126
danielk19774d887782005-02-08 08:42:27 +0000127/*
drh48d11782007-11-23 15:02:19 +0000128** Return non-zero if the table pTab in database iDb or any of its indices
129** have been opened at any point in the VDBE program beginning at location
130** iStartAddr throught the end of the program. This is used to see if
131** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
132** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000133*/
drh48d11782007-11-23 15:02:19 +0000134static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000135 int i;
drh48d11782007-11-23 15:02:19 +0000136 int iEnd = sqlite3VdbeCurrentAddr(v);
137 for(i=iStartAddr; i<iEnd; i++){
138 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000139 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000140 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
141 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000142 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000143 if( tnum==pTab->tnum ){
144 return 1;
145 }
146 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
147 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000148 return 1;
149 }
drh48d11782007-11-23 15:02:19 +0000150 }
151 }
drh543165e2007-11-27 14:46:41 +0000152#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19772dca4ac2008-01-03 11:50:29 +0000153 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
154 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000155 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000156 return 1;
danielk19774d887782005-02-08 08:42:27 +0000157 }
drh543165e2007-11-27 14:46:41 +0000158#endif
danielk19774d887782005-02-08 08:42:27 +0000159 }
160 return 0;
161}
danielk19773d1bfea2004-05-14 11:00:53 +0000162
drh9d9cf222007-02-13 15:01:11 +0000163#ifndef SQLITE_OMIT_AUTOINCREMENT
164/*
165** Write out code to initialize the autoincrement logic. This code
166** looks up the current autoincrement value in the sqlite_sequence
drh6a288a32008-01-07 19:20:24 +0000167** table and stores that value in a register. Code generated by
168** autoIncStep() will keep that register holding the largest
drh9d9cf222007-02-13 15:01:11 +0000169** rowid value. Code generated by autoIncEnd() will write the new
170** largest value of the counter back into the sqlite_sequence table.
171**
172** This routine returns the index of the mem[] cell that contains
173** the maximum rowid counter.
174**
drh6a288a32008-01-07 19:20:24 +0000175** Three consecutive registers are allocated by this routine. The
176** first two hold the name of the target table and the maximum rowid
177** inserted into the target table, respectively.
178** The third holds the rowid in sqlite_sequence where we will
179** write back the revised maximum rowid. This routine returns the
180** index of the second of these three registers.
drh9d9cf222007-02-13 15:01:11 +0000181*/
182static int autoIncBegin(
183 Parse *pParse, /* Parsing context */
184 int iDb, /* Index of the database holding pTab */
185 Table *pTab /* The table we are writing to */
186){
drh6a288a32008-01-07 19:20:24 +0000187 int memId = 0; /* Register holding maximum rowid */
drh7d10d5a2008-08-20 16:35:10 +0000188 if( pTab->tabFlags & TF_Autoincrement ){
drh9d9cf222007-02-13 15:01:11 +0000189 Vdbe *v = pParse->pVdbe;
190 Db *pDb = &pParse->db->aDb[iDb];
danielk19776ab3a2e2009-02-19 14:39:25 +0000191 int iCur = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +0000192 int addr; /* Address of the top of the loop */
drh9d9cf222007-02-13 15:01:11 +0000193 assert( v );
drh6a288a32008-01-07 19:20:24 +0000194 pParse->nMem++; /* Holds name of table */
195 memId = ++pParse->nMem;
196 pParse->nMem++;
drh9d9cf222007-02-13 15:01:11 +0000197 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh6a288a32008-01-07 19:20:24 +0000198 addr = sqlite3VdbeCurrentAddr(v);
drh1db639c2008-01-17 02:36:28 +0000199 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
drhc9ded4c2008-05-29 03:20:59 +0000200 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
drh1db639c2008-01-17 02:36:28 +0000201 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
202 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
drh35573352008-01-08 23:54:25 +0000203 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh6a288a32008-01-07 19:20:24 +0000204 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
205 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
drhc9ded4c2008-05-29 03:20:59 +0000206 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
drh1db639c2008-01-17 02:36:28 +0000207 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
drhc9ded4c2008-05-29 03:20:59 +0000208 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
drh66a51672008-01-03 00:01:23 +0000209 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000210 }
211 return memId;
212}
213
214/*
215** Update the maximum rowid for an autoincrement calculation.
216**
217** This routine should be called when the top of the stack holds a
218** new rowid that is about to be inserted. If that new rowid is
219** larger than the maximum rowid in the memId memory cell, then the
220** memory cell is updated. The stack is unchanged.
221*/
drh6a288a32008-01-07 19:20:24 +0000222static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000223 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000224 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000225 }
226}
227
228/*
229** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000230** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000231** the sqlite_sequence table.
232*/
233static void autoIncEnd(
234 Parse *pParse, /* The parsing context */
235 int iDb, /* Index of the database holding pTab */
236 Table *pTab, /* Table we are inserting into */
237 int memId /* Memory cell holding the maximum rowid */
238){
drh7d10d5a2008-08-20 16:35:10 +0000239 if( pTab->tabFlags & TF_Autoincrement ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000240 int iCur = pParse->nTab++;
drh9d9cf222007-02-13 15:01:11 +0000241 Vdbe *v = pParse->pVdbe;
242 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000243 int j1;
danielk1977a7a8e142008-02-13 18:25:27 +0000244 int iRec = ++pParse->nMem; /* Memory cell used for record */
drh6a288a32008-01-07 19:20:24 +0000245
drh9d9cf222007-02-13 15:01:11 +0000246 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000247 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000248 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
249 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
250 sqlite3VdbeJumpHere(v, j1);
danielk1977a7a8e142008-02-13 18:25:27 +0000251 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
252 sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
drh35573352008-01-08 23:54:25 +0000253 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh6a288a32008-01-07 19:20:24 +0000254 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000255 }
256}
257#else
258/*
259** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
260** above are all no-ops
261*/
262# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000263# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000264# define autoIncEnd(A,B,C,D)
265#endif /* SQLITE_OMIT_AUTOINCREMENT */
266
267
268/* Forward declaration */
269static int xferOptimization(
270 Parse *pParse, /* Parser context */
271 Table *pDest, /* The table we are inserting into */
272 Select *pSelect, /* A SELECT statement to use as the data source */
273 int onError, /* How to handle constraint errors */
274 int iDbDest /* The database of pDest */
275);
276
danielk19773d1bfea2004-05-14 11:00:53 +0000277/*
drh1ccde152000-06-17 13:12:39 +0000278** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000279**
280** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000281** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000282**
drh1ccde152000-06-17 13:12:39 +0000283** The IDLIST following the table name is always optional. If omitted,
284** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000285** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000286**
287** The pList parameter holds EXPRLIST in the first form of the INSERT
288** statement above, and pSelect is NULL. For the second form, pList is
289** NULL and pSelect is a pointer to the select statement used to generate
290** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000291**
drh9d9cf222007-02-13 15:01:11 +0000292** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000293** select with data coming from a VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01 +0000294** once straight down through. Pseudo-code follows (we call this
295** the "1st template"):
drh142e30d2002-08-28 03:00:58 +0000296**
297** open write cursor to <table> and its indices
298** puts VALUES clause expressions onto the stack
299** write the resulting record into <table>
300** cleanup
301**
drh9d9cf222007-02-13 15:01:11 +0000302** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000303**
304** INSERT INTO <table> SELECT ...
305**
drh9d9cf222007-02-13 15:01:11 +0000306** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
307** in other words if the SELECT pulls all columns from a single table
308** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
309** if <table2> and <table1> are distinct tables but have identical
310** schemas, including all the same indices, then a special optimization
311** is invoked that copies raw records from <table2> over to <table1>.
312** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01 +0000313** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000314**
315** open a write cursor to <table>
316** open read cursor on <table2>
317** transfer all records in <table2> over to <table>
318** close cursors
319** foreach index on <table>
320** open a write cursor on the <table> index
321** open a read cursor on the corresponding <table2> index
322** transfer all records from the read to the write cursors
323** close cursors
324** end foreach
325**
drhe00ee6e2008-06-20 15:24:01 +0000326** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11 +0000327** and the SELECT clause does not read from <table> at any time.
328** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000329**
drhe00ee6e2008-06-20 15:24:01 +0000330** EOF <- 0
331** X <- A
drh142e30d2002-08-28 03:00:58 +0000332** goto B
333** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000334** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000335** load values into registers R..R+n
336** yield X
drh142e30d2002-08-28 03:00:58 +0000337** end loop
338** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000339** EOF <- 1
340** yield X
drh142e30d2002-08-28 03:00:58 +0000341** goto A
drhe00ee6e2008-06-20 15:24:01 +0000342** B: open write cursor to <table> and its indices
343** C: yield X
344** if EOF goto D
345** insert the select result into <table> from R..R+n
346** goto C
drh142e30d2002-08-28 03:00:58 +0000347** D: cleanup
348**
drhe00ee6e2008-06-20 15:24:01 +0000349** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000350** values from a SELECT but the data is being inserted into a table
351** that is also read as part of the SELECT. In the third form,
352** we have to use a intermediate table to store the results of
353** the select. The template is like this:
354**
drhe00ee6e2008-06-20 15:24:01 +0000355** EOF <- 0
356** X <- A
drh142e30d2002-08-28 03:00:58 +0000357** goto B
358** A: setup for the SELECT
359** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000360** load value into register R..R+n
361** yield X
drh142e30d2002-08-28 03:00:58 +0000362** end loop
363** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000364** EOF <- 1
365** yield X
366** halt-error
367** B: open temp table
368** L: yield X
369** if EOF goto M
370** insert row from R..R+n into temp table
371** goto L
372** M: open write cursor to <table> and its indices
373** rewind temp table
374** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58 +0000375** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01 +0000376** end loop
377** D: cleanup
drhcce7d172000-05-31 15:34:51 +0000378*/
danielk19774adee202004-05-08 08:23:19 +0000379void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000380 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000381 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000382 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000383 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000384 IdList *pColumn, /* Column names corresponding to IDLIST. */
385 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000386){
drh6a288a32008-01-07 19:20:24 +0000387 sqlite3 *db; /* The main database structure */
388 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000389 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000390 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000391 int i, j, idx; /* Loop counters */
392 Vdbe *v; /* Generate code into this virtual machine */
393 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000394 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000395 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000396 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000397 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000398 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000399 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000400 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01 +0000401 int addrInsTop = 0; /* Jump to label "D" */
402 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
403 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
drh2eb95372008-06-06 15:04:36 +0000404 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24 +0000405 int newIdx = -1; /* Cursor for the NEW pseudo-table */
406 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000407 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000408 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000409
drh6a288a32008-01-07 19:20:24 +0000410 /* Register allocations */
drh1bd10f82008-12-10 21:19:56 +0000411 int regFromSelect = 0;/* Base register for data coming from SELECT */
drh6a288a32008-01-07 19:20:24 +0000412 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
413 int regRowCount = 0; /* Memory cell used for the row counter */
414 int regIns; /* Block of regs holding rowid+data being inserted */
415 int regRowid; /* registers holding insert rowid */
416 int regData; /* register holding first column to insert */
417 int regRecord; /* Holds the assemblied row record */
drh1bd10f82008-12-10 21:19:56 +0000418 int regEof = 0; /* Register recording end of SELECT data */
drhaa9b8962008-01-08 02:57:55 +0000419 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000420
danielk1977034ca142007-06-26 10:38:54 +0000421
drh798da522004-11-04 04:42:28 +0000422#ifndef SQLITE_OMIT_TRIGGER
423 int isView; /* True if attempting to insert into a view */
danielk19772f886d12009-02-28 10:47:41 +0000424 Trigger *pTrigger; /* List of triggers on pTab, if required */
425 int tmask; /* Mask of trigger times */
drh798da522004-11-04 04:42:28 +0000426#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000427
drh17435752007-08-16 04:30:38 +0000428 db = pParse->db;
drh1bd10f82008-12-10 21:19:56 +0000429 memset(&dest, 0, sizeof(dest));
drh17435752007-08-16 04:30:38 +0000430 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000431 goto insert_cleanup;
432 }
drhdaffd0e2001-04-11 14:28:42 +0000433
drh1ccde152000-06-17 13:12:39 +0000434 /* Locate the table into which we will be inserting new information.
435 */
drh113088e2003-03-20 01:16:58 +0000436 assert( pTabList->nSrc==1 );
437 zTab = pTabList->a[0].zName;
drh098d1682009-05-02 15:46:46 +0000438 if( NEVER(zTab==0) ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000439 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000440 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000441 goto insert_cleanup;
442 }
danielk1977da184232006-01-05 11:34:32 +0000443 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
444 assert( iDb<db->nDb );
445 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000446 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000447 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000448 goto insert_cleanup;
449 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000450
drhb7f91642004-10-31 02:22:47 +0000451 /* Figure out if we have any triggers and if the table being
452 ** inserted into is a view
453 */
454#ifndef SQLITE_OMIT_TRIGGER
danielk19772f886d12009-02-28 10:47:41 +0000455 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
drhb7f91642004-10-31 02:22:47 +0000456 isView = pTab->pSelect!=0;
457#else
danielk19772f886d12009-02-28 10:47:41 +0000458# define pTrigger 0
459# define tmask 0
drhb7f91642004-10-31 02:22:47 +0000460# define isView 0
461#endif
462#ifdef SQLITE_OMIT_VIEW
463# undef isView
464# define isView 0
465#endif
danielk19772f886d12009-02-28 10:47:41 +0000466 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
drhb7f91642004-10-31 02:22:47 +0000467
danielk1977c3f9bad2002-05-15 08:30:12 +0000468 /* Ensure that:
469 * (a) the table is not read-only,
470 * (b) that if it is a view then ON INSERT triggers exist
471 */
danielk19772f886d12009-02-28 10:47:41 +0000472 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000473 goto insert_cleanup;
474 }
drh43617e92006-03-06 20:55:46 +0000475 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000476
drhf573c992002-07-31 00:32:50 +0000477 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000478 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
479 ** module table).
drhf573c992002-07-31 00:32:50 +0000480 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000481 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000482 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000483 }
484
drh1ccde152000-06-17 13:12:39 +0000485 /* Allocate a VDBE
486 */
danielk19774adee202004-05-08 08:23:19 +0000487 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000488 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000489 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk19772f886d12009-02-28 10:47:41 +0000490 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
drh1ccde152000-06-17 13:12:39 +0000491
danielk1977c3f9bad2002-05-15 08:30:12 +0000492 /* if there are row triggers, allocate a temp table for new.* references. */
danielk19772f886d12009-02-28 10:47:41 +0000493 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000494 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000495 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000496
drh9d9cf222007-02-13 15:01:11 +0000497#ifndef SQLITE_OMIT_XFER_OPT
498 /* If the statement is of the form
499 **
500 ** INSERT INTO <table1> SELECT * FROM <table2>;
501 **
502 ** Then special optimizations can be applied that make the transfer
503 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000504 **
505 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000506 */
507 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
danielk19772f886d12009-02-28 10:47:41 +0000508 assert( !pTrigger );
drh9d9cf222007-02-13 15:01:11 +0000509 assert( pList==0 );
510 goto insert_cleanup;
511 }
512#endif /* SQLITE_OMIT_XFER_OPT */
513
drh2958a4e2004-11-12 03:56:15 +0000514 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000515 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000516 */
drh6a288a32008-01-07 19:20:24 +0000517 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000518
drh1ccde152000-06-17 13:12:39 +0000519 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000520 ** is coming from a SELECT statement, then generate a co-routine that
521 ** produces a single row of the SELECT on each invocation. The
522 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000523 */
drh5974a302000-06-07 14:42:26 +0000524 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000525 /* Data is coming from a SELECT. Generate code to implement that SELECT
drhe00ee6e2008-06-20 15:24:01 +0000526 ** as a co-routine. The code is common to both the 3rd and 4th
527 ** templates:
528 **
529 ** EOF <- 0
530 ** X <- A
531 ** goto B
532 ** A: setup for the SELECT
533 ** loop over the tables in the SELECT
534 ** load value into register R..R+n
535 ** yield X
536 ** end loop
537 ** cleanup after the SELECT
538 ** EOF <- 1
539 ** yield X
540 ** halt-error
541 **
542 ** On each invocation of the co-routine, it puts a single row of the
543 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
544 ** (These output registers are allocated by sqlite3Select().) When
545 ** the SELECT completes, it sets the EOF flag stored in regEof.
drh142e30d2002-08-28 03:00:58 +0000546 */
drhe00ee6e2008-06-20 15:24:01 +0000547 int rc, j1;
drh1013c932008-01-06 00:25:21 +0000548
drhe00ee6e2008-06-20 15:24:01 +0000549 regEof = ++pParse->nMem;
550 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
551 VdbeComment((v, "SELECT eof flag"));
drh92b01d52008-06-24 00:32:35 +0000552 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
drhe00ee6e2008-06-20 15:24:01 +0000553 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
drh92b01d52008-06-24 00:32:35 +0000554 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000555 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
556 VdbeComment((v, "Jump over SELECT coroutine"));
danielk1977b3bce662005-01-29 08:32:43 +0000557
558 /* Resolve the expressions in the SELECT statement and execute it. */
drh7d10d5a2008-08-20 16:35:10 +0000559 rc = sqlite3Select(pParse, pSelect, &dest);
drh098d1682009-05-02 15:46:46 +0000560 assert( pParse->nErr==0 || rc );
561 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000562 goto insert_cleanup;
563 }
drhe00ee6e2008-06-20 15:24:01 +0000564 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
drh92b01d52008-06-24 00:32:35 +0000565 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
drhe00ee6e2008-06-20 15:24:01 +0000566 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
567 VdbeComment((v, "End of SELECT coroutine"));
568 sqlite3VdbeJumpHere(v, j1); /* label B: */
danielk1977b3bce662005-01-29 08:32:43 +0000569
drh6a288a32008-01-07 19:20:24 +0000570 regFromSelect = dest.iMem;
drh5974a302000-06-07 14:42:26 +0000571 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000572 nColumn = pSelect->pEList->nExpr;
drhe00ee6e2008-06-20 15:24:01 +0000573 assert( dest.nMem==nColumn );
drh142e30d2002-08-28 03:00:58 +0000574
575 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000576 ** should be written into a temporary table (template 4). Set to
577 ** FALSE if each* row of the SELECT can be written directly into
578 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000579 **
580 ** A temp table must be used if the table being updated is also one
581 ** of the tables being read by the SELECT statement. Also use a
582 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000583 */
danielk19772f886d12009-02-28 10:47:41 +0000584 if( pTrigger || readsTable(v, addrSelect, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000585 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000586 }
drh142e30d2002-08-28 03:00:58 +0000587
588 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000589 /* Invoke the coroutine to extract information from the SELECT
590 ** and add it to a transient table srcTab. The code generated
591 ** here is from the 4th template:
592 **
593 ** B: open temp table
594 ** L: yield X
595 ** if EOF goto M
596 ** insert row from R..R+n into temp table
597 ** goto L
598 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000599 */
drhdc5ea5c2008-12-10 17:19:59 +0000600 int regRec; /* Register to hold packed record */
601 int regTempRowid; /* Register to hold temp table ROWID */
602 int addrTop; /* Label "L" */
603 int addrIf; /* Address of jump to M */
drhb7654112008-01-12 12:48:07 +0000604
drh142e30d2002-08-28 03:00:58 +0000605 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000606 regRec = sqlite3GetTempReg(pParse);
drhdc5ea5c2008-12-10 17:19:59 +0000607 regTempRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000608 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh92b01d52008-06-24 00:32:35 +0000609 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000610 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh1db639c2008-01-17 02:36:28 +0000611 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000612 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
613 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drhe00ee6e2008-06-20 15:24:01 +0000614 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
615 sqlite3VdbeJumpHere(v, addrIf);
drhb7654112008-01-12 12:48:07 +0000616 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000617 sqlite3ReleaseTempReg(pParse, regTempRowid);
drh142e30d2002-08-28 03:00:58 +0000618 }
drh5974a302000-06-07 14:42:26 +0000619 }else{
drh142e30d2002-08-28 03:00:58 +0000620 /* This is the case if the data for the INSERT is coming from a VALUES
621 ** clause
622 */
danielk1977b3bce662005-01-29 08:32:43 +0000623 NameContext sNC;
624 memset(&sNC, 0, sizeof(sNC));
625 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000626 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000627 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000628 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000629 for(i=0; i<nColumn; i++){
drh7d10d5a2008-08-20 16:35:10 +0000630 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000631 goto insert_cleanup;
632 }
drhe64e7b22002-02-18 13:56:36 +0000633 }
drh5974a302000-06-07 14:42:26 +0000634 }
drh1ccde152000-06-17 13:12:39 +0000635
636 /* Make sure the number of columns in the source data matches the number
637 ** of columns to be inserted into the table.
638 */
danielk1977034ca142007-06-26 10:38:54 +0000639 if( IsVirtual(pTab) ){
640 for(i=0; i<pTab->nCol; i++){
641 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
642 }
643 }
644 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000645 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000646 "table %S has %d columns but %d values were supplied",
drhd51397a2009-05-01 15:17:48 +0000647 pTabList, 0, pTab->nCol-nHidden, nColumn);
drhcce7d172000-05-31 15:34:51 +0000648 goto insert_cleanup;
649 }
drh967e8b72000-06-21 13:59:10 +0000650 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000651 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000652 goto insert_cleanup;
653 }
drh1ccde152000-06-17 13:12:39 +0000654
655 /* If the INSERT statement included an IDLIST term, then make sure
656 ** all elements of the IDLIST really are columns of the table and
657 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000658 **
659 ** If the table has an INTEGER PRIMARY KEY column and that column
660 ** is named in the IDLIST, then record in the keyColumn variable
661 ** the index into IDLIST of the primary key column. keyColumn is
662 ** the index of the primary key as it appears in IDLIST, not as
663 ** is appears in the original table. (The index of the primary
664 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000665 */
drh967e8b72000-06-21 13:59:10 +0000666 if( pColumn ){
667 for(i=0; i<pColumn->nId; i++){
668 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000669 }
drh967e8b72000-06-21 13:59:10 +0000670 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000671 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000672 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000673 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000674 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000675 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000676 }
drhcce7d172000-05-31 15:34:51 +0000677 break;
678 }
679 }
680 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000681 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000682 keyColumn = i;
683 }else{
danielk19774adee202004-05-08 08:23:19 +0000684 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000685 pTabList, 0, pColumn->a[i].zName);
686 pParse->nErr++;
687 goto insert_cleanup;
688 }
drhcce7d172000-05-31 15:34:51 +0000689 }
690 }
691 }
drh1ccde152000-06-17 13:12:39 +0000692
drhaacc5432002-01-06 17:07:40 +0000693 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000694 ** key, the set the keyColumn variable to the primary key column index
695 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000696 */
drh147d0cc2006-08-25 23:42:53 +0000697 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000698 keyColumn = pTab->iPKey;
699 }
700
drh142e30d2002-08-28 03:00:58 +0000701 /* Open the temp table for FOR EACH ROW triggers
702 */
danielk19772f886d12009-02-28 10:47:41 +0000703 if( pTrigger ){
danielk1977d336e222009-02-20 10:58:41 +0000704 sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000705 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000706
drhfeeb1392002-04-09 03:28:01 +0000707 /* Initialize the count of rows to be inserted
708 */
drh142e30d2002-08-28 03:00:58 +0000709 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000710 regRowCount = ++pParse->nMem;
711 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000712 }
713
danielk1977e448dc42008-01-02 11:50:51 +0000714 /* If this is not a view, open the table and and all indices */
715 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000716 int nIdx;
drhaa9b8962008-01-08 02:57:55 +0000717
drh04adf412008-01-08 18:57:50 +0000718 baseCur = pParse->nTab;
719 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drh5c070532008-04-11 15:36:03 +0000720 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000721 if( aRegIdx==0 ){
722 goto insert_cleanup;
723 }
724 for(i=0; i<nIdx; i++){
725 aRegIdx[i] = ++pParse->nMem;
726 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000727 }
728
drhe00ee6e2008-06-20 15:24:01 +0000729 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000730 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000731 /* This block codes the top of loop only. The complete loop is the
732 ** following pseudocode (template 4):
733 **
734 ** rewind temp table
735 ** C: loop over rows of intermediate table
736 ** transfer values form intermediate table into <table>
737 ** end loop
738 ** D: ...
739 */
740 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
741 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000742 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000743 /* This block codes the top of loop only. The complete loop is the
744 ** following pseudocode (template 3):
745 **
746 ** C: yield X
747 ** if EOF goto D
748 ** insert the select result into <table> from R..R+n
749 ** goto C
750 ** D: ...
751 */
drh92b01d52008-06-24 00:32:35 +0000752 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000753 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh5974a302000-06-07 14:42:26 +0000754 }
drh1ccde152000-06-17 13:12:39 +0000755
drh6a288a32008-01-07 19:20:24 +0000756 /* Allocate registers for holding the rowid of the new row,
757 ** the content of the new row, and the assemblied row record.
758 */
759 regRecord = ++pParse->nMem;
760 regRowid = regIns = pParse->nMem+1;
761 pParse->nMem += pTab->nCol + 1;
762 if( IsVirtual(pTab) ){
763 regRowid++;
764 pParse->nMem++;
765 }
766 regData = regRowid+1;
767
drh5cf590c2003-04-24 01:45:04 +0000768 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000769 */
danielk19774adee202004-05-08 08:23:19 +0000770 endOfLoop = sqlite3VdbeMakeLabel(v);
danielk19772f886d12009-02-28 10:47:41 +0000771 if( tmask & TRIGGER_BEFORE ){
drhdc5ea5c2008-12-10 17:19:59 +0000772 int regTrigRowid;
drh2d401ab2008-01-10 23:50:11 +0000773 int regCols;
774 int regRec;
danielk1977c3f9bad2002-05-15 08:30:12 +0000775
drh70ce3f02003-04-15 19:22:22 +0000776 /* build the NEW.* reference row. Note that if there is an INTEGER
777 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
778 ** translated into a unique ID for the row. But on a BEFORE trigger,
779 ** we do not know what the unique ID will be (because the insert has
780 ** not happened yet) so we substitute a rowid of -1
781 */
drhdc5ea5c2008-12-10 17:19:59 +0000782 regTrigRowid = sqlite3GetTempReg(pParse);
drh70ce3f02003-04-15 19:22:22 +0000783 if( keyColumn<0 ){
drhdc5ea5c2008-12-10 17:19:59 +0000784 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000785 }else{
drh6a288a32008-01-07 19:20:24 +0000786 int j1;
drh7fe45902009-05-01 02:08:04 +0000787 if( useTempTable ){
788 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
789 }else{
790 assert( pSelect==0 ); /* Otherwise useTempTable is true */
791 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
792 }
drhdc5ea5c2008-12-10 17:19:59 +0000793 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
794 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
drh6a288a32008-01-07 19:20:24 +0000795 sqlite3VdbeJumpHere(v, j1);
drhdc5ea5c2008-12-10 17:19:59 +0000796 sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000797 }
798
danielk1977034ca142007-06-26 10:38:54 +0000799 /* Cannot have triggers on a virtual table. If it were possible,
800 ** this block would have to account for hidden column.
801 */
802 assert(!IsVirtual(pTab));
803
drh70ce3f02003-04-15 19:22:22 +0000804 /* Create the new column data
805 */
drh2d401ab2008-01-10 23:50:11 +0000806 regCols = sqlite3GetTempRange(pParse, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000807 for(i=0; i<pTab->nCol; i++){
808 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000809 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000810 }else{
drh9adf9ac2002-05-15 11:44:13 +0000811 for(j=0; j<pColumn->nId; j++){
812 if( pColumn->a[j].idx==i ) break;
813 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000814 }
815 if( pColumn && j>=pColumn->nId ){
drh2d401ab2008-01-10 23:50:11 +0000816 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
drh142e30d2002-08-28 03:00:58 +0000817 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000818 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000819 }else{
drhd6fe9612005-01-14 01:22:00 +0000820 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000821 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000822 }
823 }
drh2d401ab2008-01-10 23:50:11 +0000824 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +0000825 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +0000826
827 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
828 ** do not attempt any conversions before assembling the record.
829 ** If this is a real table, attempt conversions as required by the
830 ** table column affinities.
831 */
832 if( !isView ){
833 sqlite3TableAffinityStr(v, pTab);
834 }
drhdc5ea5c2008-12-10 17:19:59 +0000835 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
drh2d401ab2008-01-10 23:50:11 +0000836 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000837 sqlite3ReleaseTempReg(pParse, regTrigRowid);
drh2d401ab2008-01-10 23:50:11 +0000838 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000839
drh5cf590c2003-04-24 01:45:04 +0000840 /* Fire BEFORE or INSTEAD OF triggers */
danielk19772f886d12009-02-28 10:47:41 +0000841 if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
842 pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000843 goto insert_cleanup;
844 }
drh70ce3f02003-04-15 19:22:22 +0000845 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000846
drh4a324312001-12-21 14:30:42 +0000847 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000848 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000849 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000850 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000851 */
drh5cf590c2003-04-24 01:45:04 +0000852 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000853 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000854 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000855 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000856 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000857 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000858 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000859 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000860 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000861 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000862 }else{
drhe4d90812007-03-29 05:51:49 +0000863 VdbeOp *pOp;
drh1db639c2008-01-17 02:36:28 +0000864 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
drh20411ea2009-05-29 19:00:12 +0000865 pOp = sqlite3VdbeGetOp(v, -1);
drh1b7ecbb2009-05-03 01:00:59 +0000866 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000867 appendFlag = 1;
868 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000869 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000870 pOp->p2 = regRowid;
871 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000872 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000873 }
drhf0863fe2005-06-12 21:35:51 +0000874 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000875 ** to generate a unique primary key value.
876 */
drhe4d90812007-03-29 05:51:49 +0000877 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000878 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000879 if( !IsVirtual(pTab) ){
880 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
881 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
882 sqlite3VdbeJumpHere(v, j1);
883 }else{
884 j1 = sqlite3VdbeCurrentAddr(v);
885 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
886 }
drh3c84ddf2008-01-09 02:15:38 +0000887 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000888 }
drh4cbdda92006-06-14 19:00:20 +0000889 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000890 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000891 }else{
drh04adf412008-01-08 18:57:50 +0000892 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000893 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000894 }
drh6a288a32008-01-07 19:20:24 +0000895 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000896
danielk1977c3f9bad2002-05-15 08:30:12 +0000897 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000898 ** with the first column.
899 */
danielk1977034ca142007-06-26 10:38:54 +0000900 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000901 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000902 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000903 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000904 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000905 ** Whenever this column is read, the record number will be substituted
906 ** in its place. So will fill this column with a NULL to avoid
907 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000908 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000909 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000910 }
911 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000912 if( IsHiddenColumn(&pTab->aCol[i]) ){
913 assert( IsVirtual(pTab) );
914 j = -1;
915 nHidden++;
916 }else{
917 j = i - nHidden;
918 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000919 }else{
drh9adf9ac2002-05-15 11:44:13 +0000920 for(j=0; j<pColumn->nId; j++){
921 if( pColumn->a[j].idx==i ) break;
922 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000923 }
danielk1977034ca142007-06-26 10:38:54 +0000924 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000925 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000926 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000927 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000928 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000929 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000930 }else{
danielk1977287fb612008-01-04 19:10:28 +0000931 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000932 }
drhbed86902000-06-02 13:27:59 +0000933 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000934
935 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000936 ** do the insertion.
937 */
drh4cbdda92006-06-14 19:00:20 +0000938#ifndef SQLITE_OMIT_VIRTUALTABLE
939 if( IsVirtual(pTab) ){
drh4f3dd152008-04-28 18:46:43 +0000940 sqlite3VtabMakeWritable(pParse, pTab);
drh6a288a32008-01-07 19:20:24 +0000941 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000942 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000943 }else
944#endif
945 {
danielk1977de630352009-05-04 11:42:29 +0000946 int isReplace; /* Set to true if constraints may cause a replace */
947 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
948 keyColumn>=0, 0, onError, endOfLoop, &isReplace
drh04adf412008-01-08 18:57:50 +0000949 );
950 sqlite3CompleteInsertion(
danielk1977de630352009-05-04 11:42:29 +0000951 pParse, pTab, baseCur, regIns, aRegIdx, 0,
952 (tmask&TRIGGER_AFTER) ? newIdx : -1, appendFlag, isReplace==0
953 );
drh4cbdda92006-06-14 19:00:20 +0000954 }
drh5cf590c2003-04-24 01:45:04 +0000955 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000956
drh5cf590c2003-04-24 01:45:04 +0000957 /* Update the count of rows that are inserted
958 */
959 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000960 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000961 }
drh1ccde152000-06-17 13:12:39 +0000962
danielk19772f886d12009-02-28 10:47:41 +0000963 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000964 /* Code AFTER triggers */
danielk19772f886d12009-02-28 10:47:41 +0000965 if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
966 pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000967 goto insert_cleanup;
968 }
drh1bee3d72001-10-15 00:44:35 +0000969 }
970
drhe00ee6e2008-06-20 15:24:01 +0000971 /* The bottom of the main insertion loop, if the data source
972 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:12 +0000973 */
danielk19774adee202004-05-08 08:23:19 +0000974 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000975 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000976 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
977 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:36 +0000978 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:58 +0000979 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000980 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
981 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:26 +0000982 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000983
danielk1977e448dc42008-01-02 11:50:51 +0000984 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000985 /* Close all tables opened */
drh2eb95372008-06-06 15:04:36 +0000986 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +0000987 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh2eb95372008-06-06 15:04:36 +0000988 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +0000989 }
drhcce7d172000-05-31 15:34:51 +0000990 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000991
drhf3388142004-11-13 03:48:06 +0000992 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000993 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000994 ** table.
drh2958a4e2004-11-12 03:56:15 +0000995 */
drh6a288a32008-01-07 19:20:24 +0000996 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000997
drh1bee3d72001-10-15 00:44:35 +0000998 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000999 ** Return the number of rows inserted. If this routine is
1000 ** generating code because of a call to sqlite3NestedParse(), do not
1001 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +00001002 */
danielk1977cc6bd382005-01-10 02:48:49 +00001003 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +00001004 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +00001005 sqlite3VdbeSetNumCols(v, 1);
danielk197710fb7492008-10-31 10:53:22 +00001006 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
drh1bee3d72001-10-15 00:44:35 +00001007 }
drhcce7d172000-05-31 15:34:51 +00001008
1009insert_cleanup:
drh633e6d52008-07-28 19:34:53 +00001010 sqlite3SrcListDelete(db, pTabList);
1011 sqlite3ExprListDelete(db, pList);
1012 sqlite3SelectDelete(db, pSelect);
1013 sqlite3IdListDelete(db, pColumn);
1014 sqlite3DbFree(db, aRegIdx);
drhcce7d172000-05-31 15:34:51 +00001015}
drh9cfcf5d2002-01-29 18:41:24 +00001016
drh9cfcf5d2002-01-29 18:41:24 +00001017/*
drh6a288a32008-01-07 19:20:24 +00001018** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +00001019**
drh04adf412008-01-08 18:57:50 +00001020** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +00001021**
drhf0863fe2005-06-12 21:35:51 +00001022** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +00001023** value is omitted unless we are doing an UPDATE that involves a
drha05a7222008-01-19 03:35:58 +00001024** change to the record number or writing to a virtual table.
drh0ca3e242002-01-29 23:07:02 +00001025**
drhf0863fe2005-06-12 21:35:51 +00001026** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +00001027**
1028** 3. The data in the first column of the entry after the update.
1029**
1030** i. Data from middle columns...
1031**
1032** N. The data in the last column of the entry after the update.
1033**
drh04adf412008-01-08 18:57:50 +00001034** The regRowid parameter is the index of the register containing (2).
1035**
drhf0863fe2005-06-12 21:35:51 +00001036** The old rowid shown as entry (1) above is omitted unless both isUpdate
1037** and rowidChng are 1. isUpdate is true for UPDATEs and false for
drha05a7222008-01-19 03:35:58 +00001038** INSERTs. RowidChng means that the new rowid is explicitly specified by
1039** the update or insert statement. If rowidChng is false, it means that
1040** the rowid is computed automatically in an insert or that the rowid value
1041** is not modified by the update.
drh0ca3e242002-01-29 23:07:02 +00001042**
drhaa9b8962008-01-08 02:57:55 +00001043** The code generated by this routine store new index entries into
1044** registers identified by aRegIdx[]. No index entry is created for
1045** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1046** the same as the order of indices on the linked list of indices
1047** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +00001048**
1049** This routine also generates code to check constraints. NOT NULL,
1050** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +00001051** then the appropriate action is performed. There are five possible
1052** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +00001053**
1054** Constraint type Action What Happens
1055** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +00001056** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +00001057** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +00001058** return code of SQLITE_CONSTRAINT.
1059**
drh1c928532002-01-31 15:54:21 +00001060** any ABORT Back out changes from the current command
1061** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +00001062** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +00001063** with SQLITE_CONSTRAINT.
1064**
1065** any FAIL Sqlite_exec() returns immediately with a
1066** return code of SQLITE_CONSTRAINT. The
1067** transaction is not rolled back and any
1068** prior changes are retained.
1069**
drh9cfcf5d2002-01-29 18:41:24 +00001070** any IGNORE The record number and data is popped from
1071** the stack and there is an immediate jump
1072** to label ignoreDest.
1073**
1074** NOT NULL REPLACE The NULL value is replace by the default
1075** value for that column. If the default value
1076** is NULL, the action is the same as ABORT.
1077**
1078** UNIQUE REPLACE The other row that conflicts with the row
1079** being inserted is removed.
1080**
1081** CHECK REPLACE Illegal. The results in an exception.
1082**
drh1c928532002-01-31 15:54:21 +00001083** Which action to take is determined by the overrideError parameter.
1084** Or if overrideError==OE_Default, then the pParse->onError parameter
1085** is used. Or if pParse->onError==OE_Default then the onError value
1086** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001087**
drhaaab5722002-02-19 13:39:21 +00001088** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +00001089** cursor number "baseCur". All indices of pTab must also have open
1090** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001091** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001092** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001093*/
danielk19774adee202004-05-08 08:23:19 +00001094void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001095 Parse *pParse, /* The parser context */
1096 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001097 int baseCur, /* Index of a read/write cursor pointing at pTab */
1098 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001099 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drha05a7222008-01-19 03:35:58 +00001100 int rowidChng, /* True if the rowid might collide with existing entry */
drhb419a922002-01-30 16:17:23 +00001101 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001102 int overrideError, /* Override onError to this if not OE_Default */
danielk1977de630352009-05-04 11:42:29 +00001103 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1104 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
drh9cfcf5d2002-01-29 18:41:24 +00001105){
drh1b7ecbb2009-05-03 01:00:59 +00001106 int i; /* loop counter */
1107 Vdbe *v; /* VDBE under constrution */
1108 int nCol; /* Number of columns */
1109 int onError; /* Conflict resolution strategy */
drh1bd10f82008-12-10 21:19:56 +00001110 int j1; /* Addresss of jump instruction */
1111 int j2 = 0, j3; /* Addresses of jump instructions */
drh04adf412008-01-08 18:57:50 +00001112 int regData; /* Register containing first data column */
drh1b7ecbb2009-05-03 01:00:59 +00001113 int iCur; /* Table cursor number */
1114 Index *pIdx; /* Pointer to one of the indices */
1115 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
drhf0863fe2005-06-12 21:35:51 +00001116 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001117
danielk19774adee202004-05-08 08:23:19 +00001118 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001119 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001120 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001121 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001122 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001123
drhaa9b8962008-01-08 02:57:55 +00001124
drh9cfcf5d2002-01-29 18:41:24 +00001125 /* Test all NOT NULL constraints.
1126 */
1127 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001128 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001129 continue;
1130 }
drh9cfcf5d2002-01-29 18:41:24 +00001131 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001132 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001133 if( overrideError!=OE_Default ){
1134 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001135 }else if( onError==OE_Default ){
1136 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001137 }
danielk19777977a172004-11-09 12:44:37 +00001138 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001139 onError = OE_Abort;
1140 }
danielk1977b84f96f2005-01-20 11:32:23 +00001141 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1142 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001143 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001144 case OE_Rollback:
1145 case OE_Abort:
1146 case OE_Fail: {
drhf089aa42008-07-08 19:34:06 +00001147 char *zMsg;
drh5053a792009-02-20 03:02:23 +00001148 j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1149 SQLITE_CONSTRAINT, onError, regData+i);
drhf089aa42008-07-08 19:34:06 +00001150 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1151 pTab->zName, pTab->aCol[i].zName);
drh66a51672008-01-03 00:01:23 +00001152 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001153 break;
1154 }
1155 case OE_Ignore: {
drh5053a792009-02-20 03:02:23 +00001156 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001157 break;
1158 }
drh098d1682009-05-02 15:46:46 +00001159 default: {
1160 assert( onError==OE_Replace );
drh5053a792009-02-20 03:02:23 +00001161 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
drh04adf412008-01-08 18:57:50 +00001162 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh5053a792009-02-20 03:02:23 +00001163 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001164 break;
1165 }
drh9cfcf5d2002-01-29 18:41:24 +00001166 }
1167 }
1168
1169 /* Test all CHECK constraints
1170 */
drhffe07b22005-11-03 00:41:17 +00001171#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001172 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001173 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001174 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001175 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001176 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001177 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001178 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001179 }else{
drh66a51672008-01-03 00:01:23 +00001180 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001181 }
drhffe07b22005-11-03 00:41:17 +00001182 sqlite3VdbeResolveLabel(v, allOk);
1183 }
1184#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001185
drh0bd1f4e2002-06-06 18:54:39 +00001186 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1187 ** of the new record does not previously exist. Except, if this
1188 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001189 */
drhf0863fe2005-06-12 21:35:51 +00001190 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001191 onError = pTab->keyConf;
1192 if( overrideError!=OE_Default ){
1193 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001194 }else if( onError==OE_Default ){
1195 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001196 }
drha0217ba2003-06-01 01:10:33 +00001197
drh60a713c2008-01-21 16:22:45 +00001198 if( onError!=OE_Replace || pTab->pIndex ){
drha05a7222008-01-19 03:35:58 +00001199 if( isUpdate ){
1200 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
drh79b0c952002-05-21 12:56:43 +00001201 }
drha05a7222008-01-19 03:35:58 +00001202 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1203 switch( onError ){
1204 default: {
1205 onError = OE_Abort;
1206 /* Fall thru into the next case */
drh5383ae52003-06-04 12:23:30 +00001207 }
drha05a7222008-01-19 03:35:58 +00001208 case OE_Rollback:
1209 case OE_Abort:
1210 case OE_Fail: {
1211 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1212 "PRIMARY KEY must be unique", P4_STATIC);
1213 break;
1214 }
1215 case OE_Replace: {
1216 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1217 seenReplace = 1;
1218 break;
1219 }
1220 case OE_Ignore: {
1221 assert( seenReplace==0 );
1222 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1223 break;
1224 }
drh0ca3e242002-01-29 23:07:02 +00001225 }
drha05a7222008-01-19 03:35:58 +00001226 sqlite3VdbeJumpHere(v, j3);
1227 if( isUpdate ){
1228 sqlite3VdbeJumpHere(v, j2);
drh5383ae52003-06-04 12:23:30 +00001229 }
1230 }
drh0ca3e242002-01-29 23:07:02 +00001231 }
drh0bd1f4e2002-06-06 18:54:39 +00001232
1233 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1234 ** index and making sure that duplicate entries do not already exist.
1235 ** Add the new records to the indices as we go.
1236 */
drhb2fe7d82003-04-20 17:29:23 +00001237 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001238 int regIdx;
1239 int regR;
1240
drhaa9b8962008-01-08 02:57:55 +00001241 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001242
1243 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001244 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001245 for(i=0; i<pIdx->nColumn; i++){
1246 int idx = pIdx->aiColumn[i];
1247 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001248 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001249 }else{
drh2d401ab2008-01-10 23:50:11 +00001250 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001251 }
1252 }
drh2d401ab2008-01-10 23:50:11 +00001253 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh1db639c2008-01-17 02:36:28 +00001254 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001255 sqlite3IndexAffinityStr(v, pIdx);
drhda250ea2008-04-01 05:07:14 +00001256 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001257
1258 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001259 onError = pIdx->onError;
danielk1977de630352009-05-04 11:42:29 +00001260 if( onError==OE_None ){
1261 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1262 continue; /* pIdx is not a UNIQUE index */
1263 }
drh9cfcf5d2002-01-29 18:41:24 +00001264 if( overrideError!=OE_Default ){
1265 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001266 }else if( onError==OE_Default ){
1267 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001268 }
drh5383ae52003-06-04 12:23:30 +00001269 if( seenReplace ){
1270 if( onError==OE_Ignore ) onError = OE_Replace;
1271 else if( onError==OE_Fail ) onError = OE_Abort;
1272 }
1273
drhb2fe7d82003-04-20 17:29:23 +00001274
1275 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001276 regR = sqlite3GetTempReg(pParse);
1277 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
1278 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
danielk1977de630352009-05-04 11:42:29 +00001279 regR, SQLITE_INT_TO_PTR(regIdx),
mlcreecha9e852b2008-03-06 09:58:50 +00001280 P4_INT32);
danielk1977de630352009-05-04 11:42:29 +00001281 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001282
1283 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001284 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1285 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001286 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001287 case OE_Rollback:
1288 case OE_Abort:
1289 case OE_Fail: {
drh098d1682009-05-02 15:46:46 +00001290 int j;
1291 StrAccum errMsg;
1292 const char *zSep;
1293 char *zErr;
1294
1295 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
1296 errMsg.db = pParse->db;
1297 zSep = pIdx->nColumn>1 ? "columns " : "column ";
1298 for(j=0; j<pIdx->nColumn; j++){
drh37ed48e2003-08-05 13:13:38 +00001299 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
drh098d1682009-05-02 15:46:46 +00001300 sqlite3StrAccumAppend(&errMsg, zSep, -1);
1301 zSep = ", ";
1302 sqlite3StrAccumAppend(&errMsg, zCol, -1);
drh37ed48e2003-08-05 13:13:38 +00001303 }
drh098d1682009-05-02 15:46:46 +00001304 sqlite3StrAccumAppend(&errMsg,
1305 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
1306 zErr = sqlite3StrAccumFinish(&errMsg);
1307 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErr, 0);
1308 sqlite3DbFree(errMsg.db, zErr);
drh9cfcf5d2002-01-29 18:41:24 +00001309 break;
1310 }
1311 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001312 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001313 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001314 break;
1315 }
drh098d1682009-05-02 15:46:46 +00001316 default: {
1317 assert( onError==OE_Replace );
drh2d401ab2008-01-10 23:50:11 +00001318 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
drh0ca3e242002-01-29 23:07:02 +00001319 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001320 break;
1321 }
drh9cfcf5d2002-01-29 18:41:24 +00001322 }
drh2d401ab2008-01-10 23:50:11 +00001323 sqlite3VdbeJumpHere(v, j3);
1324 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001325 }
danielk1977de630352009-05-04 11:42:29 +00001326
1327 if( pbMayReplace ){
1328 *pbMayReplace = seenReplace;
1329 }
drh9cfcf5d2002-01-29 18:41:24 +00001330}
drh0ca3e242002-01-29 23:07:02 +00001331
1332/*
1333** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001334** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001335** A consecutive range of registers starting at regRowid contains the
1336** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001337**
drhb419a922002-01-30 16:17:23 +00001338** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001339** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001340*/
danielk19774adee202004-05-08 08:23:19 +00001341void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001342 Parse *pParse, /* The parser context */
1343 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001344 int baseCur, /* Index of a read/write cursor pointing at pTab */
1345 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001346 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh70ce3f02003-04-15 19:22:22 +00001347 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001348 int newIdx, /* Index of NEW table for triggers. -1 if none */
danielk1977de630352009-05-04 11:42:29 +00001349 int appendBias, /* True if this is likely to be an append */
1350 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
drh0ca3e242002-01-29 23:07:02 +00001351){
1352 int i;
1353 Vdbe *v;
1354 int nIdx;
1355 Index *pIdx;
drh1bd10f82008-12-10 21:19:56 +00001356 u8 pik_flags;
drh04adf412008-01-08 18:57:50 +00001357 int regData;
drhb7654112008-01-12 12:48:07 +00001358 int regRec;
drh0ca3e242002-01-29 23:07:02 +00001359
danielk19774adee202004-05-08 08:23:19 +00001360 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001361 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001362 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001363 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1364 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001365 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001366 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
danielk1977de630352009-05-04 11:42:29 +00001367 if( useSeekResult ){
1368 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1369 }
drh0ca3e242002-01-29 23:07:02 +00001370 }
drh04adf412008-01-08 18:57:50 +00001371 regData = regRowid + 1;
drhb7654112008-01-12 12:48:07 +00001372 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001373 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +00001374 sqlite3TableAffinityStr(v, pTab);
drhda250ea2008-04-01 05:07:14 +00001375 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
danielk1977b84f96f2005-01-20 11:32:23 +00001376#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001377 if( newIdx>=0 ){
drhb7654112008-01-12 12:48:07 +00001378 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
drh70ce3f02003-04-15 19:22:22 +00001379 }
danielk1977b84f96f2005-01-20 11:32:23 +00001380#endif
drh4794f732004-11-05 17:17:50 +00001381 if( pParse->nested ){
1382 pik_flags = 0;
1383 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001384 pik_flags = OPFLAG_NCHANGE;
1385 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001386 }
drhe4d90812007-03-29 05:51:49 +00001387 if( appendBias ){
1388 pik_flags |= OPFLAG_APPEND;
1389 }
danielk1977de630352009-05-04 11:42:29 +00001390 if( useSeekResult ){
1391 pik_flags |= OPFLAG_USESEEKRESULT;
1392 }
drhb7654112008-01-12 12:48:07 +00001393 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
danielk197794eb6a12005-12-15 15:22:08 +00001394 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001395 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001396 }
drhb7654112008-01-12 12:48:07 +00001397 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001398}
drhcd446902004-02-24 01:05:31 +00001399
1400/*
drh290c1942004-08-21 17:54:45 +00001401** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001402** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001403** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001404**
1405** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001406*/
drhaa9b8962008-01-08 02:57:55 +00001407int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001408 Parse *pParse, /* Parsing context */
1409 Table *pTab, /* Table to be opened */
drhdfe88ec2008-11-03 20:55:06 +00001410 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001411 int op /* OP_OpenRead or OP_OpenWrite */
1412){
drhcd446902004-02-24 01:05:31 +00001413 int i;
drh4cbdda92006-06-14 19:00:20 +00001414 int iDb;
drhcd446902004-02-24 01:05:31 +00001415 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001416 Vdbe *v;
1417
drhaa9b8962008-01-08 02:57:55 +00001418 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001419 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1420 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001421 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001422 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001423 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001424 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001425 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001426 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001427 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001428 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001429 }
drh1b7ecbb2009-05-03 01:00:59 +00001430 if( pParse->nTab<baseCur+i ){
drh04adf412008-01-08 18:57:50 +00001431 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001432 }
drhaa9b8962008-01-08 02:57:55 +00001433 return i-1;
drhcd446902004-02-24 01:05:31 +00001434}
drh9d9cf222007-02-13 15:01:11 +00001435
drh91c58e22007-03-27 12:04:04 +00001436
1437#ifdef SQLITE_TEST
1438/*
1439** The following global variable is incremented whenever the
1440** transfer optimization is used. This is used for testing
1441** purposes only - to make sure the transfer optimization really
1442** is happening when it is suppose to.
1443*/
1444int sqlite3_xferopt_count;
1445#endif /* SQLITE_TEST */
1446
1447
drh9d9cf222007-02-13 15:01:11 +00001448#ifndef SQLITE_OMIT_XFER_OPT
1449/*
1450** Check to collation names to see if they are compatible.
1451*/
1452static int xferCompatibleCollation(const char *z1, const char *z2){
1453 if( z1==0 ){
1454 return z2==0;
1455 }
1456 if( z2==0 ){
1457 return 0;
1458 }
1459 return sqlite3StrICmp(z1, z2)==0;
1460}
1461
1462
1463/*
1464** Check to see if index pSrc is compatible as a source of data
1465** for index pDest in an insert transfer optimization. The rules
1466** for a compatible index:
1467**
1468** * The index is over the same set of columns
1469** * The same DESC and ASC markings occurs on all columns
1470** * The same onError processing (OE_Abort, OE_Ignore, etc)
1471** * The same collating sequence on each column
1472*/
1473static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1474 int i;
1475 assert( pDest && pSrc );
1476 assert( pDest->pTable!=pSrc->pTable );
1477 if( pDest->nColumn!=pSrc->nColumn ){
1478 return 0; /* Different number of columns */
1479 }
1480 if( pDest->onError!=pSrc->onError ){
1481 return 0; /* Different conflict resolution strategies */
1482 }
1483 for(i=0; i<pSrc->nColumn; i++){
1484 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1485 return 0; /* Different columns indexed */
1486 }
1487 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1488 return 0; /* Different sort orders */
1489 }
drh3f6e7812009-05-02 00:28:19 +00001490 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
drh60a713c2008-01-21 16:22:45 +00001491 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001492 }
1493 }
1494
1495 /* If no test above fails then the indices must be compatible */
1496 return 1;
1497}
1498
1499/*
1500** Attempt the transfer optimization on INSERTs of the form
1501**
1502** INSERT INTO tab1 SELECT * FROM tab2;
1503**
1504** This optimization is only attempted if
1505**
1506** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001507** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001508**
1509** (2) tab1 and tab2 are different tables
1510**
1511** (3) There must be no triggers on tab1
1512**
1513** (4) The result set of the SELECT statement is "*"
1514**
1515** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1516** or LIMIT clause.
1517**
1518** (6) The SELECT statement is a simple (not a compound) select that
1519** contains only tab2 in its FROM clause
1520**
1521** This method for implementing the INSERT transfers raw records from
1522** tab2 over to tab1. The columns are not decoded. Raw records from
1523** the indices of tab2 are transfered to tab1 as well. In so doing,
1524** the resulting tab1 has much less fragmentation.
1525**
1526** This routine returns TRUE if the optimization is attempted. If any
1527** of the conditions above fail so that the optimization should not
1528** be attempted, then this routine returns FALSE.
1529*/
1530static int xferOptimization(
1531 Parse *pParse, /* Parser context */
1532 Table *pDest, /* The table we are inserting into */
1533 Select *pSelect, /* A SELECT statement to use as the data source */
1534 int onError, /* How to handle constraint errors */
1535 int iDbDest /* The database of pDest */
1536){
1537 ExprList *pEList; /* The result set of the SELECT */
1538 Table *pSrc; /* The table in the FROM clause of SELECT */
1539 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1540 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1541 int i; /* Loop counter */
1542 int iDbSrc; /* The database of pSrc */
1543 int iSrc, iDest; /* Cursors from source and destination */
1544 int addr1, addr2; /* Loop addresses */
1545 int emptyDestTest; /* Address of test for empty pDest */
1546 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001547 Vdbe *v; /* The VDBE we are building */
1548 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001549 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001550 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001551 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001552
1553 if( pSelect==0 ){
1554 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1555 }
danielk19772f886d12009-02-28 10:47:41 +00001556 if( sqlite3TriggerList(pParse, pDest) ){
drh9d9cf222007-02-13 15:01:11 +00001557 return 0; /* tab1 must not have triggers */
1558 }
1559#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001560 if( pDest->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001561 return 0; /* tab1 must not be a virtual table */
1562 }
1563#endif
1564 if( onError==OE_Default ){
1565 onError = OE_Abort;
1566 }
1567 if( onError!=OE_Abort && onError!=OE_Rollback ){
1568 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1569 }
danielk19775ce240a2007-09-03 17:30:06 +00001570 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001571 if( pSelect->pSrc->nSrc!=1 ){
1572 return 0; /* FROM clause must have exactly one term */
1573 }
1574 if( pSelect->pSrc->a[0].pSelect ){
1575 return 0; /* FROM clause cannot contain a subquery */
1576 }
1577 if( pSelect->pWhere ){
1578 return 0; /* SELECT may not have a WHERE clause */
1579 }
1580 if( pSelect->pOrderBy ){
1581 return 0; /* SELECT may not have an ORDER BY clause */
1582 }
drh8103b7d2007-02-24 13:23:51 +00001583 /* Do not need to test for a HAVING clause. If HAVING is present but
1584 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001585 if( pSelect->pGroupBy ){
1586 return 0; /* SELECT may not have a GROUP BY clause */
1587 }
1588 if( pSelect->pLimit ){
1589 return 0; /* SELECT may not have a LIMIT clause */
1590 }
drh8103b7d2007-02-24 13:23:51 +00001591 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001592 if( pSelect->pPrior ){
1593 return 0; /* SELECT may not be a compound query */
1594 }
drh7d10d5a2008-08-20 16:35:10 +00001595 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:11 +00001596 return 0; /* SELECT may not be DISTINCT */
1597 }
1598 pEList = pSelect->pEList;
1599 assert( pEList!=0 );
1600 if( pEList->nExpr!=1 ){
1601 return 0; /* The result set must have exactly one column */
1602 }
1603 assert( pEList->a[0].pExpr );
1604 if( pEList->a[0].pExpr->op!=TK_ALL ){
1605 return 0; /* The result set must be the special operator "*" */
1606 }
1607
1608 /* At this point we have established that the statement is of the
1609 ** correct syntactic form to participate in this optimization. Now
1610 ** we have to check the semantics.
1611 */
1612 pItem = pSelect->pSrc->a;
drhca424112008-01-25 15:04:48 +00001613 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
drh9d9cf222007-02-13 15:01:11 +00001614 if( pSrc==0 ){
1615 return 0; /* FROM clause does not contain a real table */
1616 }
1617 if( pSrc==pDest ){
1618 return 0; /* tab1 and tab2 may not be the same table */
1619 }
1620#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001621 if( pSrc->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001622 return 0; /* tab2 must not be a virtual table */
1623 }
1624#endif
1625 if( pSrc->pSelect ){
1626 return 0; /* tab2 may not be a view */
1627 }
1628 if( pDest->nCol!=pSrc->nCol ){
1629 return 0; /* Number of columns must be the same in tab1 and tab2 */
1630 }
1631 if( pDest->iPKey!=pSrc->iPKey ){
1632 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1633 }
1634 for(i=0; i<pDest->nCol; i++){
1635 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1636 return 0; /* Affinity must be the same on all columns */
1637 }
1638 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1639 return 0; /* Collating sequence must be the same on all columns */
1640 }
1641 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1642 return 0; /* tab2 must be NOT NULL if tab1 is */
1643 }
1644 }
1645 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001646 if( pDestIdx->onError!=OE_None ){
1647 destHasUniqueIdx = 1;
1648 }
drh9d9cf222007-02-13 15:01:11 +00001649 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1650 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1651 }
1652 if( pSrcIdx==0 ){
1653 return 0; /* pDestIdx has no corresponding index in pSrc */
1654 }
1655 }
drh7fc2f412007-03-29 00:08:24 +00001656#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001657 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001658 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1659 }
drh7fc2f412007-03-29 00:08:24 +00001660#endif
drh9d9cf222007-02-13 15:01:11 +00001661
1662 /* If we get this far, it means either:
1663 **
1664 ** * We can always do the transfer if the table contains an
1665 ** an integer primary key
1666 **
1667 ** * We can conditionally do the transfer if the destination
1668 ** table is empty.
1669 */
drhdd735212007-02-24 13:53:05 +00001670#ifdef SQLITE_TEST
1671 sqlite3_xferopt_count++;
1672#endif
drh9d9cf222007-02-13 15:01:11 +00001673 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1674 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001675 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001676 iSrc = pParse->nTab++;
1677 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001678 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001679 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001680 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001681 /* If tables do not have an INTEGER PRIMARY KEY and there
1682 ** are indices to be copied and the destination is not empty,
1683 ** we have to disallow the transfer optimization because the
1684 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001685 **
1686 ** Or if the destination has a UNIQUE index and is not empty,
1687 ** we also disallow the transfer optimization because we cannot
1688 ** insure that all entries in the union of DEST and SRC will be
1689 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001690 */
drh66a51672008-01-03 00:01:23 +00001691 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1692 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001693 sqlite3VdbeJumpHere(v, addr1);
1694 }else{
1695 emptyDestTest = 0;
1696 }
1697 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001698 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001699 regData = sqlite3GetTempReg(pParse);
1700 regRowid = sqlite3GetTempReg(pParse);
drh42242de2007-03-29 13:35:35 +00001701 if( pDest->iPKey>=0 ){
drhb7654112008-01-12 12:48:07 +00001702 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1703 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
drh66a51672008-01-03 00:01:23 +00001704 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1705 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001706 sqlite3VdbeJumpHere(v, addr2);
drhb7654112008-01-12 12:48:07 +00001707 autoIncStep(pParse, regAutoinc, regRowid);
drhbd36ba62007-03-31 13:00:26 +00001708 }else if( pDest->pIndex==0 ){
drhb7654112008-01-12 12:48:07 +00001709 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
drh95bad4c2007-03-28 18:04:10 +00001710 }else{
drhb7654112008-01-12 12:48:07 +00001711 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
drh7d10d5a2008-08-20 16:35:10 +00001712 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
drh95bad4c2007-03-28 18:04:10 +00001713 }
drhb7654112008-01-12 12:48:07 +00001714 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1715 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1716 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
danielk19771f4aa332008-01-03 09:51:55 +00001717 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001718 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001719 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001720 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh1b7ecbb2009-05-03 01:00:59 +00001721 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
drh9d9cf222007-02-13 15:01:11 +00001722 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1723 }
1724 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001725 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1726 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001727 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001728 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1729 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001730 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001731 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001732 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001733 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001734 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001735 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001736 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1737 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh66a51672008-01-03 00:01:23 +00001738 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001739 sqlite3VdbeJumpHere(v, addr1);
1740 }
1741 sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00001742 sqlite3ReleaseTempReg(pParse, regRowid);
1743 sqlite3ReleaseTempReg(pParse, regData);
drh66a51672008-01-03 00:01:23 +00001744 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1745 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001746 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001747 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001748 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001749 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001750 return 0;
1751 }else{
1752 return 1;
1753 }
1754}
1755#endif /* SQLITE_OMIT_XFER_OPT */
drhf39d9582008-03-19 20:42:13 +00001756
1757/* Make sure "isView" gets undefined in case this file becomes part of
1758** the amalgamation - so that subsequent files do not see isView as a
1759** macro. */
1760#undef isView