blob: 72078c5543162973b48214f94c81f3998d02d8dd [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**
danielk1977d336e222009-02-20 10:58:41 +000015** $Id: insert.c,v 1.259 2009/02/20 10:58:42 danielk1977 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);
drh633e6d52008-07-28 19:34:53 +000048 pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
danielk1977a37cdde2004-05-16 11:15:36 +000049 if( !pIdx->zColAff ){
drh633e6d52008-07-28 19:34:53 +000050 db->mallocFailed = 1;
danielk1977a37cdde2004-05-16 11:15:36 +000051 return;
52 }
53 for(n=0; n<pIdx->nColumn; n++){
54 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
55 }
drh2d401ab2008-01-10 23:50:11 +000056 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
57 pIdx->zColAff[n] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +000058 }
danielk19773d1bfea2004-05-14 11:00:53 +000059
drh66a51672008-01-03 00:01:23 +000060 sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
danielk1977a37cdde2004-05-16 11:15:36 +000061}
62
63/*
drh66a51672008-01-03 00:01:23 +000064** Set P4 of the most recently inserted opcode to a column affinity
danielk1977a37cdde2004-05-16 11:15:36 +000065** string for table pTab. A column affinity string has one character
66** for each column indexed by the index, according to the affinity of the
67** column:
68**
69** Character Column affinity
70** ------------------------------
drh3eda0402005-11-24 13:15:32 +000071** 'a' TEXT
72** 'b' NONE
73** 'c' NUMERIC
74** 'd' INTEGER
75** 'e' REAL
danielk1977a37cdde2004-05-16 11:15:36 +000076*/
77void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
danielk19773d1bfea2004-05-14 11:00:53 +000078 /* The first time a column affinity string for a particular table
79 ** is required, it is allocated and populated here. It is then
80 ** stored as a member of the Table structure for subsequent use.
81 **
82 ** The column affinity string will eventually be deleted by
83 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
84 */
85 if( !pTab->zColAff ){
86 char *zColAff;
87 int i;
drhabb6fca2007-08-16 12:24:01 +000088 sqlite3 *db = sqlite3VdbeDb(v);
danielk19773d1bfea2004-05-14 11:00:53 +000089
drh633e6d52008-07-28 19:34:53 +000090 zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
danielk19773d1bfea2004-05-14 11:00:53 +000091 if( !zColAff ){
drh633e6d52008-07-28 19:34:53 +000092 db->mallocFailed = 1;
danielk1977a37cdde2004-05-16 11:15:36 +000093 return;
danielk19773d1bfea2004-05-14 11:00:53 +000094 }
95
96 for(i=0; i<pTab->nCol; i++){
danielk1977a37cdde2004-05-16 11:15:36 +000097 zColAff[i] = pTab->aCol[i].affinity;
danielk19773d1bfea2004-05-14 11:00:53 +000098 }
99 zColAff[pTab->nCol] = '\0';
100
101 pTab->zColAff = zColAff;
102 }
103
drh66a51672008-01-03 00:01:23 +0000104 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
danielk19773d1bfea2004-05-14 11:00:53 +0000105}
106
danielk19774d887782005-02-08 08:42:27 +0000107/*
drh48d11782007-11-23 15:02:19 +0000108** Return non-zero if the table pTab in database iDb or any of its indices
109** have been opened at any point in the VDBE program beginning at location
110** iStartAddr throught the end of the program. This is used to see if
111** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
112** run without using temporary table for the results of the SELECT.
danielk19774d887782005-02-08 08:42:27 +0000113*/
drh48d11782007-11-23 15:02:19 +0000114static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
danielk19774d887782005-02-08 08:42:27 +0000115 int i;
drh48d11782007-11-23 15:02:19 +0000116 int iEnd = sqlite3VdbeCurrentAddr(v);
117 for(i=iStartAddr; i<iEnd; i++){
118 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09 +0000119 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23 +0000120 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
121 Index *pIndex;
drh48d11782007-11-23 15:02:19 +0000122 int tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23 +0000123 if( tnum==pTab->tnum ){
124 return 1;
125 }
126 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
127 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19 +0000128 return 1;
129 }
drh48d11782007-11-23 15:02:19 +0000130 }
131 }
drh543165e2007-11-27 14:46:41 +0000132#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19772dca4ac2008-01-03 11:50:29 +0000133 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
134 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23 +0000135 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19 +0000136 return 1;
danielk19774d887782005-02-08 08:42:27 +0000137 }
drh543165e2007-11-27 14:46:41 +0000138#endif
danielk19774d887782005-02-08 08:42:27 +0000139 }
140 return 0;
141}
danielk19773d1bfea2004-05-14 11:00:53 +0000142
drh9d9cf222007-02-13 15:01:11 +0000143#ifndef SQLITE_OMIT_AUTOINCREMENT
144/*
145** Write out code to initialize the autoincrement logic. This code
146** looks up the current autoincrement value in the sqlite_sequence
drh6a288a32008-01-07 19:20:24 +0000147** table and stores that value in a register. Code generated by
148** autoIncStep() will keep that register holding the largest
drh9d9cf222007-02-13 15:01:11 +0000149** rowid value. Code generated by autoIncEnd() will write the new
150** largest value of the counter back into the sqlite_sequence table.
151**
152** This routine returns the index of the mem[] cell that contains
153** the maximum rowid counter.
154**
drh6a288a32008-01-07 19:20:24 +0000155** Three consecutive registers are allocated by this routine. The
156** first two hold the name of the target table and the maximum rowid
157** inserted into the target table, respectively.
158** The third holds the rowid in sqlite_sequence where we will
159** write back the revised maximum rowid. This routine returns the
160** index of the second of these three registers.
drh9d9cf222007-02-13 15:01:11 +0000161*/
162static int autoIncBegin(
163 Parse *pParse, /* Parsing context */
164 int iDb, /* Index of the database holding pTab */
165 Table *pTab /* The table we are writing to */
166){
drh6a288a32008-01-07 19:20:24 +0000167 int memId = 0; /* Register holding maximum rowid */
drh7d10d5a2008-08-20 16:35:10 +0000168 if( pTab->tabFlags & TF_Autoincrement ){
drh9d9cf222007-02-13 15:01:11 +0000169 Vdbe *v = pParse->pVdbe;
170 Db *pDb = &pParse->db->aDb[iDb];
danielk19776ab3a2e2009-02-19 14:39:25 +0000171 int iCur = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +0000172 int addr; /* Address of the top of the loop */
drh9d9cf222007-02-13 15:01:11 +0000173 assert( v );
drh6a288a32008-01-07 19:20:24 +0000174 pParse->nMem++; /* Holds name of table */
175 memId = ++pParse->nMem;
176 pParse->nMem++;
drh9d9cf222007-02-13 15:01:11 +0000177 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh6a288a32008-01-07 19:20:24 +0000178 addr = sqlite3VdbeCurrentAddr(v);
drh1db639c2008-01-17 02:36:28 +0000179 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
drhc9ded4c2008-05-29 03:20:59 +0000180 sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
drh1db639c2008-01-17 02:36:28 +0000181 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
182 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
drh35573352008-01-08 23:54:25 +0000183 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh6a288a32008-01-07 19:20:24 +0000184 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
185 sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
drhc9ded4c2008-05-29 03:20:59 +0000186 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
drh1db639c2008-01-17 02:36:28 +0000187 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
drhc9ded4c2008-05-29 03:20:59 +0000188 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
drh66a51672008-01-03 00:01:23 +0000189 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
drh9d9cf222007-02-13 15:01:11 +0000190 }
191 return memId;
192}
193
194/*
195** Update the maximum rowid for an autoincrement calculation.
196**
197** This routine should be called when the top of the stack holds a
198** new rowid that is about to be inserted. If that new rowid is
199** larger than the maximum rowid in the memId memory cell, then the
200** memory cell is updated. The stack is unchanged.
201*/
drh6a288a32008-01-07 19:20:24 +0000202static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11 +0000203 if( memId>0 ){
drh6a288a32008-01-07 19:20:24 +0000204 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11 +0000205 }
206}
207
208/*
209** After doing one or more inserts, the maximum rowid is stored
drh6a288a32008-01-07 19:20:24 +0000210** in reg[memId]. Generate code to write this value back into the
drh9d9cf222007-02-13 15:01:11 +0000211** the sqlite_sequence table.
212*/
213static void autoIncEnd(
214 Parse *pParse, /* The parsing context */
215 int iDb, /* Index of the database holding pTab */
216 Table *pTab, /* Table we are inserting into */
217 int memId /* Memory cell holding the maximum rowid */
218){
drh7d10d5a2008-08-20 16:35:10 +0000219 if( pTab->tabFlags & TF_Autoincrement ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000220 int iCur = pParse->nTab++;
drh9d9cf222007-02-13 15:01:11 +0000221 Vdbe *v = pParse->pVdbe;
222 Db *pDb = &pParse->db->aDb[iDb];
drh6a288a32008-01-07 19:20:24 +0000223 int j1;
danielk1977a7a8e142008-02-13 18:25:27 +0000224 int iRec = ++pParse->nMem; /* Memory cell used for record */
drh6a288a32008-01-07 19:20:24 +0000225
drh9d9cf222007-02-13 15:01:11 +0000226 assert( v );
drh9d9cf222007-02-13 15:01:11 +0000227 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh6a288a32008-01-07 19:20:24 +0000228 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
229 sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
230 sqlite3VdbeJumpHere(v, j1);
danielk1977a7a8e142008-02-13 18:25:27 +0000231 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
232 sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
drh35573352008-01-08 23:54:25 +0000233 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh6a288a32008-01-07 19:20:24 +0000234 sqlite3VdbeAddOp1(v, OP_Close, iCur);
drh9d9cf222007-02-13 15:01:11 +0000235 }
236}
237#else
238/*
239** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
240** above are all no-ops
241*/
242# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28 +0000243# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11 +0000244# define autoIncEnd(A,B,C,D)
245#endif /* SQLITE_OMIT_AUTOINCREMENT */
246
247
248/* Forward declaration */
249static int xferOptimization(
250 Parse *pParse, /* Parser context */
251 Table *pDest, /* The table we are inserting into */
252 Select *pSelect, /* A SELECT statement to use as the data source */
253 int onError, /* How to handle constraint errors */
254 int iDbDest /* The database of pDest */
255);
256
danielk19773d1bfea2004-05-14 11:00:53 +0000257/*
drh1ccde152000-06-17 13:12:39 +0000258** This routine is call to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51 +0000259**
260** insert into TABLE (IDLIST) values(EXPRLIST)
drh1ccde152000-06-17 13:12:39 +0000261** insert into TABLE (IDLIST) select
drhcce7d172000-05-31 15:34:51 +0000262**
drh1ccde152000-06-17 13:12:39 +0000263** The IDLIST following the table name is always optional. If omitted,
264** then a list of all columns for the table is substituted. The IDLIST
drh967e8b72000-06-21 13:59:10 +0000265** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
drh1ccde152000-06-17 13:12:39 +0000266**
267** The pList parameter holds EXPRLIST in the first form of the INSERT
268** statement above, and pSelect is NULL. For the second form, pList is
269** NULL and pSelect is a pointer to the select statement used to generate
270** data for the insert.
drh142e30d2002-08-28 03:00:58 +0000271**
drh9d9cf222007-02-13 15:01:11 +0000272** The code generated follows one of four templates. For a simple
drh142e30d2002-08-28 03:00:58 +0000273** select with data coming from a VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01 +0000274** once straight down through. Pseudo-code follows (we call this
275** the "1st template"):
drh142e30d2002-08-28 03:00:58 +0000276**
277** open write cursor to <table> and its indices
278** puts VALUES clause expressions onto the stack
279** write the resulting record into <table>
280** cleanup
281**
drh9d9cf222007-02-13 15:01:11 +0000282** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58 +0000283**
284** INSERT INTO <table> SELECT ...
285**
drh9d9cf222007-02-13 15:01:11 +0000286** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
287** in other words if the SELECT pulls all columns from a single table
288** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
289** if <table2> and <table1> are distinct tables but have identical
290** schemas, including all the same indices, then a special optimization
291** is invoked that copies raw records from <table2> over to <table1>.
292** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01 +0000293** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000294**
295** open a write cursor to <table>
296** open read cursor on <table2>
297** transfer all records in <table2> over to <table>
298** close cursors
299** foreach index on <table>
300** open a write cursor on the <table> index
301** open a read cursor on the corresponding <table2> index
302** transfer all records from the read to the write cursors
303** close cursors
304** end foreach
305**
drhe00ee6e2008-06-20 15:24:01 +0000306** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11 +0000307** and the SELECT clause does not read from <table> at any time.
308** The generated code follows this template:
drh142e30d2002-08-28 03:00:58 +0000309**
drhe00ee6e2008-06-20 15:24:01 +0000310** EOF <- 0
311** X <- A
drh142e30d2002-08-28 03:00:58 +0000312** goto B
313** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11 +0000314** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000315** load values into registers R..R+n
316** yield X
drh142e30d2002-08-28 03:00:58 +0000317** end loop
318** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000319** EOF <- 1
320** yield X
drh142e30d2002-08-28 03:00:58 +0000321** goto A
drhe00ee6e2008-06-20 15:24:01 +0000322** B: open write cursor to <table> and its indices
323** C: yield X
324** if EOF goto D
325** insert the select result into <table> from R..R+n
326** goto C
drh142e30d2002-08-28 03:00:58 +0000327** D: cleanup
328**
drhe00ee6e2008-06-20 15:24:01 +0000329** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58 +0000330** values from a SELECT but the data is being inserted into a table
331** that is also read as part of the SELECT. In the third form,
332** we have to use a intermediate table to store the results of
333** the select. The template is like this:
334**
drhe00ee6e2008-06-20 15:24:01 +0000335** EOF <- 0
336** X <- A
drh142e30d2002-08-28 03:00:58 +0000337** goto B
338** A: setup for the SELECT
339** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000340** load value into register R..R+n
341** yield X
drh142e30d2002-08-28 03:00:58 +0000342** end loop
343** cleanup after the SELECT
drhe00ee6e2008-06-20 15:24:01 +0000344** EOF <- 1
345** yield X
346** halt-error
347** B: open temp table
348** L: yield X
349** if EOF goto M
350** insert row from R..R+n into temp table
351** goto L
352** M: open write cursor to <table> and its indices
353** rewind temp table
354** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58 +0000355** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01 +0000356** end loop
357** D: cleanup
drhcce7d172000-05-31 15:34:51 +0000358*/
danielk19774adee202004-05-08 08:23:19 +0000359void sqlite3Insert(
drhcce7d172000-05-31 15:34:51 +0000360 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58 +0000361 SrcList *pTabList, /* Name of table into which we are inserting */
drhcce7d172000-05-31 15:34:51 +0000362 ExprList *pList, /* List of values to be inserted */
drh5974a302000-06-07 14:42:26 +0000363 Select *pSelect, /* A SELECT statement to use as the data source */
drh9cfcf5d2002-01-29 18:41:24 +0000364 IdList *pColumn, /* Column names corresponding to IDLIST. */
365 int onError /* How to handle constraint errors */
drhcce7d172000-05-31 15:34:51 +0000366){
drh6a288a32008-01-07 19:20:24 +0000367 sqlite3 *db; /* The main database structure */
368 Table *pTab; /* The table to insert into. aka TABLE */
drh113088e2003-03-20 01:16:58 +0000369 char *zTab; /* Name of the table into which we are inserting */
drhe22a3342003-04-22 20:30:37 +0000370 const char *zDb; /* Name of the database holding this table */
drh5974a302000-06-07 14:42:26 +0000371 int i, j, idx; /* Loop counters */
372 Vdbe *v; /* Generate code into this virtual machine */
373 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10 +0000374 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24 +0000375 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh04adf412008-01-08 18:57:50 +0000376 int baseCur = 0; /* VDBE Cursor number for pTab */
drh4a324312001-12-21 14:30:42 +0000377 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02 +0000378 int endOfLoop; /* Label for the end of the insertion loop */
danielk19774d887782005-02-08 08:42:27 +0000379 int useTempTable = 0; /* Store SELECT results in intermediate table */
danielk1977cfe9a692004-06-16 12:00:29 +0000380 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01 +0000381 int addrInsTop = 0; /* Jump to label "D" */
382 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
383 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
drh2eb95372008-06-06 15:04:36 +0000384 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24 +0000385 int newIdx = -1; /* Cursor for the NEW pseudo-table */
386 int iDb; /* Index of database holding TABLE */
drh2958a4e2004-11-12 03:56:15 +0000387 Db *pDb; /* The database containing table being inserted into */
drhe4d90812007-03-29 05:51:49 +0000388 int appendFlag = 0; /* True if the insert is likely to be an append */
drhcce7d172000-05-31 15:34:51 +0000389
drh6a288a32008-01-07 19:20:24 +0000390 /* Register allocations */
drh1bd10f82008-12-10 21:19:56 +0000391 int regFromSelect = 0;/* Base register for data coming from SELECT */
drh6a288a32008-01-07 19:20:24 +0000392 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
393 int regRowCount = 0; /* Memory cell used for the row counter */
394 int regIns; /* Block of regs holding rowid+data being inserted */
395 int regRowid; /* registers holding insert rowid */
396 int regData; /* register holding first column to insert */
397 int regRecord; /* Holds the assemblied row record */
drh1bd10f82008-12-10 21:19:56 +0000398 int regEof = 0; /* Register recording end of SELECT data */
drhaa9b8962008-01-08 02:57:55 +0000399 int *aRegIdx = 0; /* One register allocated to each index */
drh6a288a32008-01-07 19:20:24 +0000400
danielk1977034ca142007-06-26 10:38:54 +0000401
drh798da522004-11-04 04:42:28 +0000402#ifndef SQLITE_OMIT_TRIGGER
403 int isView; /* True if attempting to insert into a view */
drhdca76842004-12-07 14:06:13 +0000404 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
drh798da522004-11-04 04:42:28 +0000405#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000406
drh17435752007-08-16 04:30:38 +0000407 db = pParse->db;
drh1bd10f82008-12-10 21:19:56 +0000408 memset(&dest, 0, sizeof(dest));
drh17435752007-08-16 04:30:38 +0000409 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000410 goto insert_cleanup;
411 }
drhdaffd0e2001-04-11 14:28:42 +0000412
drh1ccde152000-06-17 13:12:39 +0000413 /* Locate the table into which we will be inserting new information.
414 */
drh113088e2003-03-20 01:16:58 +0000415 assert( pTabList->nSrc==1 );
416 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000417 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000418 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000419 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000420 goto insert_cleanup;
421 }
danielk1977da184232006-01-05 11:34:32 +0000422 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
423 assert( iDb<db->nDb );
424 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000425 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000426 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000427 goto insert_cleanup;
428 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000429
drhb7f91642004-10-31 02:22:47 +0000430 /* Figure out if we have any triggers and if the table being
431 ** inserted into is a view
432 */
433#ifndef SQLITE_OMIT_TRIGGER
danielk197762c14b32008-11-19 09:05:26 +0000434 triggers_exist = sqlite3TriggersExist(pTab, TK_INSERT, 0);
drhb7f91642004-10-31 02:22:47 +0000435 isView = pTab->pSelect!=0;
436#else
drhdca76842004-12-07 14:06:13 +0000437# define triggers_exist 0
drhb7f91642004-10-31 02:22:47 +0000438# define isView 0
439#endif
440#ifdef SQLITE_OMIT_VIEW
441# undef isView
442# define isView 0
443#endif
444
danielk1977c3f9bad2002-05-15 08:30:12 +0000445 /* Ensure that:
446 * (a) the table is not read-only,
447 * (b) that if it is a view then ON INSERT triggers exist
448 */
drhdca76842004-12-07 14:06:13 +0000449 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000450 goto insert_cleanup;
451 }
drh43617e92006-03-06 20:55:46 +0000452 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000453
drhf573c992002-07-31 00:32:50 +0000454 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000455 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
456 ** module table).
drhf573c992002-07-31 00:32:50 +0000457 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000458 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000459 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000460 }
461
drh1ccde152000-06-17 13:12:39 +0000462 /* Allocate a VDBE
463 */
danielk19774adee202004-05-08 08:23:19 +0000464 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000465 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000466 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk1977da184232006-01-05 11:34:32 +0000467 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
drh1ccde152000-06-17 13:12:39 +0000468
danielk1977c3f9bad2002-05-15 08:30:12 +0000469 /* if there are row triggers, allocate a temp table for new.* references. */
drhdca76842004-12-07 14:06:13 +0000470 if( triggers_exist ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000471 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000472 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000473
drh9d9cf222007-02-13 15:01:11 +0000474#ifndef SQLITE_OMIT_XFER_OPT
475 /* If the statement is of the form
476 **
477 ** INSERT INTO <table1> SELECT * FROM <table2>;
478 **
479 ** Then special optimizations can be applied that make the transfer
480 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000481 **
482 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000483 */
484 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
485 assert( !triggers_exist );
486 assert( pList==0 );
487 goto insert_cleanup;
488 }
489#endif /* SQLITE_OMIT_XFER_OPT */
490
drh2958a4e2004-11-12 03:56:15 +0000491 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000492 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000493 */
drh6a288a32008-01-07 19:20:24 +0000494 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000495
drh1ccde152000-06-17 13:12:39 +0000496 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000497 ** is coming from a SELECT statement, then generate a co-routine that
498 ** produces a single row of the SELECT on each invocation. The
499 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000500 */
drh5974a302000-06-07 14:42:26 +0000501 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000502 /* Data is coming from a SELECT. Generate code to implement that SELECT
drhe00ee6e2008-06-20 15:24:01 +0000503 ** as a co-routine. The code is common to both the 3rd and 4th
504 ** templates:
505 **
506 ** EOF <- 0
507 ** X <- A
508 ** goto B
509 ** A: setup for the SELECT
510 ** loop over the tables in the SELECT
511 ** load value into register R..R+n
512 ** yield X
513 ** end loop
514 ** cleanup after the SELECT
515 ** EOF <- 1
516 ** yield X
517 ** halt-error
518 **
519 ** On each invocation of the co-routine, it puts a single row of the
520 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
521 ** (These output registers are allocated by sqlite3Select().) When
522 ** the SELECT completes, it sets the EOF flag stored in regEof.
drh142e30d2002-08-28 03:00:58 +0000523 */
drhe00ee6e2008-06-20 15:24:01 +0000524 int rc, j1;
drh1013c932008-01-06 00:25:21 +0000525
drhe00ee6e2008-06-20 15:24:01 +0000526 regEof = ++pParse->nMem;
527 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
528 VdbeComment((v, "SELECT eof flag"));
drh92b01d52008-06-24 00:32:35 +0000529 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
drhe00ee6e2008-06-20 15:24:01 +0000530 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
drh92b01d52008-06-24 00:32:35 +0000531 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000532 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
533 VdbeComment((v, "Jump over SELECT coroutine"));
danielk1977b3bce662005-01-29 08:32:43 +0000534
535 /* Resolve the expressions in the SELECT statement and execute it. */
drh7d10d5a2008-08-20 16:35:10 +0000536 rc = sqlite3Select(pParse, pSelect, &dest);
drh17435752007-08-16 04:30:38 +0000537 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000538 goto insert_cleanup;
539 }
drhe00ee6e2008-06-20 15:24:01 +0000540 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
drh92b01d52008-06-24 00:32:35 +0000541 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
drhe00ee6e2008-06-20 15:24:01 +0000542 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
543 VdbeComment((v, "End of SELECT coroutine"));
544 sqlite3VdbeJumpHere(v, j1); /* label B: */
danielk1977b3bce662005-01-29 08:32:43 +0000545
drh6a288a32008-01-07 19:20:24 +0000546 regFromSelect = dest.iMem;
drh5974a302000-06-07 14:42:26 +0000547 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000548 nColumn = pSelect->pEList->nExpr;
drhe00ee6e2008-06-20 15:24:01 +0000549 assert( dest.nMem==nColumn );
drh142e30d2002-08-28 03:00:58 +0000550
551 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000552 ** should be written into a temporary table (template 4). Set to
553 ** FALSE if each* row of the SELECT can be written directly into
554 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000555 **
556 ** A temp table must be used if the table being updated is also one
557 ** of the tables being read by the SELECT statement. Also use a
558 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000559 */
drhe00ee6e2008-06-20 15:24:01 +0000560 if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000561 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000562 }
drh142e30d2002-08-28 03:00:58 +0000563
564 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000565 /* Invoke the coroutine to extract information from the SELECT
566 ** and add it to a transient table srcTab. The code generated
567 ** here is from the 4th template:
568 **
569 ** B: open temp table
570 ** L: yield X
571 ** if EOF goto M
572 ** insert row from R..R+n into temp table
573 ** goto L
574 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000575 */
drhdc5ea5c2008-12-10 17:19:59 +0000576 int regRec; /* Register to hold packed record */
577 int regTempRowid; /* Register to hold temp table ROWID */
578 int addrTop; /* Label "L" */
579 int addrIf; /* Address of jump to M */
drhb7654112008-01-12 12:48:07 +0000580
drh142e30d2002-08-28 03:00:58 +0000581 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000582 regRec = sqlite3GetTempReg(pParse);
drhdc5ea5c2008-12-10 17:19:59 +0000583 regTempRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000584 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh92b01d52008-06-24 00:32:35 +0000585 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000586 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh1db639c2008-01-17 02:36:28 +0000587 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000588 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
589 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drhe00ee6e2008-06-20 15:24:01 +0000590 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
591 sqlite3VdbeJumpHere(v, addrIf);
drhb7654112008-01-12 12:48:07 +0000592 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000593 sqlite3ReleaseTempReg(pParse, regTempRowid);
drh142e30d2002-08-28 03:00:58 +0000594 }
drh5974a302000-06-07 14:42:26 +0000595 }else{
drh142e30d2002-08-28 03:00:58 +0000596 /* This is the case if the data for the INSERT is coming from a VALUES
597 ** clause
598 */
danielk1977b3bce662005-01-29 08:32:43 +0000599 NameContext sNC;
600 memset(&sNC, 0, sizeof(sNC));
601 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000602 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000603 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000604 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000605 for(i=0; i<nColumn; i++){
drh7d10d5a2008-08-20 16:35:10 +0000606 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000607 goto insert_cleanup;
608 }
drhe64e7b22002-02-18 13:56:36 +0000609 }
drh5974a302000-06-07 14:42:26 +0000610 }
drh1ccde152000-06-17 13:12:39 +0000611
612 /* Make sure the number of columns in the source data matches the number
613 ** of columns to be inserted into the table.
614 */
danielk1977034ca142007-06-26 10:38:54 +0000615 if( IsVirtual(pTab) ){
616 for(i=0; i<pTab->nCol; i++){
617 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
618 }
619 }
620 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000621 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000622 "table %S has %d columns but %d values were supplied",
623 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000624 goto insert_cleanup;
625 }
drh967e8b72000-06-21 13:59:10 +0000626 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000627 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000628 goto insert_cleanup;
629 }
drh1ccde152000-06-17 13:12:39 +0000630
631 /* If the INSERT statement included an IDLIST term, then make sure
632 ** all elements of the IDLIST really are columns of the table and
633 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000634 **
635 ** If the table has an INTEGER PRIMARY KEY column and that column
636 ** is named in the IDLIST, then record in the keyColumn variable
637 ** the index into IDLIST of the primary key column. keyColumn is
638 ** the index of the primary key as it appears in IDLIST, not as
639 ** is appears in the original table. (The index of the primary
640 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000641 */
drh967e8b72000-06-21 13:59:10 +0000642 if( pColumn ){
643 for(i=0; i<pColumn->nId; i++){
644 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000645 }
drh967e8b72000-06-21 13:59:10 +0000646 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000647 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000648 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000649 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000650 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000651 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000652 }
drhcce7d172000-05-31 15:34:51 +0000653 break;
654 }
655 }
656 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000657 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000658 keyColumn = i;
659 }else{
danielk19774adee202004-05-08 08:23:19 +0000660 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000661 pTabList, 0, pColumn->a[i].zName);
662 pParse->nErr++;
663 goto insert_cleanup;
664 }
drhcce7d172000-05-31 15:34:51 +0000665 }
666 }
667 }
drh1ccde152000-06-17 13:12:39 +0000668
drhaacc5432002-01-06 17:07:40 +0000669 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000670 ** key, the set the keyColumn variable to the primary key column index
671 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000672 */
drh147d0cc2006-08-25 23:42:53 +0000673 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000674 keyColumn = pTab->iPKey;
675 }
676
drh142e30d2002-08-28 03:00:58 +0000677 /* Open the temp table for FOR EACH ROW triggers
678 */
drhdca76842004-12-07 14:06:13 +0000679 if( triggers_exist ){
danielk1977d336e222009-02-20 10:58:41 +0000680 sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000681 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000682
drhfeeb1392002-04-09 03:28:01 +0000683 /* Initialize the count of rows to be inserted
684 */
drh142e30d2002-08-28 03:00:58 +0000685 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000686 regRowCount = ++pParse->nMem;
687 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000688 }
689
danielk1977e448dc42008-01-02 11:50:51 +0000690 /* If this is not a view, open the table and and all indices */
691 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000692 int nIdx;
drhaa9b8962008-01-08 02:57:55 +0000693
drh04adf412008-01-08 18:57:50 +0000694 baseCur = pParse->nTab;
695 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drh5c070532008-04-11 15:36:03 +0000696 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000697 if( aRegIdx==0 ){
698 goto insert_cleanup;
699 }
700 for(i=0; i<nIdx; i++){
701 aRegIdx[i] = ++pParse->nMem;
702 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000703 }
704
drhe00ee6e2008-06-20 15:24:01 +0000705 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000706 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000707 /* This block codes the top of loop only. The complete loop is the
708 ** following pseudocode (template 4):
709 **
710 ** rewind temp table
711 ** C: loop over rows of intermediate table
712 ** transfer values form intermediate table into <table>
713 ** end loop
714 ** D: ...
715 */
716 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
717 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000718 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000719 /* This block codes the top of loop only. The complete loop is the
720 ** following pseudocode (template 3):
721 **
722 ** C: yield X
723 ** if EOF goto D
724 ** insert the select result into <table> from R..R+n
725 ** goto C
726 ** D: ...
727 */
drh92b01d52008-06-24 00:32:35 +0000728 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000729 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh5974a302000-06-07 14:42:26 +0000730 }
drh1ccde152000-06-17 13:12:39 +0000731
drh6a288a32008-01-07 19:20:24 +0000732 /* Allocate registers for holding the rowid of the new row,
733 ** the content of the new row, and the assemblied row record.
734 */
735 regRecord = ++pParse->nMem;
736 regRowid = regIns = pParse->nMem+1;
737 pParse->nMem += pTab->nCol + 1;
738 if( IsVirtual(pTab) ){
739 regRowid++;
740 pParse->nMem++;
741 }
742 regData = regRowid+1;
743
drh5cf590c2003-04-24 01:45:04 +0000744 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000745 */
danielk19774adee202004-05-08 08:23:19 +0000746 endOfLoop = sqlite3VdbeMakeLabel(v);
drhdca76842004-12-07 14:06:13 +0000747 if( triggers_exist & TRIGGER_BEFORE ){
drhdc5ea5c2008-12-10 17:19:59 +0000748 int regTrigRowid;
drh2d401ab2008-01-10 23:50:11 +0000749 int regCols;
750 int regRec;
danielk1977c3f9bad2002-05-15 08:30:12 +0000751
drh70ce3f02003-04-15 19:22:22 +0000752 /* build the NEW.* reference row. Note that if there is an INTEGER
753 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
754 ** translated into a unique ID for the row. But on a BEFORE trigger,
755 ** we do not know what the unique ID will be (because the insert has
756 ** not happened yet) so we substitute a rowid of -1
757 */
drhdc5ea5c2008-12-10 17:19:59 +0000758 regTrigRowid = sqlite3GetTempReg(pParse);
drh70ce3f02003-04-15 19:22:22 +0000759 if( keyColumn<0 ){
drhdc5ea5c2008-12-10 17:19:59 +0000760 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000761 }else if( useTempTable ){
drhdc5ea5c2008-12-10 17:19:59 +0000762 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000763 }else{
drh6a288a32008-01-07 19:20:24 +0000764 int j1;
drhd6fe9612005-01-14 01:22:00 +0000765 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drhdc5ea5c2008-12-10 17:19:59 +0000766 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
767 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
768 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
drh6a288a32008-01-07 19:20:24 +0000769 sqlite3VdbeJumpHere(v, j1);
drhdc5ea5c2008-12-10 17:19:59 +0000770 sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000771 }
772
danielk1977034ca142007-06-26 10:38:54 +0000773 /* Cannot have triggers on a virtual table. If it were possible,
774 ** this block would have to account for hidden column.
775 */
776 assert(!IsVirtual(pTab));
777
drh70ce3f02003-04-15 19:22:22 +0000778 /* Create the new column data
779 */
drh2d401ab2008-01-10 23:50:11 +0000780 regCols = sqlite3GetTempRange(pParse, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000781 for(i=0; i<pTab->nCol; i++){
782 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000783 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000784 }else{
drh9adf9ac2002-05-15 11:44:13 +0000785 for(j=0; j<pColumn->nId; j++){
786 if( pColumn->a[j].idx==i ) break;
787 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000788 }
789 if( pColumn && j>=pColumn->nId ){
drh2d401ab2008-01-10 23:50:11 +0000790 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
drh142e30d2002-08-28 03:00:58 +0000791 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000792 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000793 }else{
drhd6fe9612005-01-14 01:22:00 +0000794 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000795 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000796 }
797 }
drh2d401ab2008-01-10 23:50:11 +0000798 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +0000799 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +0000800
801 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
802 ** do not attempt any conversions before assembling the record.
803 ** If this is a real table, attempt conversions as required by the
804 ** table column affinities.
805 */
806 if( !isView ){
807 sqlite3TableAffinityStr(v, pTab);
808 }
drhdc5ea5c2008-12-10 17:19:59 +0000809 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
drh2d401ab2008-01-10 23:50:11 +0000810 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000811 sqlite3ReleaseTempReg(pParse, regTrigRowid);
drh2d401ab2008-01-10 23:50:11 +0000812 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000813
drh5cf590c2003-04-24 01:45:04 +0000814 /* Fire BEFORE or INSTEAD OF triggers */
drhdca76842004-12-07 14:06:13 +0000815 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
danielk19778f2c54e2008-01-01 19:02:09 +0000816 newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000817 goto insert_cleanup;
818 }
drh70ce3f02003-04-15 19:22:22 +0000819 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000820
drh4a324312001-12-21 14:30:42 +0000821 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000822 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000823 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000824 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000825 */
drh5cf590c2003-04-24 01:45:04 +0000826 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000827 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000828 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000829 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000830 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000831 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000832 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000833 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000834 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000835 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000836 }else{
drhe4d90812007-03-29 05:51:49 +0000837 VdbeOp *pOp;
drh1db639c2008-01-17 02:36:28 +0000838 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
drhe4d90812007-03-29 05:51:49 +0000839 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk1977bb50e7a2008-07-04 10:56:07 +0000840 if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000841 appendFlag = 1;
842 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000843 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000844 pOp->p2 = regRowid;
845 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000846 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000847 }
drhf0863fe2005-06-12 21:35:51 +0000848 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000849 ** to generate a unique primary key value.
850 */
drhe4d90812007-03-29 05:51:49 +0000851 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000852 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000853 if( !IsVirtual(pTab) ){
854 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
855 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
856 sqlite3VdbeJumpHere(v, j1);
857 }else{
858 j1 = sqlite3VdbeCurrentAddr(v);
859 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
860 }
drh3c84ddf2008-01-09 02:15:38 +0000861 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000862 }
drh4cbdda92006-06-14 19:00:20 +0000863 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000864 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000865 }else{
drh04adf412008-01-08 18:57:50 +0000866 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000867 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000868 }
drh6a288a32008-01-07 19:20:24 +0000869 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000870
danielk1977c3f9bad2002-05-15 08:30:12 +0000871 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000872 ** with the first column.
873 */
danielk1977034ca142007-06-26 10:38:54 +0000874 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000875 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000876 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000877 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000878 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000879 ** Whenever this column is read, the record number will be substituted
880 ** in its place. So will fill this column with a NULL to avoid
881 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000882 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000883 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000884 }
885 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000886 if( IsHiddenColumn(&pTab->aCol[i]) ){
887 assert( IsVirtual(pTab) );
888 j = -1;
889 nHidden++;
890 }else{
891 j = i - nHidden;
892 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000893 }else{
drh9adf9ac2002-05-15 11:44:13 +0000894 for(j=0; j<pColumn->nId; j++){
895 if( pColumn->a[j].idx==i ) break;
896 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000897 }
danielk1977034ca142007-06-26 10:38:54 +0000898 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000899 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000900 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000901 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000902 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000903 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000904 }else{
danielk1977287fb612008-01-04 19:10:28 +0000905 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000906 }
drhbed86902000-06-02 13:27:59 +0000907 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000908
909 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000910 ** do the insertion.
911 */
drh4cbdda92006-06-14 19:00:20 +0000912#ifndef SQLITE_OMIT_VIRTUALTABLE
913 if( IsVirtual(pTab) ){
drh4f3dd152008-04-28 18:46:43 +0000914 sqlite3VtabMakeWritable(pParse, pTab);
drh6a288a32008-01-07 19:20:24 +0000915 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000916 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000917 }else
918#endif
919 {
drh04adf412008-01-08 18:57:50 +0000920 sqlite3GenerateConstraintChecks(
921 pParse,
922 pTab,
923 baseCur,
924 regIns,
925 aRegIdx,
926 keyColumn>=0,
927 0,
928 onError,
929 endOfLoop
930 );
931 sqlite3CompleteInsertion(
932 pParse,
933 pTab,
934 baseCur,
935 regIns,
936 aRegIdx,
937 0,
drh04adf412008-01-08 18:57:50 +0000938 (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);
danielk197710fb7492008-10-31 10:53:22 +0000993 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000994 }
drhcce7d172000-05-31 15:34:51 +0000995
996insert_cleanup:
drh633e6d52008-07-28 19:34:53 +0000997 sqlite3SrcListDelete(db, pTabList);
998 sqlite3ExprListDelete(db, pList);
999 sqlite3SelectDelete(db, pSelect);
1000 sqlite3IdListDelete(db, pColumn);
1001 sqlite3DbFree(db, 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;
drh1bd10f82008-12-10 21:19:56 +00001096 int j1; /* Addresss of jump instruction */
1097 int j2 = 0, j3; /* Addresses of jump instructions */
drh04adf412008-01-08 18:57:50 +00001098 int regData; /* Register containing first data column */
drh0ca3e242002-01-29 23:07:02 +00001099 int iCur;
1100 Index *pIdx;
1101 int seenReplace = 0;
drhf0863fe2005-06-12 21:35:51 +00001102 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001103
danielk19774adee202004-05-08 08:23:19 +00001104 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001105 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001106 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001107 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001108 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001109
drhaa9b8962008-01-08 02:57:55 +00001110
drh9cfcf5d2002-01-29 18:41:24 +00001111 /* Test all NOT NULL constraints.
1112 */
1113 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001114 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001115 continue;
1116 }
drh9cfcf5d2002-01-29 18:41:24 +00001117 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001118 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001119 if( overrideError!=OE_Default ){
1120 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001121 }else if( onError==OE_Default ){
1122 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001123 }
danielk19777977a172004-11-09 12:44:37 +00001124 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001125 onError = OE_Abort;
1126 }
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;
drh5053a792009-02-20 03:02:23 +00001134 j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1135 SQLITE_CONSTRAINT, onError, regData+i);
drhf089aa42008-07-08 19:34:06 +00001136 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1137 pTab->zName, pTab->aCol[i].zName);
drh66a51672008-01-03 00:01:23 +00001138 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001139 break;
1140 }
1141 case OE_Ignore: {
drh5053a792009-02-20 03:02:23 +00001142 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001143 break;
1144 }
1145 case OE_Replace: {
drh5053a792009-02-20 03:02:23 +00001146 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
drh04adf412008-01-08 18:57:50 +00001147 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh5053a792009-02-20 03:02:23 +00001148 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001149 break;
1150 }
drh9cfcf5d2002-01-29 18:41:24 +00001151 }
1152 }
1153
1154 /* Test all CHECK constraints
1155 */
drhffe07b22005-11-03 00:41:17 +00001156#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001157 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001158 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001159 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001160 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001161 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001162 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001163 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001164 }else{
drh66a51672008-01-03 00:01:23 +00001165 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001166 }
drhffe07b22005-11-03 00:41:17 +00001167 sqlite3VdbeResolveLabel(v, allOk);
1168 }
1169#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001170
drh0bd1f4e2002-06-06 18:54:39 +00001171 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1172 ** of the new record does not previously exist. Except, if this
1173 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001174 */
drhf0863fe2005-06-12 21:35:51 +00001175 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001176 onError = pTab->keyConf;
1177 if( overrideError!=OE_Default ){
1178 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001179 }else if( onError==OE_Default ){
1180 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001181 }
drha0217ba2003-06-01 01:10:33 +00001182
drh60a713c2008-01-21 16:22:45 +00001183 if( onError!=OE_Replace || pTab->pIndex ){
drha05a7222008-01-19 03:35:58 +00001184 if( isUpdate ){
1185 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
drh79b0c952002-05-21 12:56:43 +00001186 }
drha05a7222008-01-19 03:35:58 +00001187 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1188 switch( onError ){
1189 default: {
1190 onError = OE_Abort;
1191 /* Fall thru into the next case */
drh5383ae52003-06-04 12:23:30 +00001192 }
drha05a7222008-01-19 03:35:58 +00001193 case OE_Rollback:
1194 case OE_Abort:
1195 case OE_Fail: {
1196 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1197 "PRIMARY KEY must be unique", P4_STATIC);
1198 break;
1199 }
1200 case OE_Replace: {
1201 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1202 seenReplace = 1;
1203 break;
1204 }
1205 case OE_Ignore: {
1206 assert( seenReplace==0 );
1207 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1208 break;
1209 }
drh0ca3e242002-01-29 23:07:02 +00001210 }
drha05a7222008-01-19 03:35:58 +00001211 sqlite3VdbeJumpHere(v, j3);
1212 if( isUpdate ){
1213 sqlite3VdbeJumpHere(v, j2);
drh5383ae52003-06-04 12:23:30 +00001214 }
1215 }
drh0ca3e242002-01-29 23:07:02 +00001216 }
drh0bd1f4e2002-06-06 18:54:39 +00001217
1218 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1219 ** index and making sure that duplicate entries do not already exist.
1220 ** Add the new records to the indices as we go.
1221 */
drhb2fe7d82003-04-20 17:29:23 +00001222 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001223 int regIdx;
1224 int regR;
1225
drhaa9b8962008-01-08 02:57:55 +00001226 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001227
1228 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001229 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001230 for(i=0; i<pIdx->nColumn; i++){
1231 int idx = pIdx->aiColumn[i];
1232 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001233 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001234 }else{
drh2d401ab2008-01-10 23:50:11 +00001235 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001236 }
1237 }
drh2d401ab2008-01-10 23:50:11 +00001238 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh1db639c2008-01-17 02:36:28 +00001239 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001240 sqlite3IndexAffinityStr(v, pIdx);
drhda250ea2008-04-01 05:07:14 +00001241 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
drh2d401ab2008-01-10 23:50:11 +00001242 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001243
1244 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001245 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001246 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001247 if( overrideError!=OE_Default ){
1248 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001249 }else if( onError==OE_Default ){
1250 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001251 }
drh5383ae52003-06-04 12:23:30 +00001252 if( seenReplace ){
1253 if( onError==OE_Ignore ) onError = OE_Replace;
1254 else if( onError==OE_Fail ) onError = OE_Abort;
1255 }
1256
drhb2fe7d82003-04-20 17:29:23 +00001257
1258 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001259 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
1260 regR = sqlite3GetTempReg(pParse);
1261 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
1262 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
shane1fc41292008-07-08 22:28:48 +00001263 regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
mlcreecha9e852b2008-03-06 09:58:50 +00001264 P4_INT32);
drhb2fe7d82003-04-20 17:29:23 +00001265
1266 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001267 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1268 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001269 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001270 case OE_Rollback:
1271 case OE_Abort:
1272 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001273 int j, n1, n2;
1274 char zErrMsg[200];
danielk197700e13612008-11-17 19:18:54 +00001275 sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
drh5bb3eb92007-05-04 13:15:55 +00001276 pIdx->nColumn>1 ? "columns " : "column ");
drhea678832008-12-10 19:26:22 +00001277 n1 = sqlite3Strlen30(zErrMsg);
danielk197700e13612008-11-17 19:18:54 +00001278 for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
drh37ed48e2003-08-05 13:13:38 +00001279 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
drhea678832008-12-10 19:26:22 +00001280 n2 = sqlite3Strlen30(zCol);
drh37ed48e2003-08-05 13:13:38 +00001281 if( j>0 ){
danielk197700e13612008-11-17 19:18:54 +00001282 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001283 n1 += 2;
1284 }
danielk197700e13612008-11-17 19:18:54 +00001285 if( n1+n2>ArraySize(zErrMsg)-30 ){
1286 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001287 n1 += 3;
1288 break;
1289 }else{
danielk197700e13612008-11-17 19:18:54 +00001290 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001291 n1 += n2;
1292 }
1293 }
danielk197700e13612008-11-17 19:18:54 +00001294 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001295 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001296 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001297 break;
1298 }
1299 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001300 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001301 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001302 break;
1303 }
1304 case OE_Replace: {
drh2d401ab2008-01-10 23:50:11 +00001305 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
drh0ca3e242002-01-29 23:07:02 +00001306 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001307 break;
1308 }
drh9cfcf5d2002-01-29 18:41:24 +00001309 }
drhaa9b8962008-01-08 02:57:55 +00001310 sqlite3VdbeJumpHere(v, j2);
drh2d401ab2008-01-10 23:50:11 +00001311 sqlite3VdbeJumpHere(v, j3);
1312 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001313 }
1314}
drh0ca3e242002-01-29 23:07:02 +00001315
1316/*
1317** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001318** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001319** A consecutive range of registers starting at regRowid contains the
1320** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001321**
drhb419a922002-01-30 16:17:23 +00001322** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001323** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001324*/
danielk19774adee202004-05-08 08:23:19 +00001325void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001326 Parse *pParse, /* The parser context */
1327 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001328 int baseCur, /* Index of a read/write cursor pointing at pTab */
1329 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001330 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh70ce3f02003-04-15 19:22:22 +00001331 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001332 int newIdx, /* Index of NEW table for triggers. -1 if none */
1333 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001334){
1335 int i;
1336 Vdbe *v;
1337 int nIdx;
1338 Index *pIdx;
drh1bd10f82008-12-10 21:19:56 +00001339 u8 pik_flags;
drh04adf412008-01-08 18:57:50 +00001340 int regData;
drhb7654112008-01-12 12:48:07 +00001341 int regRec;
drh0ca3e242002-01-29 23:07:02 +00001342
danielk19774adee202004-05-08 08:23:19 +00001343 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001344 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001345 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001346 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1347 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001348 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001349 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
drh0ca3e242002-01-29 23:07:02 +00001350 }
drh04adf412008-01-08 18:57:50 +00001351 regData = regRowid + 1;
drhb7654112008-01-12 12:48:07 +00001352 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001353 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +00001354 sqlite3TableAffinityStr(v, pTab);
drhda250ea2008-04-01 05:07:14 +00001355 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
danielk1977b84f96f2005-01-20 11:32:23 +00001356#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001357 if( newIdx>=0 ){
drhb7654112008-01-12 12:48:07 +00001358 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
drh70ce3f02003-04-15 19:22:22 +00001359 }
danielk1977b84f96f2005-01-20 11:32:23 +00001360#endif
drh4794f732004-11-05 17:17:50 +00001361 if( pParse->nested ){
1362 pik_flags = 0;
1363 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001364 pik_flags = OPFLAG_NCHANGE;
1365 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001366 }
drhe4d90812007-03-29 05:51:49 +00001367 if( appendBias ){
1368 pik_flags |= OPFLAG_APPEND;
1369 }
drhb7654112008-01-12 12:48:07 +00001370 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
danielk197794eb6a12005-12-15 15:22:08 +00001371 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001372 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001373 }
drhb7654112008-01-12 12:48:07 +00001374 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001375}
drhcd446902004-02-24 01:05:31 +00001376
1377/*
drh290c1942004-08-21 17:54:45 +00001378** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001379** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001380** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001381**
1382** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001383*/
drhaa9b8962008-01-08 02:57:55 +00001384int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001385 Parse *pParse, /* Parsing context */
1386 Table *pTab, /* Table to be opened */
drhdfe88ec2008-11-03 20:55:06 +00001387 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001388 int op /* OP_OpenRead or OP_OpenWrite */
1389){
drhcd446902004-02-24 01:05:31 +00001390 int i;
drh4cbdda92006-06-14 19:00:20 +00001391 int iDb;
drhcd446902004-02-24 01:05:31 +00001392 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001393 Vdbe *v;
1394
drhaa9b8962008-01-08 02:57:55 +00001395 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001396 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1397 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001398 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001399 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001400 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001401 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001402 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001403 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001404 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001405 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001406 }
drh04adf412008-01-08 18:57:50 +00001407 if( pParse->nTab<=baseCur+i ){
1408 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001409 }
drhaa9b8962008-01-08 02:57:55 +00001410 return i-1;
drhcd446902004-02-24 01:05:31 +00001411}
drh9d9cf222007-02-13 15:01:11 +00001412
drh91c58e22007-03-27 12:04:04 +00001413
1414#ifdef SQLITE_TEST
1415/*
1416** The following global variable is incremented whenever the
1417** transfer optimization is used. This is used for testing
1418** purposes only - to make sure the transfer optimization really
1419** is happening when it is suppose to.
1420*/
1421int sqlite3_xferopt_count;
1422#endif /* SQLITE_TEST */
1423
1424
drh9d9cf222007-02-13 15:01:11 +00001425#ifndef SQLITE_OMIT_XFER_OPT
1426/*
1427** Check to collation names to see if they are compatible.
1428*/
1429static int xferCompatibleCollation(const char *z1, const char *z2){
1430 if( z1==0 ){
1431 return z2==0;
1432 }
1433 if( z2==0 ){
1434 return 0;
1435 }
1436 return sqlite3StrICmp(z1, z2)==0;
1437}
1438
1439
1440/*
1441** Check to see if index pSrc is compatible as a source of data
1442** for index pDest in an insert transfer optimization. The rules
1443** for a compatible index:
1444**
1445** * The index is over the same set of columns
1446** * The same DESC and ASC markings occurs on all columns
1447** * The same onError processing (OE_Abort, OE_Ignore, etc)
1448** * The same collating sequence on each column
1449*/
1450static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1451 int i;
1452 assert( pDest && pSrc );
1453 assert( pDest->pTable!=pSrc->pTable );
1454 if( pDest->nColumn!=pSrc->nColumn ){
1455 return 0; /* Different number of columns */
1456 }
1457 if( pDest->onError!=pSrc->onError ){
1458 return 0; /* Different conflict resolution strategies */
1459 }
1460 for(i=0; i<pSrc->nColumn; i++){
1461 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1462 return 0; /* Different columns indexed */
1463 }
1464 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1465 return 0; /* Different sort orders */
1466 }
1467 if( pSrc->azColl[i]!=pDest->azColl[i] ){
drh60a713c2008-01-21 16:22:45 +00001468 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001469 }
1470 }
1471
1472 /* If no test above fails then the indices must be compatible */
1473 return 1;
1474}
1475
1476/*
1477** Attempt the transfer optimization on INSERTs of the form
1478**
1479** INSERT INTO tab1 SELECT * FROM tab2;
1480**
1481** This optimization is only attempted if
1482**
1483** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001484** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001485**
1486** (2) tab1 and tab2 are different tables
1487**
1488** (3) There must be no triggers on tab1
1489**
1490** (4) The result set of the SELECT statement is "*"
1491**
1492** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1493** or LIMIT clause.
1494**
1495** (6) The SELECT statement is a simple (not a compound) select that
1496** contains only tab2 in its FROM clause
1497**
1498** This method for implementing the INSERT transfers raw records from
1499** tab2 over to tab1. The columns are not decoded. Raw records from
1500** the indices of tab2 are transfered to tab1 as well. In so doing,
1501** the resulting tab1 has much less fragmentation.
1502**
1503** This routine returns TRUE if the optimization is attempted. If any
1504** of the conditions above fail so that the optimization should not
1505** be attempted, then this routine returns FALSE.
1506*/
1507static int xferOptimization(
1508 Parse *pParse, /* Parser context */
1509 Table *pDest, /* The table we are inserting into */
1510 Select *pSelect, /* A SELECT statement to use as the data source */
1511 int onError, /* How to handle constraint errors */
1512 int iDbDest /* The database of pDest */
1513){
1514 ExprList *pEList; /* The result set of the SELECT */
1515 Table *pSrc; /* The table in the FROM clause of SELECT */
1516 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1517 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1518 int i; /* Loop counter */
1519 int iDbSrc; /* The database of pSrc */
1520 int iSrc, iDest; /* Cursors from source and destination */
1521 int addr1, addr2; /* Loop addresses */
1522 int emptyDestTest; /* Address of test for empty pDest */
1523 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001524 Vdbe *v; /* The VDBE we are building */
1525 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001526 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001527 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001528 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001529
1530 if( pSelect==0 ){
1531 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1532 }
1533 if( pDest->pTrigger ){
1534 return 0; /* tab1 must not have triggers */
1535 }
1536#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001537 if( pDest->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001538 return 0; /* tab1 must not be a virtual table */
1539 }
1540#endif
1541 if( onError==OE_Default ){
1542 onError = OE_Abort;
1543 }
1544 if( onError!=OE_Abort && onError!=OE_Rollback ){
1545 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1546 }
danielk19775ce240a2007-09-03 17:30:06 +00001547 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001548 if( pSelect->pSrc->nSrc!=1 ){
1549 return 0; /* FROM clause must have exactly one term */
1550 }
1551 if( pSelect->pSrc->a[0].pSelect ){
1552 return 0; /* FROM clause cannot contain a subquery */
1553 }
1554 if( pSelect->pWhere ){
1555 return 0; /* SELECT may not have a WHERE clause */
1556 }
1557 if( pSelect->pOrderBy ){
1558 return 0; /* SELECT may not have an ORDER BY clause */
1559 }
drh8103b7d2007-02-24 13:23:51 +00001560 /* Do not need to test for a HAVING clause. If HAVING is present but
1561 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001562 if( pSelect->pGroupBy ){
1563 return 0; /* SELECT may not have a GROUP BY clause */
1564 }
1565 if( pSelect->pLimit ){
1566 return 0; /* SELECT may not have a LIMIT clause */
1567 }
drh8103b7d2007-02-24 13:23:51 +00001568 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001569 if( pSelect->pPrior ){
1570 return 0; /* SELECT may not be a compound query */
1571 }
drh7d10d5a2008-08-20 16:35:10 +00001572 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:11 +00001573 return 0; /* SELECT may not be DISTINCT */
1574 }
1575 pEList = pSelect->pEList;
1576 assert( pEList!=0 );
1577 if( pEList->nExpr!=1 ){
1578 return 0; /* The result set must have exactly one column */
1579 }
1580 assert( pEList->a[0].pExpr );
1581 if( pEList->a[0].pExpr->op!=TK_ALL ){
1582 return 0; /* The result set must be the special operator "*" */
1583 }
1584
1585 /* At this point we have established that the statement is of the
1586 ** correct syntactic form to participate in this optimization. Now
1587 ** we have to check the semantics.
1588 */
1589 pItem = pSelect->pSrc->a;
drhca424112008-01-25 15:04:48 +00001590 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
drh9d9cf222007-02-13 15:01:11 +00001591 if( pSrc==0 ){
1592 return 0; /* FROM clause does not contain a real table */
1593 }
1594 if( pSrc==pDest ){
1595 return 0; /* tab1 and tab2 may not be the same table */
1596 }
1597#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001598 if( pSrc->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001599 return 0; /* tab2 must not be a virtual table */
1600 }
1601#endif
1602 if( pSrc->pSelect ){
1603 return 0; /* tab2 may not be a view */
1604 }
1605 if( pDest->nCol!=pSrc->nCol ){
1606 return 0; /* Number of columns must be the same in tab1 and tab2 */
1607 }
1608 if( pDest->iPKey!=pSrc->iPKey ){
1609 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1610 }
1611 for(i=0; i<pDest->nCol; i++){
1612 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1613 return 0; /* Affinity must be the same on all columns */
1614 }
1615 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1616 return 0; /* Collating sequence must be the same on all columns */
1617 }
1618 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1619 return 0; /* tab2 must be NOT NULL if tab1 is */
1620 }
1621 }
1622 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001623 if( pDestIdx->onError!=OE_None ){
1624 destHasUniqueIdx = 1;
1625 }
drh9d9cf222007-02-13 15:01:11 +00001626 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1627 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1628 }
1629 if( pSrcIdx==0 ){
1630 return 0; /* pDestIdx has no corresponding index in pSrc */
1631 }
1632 }
drh7fc2f412007-03-29 00:08:24 +00001633#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001634 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001635 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1636 }
drh7fc2f412007-03-29 00:08:24 +00001637#endif
drh9d9cf222007-02-13 15:01:11 +00001638
1639 /* If we get this far, it means either:
1640 **
1641 ** * We can always do the transfer if the table contains an
1642 ** an integer primary key
1643 **
1644 ** * We can conditionally do the transfer if the destination
1645 ** table is empty.
1646 */
drhdd735212007-02-24 13:53:05 +00001647#ifdef SQLITE_TEST
1648 sqlite3_xferopt_count++;
1649#endif
drh9d9cf222007-02-13 15:01:11 +00001650 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1651 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001652 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001653 iSrc = pParse->nTab++;
1654 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001655 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001656 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001657 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001658 /* If tables do not have an INTEGER PRIMARY KEY and there
1659 ** are indices to be copied and the destination is not empty,
1660 ** we have to disallow the transfer optimization because the
1661 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001662 **
1663 ** Or if the destination has a UNIQUE index and is not empty,
1664 ** we also disallow the transfer optimization because we cannot
1665 ** insure that all entries in the union of DEST and SRC will be
1666 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001667 */
drh66a51672008-01-03 00:01:23 +00001668 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1669 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001670 sqlite3VdbeJumpHere(v, addr1);
1671 }else{
1672 emptyDestTest = 0;
1673 }
1674 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001675 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001676 regData = sqlite3GetTempReg(pParse);
1677 regRowid = sqlite3GetTempReg(pParse);
drh42242de2007-03-29 13:35:35 +00001678 if( pDest->iPKey>=0 ){
drhb7654112008-01-12 12:48:07 +00001679 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1680 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
drh66a51672008-01-03 00:01:23 +00001681 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1682 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001683 sqlite3VdbeJumpHere(v, addr2);
drhb7654112008-01-12 12:48:07 +00001684 autoIncStep(pParse, regAutoinc, regRowid);
drhbd36ba62007-03-31 13:00:26 +00001685 }else if( pDest->pIndex==0 ){
drhb7654112008-01-12 12:48:07 +00001686 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
drh95bad4c2007-03-28 18:04:10 +00001687 }else{
drhb7654112008-01-12 12:48:07 +00001688 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
drh7d10d5a2008-08-20 16:35:10 +00001689 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
drh95bad4c2007-03-28 18:04:10 +00001690 }
drhb7654112008-01-12 12:48:07 +00001691 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1692 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1693 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
danielk19771f4aa332008-01-03 09:51:55 +00001694 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001695 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001696 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001697 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1698 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1699 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1700 }
1701 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001702 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1703 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001704 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001705 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1706 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001707 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001708 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001709 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001710 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001711 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001712 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001713 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1714 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh66a51672008-01-03 00:01:23 +00001715 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001716 sqlite3VdbeJumpHere(v, addr1);
1717 }
1718 sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00001719 sqlite3ReleaseTempReg(pParse, regRowid);
1720 sqlite3ReleaseTempReg(pParse, regData);
drh66a51672008-01-03 00:01:23 +00001721 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1722 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001723 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001724 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001725 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001726 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001727 return 0;
1728 }else{
1729 return 1;
1730 }
1731}
1732#endif /* SQLITE_OMIT_XFER_OPT */
drhf39d9582008-03-19 20:42:13 +00001733
1734/* Make sure "isView" gets undefined in case this file becomes part of
1735** the amalgamation - so that subsequent files do not see isView as a
1736** macro. */
1737#undef isView