blob: 9b23c86667c03bad9528a30cc4eb7347e5db9df0 [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**
danielk19772f886d12009-02-28 10:47:41 +000015** $Id: insert.c,v 1.260 2009/02/28 10:47: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 */
danielk19772f886d12009-02-28 10:47:41 +0000404 Trigger *pTrigger; /* List of triggers on pTab, if required */
405 int tmask; /* Mask of trigger times */
drh798da522004-11-04 04:42:28 +0000406#endif
danielk1977c3f9bad2002-05-15 08:30:12 +0000407
drh17435752007-08-16 04:30:38 +0000408 db = pParse->db;
drh1bd10f82008-12-10 21:19:56 +0000409 memset(&dest, 0, sizeof(dest));
drh17435752007-08-16 04:30:38 +0000410 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000411 goto insert_cleanup;
412 }
drhdaffd0e2001-04-11 14:28:42 +0000413
drh1ccde152000-06-17 13:12:39 +0000414 /* Locate the table into which we will be inserting new information.
415 */
drh113088e2003-03-20 01:16:58 +0000416 assert( pTabList->nSrc==1 );
417 zTab = pTabList->a[0].zName;
drhdaffd0e2001-04-11 14:28:42 +0000418 if( zTab==0 ) goto insert_cleanup;
danielk19774adee202004-05-08 08:23:19 +0000419 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12 +0000420 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000421 goto insert_cleanup;
422 }
danielk1977da184232006-01-05 11:34:32 +0000423 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
424 assert( iDb<db->nDb );
425 pDb = &db->aDb[iDb];
drh2958a4e2004-11-12 03:56:15 +0000426 zDb = pDb->zName;
danielk19774adee202004-05-08 08:23:19 +0000427 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
drh1962bda2003-01-12 19:33:52 +0000428 goto insert_cleanup;
429 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000430
drhb7f91642004-10-31 02:22:47 +0000431 /* Figure out if we have any triggers and if the table being
432 ** inserted into is a view
433 */
434#ifndef SQLITE_OMIT_TRIGGER
danielk19772f886d12009-02-28 10:47:41 +0000435 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
drhb7f91642004-10-31 02:22:47 +0000436 isView = pTab->pSelect!=0;
437#else
danielk19772f886d12009-02-28 10:47:41 +0000438# define pTrigger 0
439# define tmask 0
drhb7f91642004-10-31 02:22:47 +0000440# define isView 0
441#endif
442#ifdef SQLITE_OMIT_VIEW
443# undef isView
444# define isView 0
445#endif
danielk19772f886d12009-02-28 10:47:41 +0000446 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
drhb7f91642004-10-31 02:22:47 +0000447
danielk1977c3f9bad2002-05-15 08:30:12 +0000448 /* Ensure that:
449 * (a) the table is not read-only,
450 * (b) that if it is a view then ON INSERT triggers exist
451 */
danielk19772f886d12009-02-28 10:47:41 +0000452 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000453 goto insert_cleanup;
454 }
drh43617e92006-03-06 20:55:46 +0000455 assert( pTab!=0 );
drh1ccde152000-06-17 13:12:39 +0000456
drhf573c992002-07-31 00:32:50 +0000457 /* If pTab is really a view, make sure it has been initialized.
danielk1977b3d24bf2006-06-19 03:05:10 +0000458 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
459 ** module table).
drhf573c992002-07-31 00:32:50 +0000460 */
danielk1977b3d24bf2006-06-19 03:05:10 +0000461 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:04 +0000462 goto insert_cleanup;
drhf573c992002-07-31 00:32:50 +0000463 }
464
drh1ccde152000-06-17 13:12:39 +0000465 /* Allocate a VDBE
466 */
danielk19774adee202004-05-08 08:23:19 +0000467 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:26 +0000468 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:50 +0000469 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk19772f886d12009-02-28 10:47:41 +0000470 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
drh1ccde152000-06-17 13:12:39 +0000471
danielk1977c3f9bad2002-05-15 08:30:12 +0000472 /* if there are row triggers, allocate a temp table for new.* references. */
danielk19772f886d12009-02-28 10:47:41 +0000473 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000474 newIdx = pParse->nTab++;
danielk1977f29ce552002-05-19 23:43:12 +0000475 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000476
drh9d9cf222007-02-13 15:01:11 +0000477#ifndef SQLITE_OMIT_XFER_OPT
478 /* If the statement is of the form
479 **
480 ** INSERT INTO <table1> SELECT * FROM <table2>;
481 **
482 ** Then special optimizations can be applied that make the transfer
483 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:01 +0000484 **
485 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:11 +0000486 */
487 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
danielk19772f886d12009-02-28 10:47:41 +0000488 assert( !pTrigger );
drh9d9cf222007-02-13 15:01:11 +0000489 assert( pList==0 );
490 goto insert_cleanup;
491 }
492#endif /* SQLITE_OMIT_XFER_OPT */
493
drh2958a4e2004-11-12 03:56:15 +0000494 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:24 +0000495 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:15 +0000496 */
drh6a288a32008-01-07 19:20:24 +0000497 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:15 +0000498
drh1ccde152000-06-17 13:12:39 +0000499 /* Figure out how many columns of data are supplied. If the data
drhe00ee6e2008-06-20 15:24:01 +0000500 ** is coming from a SELECT statement, then generate a co-routine that
501 ** produces a single row of the SELECT on each invocation. The
502 ** co-routine is the common header to the 3rd and 4th templates.
drh1ccde152000-06-17 13:12:39 +0000503 */
drh5974a302000-06-07 14:42:26 +0000504 if( pSelect ){
drh142e30d2002-08-28 03:00:58 +0000505 /* Data is coming from a SELECT. Generate code to implement that SELECT
drhe00ee6e2008-06-20 15:24:01 +0000506 ** as a co-routine. The code is common to both the 3rd and 4th
507 ** templates:
508 **
509 ** EOF <- 0
510 ** X <- A
511 ** goto B
512 ** A: setup for the SELECT
513 ** loop over the tables in the SELECT
514 ** load value into register R..R+n
515 ** yield X
516 ** end loop
517 ** cleanup after the SELECT
518 ** EOF <- 1
519 ** yield X
520 ** halt-error
521 **
522 ** On each invocation of the co-routine, it puts a single row of the
523 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
524 ** (These output registers are allocated by sqlite3Select().) When
525 ** the SELECT completes, it sets the EOF flag stored in regEof.
drh142e30d2002-08-28 03:00:58 +0000526 */
drhe00ee6e2008-06-20 15:24:01 +0000527 int rc, j1;
drh1013c932008-01-06 00:25:21 +0000528
drhe00ee6e2008-06-20 15:24:01 +0000529 regEof = ++pParse->nMem;
530 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
531 VdbeComment((v, "SELECT eof flag"));
drh92b01d52008-06-24 00:32:35 +0000532 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
drhe00ee6e2008-06-20 15:24:01 +0000533 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
drh92b01d52008-06-24 00:32:35 +0000534 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000535 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
536 VdbeComment((v, "Jump over SELECT coroutine"));
danielk1977b3bce662005-01-29 08:32:43 +0000537
538 /* Resolve the expressions in the SELECT statement and execute it. */
drh7d10d5a2008-08-20 16:35:10 +0000539 rc = sqlite3Select(pParse, pSelect, &dest);
drh17435752007-08-16 04:30:38 +0000540 if( rc || pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +0000541 goto insert_cleanup;
542 }
drhe00ee6e2008-06-20 15:24:01 +0000543 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
drh92b01d52008-06-24 00:32:35 +0000544 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
drhe00ee6e2008-06-20 15:24:01 +0000545 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
546 VdbeComment((v, "End of SELECT coroutine"));
547 sqlite3VdbeJumpHere(v, j1); /* label B: */
danielk1977b3bce662005-01-29 08:32:43 +0000548
drh6a288a32008-01-07 19:20:24 +0000549 regFromSelect = dest.iMem;
drh5974a302000-06-07 14:42:26 +0000550 assert( pSelect->pEList );
drh967e8b72000-06-21 13:59:10 +0000551 nColumn = pSelect->pEList->nExpr;
drhe00ee6e2008-06-20 15:24:01 +0000552 assert( dest.nMem==nColumn );
drh142e30d2002-08-28 03:00:58 +0000553
554 /* Set useTempTable to TRUE if the result of the SELECT statement
drhe00ee6e2008-06-20 15:24:01 +0000555 ** should be written into a temporary table (template 4). Set to
556 ** FALSE if each* row of the SELECT can be written directly into
557 ** the destination table (template 3).
drh048c5302003-04-03 01:50:44 +0000558 **
559 ** A temp table must be used if the table being updated is also one
560 ** of the tables being read by the SELECT statement. Also use a
561 ** temp table in the case of row triggers.
drh142e30d2002-08-28 03:00:58 +0000562 */
danielk19772f886d12009-02-28 10:47:41 +0000563 if( pTrigger || readsTable(v, addrSelect, iDb, pTab) ){
drh048c5302003-04-03 01:50:44 +0000564 useTempTable = 1;
drh048c5302003-04-03 01:50:44 +0000565 }
drh142e30d2002-08-28 03:00:58 +0000566
567 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000568 /* Invoke the coroutine to extract information from the SELECT
569 ** and add it to a transient table srcTab. The code generated
570 ** here is from the 4th template:
571 **
572 ** B: open temp table
573 ** L: yield X
574 ** if EOF goto M
575 ** insert row from R..R+n into temp table
576 ** goto L
577 ** M: ...
drh142e30d2002-08-28 03:00:58 +0000578 */
drhdc5ea5c2008-12-10 17:19:59 +0000579 int regRec; /* Register to hold packed record */
580 int regTempRowid; /* Register to hold temp table ROWID */
581 int addrTop; /* Label "L" */
582 int addrIf; /* Address of jump to M */
drhb7654112008-01-12 12:48:07 +0000583
drh142e30d2002-08-28 03:00:58 +0000584 srcTab = pParse->nTab++;
drhb7654112008-01-12 12:48:07 +0000585 regRec = sqlite3GetTempReg(pParse);
drhdc5ea5c2008-12-10 17:19:59 +0000586 regTempRowid = sqlite3GetTempReg(pParse);
drhe00ee6e2008-06-20 15:24:01 +0000587 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh92b01d52008-06-24 00:32:35 +0000588 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000589 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh1db639c2008-01-17 02:36:28 +0000590 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000591 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
592 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drhe00ee6e2008-06-20 15:24:01 +0000593 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
594 sqlite3VdbeJumpHere(v, addrIf);
drhb7654112008-01-12 12:48:07 +0000595 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000596 sqlite3ReleaseTempReg(pParse, regTempRowid);
drh142e30d2002-08-28 03:00:58 +0000597 }
drh5974a302000-06-07 14:42:26 +0000598 }else{
drh142e30d2002-08-28 03:00:58 +0000599 /* This is the case if the data for the INSERT is coming from a VALUES
600 ** clause
601 */
danielk1977b3bce662005-01-29 08:32:43 +0000602 NameContext sNC;
603 memset(&sNC, 0, sizeof(sNC));
604 sNC.pParse = pParse;
drh5974a302000-06-07 14:42:26 +0000605 srcTab = -1;
drh48d11782007-11-23 15:02:19 +0000606 assert( useTempTable==0 );
drh147d0cc2006-08-25 23:42:53 +0000607 nColumn = pList ? pList->nExpr : 0;
drhe64e7b22002-02-18 13:56:36 +0000608 for(i=0; i<nColumn; i++){
drh7d10d5a2008-08-20 16:35:10 +0000609 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
drhb04a5d82002-04-12 03:55:15 +0000610 goto insert_cleanup;
611 }
drhe64e7b22002-02-18 13:56:36 +0000612 }
drh5974a302000-06-07 14:42:26 +0000613 }
drh1ccde152000-06-17 13:12:39 +0000614
615 /* Make sure the number of columns in the source data matches the number
616 ** of columns to be inserted into the table.
617 */
danielk1977034ca142007-06-26 10:38:54 +0000618 if( IsVirtual(pTab) ){
619 for(i=0; i<pTab->nCol; i++){
620 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
621 }
622 }
623 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
danielk19774adee202004-05-08 08:23:19 +0000624 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000625 "table %S has %d columns but %d values were supplied",
626 pTabList, 0, pTab->nCol, nColumn);
drhcce7d172000-05-31 15:34:51 +0000627 goto insert_cleanup;
628 }
drh967e8b72000-06-21 13:59:10 +0000629 if( pColumn!=0 && nColumn!=pColumn->nId ){
danielk19774adee202004-05-08 08:23:19 +0000630 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
drhcce7d172000-05-31 15:34:51 +0000631 goto insert_cleanup;
632 }
drh1ccde152000-06-17 13:12:39 +0000633
634 /* If the INSERT statement included an IDLIST term, then make sure
635 ** all elements of the IDLIST really are columns of the table and
636 ** remember the column indices.
drhc8392582001-12-31 02:48:51 +0000637 **
638 ** If the table has an INTEGER PRIMARY KEY column and that column
639 ** is named in the IDLIST, then record in the keyColumn variable
640 ** the index into IDLIST of the primary key column. keyColumn is
641 ** the index of the primary key as it appears in IDLIST, not as
642 ** is appears in the original table. (The index of the primary
643 ** key in the original table is pTab->iPKey.)
drh1ccde152000-06-17 13:12:39 +0000644 */
drh967e8b72000-06-21 13:59:10 +0000645 if( pColumn ){
646 for(i=0; i<pColumn->nId; i++){
647 pColumn->a[i].idx = -1;
drhcce7d172000-05-31 15:34:51 +0000648 }
drh967e8b72000-06-21 13:59:10 +0000649 for(i=0; i<pColumn->nId; i++){
drhcce7d172000-05-31 15:34:51 +0000650 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +0000651 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
drh967e8b72000-06-21 13:59:10 +0000652 pColumn->a[i].idx = j;
drh4a324312001-12-21 14:30:42 +0000653 if( j==pTab->iPKey ){
drh9aa028d2001-12-22 21:48:29 +0000654 keyColumn = i;
drh4a324312001-12-21 14:30:42 +0000655 }
drhcce7d172000-05-31 15:34:51 +0000656 break;
657 }
658 }
659 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +0000660 if( sqlite3IsRowid(pColumn->a[i].zName) ){
drha0217ba2003-06-01 01:10:33 +0000661 keyColumn = i;
662 }else{
danielk19774adee202004-05-08 08:23:19 +0000663 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha0217ba2003-06-01 01:10:33 +0000664 pTabList, 0, pColumn->a[i].zName);
665 pParse->nErr++;
666 goto insert_cleanup;
667 }
drhcce7d172000-05-31 15:34:51 +0000668 }
669 }
670 }
drh1ccde152000-06-17 13:12:39 +0000671
drhaacc5432002-01-06 17:07:40 +0000672 /* If there is no IDLIST term but the table has an integer primary
drhc8392582001-12-31 02:48:51 +0000673 ** key, the set the keyColumn variable to the primary key column index
674 ** in the original table definition.
drh4a324312001-12-21 14:30:42 +0000675 */
drh147d0cc2006-08-25 23:42:53 +0000676 if( pColumn==0 && nColumn>0 ){
drh4a324312001-12-21 14:30:42 +0000677 keyColumn = pTab->iPKey;
678 }
679
drh142e30d2002-08-28 03:00:58 +0000680 /* Open the temp table for FOR EACH ROW triggers
681 */
danielk19772f886d12009-02-28 10:47:41 +0000682 if( pTrigger ){
danielk1977d336e222009-02-20 10:58:41 +0000683 sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
danielk1977f29ce552002-05-19 23:43:12 +0000684 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000685
drhfeeb1392002-04-09 03:28:01 +0000686 /* Initialize the count of rows to be inserted
687 */
drh142e30d2002-08-28 03:00:58 +0000688 if( db->flags & SQLITE_CountRows ){
drh6a288a32008-01-07 19:20:24 +0000689 regRowCount = ++pParse->nMem;
690 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:01 +0000691 }
692
danielk1977e448dc42008-01-02 11:50:51 +0000693 /* If this is not a view, open the table and and all indices */
694 if( !isView ){
drhaa9b8962008-01-08 02:57:55 +0000695 int nIdx;
drhaa9b8962008-01-08 02:57:55 +0000696
drh04adf412008-01-08 18:57:50 +0000697 baseCur = pParse->nTab;
698 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
drh5c070532008-04-11 15:36:03 +0000699 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
drhaa9b8962008-01-08 02:57:55 +0000700 if( aRegIdx==0 ){
701 goto insert_cleanup;
702 }
703 for(i=0; i<nIdx; i++){
704 aRegIdx[i] = ++pParse->nMem;
705 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000706 }
707
drhe00ee6e2008-06-20 15:24:01 +0000708 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:58 +0000709 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000710 /* This block codes the top of loop only. The complete loop is the
711 ** following pseudocode (template 4):
712 **
713 ** rewind temp table
714 ** C: loop over rows of intermediate table
715 ** transfer values form intermediate table into <table>
716 ** end loop
717 ** D: ...
718 */
719 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
720 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:58 +0000721 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000722 /* This block codes the top of loop only. The complete loop is the
723 ** following pseudocode (template 3):
724 **
725 ** C: yield X
726 ** if EOF goto D
727 ** insert the select result into <table> from R..R+n
728 ** goto C
729 ** D: ...
730 */
drh92b01d52008-06-24 00:32:35 +0000731 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
drhe00ee6e2008-06-20 15:24:01 +0000732 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
drh5974a302000-06-07 14:42:26 +0000733 }
drh1ccde152000-06-17 13:12:39 +0000734
drh6a288a32008-01-07 19:20:24 +0000735 /* Allocate registers for holding the rowid of the new row,
736 ** the content of the new row, and the assemblied row record.
737 */
738 regRecord = ++pParse->nMem;
739 regRowid = regIns = pParse->nMem+1;
740 pParse->nMem += pTab->nCol + 1;
741 if( IsVirtual(pTab) ){
742 regRowid++;
743 pParse->nMem++;
744 }
745 regData = regRowid+1;
746
drh5cf590c2003-04-24 01:45:04 +0000747 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:22 +0000748 */
danielk19774adee202004-05-08 08:23:19 +0000749 endOfLoop = sqlite3VdbeMakeLabel(v);
danielk19772f886d12009-02-28 10:47:41 +0000750 if( tmask & TRIGGER_BEFORE ){
drhdc5ea5c2008-12-10 17:19:59 +0000751 int regTrigRowid;
drh2d401ab2008-01-10 23:50:11 +0000752 int regCols;
753 int regRec;
danielk1977c3f9bad2002-05-15 08:30:12 +0000754
drh70ce3f02003-04-15 19:22:22 +0000755 /* build the NEW.* reference row. Note that if there is an INTEGER
756 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
757 ** translated into a unique ID for the row. But on a BEFORE trigger,
758 ** we do not know what the unique ID will be (because the insert has
759 ** not happened yet) so we substitute a rowid of -1
760 */
drhdc5ea5c2008-12-10 17:19:59 +0000761 regTrigRowid = sqlite3GetTempReg(pParse);
drh70ce3f02003-04-15 19:22:22 +0000762 if( keyColumn<0 ){
drhdc5ea5c2008-12-10 17:19:59 +0000763 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000764 }else if( useTempTable ){
drhdc5ea5c2008-12-10 17:19:59 +0000765 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000766 }else{
drh6a288a32008-01-07 19:20:24 +0000767 int j1;
drhd6fe9612005-01-14 01:22:00 +0000768 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drhdc5ea5c2008-12-10 17:19:59 +0000769 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
770 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
771 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
drh6a288a32008-01-07 19:20:24 +0000772 sqlite3VdbeJumpHere(v, j1);
drhdc5ea5c2008-12-10 17:19:59 +0000773 sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
drh70ce3f02003-04-15 19:22:22 +0000774 }
775
danielk1977034ca142007-06-26 10:38:54 +0000776 /* Cannot have triggers on a virtual table. If it were possible,
777 ** this block would have to account for hidden column.
778 */
779 assert(!IsVirtual(pTab));
780
drh70ce3f02003-04-15 19:22:22 +0000781 /* Create the new column data
782 */
drh2d401ab2008-01-10 23:50:11 +0000783 regCols = sqlite3GetTempRange(pParse, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000784 for(i=0; i<pTab->nCol; i++){
785 if( pColumn==0 ){
drh9adf9ac2002-05-15 11:44:13 +0000786 j = i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000787 }else{
drh9adf9ac2002-05-15 11:44:13 +0000788 for(j=0; j<pColumn->nId; j++){
789 if( pColumn->a[j].idx==i ) break;
790 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000791 }
792 if( pColumn && j>=pColumn->nId ){
drh2d401ab2008-01-10 23:50:11 +0000793 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
drh142e30d2002-08-28 03:00:58 +0000794 }else if( useTempTable ){
drh2d401ab2008-01-10 23:50:11 +0000795 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000796 }else{
drhd6fe9612005-01-14 01:22:00 +0000797 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drh2d401ab2008-01-10 23:50:11 +0000798 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
danielk1977c3f9bad2002-05-15 08:30:12 +0000799 }
800 }
drh2d401ab2008-01-10 23:50:11 +0000801 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +0000802 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +0000803
804 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
805 ** do not attempt any conversions before assembling the record.
806 ** If this is a real table, attempt conversions as required by the
807 ** table column affinities.
808 */
809 if( !isView ){
810 sqlite3TableAffinityStr(v, pTab);
811 }
drhdc5ea5c2008-12-10 17:19:59 +0000812 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
drh2d401ab2008-01-10 23:50:11 +0000813 sqlite3ReleaseTempReg(pParse, regRec);
drhdc5ea5c2008-12-10 17:19:59 +0000814 sqlite3ReleaseTempReg(pParse, regTrigRowid);
drh2d401ab2008-01-10 23:50:11 +0000815 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
danielk1977c3f9bad2002-05-15 08:30:12 +0000816
drh5cf590c2003-04-24 01:45:04 +0000817 /* Fire BEFORE or INSTEAD OF triggers */
danielk19772f886d12009-02-28 10:47:41 +0000818 if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
819 pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000820 goto insert_cleanup;
821 }
drh70ce3f02003-04-15 19:22:22 +0000822 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000823
drh4a324312001-12-21 14:30:42 +0000824 /* Push the record number for the new entry onto the stack. The
drhf0863fe2005-06-12 21:35:51 +0000825 ** record number is a randomly generate integer created by NewRowid
drh4a324312001-12-21 14:30:42 +0000826 ** except when the table has an INTEGER PRIMARY KEY column, in which
drhb419a922002-01-30 16:17:23 +0000827 ** case the record number is the same as that column.
drh1ccde152000-06-17 13:12:39 +0000828 */
drh5cf590c2003-04-24 01:45:04 +0000829 if( !isView ){
drh4cbdda92006-06-14 19:00:20 +0000830 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:28 +0000831 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:24 +0000832 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:20 +0000833 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000834 if( keyColumn>=0 ){
drh142e30d2002-08-28 03:00:58 +0000835 if( useTempTable ){
drh6a288a32008-01-07 19:20:24 +0000836 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
drh142e30d2002-08-28 03:00:58 +0000837 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000838 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000839 }else{
drhe4d90812007-03-29 05:51:49 +0000840 VdbeOp *pOp;
drh1db639c2008-01-17 02:36:28 +0000841 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
drhe4d90812007-03-29 05:51:49 +0000842 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
danielk1977bb50e7a2008-07-04 10:56:07 +0000843 if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
drhe4d90812007-03-29 05:51:49 +0000844 appendFlag = 1;
845 pOp->opcode = OP_NewRowid;
drh04adf412008-01-08 18:57:50 +0000846 pOp->p1 = baseCur;
drh6a288a32008-01-07 19:20:24 +0000847 pOp->p2 = regRowid;
848 pOp->p3 = regAutoinc;
drhe4d90812007-03-29 05:51:49 +0000849 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000850 }
drhf0863fe2005-06-12 21:35:51 +0000851 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:43 +0000852 ** to generate a unique primary key value.
853 */
drhe4d90812007-03-29 05:51:49 +0000854 if( !appendFlag ){
drh1db639c2008-01-17 02:36:28 +0000855 int j1;
danielk1977bb50e7a2008-07-04 10:56:07 +0000856 if( !IsVirtual(pTab) ){
857 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
858 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
859 sqlite3VdbeJumpHere(v, j1);
860 }else{
861 j1 = sqlite3VdbeCurrentAddr(v);
862 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
863 }
drh3c84ddf2008-01-09 02:15:38 +0000864 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
drhe4d90812007-03-29 05:51:49 +0000865 }
drh4cbdda92006-06-14 19:00:20 +0000866 }else if( IsVirtual(pTab) ){
drh6a288a32008-01-07 19:20:24 +0000867 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:12 +0000868 }else{
drh04adf412008-01-08 18:57:50 +0000869 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:49 +0000870 appendFlag = 1;
drh4a324312001-12-21 14:30:42 +0000871 }
drh6a288a32008-01-07 19:20:24 +0000872 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:42 +0000873
danielk1977c3f9bad2002-05-15 08:30:12 +0000874 /* Push onto the stack, data for all columns of the new entry, beginning
danielk1977f29ce552002-05-19 23:43:12 +0000875 ** with the first column.
876 */
danielk1977034ca142007-06-26 10:38:54 +0000877 nHidden = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000878 for(i=0; i<pTab->nCol; i++){
drh6a288a32008-01-07 19:20:24 +0000879 int iRegStore = regRowid+1+i;
danielk1977c3f9bad2002-05-15 08:30:12 +0000880 if( i==pTab->iPKey ){
drh9adf9ac2002-05-15 11:44:13 +0000881 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
danielk1977f29ce552002-05-19 23:43:12 +0000882 ** Whenever this column is read, the record number will be substituted
883 ** in its place. So will fill this column with a NULL to avoid
884 ** taking up data space with information that will never be used. */
drh4c583122008-01-04 22:01:03 +0000885 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
drh9adf9ac2002-05-15 11:44:13 +0000886 continue;
danielk1977c3f9bad2002-05-15 08:30:12 +0000887 }
888 if( pColumn==0 ){
danielk1977034ca142007-06-26 10:38:54 +0000889 if( IsHiddenColumn(&pTab->aCol[i]) ){
890 assert( IsVirtual(pTab) );
891 j = -1;
892 nHidden++;
893 }else{
894 j = i - nHidden;
895 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000896 }else{
drh9adf9ac2002-05-15 11:44:13 +0000897 for(j=0; j<pColumn->nId; j++){
898 if( pColumn->a[j].idx==i ) break;
899 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000900 }
danielk1977034ca142007-06-26 10:38:54 +0000901 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
danielk1977287fb612008-01-04 19:10:28 +0000902 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000903 }else if( useTempTable ){
danielk1977287fb612008-01-04 19:10:28 +0000904 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
drh142e30d2002-08-28 03:00:58 +0000905 }else if( pSelect ){
drhb7654112008-01-12 12:48:07 +0000906 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
danielk1977c3f9bad2002-05-15 08:30:12 +0000907 }else{
danielk1977287fb612008-01-04 19:10:28 +0000908 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
drh5974a302000-06-07 14:42:26 +0000909 }
drhbed86902000-06-02 13:27:59 +0000910 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000911
912 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:12 +0000913 ** do the insertion.
914 */
drh4cbdda92006-06-14 19:00:20 +0000915#ifndef SQLITE_OMIT_VIRTUALTABLE
916 if( IsVirtual(pTab) ){
drh4f3dd152008-04-28 18:46:43 +0000917 sqlite3VtabMakeWritable(pParse, pTab);
drh6a288a32008-01-07 19:20:24 +0000918 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
drh66a51672008-01-03 00:01:23 +0000919 (const char*)pTab->pVtab, P4_VTAB);
drh4cbdda92006-06-14 19:00:20 +0000920 }else
921#endif
922 {
drh04adf412008-01-08 18:57:50 +0000923 sqlite3GenerateConstraintChecks(
924 pParse,
925 pTab,
926 baseCur,
927 regIns,
928 aRegIdx,
929 keyColumn>=0,
930 0,
931 onError,
932 endOfLoop
933 );
934 sqlite3CompleteInsertion(
935 pParse,
936 pTab,
937 baseCur,
938 regIns,
939 aRegIdx,
940 0,
danielk19772f886d12009-02-28 10:47:41 +0000941 (tmask&TRIGGER_AFTER) ? newIdx : -1,
drh04adf412008-01-08 18:57:50 +0000942 appendFlag
943 );
drh4cbdda92006-06-14 19:00:20 +0000944 }
drh5cf590c2003-04-24 01:45:04 +0000945 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000946
drh5cf590c2003-04-24 01:45:04 +0000947 /* Update the count of rows that are inserted
948 */
949 if( (db->flags & SQLITE_CountRows)!=0 ){
drh6a288a32008-01-07 19:20:24 +0000950 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:26 +0000951 }
drh1ccde152000-06-17 13:12:39 +0000952
danielk19772f886d12009-02-28 10:47:41 +0000953 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000954 /* Code AFTER triggers */
danielk19772f886d12009-02-28 10:47:41 +0000955 if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
956 pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
danielk1977f29ce552002-05-19 23:43:12 +0000957 goto insert_cleanup;
958 }
drh1bee3d72001-10-15 00:44:35 +0000959 }
960
drhe00ee6e2008-06-20 15:24:01 +0000961 /* The bottom of the main insertion loop, if the data source
962 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:12 +0000963 */
danielk19774adee202004-05-08 08:23:19 +0000964 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:58 +0000965 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:01 +0000966 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
967 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:36 +0000968 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:58 +0000969 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:01 +0000970 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
971 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:26 +0000972 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000973
danielk1977e448dc42008-01-02 11:50:51 +0000974 if( !IsVirtual(pTab) && !isView ){
danielk1977c3f9bad2002-05-15 08:30:12 +0000975 /* Close all tables opened */
drh2eb95372008-06-06 15:04:36 +0000976 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +0000977 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
drh2eb95372008-06-06 15:04:36 +0000978 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
danielk1977c3f9bad2002-05-15 08:30:12 +0000979 }
drhcce7d172000-05-31 15:34:51 +0000980 }
danielk1977c3f9bad2002-05-15 08:30:12 +0000981
drhf3388142004-11-13 03:48:06 +0000982 /* Update the sqlite_sequence table by storing the content of the
drh6a288a32008-01-07 19:20:24 +0000983 ** counter value in memory regAutoinc back into the sqlite_sequence
drhf3388142004-11-13 03:48:06 +0000984 ** table.
drh2958a4e2004-11-12 03:56:15 +0000985 */
drh6a288a32008-01-07 19:20:24 +0000986 autoIncEnd(pParse, iDb, pTab, regAutoinc);
drh2958a4e2004-11-12 03:56:15 +0000987
drh1bee3d72001-10-15 00:44:35 +0000988 /*
danielk1977e7de6f22004-11-05 06:02:06 +0000989 ** Return the number of rows inserted. If this routine is
990 ** generating code because of a call to sqlite3NestedParse(), do not
991 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:35 +0000992 */
danielk1977cc6bd382005-01-10 02:48:49 +0000993 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
drh6a288a32008-01-07 19:20:24 +0000994 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
danielk197722322fd2004-05-25 23:35:17 +0000995 sqlite3VdbeSetNumCols(v, 1);
danielk197710fb7492008-10-31 10:53:22 +0000996 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
drh1bee3d72001-10-15 00:44:35 +0000997 }
drhcce7d172000-05-31 15:34:51 +0000998
999insert_cleanup:
drh633e6d52008-07-28 19:34:53 +00001000 sqlite3SrcListDelete(db, pTabList);
1001 sqlite3ExprListDelete(db, pList);
1002 sqlite3SelectDelete(db, pSelect);
1003 sqlite3IdListDelete(db, pColumn);
1004 sqlite3DbFree(db, aRegIdx);
drhcce7d172000-05-31 15:34:51 +00001005}
drh9cfcf5d2002-01-29 18:41:24 +00001006
drh9cfcf5d2002-01-29 18:41:24 +00001007/*
drh6a288a32008-01-07 19:20:24 +00001008** Generate code to do constraint checks prior to an INSERT or an UPDATE.
drh9cfcf5d2002-01-29 18:41:24 +00001009**
drh04adf412008-01-08 18:57:50 +00001010** The input is a range of consecutive registers as follows:
drh0ca3e242002-01-29 23:07:02 +00001011**
drhf0863fe2005-06-12 21:35:51 +00001012** 1. The rowid of the row to be updated before the update. This
drhb419a922002-01-30 16:17:23 +00001013** value is omitted unless we are doing an UPDATE that involves a
drha05a7222008-01-19 03:35:58 +00001014** change to the record number or writing to a virtual table.
drh0ca3e242002-01-29 23:07:02 +00001015**
drhf0863fe2005-06-12 21:35:51 +00001016** 2. The rowid of the row after the update.
drh0ca3e242002-01-29 23:07:02 +00001017**
1018** 3. The data in the first column of the entry after the update.
1019**
1020** i. Data from middle columns...
1021**
1022** N. The data in the last column of the entry after the update.
1023**
drh04adf412008-01-08 18:57:50 +00001024** The regRowid parameter is the index of the register containing (2).
1025**
drhf0863fe2005-06-12 21:35:51 +00001026** The old rowid shown as entry (1) above is omitted unless both isUpdate
1027** and rowidChng are 1. isUpdate is true for UPDATEs and false for
drha05a7222008-01-19 03:35:58 +00001028** INSERTs. RowidChng means that the new rowid is explicitly specified by
1029** the update or insert statement. If rowidChng is false, it means that
1030** the rowid is computed automatically in an insert or that the rowid value
1031** is not modified by the update.
drh0ca3e242002-01-29 23:07:02 +00001032**
drhaa9b8962008-01-08 02:57:55 +00001033** The code generated by this routine store new index entries into
1034** registers identified by aRegIdx[]. No index entry is created for
1035** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1036** the same as the order of indices on the linked list of indices
1037** attached to the table.
drh9cfcf5d2002-01-29 18:41:24 +00001038**
1039** This routine also generates code to check constraints. NOT NULL,
1040** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:21 +00001041** then the appropriate action is performed. There are five possible
1042** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:24 +00001043**
1044** Constraint type Action What Happens
1045** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:21 +00001046** any ROLLBACK The current transaction is rolled back and
danielk197724b03fd2004-05-10 10:34:34 +00001047** sqlite3_exec() returns immediately with a
drh9cfcf5d2002-01-29 18:41:24 +00001048** return code of SQLITE_CONSTRAINT.
1049**
drh1c928532002-01-31 15:54:21 +00001050** any ABORT Back out changes from the current command
1051** only (do not do a complete rollback) then
danielk197724b03fd2004-05-10 10:34:34 +00001052** cause sqlite3_exec() to return immediately
drh1c928532002-01-31 15:54:21 +00001053** with SQLITE_CONSTRAINT.
1054**
1055** any FAIL Sqlite_exec() returns immediately with a
1056** return code of SQLITE_CONSTRAINT. The
1057** transaction is not rolled back and any
1058** prior changes are retained.
1059**
drh9cfcf5d2002-01-29 18:41:24 +00001060** any IGNORE The record number and data is popped from
1061** the stack and there is an immediate jump
1062** to label ignoreDest.
1063**
1064** NOT NULL REPLACE The NULL value is replace by the default
1065** value for that column. If the default value
1066** is NULL, the action is the same as ABORT.
1067**
1068** UNIQUE REPLACE The other row that conflicts with the row
1069** being inserted is removed.
1070**
1071** CHECK REPLACE Illegal. The results in an exception.
1072**
drh1c928532002-01-31 15:54:21 +00001073** Which action to take is determined by the overrideError parameter.
1074** Or if overrideError==OE_Default, then the pParse->onError parameter
1075** is used. Or if pParse->onError==OE_Default then the onError value
1076** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:24 +00001077**
drhaaab5722002-02-19 13:39:21 +00001078** The calling routine must open a read/write cursor for pTab with
drh04adf412008-01-08 18:57:50 +00001079** cursor number "baseCur". All indices of pTab must also have open
1080** read/write cursors with cursor number baseCur+i for the i-th cursor.
drh9cfcf5d2002-01-29 18:41:24 +00001081** Except, if there is no possibility of a REPLACE action then
drhaa9b8962008-01-08 02:57:55 +00001082** cursors do not need to be open for indices where aRegIdx[i]==0.
drh9cfcf5d2002-01-29 18:41:24 +00001083*/
danielk19774adee202004-05-08 08:23:19 +00001084void sqlite3GenerateConstraintChecks(
drh9cfcf5d2002-01-29 18:41:24 +00001085 Parse *pParse, /* The parser context */
1086 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001087 int baseCur, /* Index of a read/write cursor pointing at pTab */
1088 int regRowid, /* Index of the range of input registers */
drhaa9b8962008-01-08 02:57:55 +00001089 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drha05a7222008-01-19 03:35:58 +00001090 int rowidChng, /* True if the rowid might collide with existing entry */
drhb419a922002-01-30 16:17:23 +00001091 int isUpdate, /* True for UPDATE, False for INSERT */
drh9cfcf5d2002-01-29 18:41:24 +00001092 int overrideError, /* Override onError to this if not OE_Default */
drhb419a922002-01-30 16:17:23 +00001093 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
drh9cfcf5d2002-01-29 18:41:24 +00001094){
1095 int i;
1096 Vdbe *v;
1097 int nCol;
1098 int onError;
drh1bd10f82008-12-10 21:19:56 +00001099 int j1; /* Addresss of jump instruction */
1100 int j2 = 0, j3; /* Addresses of jump instructions */
drh04adf412008-01-08 18:57:50 +00001101 int regData; /* Register containing first data column */
drh0ca3e242002-01-29 23:07:02 +00001102 int iCur;
1103 Index *pIdx;
1104 int seenReplace = 0;
drhf0863fe2005-06-12 21:35:51 +00001105 int hasTwoRowids = (isUpdate && rowidChng);
drh9cfcf5d2002-01-29 18:41:24 +00001106
danielk19774adee202004-05-08 08:23:19 +00001107 v = sqlite3GetVdbe(pParse);
drh9cfcf5d2002-01-29 18:41:24 +00001108 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001109 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:24 +00001110 nCol = pTab->nCol;
drh04adf412008-01-08 18:57:50 +00001111 regData = regRowid + 1;
drh9cfcf5d2002-01-29 18:41:24 +00001112
drhaa9b8962008-01-08 02:57:55 +00001113
drh9cfcf5d2002-01-29 18:41:24 +00001114 /* Test all NOT NULL constraints.
1115 */
1116 for(i=0; i<nCol; i++){
drh0ca3e242002-01-29 23:07:02 +00001117 if( i==pTab->iPKey ){
drh0ca3e242002-01-29 23:07:02 +00001118 continue;
1119 }
drh9cfcf5d2002-01-29 18:41:24 +00001120 onError = pTab->aCol[i].notNull;
drh0ca3e242002-01-29 23:07:02 +00001121 if( onError==OE_None ) continue;
drh9cfcf5d2002-01-29 18:41:24 +00001122 if( overrideError!=OE_Default ){
1123 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001124 }else if( onError==OE_Default ){
1125 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001126 }
danielk19777977a172004-11-09 12:44:37 +00001127 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
drh9cfcf5d2002-01-29 18:41:24 +00001128 onError = OE_Abort;
1129 }
danielk1977b84f96f2005-01-20 11:32:23 +00001130 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1131 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001132 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001133 case OE_Rollback:
1134 case OE_Abort:
1135 case OE_Fail: {
drhf089aa42008-07-08 19:34:06 +00001136 char *zMsg;
drh5053a792009-02-20 03:02:23 +00001137 j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1138 SQLITE_CONSTRAINT, onError, regData+i);
drhf089aa42008-07-08 19:34:06 +00001139 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1140 pTab->zName, pTab->aCol[i].zName);
drh66a51672008-01-03 00:01:23 +00001141 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
drh9cfcf5d2002-01-29 18:41:24 +00001142 break;
1143 }
1144 case OE_Ignore: {
drh5053a792009-02-20 03:02:23 +00001145 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001146 break;
1147 }
1148 case OE_Replace: {
drh5053a792009-02-20 03:02:23 +00001149 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
drh04adf412008-01-08 18:57:50 +00001150 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
drh5053a792009-02-20 03:02:23 +00001151 sqlite3VdbeJumpHere(v, j1);
drh9cfcf5d2002-01-29 18:41:24 +00001152 break;
1153 }
drh9cfcf5d2002-01-29 18:41:24 +00001154 }
1155 }
1156
1157 /* Test all CHECK constraints
1158 */
drhffe07b22005-11-03 00:41:17 +00001159#ifndef SQLITE_OMIT_CHECK
drh0cd2d4c2005-11-03 02:15:02 +00001160 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
drhffe07b22005-11-03 00:41:17 +00001161 int allOk = sqlite3VdbeMakeLabel(v);
drhaa9b8962008-01-08 02:57:55 +00001162 pParse->ckBase = regData;
drh35573352008-01-08 23:54:25 +00001163 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
drhaa01c7e2006-03-15 16:26:10 +00001164 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2e06c672007-07-23 19:39:46 +00001165 if( onError==OE_Ignore ){
drh66a51672008-01-03 00:01:23 +00001166 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drhaa01c7e2006-03-15 16:26:10 +00001167 }else{
drh66a51672008-01-03 00:01:23 +00001168 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
drhaa01c7e2006-03-15 16:26:10 +00001169 }
drhffe07b22005-11-03 00:41:17 +00001170 sqlite3VdbeResolveLabel(v, allOk);
1171 }
1172#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:24 +00001173
drh0bd1f4e2002-06-06 18:54:39 +00001174 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1175 ** of the new record does not previously exist. Except, if this
1176 ** is an UPDATE and the primary key is not changing, that is OK.
drh9cfcf5d2002-01-29 18:41:24 +00001177 */
drhf0863fe2005-06-12 21:35:51 +00001178 if( rowidChng ){
drh0ca3e242002-01-29 23:07:02 +00001179 onError = pTab->keyConf;
1180 if( overrideError!=OE_Default ){
1181 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001182 }else if( onError==OE_Default ){
1183 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:02 +00001184 }
drha0217ba2003-06-01 01:10:33 +00001185
drh60a713c2008-01-21 16:22:45 +00001186 if( onError!=OE_Replace || pTab->pIndex ){
drha05a7222008-01-19 03:35:58 +00001187 if( isUpdate ){
1188 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
drh79b0c952002-05-21 12:56:43 +00001189 }
drha05a7222008-01-19 03:35:58 +00001190 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1191 switch( onError ){
1192 default: {
1193 onError = OE_Abort;
1194 /* Fall thru into the next case */
drh5383ae52003-06-04 12:23:30 +00001195 }
drha05a7222008-01-19 03:35:58 +00001196 case OE_Rollback:
1197 case OE_Abort:
1198 case OE_Fail: {
1199 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1200 "PRIMARY KEY must be unique", P4_STATIC);
1201 break;
1202 }
1203 case OE_Replace: {
1204 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1205 seenReplace = 1;
1206 break;
1207 }
1208 case OE_Ignore: {
1209 assert( seenReplace==0 );
1210 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1211 break;
1212 }
drh0ca3e242002-01-29 23:07:02 +00001213 }
drha05a7222008-01-19 03:35:58 +00001214 sqlite3VdbeJumpHere(v, j3);
1215 if( isUpdate ){
1216 sqlite3VdbeJumpHere(v, j2);
drh5383ae52003-06-04 12:23:30 +00001217 }
1218 }
drh0ca3e242002-01-29 23:07:02 +00001219 }
drh0bd1f4e2002-06-06 18:54:39 +00001220
1221 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1222 ** index and making sure that duplicate entries do not already exist.
1223 ** Add the new records to the indices as we go.
1224 */
drhb2fe7d82003-04-20 17:29:23 +00001225 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
drh2d401ab2008-01-10 23:50:11 +00001226 int regIdx;
1227 int regR;
1228
drhaa9b8962008-01-08 02:57:55 +00001229 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
drhb2fe7d82003-04-20 17:29:23 +00001230
1231 /* Create a key for accessing the index entry */
drh2d401ab2008-01-10 23:50:11 +00001232 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
drh9cfcf5d2002-01-29 18:41:24 +00001233 for(i=0; i<pIdx->nColumn; i++){
1234 int idx = pIdx->aiColumn[i];
1235 if( idx==pTab->iPKey ){
drh2d401ab2008-01-10 23:50:11 +00001236 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001237 }else{
drh2d401ab2008-01-10 23:50:11 +00001238 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
drh9cfcf5d2002-01-29 18:41:24 +00001239 }
1240 }
drh2d401ab2008-01-10 23:50:11 +00001241 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
drh1db639c2008-01-17 02:36:28 +00001242 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
danielk1977a37cdde2004-05-16 11:15:36 +00001243 sqlite3IndexAffinityStr(v, pIdx);
drhda250ea2008-04-01 05:07:14 +00001244 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
drh2d401ab2008-01-10 23:50:11 +00001245 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
drhb2fe7d82003-04-20 17:29:23 +00001246
1247 /* Find out what action to take in case there is an indexing conflict */
drh9cfcf5d2002-01-29 18:41:24 +00001248 onError = pIdx->onError;
drhb2fe7d82003-04-20 17:29:23 +00001249 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
drh9cfcf5d2002-01-29 18:41:24 +00001250 if( overrideError!=OE_Default ){
1251 onError = overrideError;
drha996e472003-05-16 02:30:27 +00001252 }else if( onError==OE_Default ){
1253 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:24 +00001254 }
drh5383ae52003-06-04 12:23:30 +00001255 if( seenReplace ){
1256 if( onError==OE_Ignore ) onError = OE_Replace;
1257 else if( onError==OE_Fail ) onError = OE_Abort;
1258 }
1259
drhb2fe7d82003-04-20 17:29:23 +00001260
1261 /* Check to see if the new index entry will be unique */
drh2d401ab2008-01-10 23:50:11 +00001262 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
1263 regR = sqlite3GetTempReg(pParse);
1264 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
1265 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
shane1fc41292008-07-08 22:28:48 +00001266 regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
mlcreecha9e852b2008-03-06 09:58:50 +00001267 P4_INT32);
drhb2fe7d82003-04-20 17:29:23 +00001268
1269 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:23 +00001270 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1271 || onError==OE_Ignore || onError==OE_Replace );
drh9cfcf5d2002-01-29 18:41:24 +00001272 switch( onError ){
drh1c928532002-01-31 15:54:21 +00001273 case OE_Rollback:
1274 case OE_Abort:
1275 case OE_Fail: {
drh37ed48e2003-08-05 13:13:38 +00001276 int j, n1, n2;
1277 char zErrMsg[200];
danielk197700e13612008-11-17 19:18:54 +00001278 sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
drh5bb3eb92007-05-04 13:15:55 +00001279 pIdx->nColumn>1 ? "columns " : "column ");
drhea678832008-12-10 19:26:22 +00001280 n1 = sqlite3Strlen30(zErrMsg);
danielk197700e13612008-11-17 19:18:54 +00001281 for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
drh37ed48e2003-08-05 13:13:38 +00001282 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
drhea678832008-12-10 19:26:22 +00001283 n2 = sqlite3Strlen30(zCol);
drh37ed48e2003-08-05 13:13:38 +00001284 if( j>0 ){
danielk197700e13612008-11-17 19:18:54 +00001285 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
drh37ed48e2003-08-05 13:13:38 +00001286 n1 += 2;
1287 }
danielk197700e13612008-11-17 19:18:54 +00001288 if( n1+n2>ArraySize(zErrMsg)-30 ){
1289 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
drh37ed48e2003-08-05 13:13:38 +00001290 n1 += 3;
1291 break;
1292 }else{
danielk197700e13612008-11-17 19:18:54 +00001293 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
drh37ed48e2003-08-05 13:13:38 +00001294 n1 += n2;
1295 }
1296 }
danielk197700e13612008-11-17 19:18:54 +00001297 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
drh37ed48e2003-08-05 13:13:38 +00001298 pIdx->nColumn>1 ? " are not unique" : " is not unique");
drh66a51672008-01-03 00:01:23 +00001299 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
drh9cfcf5d2002-01-29 18:41:24 +00001300 break;
1301 }
1302 case OE_Ignore: {
drh0ca3e242002-01-29 23:07:02 +00001303 assert( seenReplace==0 );
drh66a51672008-01-03 00:01:23 +00001304 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
drh9cfcf5d2002-01-29 18:41:24 +00001305 break;
1306 }
1307 case OE_Replace: {
drh2d401ab2008-01-10 23:50:11 +00001308 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
drh0ca3e242002-01-29 23:07:02 +00001309 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:24 +00001310 break;
1311 }
drh9cfcf5d2002-01-29 18:41:24 +00001312 }
drhaa9b8962008-01-08 02:57:55 +00001313 sqlite3VdbeJumpHere(v, j2);
drh2d401ab2008-01-10 23:50:11 +00001314 sqlite3VdbeJumpHere(v, j3);
1315 sqlite3ReleaseTempReg(pParse, regR);
drh9cfcf5d2002-01-29 18:41:24 +00001316 }
1317}
drh0ca3e242002-01-29 23:07:02 +00001318
1319/*
1320** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:19 +00001321** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh04adf412008-01-08 18:57:50 +00001322** A consecutive range of registers starting at regRowid contains the
1323** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:02 +00001324**
drhb419a922002-01-30 16:17:23 +00001325** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:19 +00001326** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:02 +00001327*/
danielk19774adee202004-05-08 08:23:19 +00001328void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:02 +00001329 Parse *pParse, /* The parser context */
1330 Table *pTab, /* the table into which we are inserting */
drh04adf412008-01-08 18:57:50 +00001331 int baseCur, /* Index of a read/write cursor pointing at pTab */
1332 int regRowid, /* Range of content */
drhaa9b8962008-01-08 02:57:55 +00001333 int *aRegIdx, /* Register used by each index. 0 for unused indices */
drh70ce3f02003-04-15 19:22:22 +00001334 int isUpdate, /* True for UPDATE, False for INSERT */
drhe4d90812007-03-29 05:51:49 +00001335 int newIdx, /* Index of NEW table for triggers. -1 if none */
1336 int appendBias /* True if this is likely to be an append */
drh0ca3e242002-01-29 23:07:02 +00001337){
1338 int i;
1339 Vdbe *v;
1340 int nIdx;
1341 Index *pIdx;
drh1bd10f82008-12-10 21:19:56 +00001342 u8 pik_flags;
drh04adf412008-01-08 18:57:50 +00001343 int regData;
drhb7654112008-01-12 12:48:07 +00001344 int regRec;
drh0ca3e242002-01-29 23:07:02 +00001345
danielk19774adee202004-05-08 08:23:19 +00001346 v = sqlite3GetVdbe(pParse);
drh0ca3e242002-01-29 23:07:02 +00001347 assert( v!=0 );
drh417be792002-03-03 18:59:40 +00001348 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
drh0ca3e242002-01-29 23:07:02 +00001349 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1350 for(i=nIdx-1; i>=0; i--){
drhaa9b8962008-01-08 02:57:55 +00001351 if( aRegIdx[i]==0 ) continue;
drh04adf412008-01-08 18:57:50 +00001352 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
drh0ca3e242002-01-29 23:07:02 +00001353 }
drh04adf412008-01-08 18:57:50 +00001354 regData = regRowid + 1;
drhb7654112008-01-12 12:48:07 +00001355 regRec = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00001356 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
danielk1977a37cdde2004-05-16 11:15:36 +00001357 sqlite3TableAffinityStr(v, pTab);
drhda250ea2008-04-01 05:07:14 +00001358 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
danielk1977b84f96f2005-01-20 11:32:23 +00001359#ifndef SQLITE_OMIT_TRIGGER
drh70ce3f02003-04-15 19:22:22 +00001360 if( newIdx>=0 ){
drhb7654112008-01-12 12:48:07 +00001361 sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
drh70ce3f02003-04-15 19:22:22 +00001362 }
danielk1977b84f96f2005-01-20 11:32:23 +00001363#endif
drh4794f732004-11-05 17:17:50 +00001364 if( pParse->nested ){
1365 pik_flags = 0;
1366 }else{
danielk197794eb6a12005-12-15 15:22:08 +00001367 pik_flags = OPFLAG_NCHANGE;
1368 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:50 +00001369 }
drhe4d90812007-03-29 05:51:49 +00001370 if( appendBias ){
1371 pik_flags |= OPFLAG_APPEND;
1372 }
drhb7654112008-01-12 12:48:07 +00001373 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
danielk197794eb6a12005-12-15 15:22:08 +00001374 if( !pParse->nested ){
drh66a51672008-01-03 00:01:23 +00001375 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
danielk197794eb6a12005-12-15 15:22:08 +00001376 }
drhb7654112008-01-12 12:48:07 +00001377 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:02 +00001378}
drhcd446902004-02-24 01:05:31 +00001379
1380/*
drh290c1942004-08-21 17:54:45 +00001381** Generate code that will open cursors for a table and for all
drh04adf412008-01-08 18:57:50 +00001382** indices of that table. The "baseCur" parameter is the cursor number used
drhcd446902004-02-24 01:05:31 +00001383** for the table. Indices are opened on subsequent cursors.
drhaa9b8962008-01-08 02:57:55 +00001384**
1385** Return the number of indices on the table.
drhcd446902004-02-24 01:05:31 +00001386*/
drhaa9b8962008-01-08 02:57:55 +00001387int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:45 +00001388 Parse *pParse, /* Parsing context */
1389 Table *pTab, /* Table to be opened */
drhdfe88ec2008-11-03 20:55:06 +00001390 int baseCur, /* Cursor number assigned to the table */
drh290c1942004-08-21 17:54:45 +00001391 int op /* OP_OpenRead or OP_OpenWrite */
1392){
drhcd446902004-02-24 01:05:31 +00001393 int i;
drh4cbdda92006-06-14 19:00:20 +00001394 int iDb;
drhcd446902004-02-24 01:05:31 +00001395 Index *pIdx;
drh4cbdda92006-06-14 19:00:20 +00001396 Vdbe *v;
1397
drhaa9b8962008-01-08 02:57:55 +00001398 if( IsVirtual(pTab) ) return 0;
drh4cbdda92006-06-14 19:00:20 +00001399 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1400 v = sqlite3GetVdbe(pParse);
drhcd446902004-02-24 01:05:31 +00001401 assert( v!=0 );
drh04adf412008-01-08 18:57:50 +00001402 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
drhcd446902004-02-24 01:05:31 +00001403 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
danielk1977b3bf5562006-01-10 17:58:23 +00001404 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk1977da184232006-01-05 11:34:32 +00001405 assert( pIdx->pSchema==pTab->pSchema );
drh04adf412008-01-08 18:57:50 +00001406 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001407 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001408 VdbeComment((v, "%s", pIdx->zName));
drhcd446902004-02-24 01:05:31 +00001409 }
drh04adf412008-01-08 18:57:50 +00001410 if( pParse->nTab<=baseCur+i ){
1411 pParse->nTab = baseCur+i;
drh290c1942004-08-21 17:54:45 +00001412 }
drhaa9b8962008-01-08 02:57:55 +00001413 return i-1;
drhcd446902004-02-24 01:05:31 +00001414}
drh9d9cf222007-02-13 15:01:11 +00001415
drh91c58e22007-03-27 12:04:04 +00001416
1417#ifdef SQLITE_TEST
1418/*
1419** The following global variable is incremented whenever the
1420** transfer optimization is used. This is used for testing
1421** purposes only - to make sure the transfer optimization really
1422** is happening when it is suppose to.
1423*/
1424int sqlite3_xferopt_count;
1425#endif /* SQLITE_TEST */
1426
1427
drh9d9cf222007-02-13 15:01:11 +00001428#ifndef SQLITE_OMIT_XFER_OPT
1429/*
1430** Check to collation names to see if they are compatible.
1431*/
1432static int xferCompatibleCollation(const char *z1, const char *z2){
1433 if( z1==0 ){
1434 return z2==0;
1435 }
1436 if( z2==0 ){
1437 return 0;
1438 }
1439 return sqlite3StrICmp(z1, z2)==0;
1440}
1441
1442
1443/*
1444** Check to see if index pSrc is compatible as a source of data
1445** for index pDest in an insert transfer optimization. The rules
1446** for a compatible index:
1447**
1448** * The index is over the same set of columns
1449** * The same DESC and ASC markings occurs on all columns
1450** * The same onError processing (OE_Abort, OE_Ignore, etc)
1451** * The same collating sequence on each column
1452*/
1453static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1454 int i;
1455 assert( pDest && pSrc );
1456 assert( pDest->pTable!=pSrc->pTable );
1457 if( pDest->nColumn!=pSrc->nColumn ){
1458 return 0; /* Different number of columns */
1459 }
1460 if( pDest->onError!=pSrc->onError ){
1461 return 0; /* Different conflict resolution strategies */
1462 }
1463 for(i=0; i<pSrc->nColumn; i++){
1464 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1465 return 0; /* Different columns indexed */
1466 }
1467 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1468 return 0; /* Different sort orders */
1469 }
1470 if( pSrc->azColl[i]!=pDest->azColl[i] ){
drh60a713c2008-01-21 16:22:45 +00001471 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:11 +00001472 }
1473 }
1474
1475 /* If no test above fails then the indices must be compatible */
1476 return 1;
1477}
1478
1479/*
1480** Attempt the transfer optimization on INSERTs of the form
1481**
1482** INSERT INTO tab1 SELECT * FROM tab2;
1483**
1484** This optimization is only attempted if
1485**
1486** (1) tab1 and tab2 have identical schemas including all the
drh8103b7d2007-02-24 13:23:51 +00001487** same indices and constraints
drh9d9cf222007-02-13 15:01:11 +00001488**
1489** (2) tab1 and tab2 are different tables
1490**
1491** (3) There must be no triggers on tab1
1492**
1493** (4) The result set of the SELECT statement is "*"
1494**
1495** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1496** or LIMIT clause.
1497**
1498** (6) The SELECT statement is a simple (not a compound) select that
1499** contains only tab2 in its FROM clause
1500**
1501** This method for implementing the INSERT transfers raw records from
1502** tab2 over to tab1. The columns are not decoded. Raw records from
1503** the indices of tab2 are transfered to tab1 as well. In so doing,
1504** the resulting tab1 has much less fragmentation.
1505**
1506** This routine returns TRUE if the optimization is attempted. If any
1507** of the conditions above fail so that the optimization should not
1508** be attempted, then this routine returns FALSE.
1509*/
1510static int xferOptimization(
1511 Parse *pParse, /* Parser context */
1512 Table *pDest, /* The table we are inserting into */
1513 Select *pSelect, /* A SELECT statement to use as the data source */
1514 int onError, /* How to handle constraint errors */
1515 int iDbDest /* The database of pDest */
1516){
1517 ExprList *pEList; /* The result set of the SELECT */
1518 Table *pSrc; /* The table in the FROM clause of SELECT */
1519 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1520 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1521 int i; /* Loop counter */
1522 int iDbSrc; /* The database of pSrc */
1523 int iSrc, iDest; /* Cursors from source and destination */
1524 int addr1, addr2; /* Loop addresses */
1525 int emptyDestTest; /* Address of test for empty pDest */
1526 int emptySrcTest; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:11 +00001527 Vdbe *v; /* The VDBE we are building */
1528 KeyInfo *pKey; /* Key information for an index */
drh6a288a32008-01-07 19:20:24 +00001529 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:55 +00001530 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:07 +00001531 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:11 +00001532
1533 if( pSelect==0 ){
1534 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1535 }
danielk19772f886d12009-02-28 10:47:41 +00001536 if( sqlite3TriggerList(pParse, pDest) ){
drh9d9cf222007-02-13 15:01:11 +00001537 return 0; /* tab1 must not have triggers */
1538 }
1539#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001540 if( pDest->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001541 return 0; /* tab1 must not be a virtual table */
1542 }
1543#endif
1544 if( onError==OE_Default ){
1545 onError = OE_Abort;
1546 }
1547 if( onError!=OE_Abort && onError!=OE_Rollback ){
1548 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1549 }
danielk19775ce240a2007-09-03 17:30:06 +00001550 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:11 +00001551 if( pSelect->pSrc->nSrc!=1 ){
1552 return 0; /* FROM clause must have exactly one term */
1553 }
1554 if( pSelect->pSrc->a[0].pSelect ){
1555 return 0; /* FROM clause cannot contain a subquery */
1556 }
1557 if( pSelect->pWhere ){
1558 return 0; /* SELECT may not have a WHERE clause */
1559 }
1560 if( pSelect->pOrderBy ){
1561 return 0; /* SELECT may not have an ORDER BY clause */
1562 }
drh8103b7d2007-02-24 13:23:51 +00001563 /* Do not need to test for a HAVING clause. If HAVING is present but
1564 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:11 +00001565 if( pSelect->pGroupBy ){
1566 return 0; /* SELECT may not have a GROUP BY clause */
1567 }
1568 if( pSelect->pLimit ){
1569 return 0; /* SELECT may not have a LIMIT clause */
1570 }
drh8103b7d2007-02-24 13:23:51 +00001571 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
drh9d9cf222007-02-13 15:01:11 +00001572 if( pSelect->pPrior ){
1573 return 0; /* SELECT may not be a compound query */
1574 }
drh7d10d5a2008-08-20 16:35:10 +00001575 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:11 +00001576 return 0; /* SELECT may not be DISTINCT */
1577 }
1578 pEList = pSelect->pEList;
1579 assert( pEList!=0 );
1580 if( pEList->nExpr!=1 ){
1581 return 0; /* The result set must have exactly one column */
1582 }
1583 assert( pEList->a[0].pExpr );
1584 if( pEList->a[0].pExpr->op!=TK_ALL ){
1585 return 0; /* The result set must be the special operator "*" */
1586 }
1587
1588 /* At this point we have established that the statement is of the
1589 ** correct syntactic form to participate in this optimization. Now
1590 ** we have to check the semantics.
1591 */
1592 pItem = pSelect->pSrc->a;
drhca424112008-01-25 15:04:48 +00001593 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
drh9d9cf222007-02-13 15:01:11 +00001594 if( pSrc==0 ){
1595 return 0; /* FROM clause does not contain a real table */
1596 }
1597 if( pSrc==pDest ){
1598 return 0; /* tab1 and tab2 may not be the same table */
1599 }
1600#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7d10d5a2008-08-20 16:35:10 +00001601 if( pSrc->tabFlags & TF_Virtual ){
drh9d9cf222007-02-13 15:01:11 +00001602 return 0; /* tab2 must not be a virtual table */
1603 }
1604#endif
1605 if( pSrc->pSelect ){
1606 return 0; /* tab2 may not be a view */
1607 }
1608 if( pDest->nCol!=pSrc->nCol ){
1609 return 0; /* Number of columns must be the same in tab1 and tab2 */
1610 }
1611 if( pDest->iPKey!=pSrc->iPKey ){
1612 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1613 }
1614 for(i=0; i<pDest->nCol; i++){
1615 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1616 return 0; /* Affinity must be the same on all columns */
1617 }
1618 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1619 return 0; /* Collating sequence must be the same on all columns */
1620 }
1621 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1622 return 0; /* tab2 must be NOT NULL if tab1 is */
1623 }
1624 }
1625 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drhf33c9fa2007-04-10 18:17:55 +00001626 if( pDestIdx->onError!=OE_None ){
1627 destHasUniqueIdx = 1;
1628 }
drh9d9cf222007-02-13 15:01:11 +00001629 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1630 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1631 }
1632 if( pSrcIdx==0 ){
1633 return 0; /* pDestIdx has no corresponding index in pSrc */
1634 }
1635 }
drh7fc2f412007-03-29 00:08:24 +00001636#ifndef SQLITE_OMIT_CHECK
drhfb658de2007-02-24 15:18:49 +00001637 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
drh8103b7d2007-02-24 13:23:51 +00001638 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1639 }
drh7fc2f412007-03-29 00:08:24 +00001640#endif
drh9d9cf222007-02-13 15:01:11 +00001641
1642 /* If we get this far, it means either:
1643 **
1644 ** * We can always do the transfer if the table contains an
1645 ** an integer primary key
1646 **
1647 ** * We can conditionally do the transfer if the destination
1648 ** table is empty.
1649 */
drhdd735212007-02-24 13:53:05 +00001650#ifdef SQLITE_TEST
1651 sqlite3_xferopt_count++;
1652#endif
drh9d9cf222007-02-13 15:01:11 +00001653 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1654 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:58 +00001655 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:11 +00001656 iSrc = pParse->nTab++;
1657 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:24 +00001658 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drh9d9cf222007-02-13 15:01:11 +00001659 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
drhf33c9fa2007-04-10 18:17:55 +00001660 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
drhbd36ba62007-03-31 13:00:26 +00001661 /* If tables do not have an INTEGER PRIMARY KEY and there
1662 ** are indices to be copied and the destination is not empty,
1663 ** we have to disallow the transfer optimization because the
1664 ** the rowids might change which will mess up indexing.
drhf33c9fa2007-04-10 18:17:55 +00001665 **
1666 ** Or if the destination has a UNIQUE index and is not empty,
1667 ** we also disallow the transfer optimization because we cannot
1668 ** insure that all entries in the union of DEST and SRC will be
1669 ** unique.
drh9d9cf222007-02-13 15:01:11 +00001670 */
drh66a51672008-01-03 00:01:23 +00001671 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1672 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
drh9d9cf222007-02-13 15:01:11 +00001673 sqlite3VdbeJumpHere(v, addr1);
1674 }else{
1675 emptyDestTest = 0;
1676 }
1677 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00001678 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001679 regData = sqlite3GetTempReg(pParse);
1680 regRowid = sqlite3GetTempReg(pParse);
drh42242de2007-03-29 13:35:35 +00001681 if( pDest->iPKey>=0 ){
drhb7654112008-01-12 12:48:07 +00001682 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1683 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
drh66a51672008-01-03 00:01:23 +00001684 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
1685 "PRIMARY KEY must be unique", P4_STATIC);
drh95bad4c2007-03-28 18:04:10 +00001686 sqlite3VdbeJumpHere(v, addr2);
drhb7654112008-01-12 12:48:07 +00001687 autoIncStep(pParse, regAutoinc, regRowid);
drhbd36ba62007-03-31 13:00:26 +00001688 }else if( pDest->pIndex==0 ){
drhb7654112008-01-12 12:48:07 +00001689 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
drh95bad4c2007-03-28 18:04:10 +00001690 }else{
drhb7654112008-01-12 12:48:07 +00001691 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
drh7d10d5a2008-08-20 16:35:10 +00001692 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
drh95bad4c2007-03-28 18:04:10 +00001693 }
drhb7654112008-01-12 12:48:07 +00001694 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1695 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1696 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
danielk19771f4aa332008-01-03 09:51:55 +00001697 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
drh66a51672008-01-03 00:01:23 +00001698 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
drh6a288a32008-01-07 19:20:24 +00001699 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
drh9d9cf222007-02-13 15:01:11 +00001700 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1701 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1702 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1703 }
1704 assert( pSrcIdx );
drh66a51672008-01-03 00:01:23 +00001705 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1706 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001707 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
danielk1977207872a2008-01-03 07:54:23 +00001708 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1709 (char*)pKey, P4_KEYINFO_HANDOFF);
drhd4e70eb2008-01-02 00:34:36 +00001710 VdbeComment((v, "%s", pSrcIdx->zName));
drh9d9cf222007-02-13 15:01:11 +00001711 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
danielk1977207872a2008-01-03 07:54:23 +00001712 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
drh66a51672008-01-03 00:01:23 +00001713 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001714 VdbeComment((v, "%s", pDestIdx->zName));
drh66a51672008-01-03 00:01:23 +00001715 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
drhb7654112008-01-12 12:48:07 +00001716 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1717 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
drh66a51672008-01-03 00:01:23 +00001718 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
drh9d9cf222007-02-13 15:01:11 +00001719 sqlite3VdbeJumpHere(v, addr1);
1720 }
1721 sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:07 +00001722 sqlite3ReleaseTempReg(pParse, regRowid);
1723 sqlite3ReleaseTempReg(pParse, regData);
drh66a51672008-01-03 00:01:23 +00001724 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1725 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001726 if( emptyDestTest ){
drh66a51672008-01-03 00:01:23 +00001727 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:11 +00001728 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:23 +00001729 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:11 +00001730 return 0;
1731 }else{
1732 return 1;
1733 }
1734}
1735#endif /* SQLITE_OMIT_XFER_OPT */
drhf39d9582008-03-19 20:42:13 +00001736
1737/* Make sure "isView" gets undefined in case this file becomes part of
1738** the amalgamation - so that subsequent files do not see isView as a
1739** macro. */
1740#undef isView