blob: bada466542b14cd72b6721bb9e0dafe1445a02ed [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**
drhf089aa42008-07-08 19:34:06 +000015** $Id: insert.c,v 1.245 2008/07/08 19:34:07 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
19/*
drh66a51672008-01-03 00:01:23 +000020** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000021** string for index pIdx. A column affinity string has one character
danielk19773d1bfea2004-05-14 11:00:53 +000022** for each column in the table, according to the affinity of the column:
23**
24** Character Column affinity
25** ------------------------------
drh3eda0402005-11-24 13:15:32 +000026** 'a' TEXT
27** 'b' NONE
28** 'c' NUMERIC
29** 'd' INTEGER
30** 'e' REAL
drh2d401ab2008-01-10 23:50:11 +000031**
32** An extra 'b' is appended to the end of the string to cover the
33** rowid that appears as the last column in every index.
danielk19773d1bfea2004-05-14 11:00:53 +000034*/
danielk1977a37cdde2004-05-16 11:15:36 +000035void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
36 if( !pIdx->zColAff ){
danielk1977e014a832004-05-17 10:48:57 +000037 /* The first time a column affinity string for a particular index is
danielk1977a37cdde2004-05-16 11:15:36 +000038 ** required, it is allocated and populated here. It is then stored as
danielk1977e014a832004-05-17 10:48:57 +000039 ** a member of the Index structure for subsequent use.
danielk1977a37cdde2004-05-16 11:15:36 +000040 **
41 ** The column affinity string will eventually be deleted by
danielk1977e014a832004-05-17 10:48:57 +000042 ** sqliteDeleteIndex() when the Index structure itself is cleaned
danielk1977a37cdde2004-05-16 11:15:36 +000043 ** up.
44 */
45 int n;
46 Table *pTab = pIdx->pTable;
drhabb6fca2007-08-16 12:24:01 +000047 sqlite3 *db = sqlite3VdbeDb(v);
drh5c070532008-04-11 15:36:03 +000048 pIdx->zColAff = (char *)sqlite3DbMallocRaw(db, pIdx->nColumn+2);
danielk1977a37cdde2004-05-16 11:15:36 +000049 if( !pIdx->zColAff ){
50 return;
51 }
52 for(n=0; n<pIdx->nColumn; n++){
53 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
54 }
drh2d401ab2008-01-10 23:50:11 +000055 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
56 pIdx->zColAff[n] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +000057 }
danielk19773d1bfea2004-05-14 11:00:53 +000058
drh66a51672008-01-03 00:01:23 +000059 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000060}
61
62/*
drh66a51672008-01-03 00:01:23 +000063** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000064** string for table pTab. A column affinity string has one character
65** for each column indexed by the index, according to the affinity of the
66** column:
67**
68** Character Column affinity
69** ------------------------------
drh3eda0402005-11-24 13:15:32 +000070** 'a' TEXT
71** 'b' NONE
72** 'c' NUMERIC
73** 'd' INTEGER
74** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000075*/
76void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000077 /* The first time a column affinity string for a particular table
78 ** is required, it is allocated and populated here. It is then
79 ** stored as a member of the Table structure for subsequent use.
80 **
81 ** The column affinity string will eventually be deleted by
82 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
83 */
84 if( !pTab->zColAff ){
85 char *zColAff;
86 int i;
drhabb6fca2007-08-16 12:24:01 +000087 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +000088
drh5c070532008-04-11 15:36:03 +000089 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000090 if( !zColAff ){
danielk1977a37cdde2004-05-16 11:15:36 +000091 return;
danielk19773d1bfea2004-05-14 11:00:53 +000092 }
93
94 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000095 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000096 }
97 zColAff[pTab->nCol] = '\0';
98
99 pTab->zColAff = zColAff;
100 }
101
drh66a51672008-01-03 00:01:23 +0000102 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +0000103}
104
danielk19774d887782005-02-08 08:42:27 +0000105/*
drh48d11782007-11-23 15:02:19 +0000106** Return non-zero if the table pTab in database iDb or any of its indices
107** have been opened at any point in the VDBE program beginning at location
108** iStartAddr throught the end of the program. This is used to see if
109** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
110** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000111*/
drh48d11782007-11-23 15:02:19 +0000112static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000113 int i;
drh48d11782007-11-23 15:02:19 +0000114 int iEnd = sqlite3VdbeCurrentAddr(v);
115 for(i=iStartAddr; i<iEnd; i++){
116 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000117 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000118 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
119 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000120 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000121 if( tnum==pTab->tnum ){
122 return 1;
123 }
124 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
125 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000126 return 1;
127 }
drh48d11782007-11-23 15:02:19 +0000128 }
129 }
drh543165e2007-11-27 14:46:41 +0000130#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19772dca4ac2008-01-03 11:50:29 +0000131 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
132 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000133 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000134 return 1;
danielk19774d887782005-02-08 08:42:27 +0000135 }
drh543165e2007-11-27 14:46:41 +0000136#endif
danielk19774d887782005-02-08 08:42:27 +0000137 }
138 return 0;
139}
danielk19773d1bfea2004-05-14 11:00:53 +0000140
drh9d9cf222007-02-13 15:01:11 +0000141#ifndef SQLITE_OMIT_AUTOINCREMENT
142/*
143** Write out code to initialize the autoincrement logic. This code
144** looks up the current autoincrement value in the sqlite_sequence
drh6a288a32008-01-07 19:20:24 +0000145** table and stores that value in a register. Code generated by
146** autoIncStep() will keep that register holding the largest
drh9d9cf222007-02-13 15:01:11 +0000147** rowid value. Code generated by autoIncEnd() will write the new
148** largest value of the counter back into the sqlite_sequence table.
149**
150** This routine returns the index of the mem[] cell that contains
151** the maximum rowid counter.
152**
drh6a288a32008-01-07 19:20:24 +0000153** Three consecutive registers are allocated by this routine. The
154** first two hold the name of the target table and the maximum rowid
155** inserted into the target table, respectively.
156** The third holds the rowid in sqlite_sequence where we will
157** write back the revised maximum rowid. This routine returns the
158** index of the second of these three registers.
drh9d9cf222007-02-13 15:01:11 +0000159*/
160static int autoIncBegin(
161 Parse *pParse, /* Parsing context */
162 int iDb, /* Index of the database holding pTab */
163 Table *pTab /* The table we are writing to */
164){
drh6a288a32008-01-07 19:20:24 +0000165 int memId = 0; /* Register holding maximum rowid */
drh9d9cf222007-02-13 15:01:11 +0000166 if( pTab->autoInc ){
167 Vdbe *v = pParse->pVdbe;
168 Db *pDb = &pParse->db->aDb[iDb];
169 int iCur = pParse->nTab;
drh6a288a32008-01-07 19:20:24 +0000170 int addr; /* Address of the top of the loop */
drh9d9cf222007-02-13 15:01:11 +0000171 assert( v );
drh6a288a32008-01-07 19:20:24 +0000172 pParse->nMem++; /* Holds name of table */
173 memId = ++pParse->nMem;
174 pParse->nMem++;
drh9d9cf222007-02-13 15:01:11 +0000175 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh6a288a32008-01-07 19:20:24 +0000176 addr = sqlite3VdbeCurrentAddr(v);
drh1db639c2008-01-17 02:36:28 +0000177 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
drhc9ded4c2008-05-29 03:20:59 +0000178 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
drh1db639c2008-01-17 02:36:28 +0000179 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
180 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
drh35573352008-01-08 23:54:25 +0000181 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh6a288a32008-01-07 19:20:24 +0000182 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
183 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
drhc9ded4c2008-05-29 03:20:59 +0000184 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
drh1db639c2008-01-17 02:36:28 +0000185 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
drhc9ded4c2008-05-29 03:20:59 +0000186 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
drh66a51672008-01-03 00:01:23 +0000187 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000188 }
189 return memId;
190}
191
192/*
193** Update the maximum rowid for an autoincrement calculation.
194**
195** This routine should be called when the top of the stack holds a
196** new rowid that is about to be inserted. If that new rowid is
197** larger than the maximum rowid in the memId memory cell, then the
198** memory cell is updated. The stack is unchanged.
199*/
drh6a288a32008-01-07 19:20:24 +0000200static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000201 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000202 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000203 }
204}
205
206/*
207** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000208** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000209** the sqlite_sequence table.
210*/
211static void autoIncEnd(
212 Parse *pParse, /* The parsing context */
213 int iDb, /* Index of the database holding pTab */
214 Table *pTab, /* Table we are inserting into */
215 int memId /* Memory cell holding the maximum rowid */
216){
217 if( pTab->autoInc ){
218 int iCur = pParse->nTab;
219 Vdbe *v = pParse->pVdbe;
220 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000221 int j1;
danielk1977a7a8e142008-02-13 18:25:27 +0000222 int iRec = ++pParse->nMem; /* Memory cell used for record */
drh6a288a32008-01-07 19:20:24 +0000223
drh9d9cf222007-02-13 15:01:11 +0000224 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000225 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000226 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
227 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
228 sqlite3VdbeJumpHere(v, j1);
danielk1977a7a8e142008-02-13 18:25:27 +0000229 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
230 sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
drh35573352008-01-08 23:54:25 +0000231 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh6a288a32008-01-07 19:20:24 +0000232 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000233 }
234}
235#else
236/*
237** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
238** above are all no-ops
239*/
240# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000241# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000242# define autoIncEnd(A,B,C,D)
243#endif /* SQLITE_OMIT_AUTOINCREMENT */
244
245
246/* Forward declaration */
247static int xferOptimization(
248 Parse *pParse, /* Parser context */
249 Table *pDest, /* The table we are inserting into */
250 Select *pSelect, /* A SELECT statement to use as the data source */
251 int onError, /* How to handle constraint errors */
252 int iDbDest /* The database of pDest */
253);
254
danielk19773d1bfea2004-05-14 11:00:53 +0000255/*
drh1ccde152000-06-17 13:12:39 +0000256** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000257**
258** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000259** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000260**
drh1ccde152000-06-17 13:12:39 +0000261** The IDLIST following the table name is always optional. If omitted,
262** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000263** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000264**
265** The pList parameter holds EXPRLIST in the first form of the INSERT
266** statement above, and pSelect is NULL. For the second form, pList is
267** NULL and pSelect is a pointer to the select statement used to generate
268** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000269**
drh9d9cf222007-02-13 15:01:11 +0000270** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000271** select with data coming from a VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01 +0000272** once straight down through. Pseudo-code follows (we call this
273** the "1st template"):
drh142e30d2002-08-28 03:00:58 +0000274**
275** open write cursor to <table> and its indices
276** puts VALUES clause expressions onto the stack
277** write the resulting record into <table>
278** cleanup
279**
drh9d9cf222007-02-13 15:01:11 +0000280** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000281**
282** INSERT INTO <table> SELECT ...
283**
drh9d9cf222007-02-13 15:01:11 +0000284** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
285** in other words if the SELECT pulls all columns from a single table
286** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
287** if <table2> and <table1> are distinct tables but have identical
288** schemas, including all the same indices, then a special optimization
289** is invoked that copies raw records from <table2> over to <table1>.
290** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01 +0000291** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000292**
293** open a write cursor to <table>
294** open read cursor on <table2>
295** transfer all records in <table2> over to <table>
296** close cursors
297** foreach index on <table>
298** open a write cursor on the <table> index
299** open a read cursor on the corresponding <table2> index
300** transfer all records from the read to the write cursors
301** close cursors
302** end foreach
303**
drhe00ee6e2008-06-20 15:24:01 +0000304** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11 +0000305** and the SELECT clause does not read from <table> at any time.
306** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000307**
drhe00ee6e2008-06-20 15:24:01 +0000308** EOF <- 0
309** X <- A
drh142e30d2002-08-28 03:00:58 +0000310** goto B
311** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000312** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000313** load values into registers R..R+n
314** yield X
drh142e30d2002-08-28 03:00:58 +0000315** end loop
316** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000317** EOF <- 1
318** yield X
drh142e30d2002-08-28 03:00:58 +0000319** goto A
drhe00ee6e2008-06-20 15:24:01 +0000320** B: open write cursor to <table> and its indices
321** C: yield X
322** if EOF goto D
323** insert the select result into <table> from R..R+n
324** goto C
drh142e30d2002-08-28 03:00:58 +0000325** D: cleanup
326**
drhe00ee6e2008-06-20 15:24:01 +0000327** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000328** values from a SELECT but the data is being inserted into a table
329** that is also read as part of the SELECT. In the third form,
330** we have to use a intermediate table to store the results of
331** the select. The template is like this:
332**
drhe00ee6e2008-06-20 15:24:01 +0000333** EOF <- 0
334** X <- A
drh142e30d2002-08-28 03:00:58 +0000335** goto B
336** A: setup for the SELECT
337** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000338** load value into register R..R+n
339** yield X
drh142e30d2002-08-28 03:00:58 +0000340** end loop
341** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000342** EOF <- 1
343** yield X
344** halt-error
345** B: open temp table
346** L: yield X
347** if EOF goto M
348** insert row from R..R+n into temp table
349** goto L
350** M: open write cursor to <table> and its indices
351** rewind temp table
352** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58 +0000353** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01 +0000354** end loop
355** D: cleanup
drhcce7d172000-05-31 15:34:51 +0000356*/
danielk19774adee202004-05-08 08:23:19 +0000357void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000358 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000359 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000360 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000361 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000362 IdList *pColumn, /* Column names corresponding to IDLIST. */
363 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000364){
drh6a288a32008-01-07 19:20:24 +0000365 sqlite3 *db; /* The main database structure */
366 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000367 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000368 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000369 int i, j, idx; /* Loop counters */
370 Vdbe *v; /* Generate code into this virtual machine */
371 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000372 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000373 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000374 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000375 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000376 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000377 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000378 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01 +0000379 int addrInsTop = 0; /* Jump to label "D" */
380 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
381 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
drh2eb95372008-06-06 15:04:36 +0000382 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24 +0000383 int newIdx = -1; /* Cursor for the NEW pseudo-table */
384 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000385 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000386 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000387
drh6a288a32008-01-07 19:20:24 +0000388 /* Register allocations */
389 int regFromSelect; /* Base register for data coming from SELECT */
390 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
391 int regRowCount = 0; /* Memory cell used for the row counter */
392 int regIns; /* Block of regs holding rowid+data being inserted */
393 int regRowid; /* registers holding insert rowid */
394 int regData; /* register holding first column to insert */
395 int regRecord; /* Holds the assemblied row record */
drhe00ee6e2008-06-20 15:24:01 +0000396 int regEof; /* Register recording end of SELECT data */
drhaa9b8962008-01-08 02:57:55 +0000397 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000398
danielk1977034ca142007-06-26 10:38:54 +0000399
drh798da522004-11-04 04:42:28 +0000400#ifndef SQLITE_OMIT_TRIGGER
401 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000402 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000403#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000404
drh17435752007-08-16 04:30:38 +0000405 db = pParse->db;
406 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000407 goto insert_cleanup;
408 }
drhdaffd0e2001-04-11 14:28:42 +0000409
drh1ccde152000-06-17 13:12:39 +0000410 /* Locate the table into which we will be inserting new information.
411 */
drh113088e2003-03-20 01:16:58 +0000412 assert( pTabList->nSrc==1 );
413 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000414 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000415 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000416 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000417 goto insert_cleanup;
418 }
danielk1977da184232006-01-05 11:34:32 +0000419 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
420 assert( iDb<db->nDb );
421 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000422 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000423 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000424 goto insert_cleanup;
425 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000426
drhb7f91642004-10-31 02:22:47 +0000427 /* Figure out if we have any triggers and if the table being
428 ** inserted into is a view
429 */
430#ifndef SQLITE_OMIT_TRIGGER
drhdca76842004-12-07 14:06:13 +0000431 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000432 isView = pTab->pSelect!=0;
433#else
drhdca76842004-12-07 14:06:13 +0000434# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000435# define isView 0
436#endif
437#ifdef SQLITE_OMIT_VIEW
438# undef isView
439# define isView 0
440#endif
441
danielk1977c3f9bad2002-05-15 08:30:12 +0000442 /* Ensure that:
443 * (a) the table is not read-only,
444 * (b) that if it is a view then ON INSERT triggers exist
445 */
drhdca76842004-12-07 14:06:13 +0000446 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000447 goto insert_cleanup;
448 }
drh43617e92006-03-06 20:55:46 +0000449 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000450
drhf573c992002-07-31 00:32:50 +0000451 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000452 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
453 ** module table).
drhf573c992002-07-31 00:32:50 +0000454 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000455 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000456 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000457 }
458
drh1ccde152000-06-17 13:12:39 +0000459 /* Allocate a VDBE
460 */
danielk19774adee202004-05-08 08:23:19 +0000461 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000462 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000463 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000464 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000465
danielk1977c3f9bad2002-05-15 08:30:12 +0000466 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000467 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000468 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000469 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000470
drh9d9cf222007-02-13 15:01:11 +0000471#ifndef SQLITE_OMIT_XFER_OPT
472 /* If the statement is of the form
473 **
474 ** INSERT INTO <table1> SELECT * FROM <table2>;
475 **
476 ** Then special optimizations can be applied that make the transfer
477 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000478 **
479 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000480 */
481 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
482 assert( !triggers_exist );
483 assert( pList==0 );
484 goto insert_cleanup;
485 }
486#endif /* SQLITE_OMIT_XFER_OPT */
487
drh2958a4e2004-11-12 03:56:15 +0000488 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000489 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000490 */
drh6a288a32008-01-07 19:20:24 +0000491 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000492
drh1ccde152000-06-17 13:12:39 +0000493 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000494 ** is coming from a SELECT statement, then generate a co-routine that
495 ** produces a single row of the SELECT on each invocation. The
496 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000497 */
drh5974a302000-06-07 14:42:26 +0000498 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000499 /* Data is coming from a SELECT. Generate code to implement that SELECT
drhe00ee6e2008-06-20 15:24:01 +0000500 ** as a co-routine. The code is common to both the 3rd and 4th
501 ** templates:
502 **
503 ** EOF <- 0
504 ** X <- A
505 ** goto B
506 ** A: setup for the SELECT
507 ** loop over the tables in the SELECT
508 ** load value into register R..R+n
509 ** yield X
510 ** end loop
511 ** cleanup after the SELECT
512 ** EOF <- 1
513 ** yield X
514 ** halt-error
515 **
516 ** On each invocation of the co-routine, it puts a single row of the
517 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
518 ** (These output registers are allocated by sqlite3Select().) When
519 ** the SELECT completes, it sets the EOF flag stored in regEof.
drh142e30d2002-08-28 03:00:58 +0000520 */
drhe00ee6e2008-06-20 15:24:01 +0000521 int rc, j1;
drh1013c932008-01-06 00:25:21 +0000522
drhe00ee6e2008-06-20 15:24:01 +0000523 regEof = ++pParse->nMem;
524 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
525 VdbeComment((v, "SELECT eof flag"));
drh92b01d52008-06-24 00:32:35 +0000526 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
drhe00ee6e2008-06-20 15:24:01 +0000527 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
drh92b01d52008-06-24 00:32:35 +0000528 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000529 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
530 VdbeComment((v, "Jump over SELECT coroutine"));
danielk1977b3bce662005-01-29 08:32:43 +0000531
532 /* Resolve the expressions in the SELECT statement and execute it. */
danielk19776c8c8ce2008-01-02 16:27:09 +0000533 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
drh17435752007-08-16 04:30:38 +0000534 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000535 goto insert_cleanup;
536 }
drhe00ee6e2008-06-20 15:24:01 +0000537 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
drh92b01d52008-06-24 00:32:35 +0000538 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
drhe00ee6e2008-06-20 15:24:01 +0000539 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
540 VdbeComment((v, "End of SELECT coroutine"));
541 sqlite3VdbeJumpHere(v, j1); /* label B: */
danielk1977b3bce662005-01-29 08:32:43 +0000542
drh6a288a32008-01-07 19:20:24 +0000543 regFromSelect = dest.iMem;
drh5974a302000-06-07 14:42:26 +0000544 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000545 nColumn = pSelect->pEList->nExpr;
drhe00ee6e2008-06-20 15:24:01 +0000546 assert( dest.nMem==nColumn );
drh142e30d2002-08-28 03:00:58 +0000547
548 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000549 ** should be written into a temporary table (template 4). Set to
550 ** FALSE if each* row of the SELECT can be written directly into
551 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000552 **
553 ** A temp table must be used if the table being updated is also one
554 ** of the tables being read by the SELECT statement. Also use a
555 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000556 */
drhe00ee6e2008-06-20 15:24:01 +0000557 if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000558 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000559 }
drh142e30d2002-08-28 03:00:58 +0000560
561 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000562 /* Invoke the coroutine to extract information from the SELECT
563 ** and add it to a transient table srcTab. The code generated
564 ** here is from the 4th template:
565 **
566 ** B: open temp table
567 ** L: yield X
568 ** if EOF goto M
569 ** insert row from R..R+n into temp table
570 ** goto L
571 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000572 */
drhe00ee6e2008-06-20 15:24:01 +0000573 int regRec; /* Register to hold packed record */
574 int regRowid; /* Register to hold temp table ROWID */
575 int addrTop; /* Label "L" */
576 int addrIf; /* Address of jump to M */
drhb7654112008-01-12 12:48:07 +0000577
drh142e30d2002-08-28 03:00:58 +0000578 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000579 regRec = sqlite3GetTempReg(pParse);
580 regRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000581 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh92b01d52008-06-24 00:32:35 +0000582 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000583 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh1db639c2008-01-17 02:36:28 +0000584 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhb7654112008-01-12 12:48:07 +0000585 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
586 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
drhe00ee6e2008-06-20 15:24:01 +0000587 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
588 sqlite3VdbeJumpHere(v, addrIf);
drhb7654112008-01-12 12:48:07 +0000589 sqlite3ReleaseTempReg(pParse, regRec);
590 sqlite3ReleaseTempReg(pParse, regRowid);
drh142e30d2002-08-28 03:00:58 +0000591 }
drh5974a302000-06-07 14:42:26 +0000592 }else{
drh142e30d2002-08-28 03:00:58 +0000593 /* This is the case if the data for the INSERT is coming from a VALUES
594 ** clause
595 */
danielk1977b3bce662005-01-29 08:32:43 +0000596 NameContext sNC;
597 memset(&sNC, 0, sizeof(sNC));
598 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000599 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000600 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000601 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000602 for(i=0; i<nColumn; i++){
danielk1977b3bce662005-01-29 08:32:43 +0000603 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000604 goto insert_cleanup;
605 }
drhe64e7b22002-02-18 13:56:36 +0000606 }
drh5974a302000-06-07 14:42:26 +0000607 }
drh1ccde152000-06-17 13:12:39 +0000608
609 /* Make sure the number of columns in the source data matches the number
610 ** of columns to be inserted into the table.
611 */
danielk1977034ca142007-06-26 10:38:54 +0000612 if( IsVirtual(pTab) ){
613 for(i=0; i<pTab->nCol; i++){
614 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
615 }
616 }
617 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000618 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000619 "table %S has %d columns but %d values were supplied",
620 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000621 goto insert_cleanup;
622 }
drh967e8b72000-06-21 13:59:10 +0000623 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000624 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000625 goto insert_cleanup;
626 }
drh1ccde152000-06-17 13:12:39 +0000627
628 /* If the INSERT statement included an IDLIST term, then make sure
629 ** all elements of the IDLIST really are columns of the table and
630 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000631 **
632 ** If the table has an INTEGER PRIMARY KEY column and that column
633 ** is named in the IDLIST, then record in the keyColumn variable
634 ** the index into IDLIST of the primary key column. keyColumn is
635 ** the index of the primary key as it appears in IDLIST, not as
636 ** is appears in the original table. (The index of the primary
637 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000638 */
drh967e8b72000-06-21 13:59:10 +0000639 if( pColumn ){
640 for(i=0; i<pColumn->nId; i++){
641 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000642 }
drh967e8b72000-06-21 13:59:10 +0000643 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000644 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000645 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000646 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000647 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000648 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000649 }
drhcce7d172000-05-31 15:34:51 +0000650 break;
651 }
652 }
653 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000654 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000655 keyColumn = i;
656 }else{
danielk19774adee202004-05-08 08:23:19 +0000657 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000658 pTabList, 0, pColumn->a[i].zName);
659 pParse->nErr++;
660 goto insert_cleanup;
661 }
drhcce7d172000-05-31 15:34:51 +0000662 }
663 }
664 }
drh1ccde152000-06-17 13:12:39 +0000665
drhaacc5432002-01-06 17:07:40 +0000666 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000667 ** key, the set the keyColumn variable to the primary key column index
668 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000669 */
drh147d0cc2006-08-25 23:42:53 +0000670 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000671 keyColumn = pTab->iPKey;
672 }
673
drh142e30d2002-08-28 03:00:58 +0000674 /* Open the temp table for FOR EACH ROW triggers
675 */
drhdca76842004-12-07 14:06:13 +0000676 if( triggers_exist ){
danielk1977cd3e8f72008-03-25 09:47:35 +0000677 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
drh66a51672008-01-03 00:01:23 +0000678 sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
danielk1977f29ce552002-05-19 23:43:12 +0000679 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000680
drhfeeb1392002-04-09 03:28:01 +0000681 /* Initialize the count of rows to be inserted
682 */
drh142e30d2002-08-28 03:00:58 +0000683 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000684 regRowCount = ++pParse->nMem;
685 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000686 }
687
danielk1977e448dc42008-01-02 11:50:51 +0000688 /* If this is not a view, open the table and and all indices */
689 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000690 int nIdx;
691 int i;
692
drh04adf412008-01-08 18:57:50 +0000693 baseCur = pParse->nTab;
694 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drh5c070532008-04-11 15:36:03 +0000695 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000696 if( aRegIdx==0 ){
697 goto insert_cleanup;
698 }
699 for(i=0; i<nIdx; i++){
700 aRegIdx[i] = ++pParse->nMem;
701 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000702 }
703
drhe00ee6e2008-06-20 15:24:01 +0000704 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000705 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000706 /* This block codes the top of loop only. The complete loop is the
707 ** following pseudocode (template 4):
708 **
709 ** rewind temp table
710 ** C: loop over rows of intermediate table
711 ** transfer values form intermediate table into <table>
712 ** end loop
713 ** D: ...
714 */
715 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
716 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000717 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000718 /* This block codes the top of loop only. The complete loop is the
719 ** following pseudocode (template 3):
720 **
721 ** C: yield X
722 ** if EOF goto D
723 ** insert the select result into <table> from R..R+n
724 ** goto C
725 ** D: ...
726 */
drh92b01d52008-06-24 00:32:35 +0000727 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000728 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh5974a302000-06-07 14:42:26 +0000729 }
drh1ccde152000-06-17 13:12:39 +0000730
drh6a288a32008-01-07 19:20:24 +0000731 /* Allocate registers for holding the rowid of the new row,
732 ** the content of the new row, and the assemblied row record.
733 */
734 regRecord = ++pParse->nMem;
735 regRowid = regIns = pParse->nMem+1;
736 pParse->nMem += pTab->nCol + 1;
737 if( IsVirtual(pTab) ){
738 regRowid++;
739 pParse->nMem++;
740 }
741 regData = regRowid+1;
742
drh5cf590c2003-04-24 01:45:04 +0000743 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000744 */
danielk19774adee202004-05-08 08:23:19 +0000745 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000746 if( triggers_exist & TRIGGER_BEFORE ){
drh2d401ab2008-01-10 23:50:11 +0000747 int regRowid;
748 int regCols;
749 int regRec;
danielk1977c3f9bad2002-05-15 08:30:12 +0000750
drh70ce3f02003-04-15 19:22:22 +0000751 /* build the NEW.* reference row. Note that if there is an INTEGER
752 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
753 ** translated into a unique ID for the row. But on a BEFORE trigger,
754 ** we do not know what the unique ID will be (because the insert has
755 ** not happened yet) so we substitute a rowid of -1
756 */
drh2d401ab2008-01-10 23:50:11 +0000757 regRowid = sqlite3GetTempReg(pParse);
drh70ce3f02003-04-15 19:22:22 +0000758 if( keyColumn<0 ){
drh2d401ab2008-01-10 23:50:11 +0000759 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
drh70ce3f02003-04-15 19:22:22 +0000760 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000761 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh70ce3f02003-04-15 19:22:22 +0000762 }else{
drh6a288a32008-01-07 19:20:24 +0000763 int j1;
drhd6fe9612005-01-14 01:22:00 +0000764 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000765 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
766 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
767 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
drh6a288a32008-01-07 19:20:24 +0000768 sqlite3VdbeJumpHere(v, j1);
drh2d401ab2008-01-10 23:50:11 +0000769 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drh70ce3f02003-04-15 19:22:22 +0000770 }
771
danielk1977034ca142007-06-26 10:38:54 +0000772 /* Cannot have triggers on a virtual table. If it were possible,
773 ** this block would have to account for hidden column.
774 */
775 assert(!IsVirtual(pTab));
776
drh70ce3f02003-04-15 19:22:22 +0000777 /* Create the new column data
778 */
drh2d401ab2008-01-10 23:50:11 +0000779 regCols = sqlite3GetTempRange(pParse, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000780 for(i=0; i<pTab->nCol; i++){
781 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000782 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000783 }else{
drh9adf9ac2002-05-15 11:44:13 +0000784 for(j=0; j<pColumn->nId; j++){
785 if( pColumn->a[j].idx==i ) break;
786 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000787 }
788 if( pColumn && j>=pColumn->nId ){
drh2d401ab2008-01-10 23:50:11 +0000789 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
drh142e30d2002-08-28 03:00:58 +0000790 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000791 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000792 }else{
drhd6fe9612005-01-14 01:22:00 +0000793 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000794 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000795 }
796 }
drh2d401ab2008-01-10 23:50:11 +0000797 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +0000798 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +0000799
800 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
801 ** do not attempt any conversions before assembling the record.
802 ** If this is a real table, attempt conversions as required by the
803 ** table column affinities.
804 */
805 if( !isView ){
806 sqlite3TableAffinityStr(v, pTab);
807 }
drh2d401ab2008-01-10 23:50:11 +0000808 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
809 sqlite3ReleaseTempReg(pParse, regRec);
810 sqlite3ReleaseTempReg(pParse, regRowid);
811 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000812
drh5cf590c2003-04-24 01:45:04 +0000813 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000814 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000815 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000816 goto insert_cleanup;
817 }
drh70ce3f02003-04-15 19:22:22 +0000818 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000819
drh4a324312001-12-21 14:30:42 +0000820 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000821 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000822 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000823 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000824 */
drh5cf590c2003-04-24 01:45:04 +0000825 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000826 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000827 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000828 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000829 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000830 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000831 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000832 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000833 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000834 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000835 }else{
drhe4d90812007-03-29 05:51:49 +0000836 VdbeOp *pOp;
drh1db639c2008-01-17 02:36:28 +0000837 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
drhe4d90812007-03-29 05:51:49 +0000838 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk1977bb50e7a2008-07-04 10:56:07 +0000839 if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000840 appendFlag = 1;
841 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000842 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000843 pOp->p2 = regRowid;
844 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000845 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000846 }
drhf0863fe2005-06-12 21:35:51 +0000847 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000848 ** to generate a unique primary key value.
849 */
drhe4d90812007-03-29 05:51:49 +0000850 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000851 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000852 if( !IsVirtual(pTab) ){
853 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
854 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
855 sqlite3VdbeJumpHere(v, j1);
856 }else{
857 j1 = sqlite3VdbeCurrentAddr(v);
858 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
859 }
drh3c84ddf2008-01-09 02:15:38 +0000860 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000861 }
drh4cbdda92006-06-14 19:00:20 +0000862 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000863 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000864 }else{
drh04adf412008-01-08 18:57:50 +0000865 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000866 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000867 }
drh6a288a32008-01-07 19:20:24 +0000868 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000869
danielk1977c3f9bad2002-05-15 08:30:12 +0000870 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000871 ** with the first column.
872 */
danielk1977034ca142007-06-26 10:38:54 +0000873 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000874 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000875 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000876 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000877 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000878 ** Whenever this column is read, the record number will be substituted
879 ** in its place. So will fill this column with a NULL to avoid
880 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000881 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000882 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000883 }
884 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000885 if( IsHiddenColumn(&pTab->aCol[i]) ){
886 assert( IsVirtual(pTab) );
887 j = -1;
888 nHidden++;
889 }else{
890 j = i - nHidden;
891 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000892 }else{
drh9adf9ac2002-05-15 11:44:13 +0000893 for(j=0; j<pColumn->nId; j++){
894 if( pColumn->a[j].idx==i ) break;
895 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000896 }
danielk1977034ca142007-06-26 10:38:54 +0000897 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000898 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000899 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000900 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000901 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000902 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000903 }else{
danielk1977287fb612008-01-04 19:10:28 +0000904 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000905 }
drhbed86902000-06-02 13:27:59 +0000906 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000907
908 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000909 ** do the insertion.
910 */
drh4cbdda92006-06-14 19:00:20 +0000911#ifndef SQLITE_OMIT_VIRTUALTABLE
912 if( IsVirtual(pTab) ){
drh4f3dd152008-04-28 18:46:43 +0000913 sqlite3VtabMakeWritable(pParse, pTab);
drh6a288a32008-01-07 19:20:24 +0000914 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000915 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000916 }else
917#endif
918 {
drh04adf412008-01-08 18:57:50 +0000919 sqlite3GenerateConstraintChecks(
920 pParse,
921 pTab,
922 baseCur,
923 regIns,
924 aRegIdx,
925 keyColumn>=0,
926 0,
927 onError,
928 endOfLoop
929 );
930 sqlite3CompleteInsertion(
931 pParse,
932 pTab,
933 baseCur,
934 regIns,
935 aRegIdx,
936 0,
937 0,
938 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
939 appendFlag
940 );
drh4cbdda92006-06-14 19:00:20 +0000941 }
drh5cf590c2003-04-24 01:45:04 +0000942 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000943
drh5cf590c2003-04-24 01:45:04 +0000944 /* Update the count of rows that are inserted
945 */
946 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000947 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000948 }
drh1ccde152000-06-17 13:12:39 +0000949
drhdca76842004-12-07 14:06:13 +0000950 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000951 /* Code AFTER triggers */
drhdca76842004-12-07 14:06:13 +0000952 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000953 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000954 goto insert_cleanup;
955 }
drh1bee3d72001-10-15 00:44:35 +0000956 }
957
drhe00ee6e2008-06-20 15:24:01 +0000958 /* The bottom of the main insertion loop, if the data source
959 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:12 +0000960 */
danielk19774adee202004-05-08 08:23:19 +0000961 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000962 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000963 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
964 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:36 +0000965 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:58 +0000966 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000967 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
968 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:26 +0000969 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000970
danielk1977e448dc42008-01-02 11:50:51 +0000971 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000972 /* Close all tables opened */
drh2eb95372008-06-06 15:04:36 +0000973 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +0000974 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh2eb95372008-06-06 15:04:36 +0000975 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +0000976 }
drhcce7d172000-05-31 15:34:51 +0000977 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000978
drhf3388142004-11-13 03:48:06 +0000979 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000980 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000981 ** table.
drh2958a4e2004-11-12 03:56:15 +0000982 */
drh6a288a32008-01-07 19:20:24 +0000983 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000984
drh1bee3d72001-10-15 00:44:35 +0000985 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000986 ** Return the number of rows inserted. If this routine is
987 ** generating code because of a call to sqlite3NestedParse(), do not
988 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000989 */
danielk1977cc6bd382005-01-10 02:48:49 +0000990 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +0000991 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +0000992 sqlite3VdbeSetNumCols(v, 1);
drh66a51672008-01-03 00:01:23 +0000993 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000994 }
drhcce7d172000-05-31 15:34:51 +0000995
996insert_cleanup:
danielk19774adee202004-05-08 08:23:19 +0000997 sqlite3SrcListDelete(pTabList);
danielk1977d5d56522005-03-16 12:15:20 +0000998 sqlite3ExprListDelete(pList);
999 sqlite3SelectDelete(pSelect);
danielk19774adee202004-05-08 08:23:19 +00001000 sqlite3IdListDelete(pColumn);
drhaa9b8962008-01-08 02:57:55 +00001001 sqlite3_free(aRegIdx);
drhcce7d172000-05-31 15:34:51 +00001002}
drh9cfcf5d2002-01-29 18:41:24 +00001003
drh9cfcf5d2002-01-29 18:41:24 +00001004/*
drh6a288a32008-01-07 19:20:24 +00001005** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +00001006**
drh04adf412008-01-08 18:57:50 +00001007** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +00001008**
drhf0863fe2005-06-12 21:35:51 +00001009** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +00001010** value is omitted unless we are doing an UPDATE that involves a
drha05a7222008-01-19 03:35:58 +00001011** change to the record number or writing to a virtual table.
drh0ca3e242002-01-29 23:07:02 +00001012**
drhf0863fe2005-06-12 21:35:51 +00001013** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +00001014**
1015** 3. The data in the first column of the entry after the update.
1016**
1017** i. Data from middle columns...
1018**
1019** N. The data in the last column of the entry after the update.
1020**
drh04adf412008-01-08 18:57:50 +00001021** The regRowid parameter is the index of the register containing (2).
1022**
drhf0863fe2005-06-12 21:35:51 +00001023** The old rowid shown as entry (1) above is omitted unless both isUpdate
1024** and rowidChng are 1. isUpdate is true for UPDATEs and false for
drha05a7222008-01-19 03:35:58 +00001025** INSERTs. RowidChng means that the new rowid is explicitly specified by
1026** the update or insert statement. If rowidChng is false, it means that
1027** the rowid is computed automatically in an insert or that the rowid value
1028** is not modified by the update.
drh0ca3e242002-01-29 23:07:02 +00001029**
drhaa9b8962008-01-08 02:57:55 +00001030** The code generated by this routine store new index entries into
1031** registers identified by aRegIdx[]. No index entry is created for
1032** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1033** the same as the order of indices on the linked list of indices
1034** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +00001035**
1036** This routine also generates code to check constraints. NOT NULL,
1037** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +00001038** then the appropriate action is performed. There are five possible
1039** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +00001040**
1041** Constraint type Action What Happens
1042** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +00001043** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +00001044** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +00001045** return code of SQLITE_CONSTRAINT.
1046**
drh1c928532002-01-31 15:54:21 +00001047** any ABORT Back out changes from the current command
1048** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +00001049** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +00001050** with SQLITE_CONSTRAINT.
1051**
1052** any FAIL Sqlite_exec() returns immediately with a
1053** return code of SQLITE_CONSTRAINT. The
1054** transaction is not rolled back and any
1055** prior changes are retained.
1056**
drh9cfcf5d2002-01-29 18:41:24 +00001057** any IGNORE The record number and data is popped from
1058** the stack and there is an immediate jump
1059** to label ignoreDest.
1060**
1061** NOT NULL REPLACE The NULL value is replace by the default
1062** value for that column. If the default value
1063** is NULL, the action is the same as ABORT.
1064**
1065** UNIQUE REPLACE The other row that conflicts with the row
1066** being inserted is removed.
1067**
1068** CHECK REPLACE Illegal. The results in an exception.
1069**
drh1c928532002-01-31 15:54:21 +00001070** Which action to take is determined by the overrideError parameter.
1071** Or if overrideError==OE_Default, then the pParse->onError parameter
1072** is used. Or if pParse->onError==OE_Default then the onError value
1073** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001074**
drhaaab5722002-02-19 13:39:21 +00001075** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +00001076** cursor number "baseCur". All indices of pTab must also have open
1077** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001078** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001079** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001080*/
danielk19774adee202004-05-08 08:23:19 +00001081void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001082 Parse *pParse, /* The parser context */
1083 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001084 int baseCur, /* Index of a read/write cursor pointing at pTab */
1085 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001086 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drha05a7222008-01-19 03:35:58 +00001087 int rowidChng, /* True if the rowid might collide with existing entry */
drhb419a922002-01-30 16:17:23 +00001088 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001089 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +00001090 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +00001091){
1092 int i;
1093 Vdbe *v;
1094 int nCol;
1095 int onError;
drha05a7222008-01-19 03:35:58 +00001096 int j1, j2, j3; /* Addresses of jump instructions */
drh04adf412008-01-08 18:57:50 +00001097 int regData; /* Register containing first data column */
drh0ca3e242002-01-29 23:07:02 +00001098 int iCur;
1099 Index *pIdx;
1100 int seenReplace = 0;
drhf0863fe2005-06-12 21:35:51 +00001101 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001102
danielk19774adee202004-05-08 08:23:19 +00001103 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001104 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001105 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001106 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001107 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001108
drhaa9b8962008-01-08 02:57:55 +00001109
drh9cfcf5d2002-01-29 18:41:24 +00001110 /* Test all NOT NULL constraints.
1111 */
1112 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001113 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001114 continue;
1115 }
drh9cfcf5d2002-01-29 18:41:24 +00001116 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001117 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001118 if( overrideError!=OE_Default ){
1119 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001120 }else if( onError==OE_Default ){
1121 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001122 }
danielk19777977a172004-11-09 12:44:37 +00001123 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001124 onError = OE_Abort;
1125 }
drhaa9b8962008-01-08 02:57:55 +00001126 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
danielk1977b84f96f2005-01-20 11:32:23 +00001127 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1128 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001129 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001130 case OE_Rollback:
1131 case OE_Abort:
1132 case OE_Fail: {
drhf089aa42008-07-08 19:34:06 +00001133 char *zMsg;
drh66a51672008-01-03 00:01:23 +00001134 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhf089aa42008-07-08 19:34:06 +00001135 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1136 pTab->zName, pTab->aCol[i].zName);
drh66a51672008-01-03 00:01:23 +00001137 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001138 break;
1139 }
1140 case OE_Ignore: {
drh66a51672008-01-03 00:01:23 +00001141 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001142 break;
1143 }
1144 case OE_Replace: {
drh04adf412008-01-08 18:57:50 +00001145 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh9cfcf5d2002-01-29 18:41:24 +00001146 break;
1147 }
drh9cfcf5d2002-01-29 18:41:24 +00001148 }
drhaa9b8962008-01-08 02:57:55 +00001149 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001150 }
1151
1152 /* Test all CHECK constraints
1153 */
drhffe07b22005-11-03 00:41:17 +00001154#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001155 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001156 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001157 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001158 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001159 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001160 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001161 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001162 }else{
drh66a51672008-01-03 00:01:23 +00001163 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001164 }
drhffe07b22005-11-03 00:41:17 +00001165 sqlite3VdbeResolveLabel(v, allOk);
1166 }
1167#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001168
drh0bd1f4e2002-06-06 18:54:39 +00001169 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1170 ** of the new record does not previously exist. Except, if this
1171 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001172 */
drhf0863fe2005-06-12 21:35:51 +00001173 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001174 onError = pTab->keyConf;
1175 if( overrideError!=OE_Default ){
1176 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001177 }else if( onError==OE_Default ){
1178 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001179 }
drha0217ba2003-06-01 01:10:33 +00001180
drh60a713c2008-01-21 16:22:45 +00001181 if( onError!=OE_Replace || pTab->pIndex ){
drha05a7222008-01-19 03:35:58 +00001182 if( isUpdate ){
1183 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
drh79b0c952002-05-21 12:56:43 +00001184 }
drha05a7222008-01-19 03:35:58 +00001185 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1186 switch( onError ){
1187 default: {
1188 onError = OE_Abort;
1189 /* Fall thru into the next case */
drh5383ae52003-06-04 12:23:30 +00001190 }
drha05a7222008-01-19 03:35:58 +00001191 case OE_Rollback:
1192 case OE_Abort:
1193 case OE_Fail: {
1194 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1195 "PRIMARY KEY must be unique", P4_STATIC);
1196 break;
1197 }
1198 case OE_Replace: {
1199 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1200 seenReplace = 1;
1201 break;
1202 }
1203 case OE_Ignore: {
1204 assert( seenReplace==0 );
1205 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1206 break;
1207 }
drh0ca3e242002-01-29 23:07:02 +00001208 }
drha05a7222008-01-19 03:35:58 +00001209 sqlite3VdbeJumpHere(v, j3);
1210 if( isUpdate ){
1211 sqlite3VdbeJumpHere(v, j2);
drh5383ae52003-06-04 12:23:30 +00001212 }
1213 }
drh0ca3e242002-01-29 23:07:02 +00001214 }
drh0bd1f4e2002-06-06 18:54:39 +00001215
1216 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1217 ** index and making sure that duplicate entries do not already exist.
1218 ** Add the new records to the indices as we go.
1219 */
drhb2fe7d82003-04-20 17:29:23 +00001220 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001221 int regIdx;
1222 int regR;
1223
drhaa9b8962008-01-08 02:57:55 +00001224 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001225
1226 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001227 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001228 for(i=0; i<pIdx->nColumn; i++){
1229 int idx = pIdx->aiColumn[i];
1230 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001231 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001232 }else{
drh2d401ab2008-01-10 23:50:11 +00001233 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001234 }
1235 }
drh2d401ab2008-01-10 23:50:11 +00001236 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh1db639c2008-01-17 02:36:28 +00001237 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001238 sqlite3IndexAffinityStr(v, pIdx);
drhda250ea2008-04-01 05:07:14 +00001239 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
drh2d401ab2008-01-10 23:50:11 +00001240 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001241
1242 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001243 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001244 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001245 if( overrideError!=OE_Default ){
1246 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001247 }else if( onError==OE_Default ){
1248 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001249 }
drh5383ae52003-06-04 12:23:30 +00001250 if( seenReplace ){
1251 if( onError==OE_Ignore ) onError = OE_Replace;
1252 else if( onError==OE_Fail ) onError = OE_Abort;
1253 }
1254
drhb2fe7d82003-04-20 17:29:23 +00001255
1256 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001257 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
1258 regR = sqlite3GetTempReg(pParse);
1259 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
1260 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
drh7209c692008-04-27 18:40:11 +00001261 regR, (char*)aRegIdx[iCur],
mlcreecha9e852b2008-03-06 09:58:50 +00001262 P4_INT32);
drhb2fe7d82003-04-20 17:29:23 +00001263
1264 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001265 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1266 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001267 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001268 case OE_Rollback:
1269 case OE_Abort:
1270 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001271 int j, n1, n2;
1272 char zErrMsg[200];
drh5bb3eb92007-05-04 13:15:55 +00001273 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1274 pIdx->nColumn>1 ? "columns " : "column ");
drh37ed48e2003-08-05 13:13:38 +00001275 n1 = strlen(zErrMsg);
1276 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1277 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1278 n2 = strlen(zCol);
1279 if( j>0 ){
drh5bb3eb92007-05-04 13:15:55 +00001280 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001281 n1 += 2;
1282 }
1283 if( n1+n2>sizeof(zErrMsg)-30 ){
drh5bb3eb92007-05-04 13:15:55 +00001284 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001285 n1 += 3;
1286 break;
1287 }else{
drh5bb3eb92007-05-04 13:15:55 +00001288 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001289 n1 += n2;
1290 }
1291 }
drh5bb3eb92007-05-04 13:15:55 +00001292 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001293 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001294 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001295 break;
1296 }
1297 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001298 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001299 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001300 break;
1301 }
1302 case OE_Replace: {
drh2d401ab2008-01-10 23:50:11 +00001303 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
drh0ca3e242002-01-29 23:07:02 +00001304 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001305 break;
1306 }
drh9cfcf5d2002-01-29 18:41:24 +00001307 }
drhaa9b8962008-01-08 02:57:55 +00001308 sqlite3VdbeJumpHere(v, j2);
drh2d401ab2008-01-10 23:50:11 +00001309 sqlite3VdbeJumpHere(v, j3);
1310 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001311 }
1312}
drh0ca3e242002-01-29 23:07:02 +00001313
1314/*
1315** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001316** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001317** A consecutive range of registers starting at regRowid contains the
1318** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001319**
drhb419a922002-01-30 16:17:23 +00001320** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001321** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001322*/
danielk19774adee202004-05-08 08:23:19 +00001323void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001324 Parse *pParse, /* The parser context */
1325 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001326 int baseCur, /* Index of a read/write cursor pointing at pTab */
1327 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001328 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drhf0863fe2005-06-12 21:35:51 +00001329 int rowidChng, /* True if the record number will change */
drh70ce3f02003-04-15 19:22:22 +00001330 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001331 int newIdx, /* Index of NEW table for triggers. -1 if none */
1332 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001333){
1334 int i;
1335 Vdbe *v;
1336 int nIdx;
1337 Index *pIdx;
danielk1977b28af712004-06-21 06:50:26 +00001338 int pik_flags;
drh04adf412008-01-08 18:57:50 +00001339 int regData;
drhb7654112008-01-12 12:48:07 +00001340 int regRec;
drh0ca3e242002-01-29 23:07:02 +00001341
danielk19774adee202004-05-08 08:23:19 +00001342 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001343 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001344 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001345 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1346 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001347 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001348 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
drh0ca3e242002-01-29 23:07:02 +00001349 }
drh04adf412008-01-08 18:57:50 +00001350 regData = regRowid + 1;
drhb7654112008-01-12 12:48:07 +00001351 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001352 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +00001353 sqlite3TableAffinityStr(v, pTab);
drhda250ea2008-04-01 05:07:14 +00001354 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
danielk1977b84f96f2005-01-20 11:32:23 +00001355#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001356 if( newIdx>=0 ){
drhb7654112008-01-12 12:48:07 +00001357 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
drh70ce3f02003-04-15 19:22:22 +00001358 }
danielk1977b84f96f2005-01-20 11:32:23 +00001359#endif
drh4794f732004-11-05 17:17:50 +00001360 if( pParse->nested ){
1361 pik_flags = 0;
1362 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001363 pik_flags = OPFLAG_NCHANGE;
1364 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001365 }
drhe4d90812007-03-29 05:51:49 +00001366 if( appendBias ){
1367 pik_flags |= OPFLAG_APPEND;
1368 }
drhb7654112008-01-12 12:48:07 +00001369 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
danielk197794eb6a12005-12-15 15:22:08 +00001370 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001371 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001372 }
drhb7654112008-01-12 12:48:07 +00001373 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001374}
drhcd446902004-02-24 01:05:31 +00001375
1376/*
drh290c1942004-08-21 17:54:45 +00001377** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001378** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001379** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001380**
1381** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001382*/
drhaa9b8962008-01-08 02:57:55 +00001383int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001384 Parse *pParse, /* Parsing context */
1385 Table *pTab, /* Table to be opened */
drh04adf412008-01-08 18:57:50 +00001386 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001387 int op /* OP_OpenRead or OP_OpenWrite */
1388){
drhcd446902004-02-24 01:05:31 +00001389 int i;
drh4cbdda92006-06-14 19:00:20 +00001390 int iDb;
drhcd446902004-02-24 01:05:31 +00001391 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001392 Vdbe *v;
1393
drhaa9b8962008-01-08 02:57:55 +00001394 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001395 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1396 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001397 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001398 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001399 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001400 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001401 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001402 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001403 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001404 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001405 }
drh04adf412008-01-08 18:57:50 +00001406 if( pParse->nTab<=baseCur+i ){
1407 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001408 }
drhaa9b8962008-01-08 02:57:55 +00001409 return i-1;
drhcd446902004-02-24 01:05:31 +00001410}
drh9d9cf222007-02-13 15:01:11 +00001411
drh91c58e22007-03-27 12:04:04 +00001412
1413#ifdef SQLITE_TEST
1414/*
1415** The following global variable is incremented whenever the
1416** transfer optimization is used. This is used for testing
1417** purposes only - to make sure the transfer optimization really
1418** is happening when it is suppose to.
1419*/
1420int sqlite3_xferopt_count;
1421#endif /* SQLITE_TEST */
1422
1423
drh9d9cf222007-02-13 15:01:11 +00001424#ifndef SQLITE_OMIT_XFER_OPT
1425/*
1426** Check to collation names to see if they are compatible.
1427*/
1428static int xferCompatibleCollation(const char *z1, const char *z2){
1429 if( z1==0 ){
1430 return z2==0;
1431 }
1432 if( z2==0 ){
1433 return 0;
1434 }
1435 return sqlite3StrICmp(z1, z2)==0;
1436}
1437
1438
1439/*
1440** Check to see if index pSrc is compatible as a source of data
1441** for index pDest in an insert transfer optimization. The rules
1442** for a compatible index:
1443**
1444** * The index is over the same set of columns
1445** * The same DESC and ASC markings occurs on all columns
1446** * The same onError processing (OE_Abort, OE_Ignore, etc)
1447** * The same collating sequence on each column
1448*/
1449static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1450 int i;
1451 assert( pDest && pSrc );
1452 assert( pDest->pTable!=pSrc->pTable );
1453 if( pDest->nColumn!=pSrc->nColumn ){
1454 return 0; /* Different number of columns */
1455 }
1456 if( pDest->onError!=pSrc->onError ){
1457 return 0; /* Different conflict resolution strategies */
1458 }
1459 for(i=0; i<pSrc->nColumn; i++){
1460 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1461 return 0; /* Different columns indexed */
1462 }
1463 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1464 return 0; /* Different sort orders */
1465 }
1466 if( pSrc->azColl[i]!=pDest->azColl[i] ){
drh60a713c2008-01-21 16:22:45 +00001467 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001468 }
1469 }
1470
1471 /* If no test above fails then the indices must be compatible */
1472 return 1;
1473}
1474
1475/*
1476** Attempt the transfer optimization on INSERTs of the form
1477**
1478** INSERT INTO tab1 SELECT * FROM tab2;
1479**
1480** This optimization is only attempted if
1481**
1482** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001483** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001484**
1485** (2) tab1 and tab2 are different tables
1486**
1487** (3) There must be no triggers on tab1
1488**
1489** (4) The result set of the SELECT statement is "*"
1490**
1491** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1492** or LIMIT clause.
1493**
1494** (6) The SELECT statement is a simple (not a compound) select that
1495** contains only tab2 in its FROM clause
1496**
1497** This method for implementing the INSERT transfers raw records from
1498** tab2 over to tab1. The columns are not decoded. Raw records from
1499** the indices of tab2 are transfered to tab1 as well. In so doing,
1500** the resulting tab1 has much less fragmentation.
1501**
1502** This routine returns TRUE if the optimization is attempted. If any
1503** of the conditions above fail so that the optimization should not
1504** be attempted, then this routine returns FALSE.
1505*/
1506static int xferOptimization(
1507 Parse *pParse, /* Parser context */
1508 Table *pDest, /* The table we are inserting into */
1509 Select *pSelect, /* A SELECT statement to use as the data source */
1510 int onError, /* How to handle constraint errors */
1511 int iDbDest /* The database of pDest */
1512){
1513 ExprList *pEList; /* The result set of the SELECT */
1514 Table *pSrc; /* The table in the FROM clause of SELECT */
1515 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1516 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1517 int i; /* Loop counter */
1518 int iDbSrc; /* The database of pSrc */
1519 int iSrc, iDest; /* Cursors from source and destination */
1520 int addr1, addr2; /* Loop addresses */
1521 int emptyDestTest; /* Address of test for empty pDest */
1522 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001523 Vdbe *v; /* The VDBE we are building */
1524 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001525 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001526 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001527 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001528
1529 if( pSelect==0 ){
1530 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1531 }
1532 if( pDest->pTrigger ){
1533 return 0; /* tab1 must not have triggers */
1534 }
1535#ifndef SQLITE_OMIT_VIRTUALTABLE
1536 if( pDest->isVirtual ){
1537 return 0; /* tab1 must not be a virtual table */
1538 }
1539#endif
1540 if( onError==OE_Default ){
1541 onError = OE_Abort;
1542 }
1543 if( onError!=OE_Abort && onError!=OE_Rollback ){
1544 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1545 }
danielk19775ce240a2007-09-03 17:30:06 +00001546 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001547 if( pSelect->pSrc->nSrc!=1 ){
1548 return 0; /* FROM clause must have exactly one term */
1549 }
1550 if( pSelect->pSrc->a[0].pSelect ){
1551 return 0; /* FROM clause cannot contain a subquery */
1552 }
1553 if( pSelect->pWhere ){
1554 return 0; /* SELECT may not have a WHERE clause */
1555 }
1556 if( pSelect->pOrderBy ){
1557 return 0; /* SELECT may not have an ORDER BY clause */
1558 }
drh8103b7d2007-02-24 13:23:51 +00001559 /* Do not need to test for a HAVING clause. If HAVING is present but
1560 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001561 if( pSelect->pGroupBy ){
1562 return 0; /* SELECT may not have a GROUP BY clause */
1563 }
1564 if( pSelect->pLimit ){
1565 return 0; /* SELECT may not have a LIMIT clause */
1566 }
drh8103b7d2007-02-24 13:23:51 +00001567 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001568 if( pSelect->pPrior ){
1569 return 0; /* SELECT may not be a compound query */
1570 }
1571 if( pSelect->isDistinct ){
1572 return 0; /* SELECT may not be DISTINCT */
1573 }
1574 pEList = pSelect->pEList;
1575 assert( pEList!=0 );
1576 if( pEList->nExpr!=1 ){
1577 return 0; /* The result set must have exactly one column */
1578 }
1579 assert( pEList->a[0].pExpr );
1580 if( pEList->a[0].pExpr->op!=TK_ALL ){
1581 return 0; /* The result set must be the special operator "*" */
1582 }
1583
1584 /* At this point we have established that the statement is of the
1585 ** correct syntactic form to participate in this optimization. Now
1586 ** we have to check the semantics.
1587 */
1588 pItem = pSelect->pSrc->a;
drhca424112008-01-25 15:04:48 +00001589 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
drh9d9cf222007-02-13 15:01:11 +00001590 if( pSrc==0 ){
1591 return 0; /* FROM clause does not contain a real table */
1592 }
1593 if( pSrc==pDest ){
1594 return 0; /* tab1 and tab2 may not be the same table */
1595 }
1596#ifndef SQLITE_OMIT_VIRTUALTABLE
1597 if( pSrc->isVirtual ){
1598 return 0; /* tab2 must not be a virtual table */
1599 }
1600#endif
1601 if( pSrc->pSelect ){
1602 return 0; /* tab2 may not be a view */
1603 }
1604 if( pDest->nCol!=pSrc->nCol ){
1605 return 0; /* Number of columns must be the same in tab1 and tab2 */
1606 }
1607 if( pDest->iPKey!=pSrc->iPKey ){
1608 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1609 }
1610 for(i=0; i<pDest->nCol; i++){
1611 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1612 return 0; /* Affinity must be the same on all columns */
1613 }
1614 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1615 return 0; /* Collating sequence must be the same on all columns */
1616 }
1617 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1618 return 0; /* tab2 must be NOT NULL if tab1 is */
1619 }
1620 }
1621 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001622 if( pDestIdx->onError!=OE_None ){
1623 destHasUniqueIdx = 1;
1624 }
drh9d9cf222007-02-13 15:01:11 +00001625 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1626 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1627 }
1628 if( pSrcIdx==0 ){
1629 return 0; /* pDestIdx has no corresponding index in pSrc */
1630 }
1631 }
drh7fc2f412007-03-29 00:08:24 +00001632#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001633 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001634 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1635 }
drh7fc2f412007-03-29 00:08:24 +00001636#endif
drh9d9cf222007-02-13 15:01:11 +00001637
1638 /* If we get this far, it means either:
1639 **
1640 ** * We can always do the transfer if the table contains an
1641 ** an integer primary key
1642 **
1643 ** * We can conditionally do the transfer if the destination
1644 ** table is empty.
1645 */
drhdd735212007-02-24 13:53:05 +00001646#ifdef SQLITE_TEST
1647 sqlite3_xferopt_count++;
1648#endif
drh9d9cf222007-02-13 15:01:11 +00001649 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1650 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001651 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001652 iSrc = pParse->nTab++;
1653 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001654 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001655 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001656 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001657 /* If tables do not have an INTEGER PRIMARY KEY and there
1658 ** are indices to be copied and the destination is not empty,
1659 ** we have to disallow the transfer optimization because the
1660 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001661 **
1662 ** Or if the destination has a UNIQUE index and is not empty,
1663 ** we also disallow the transfer optimization because we cannot
1664 ** insure that all entries in the union of DEST and SRC will be
1665 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001666 */
drh66a51672008-01-03 00:01:23 +00001667 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1668 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001669 sqlite3VdbeJumpHere(v, addr1);
1670 }else{
1671 emptyDestTest = 0;
1672 }
1673 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001674 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001675 regData = sqlite3GetTempReg(pParse);
1676 regRowid = sqlite3GetTempReg(pParse);
drh42242de2007-03-29 13:35:35 +00001677 if( pDest->iPKey>=0 ){
drhb7654112008-01-12 12:48:07 +00001678 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1679 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
drh66a51672008-01-03 00:01:23 +00001680 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1681 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001682 sqlite3VdbeJumpHere(v, addr2);
drhb7654112008-01-12 12:48:07 +00001683 autoIncStep(pParse, regAutoinc, regRowid);
drhbd36ba62007-03-31 13:00:26 +00001684 }else if( pDest->pIndex==0 ){
drhb7654112008-01-12 12:48:07 +00001685 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
drh95bad4c2007-03-28 18:04:10 +00001686 }else{
drhb7654112008-01-12 12:48:07 +00001687 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
drh42242de2007-03-29 13:35:35 +00001688 assert( pDest->autoInc==0 );
drh95bad4c2007-03-28 18:04:10 +00001689 }
drhb7654112008-01-12 12:48:07 +00001690 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1691 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1692 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
danielk19771f4aa332008-01-03 09:51:55 +00001693 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001694 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001695 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001696 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1697 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1698 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1699 }
1700 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001701 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1702 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001703 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001704 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1705 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001706 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001707 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001708 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001709 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001710 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001711 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001712 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1713 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh66a51672008-01-03 00:01:23 +00001714 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001715 sqlite3VdbeJumpHere(v, addr1);
1716 }
1717 sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00001718 sqlite3ReleaseTempReg(pParse, regRowid);
1719 sqlite3ReleaseTempReg(pParse, regData);
drh66a51672008-01-03 00:01:23 +00001720 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1721 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001722 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001723 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001724 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001725 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001726 return 0;
1727 }else{
1728 return 1;
1729 }
1730}
1731#endif /* SQLITE_OMIT_XFER_OPT */
drhf39d9582008-03-19 20:42:13 +00001732
1733/* Make sure "isView" gets undefined in case this file becomes part of
1734** the amalgamation - so that subsequent files do not see isView as a
1735** macro. */
1736#undef isView