xref: /sqlite-3.40.0/src/insert.c (revision 142e30df)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh **
15*142e30dfSdrh ** $Id: insert.c,v 1.66 2002/08/28 03:00:58 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
201ccde15dSdrh ** This routine is call to handle SQL of the following forms:
21cce7d176Sdrh **
22cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
231ccde15dSdrh **    insert into TABLE (IDLIST) select
24cce7d176Sdrh **
251ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
261ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
27967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
281ccde15dSdrh **
291ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
301ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
311ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
321ccde15dSdrh ** data for the insert.
33*142e30dfSdrh **
34*142e30dfSdrh ** The code generated follows one of three templates.  For a simple
35*142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
36*142e30dfSdrh ** once straight down through.  The template looks like this:
37*142e30dfSdrh **
38*142e30dfSdrh **         open write cursor to <table> and its indices
39*142e30dfSdrh **         puts VALUES clause expressions onto the stack
40*142e30dfSdrh **         write the resulting record into <table>
41*142e30dfSdrh **         cleanup
42*142e30dfSdrh **
43*142e30dfSdrh ** If the statement is of the form
44*142e30dfSdrh **
45*142e30dfSdrh **   INSERT INTO <table> SELECT ...
46*142e30dfSdrh **
47*142e30dfSdrh ** And the SELECT clause does not read from <table> at any time, then
48*142e30dfSdrh ** the generated code follows this template:
49*142e30dfSdrh **
50*142e30dfSdrh **         goto B
51*142e30dfSdrh **      A: setup for the SELECT
52*142e30dfSdrh **         loop over the tables in the SELECT
53*142e30dfSdrh **           gosub C
54*142e30dfSdrh **         end loop
55*142e30dfSdrh **         cleanup after the SELECT
56*142e30dfSdrh **         goto D
57*142e30dfSdrh **      B: open write cursor to <table> and its indices
58*142e30dfSdrh **         goto A
59*142e30dfSdrh **      C: insert the select result into <table>
60*142e30dfSdrh **         return
61*142e30dfSdrh **      D: cleanup
62*142e30dfSdrh **
63*142e30dfSdrh ** The third template is used if the insert statement takes its
64*142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
65*142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
66*142e30dfSdrh ** we have to use a intermediate table to store the results of
67*142e30dfSdrh ** the select.  The template is like this:
68*142e30dfSdrh **
69*142e30dfSdrh **         goto B
70*142e30dfSdrh **      A: setup for the SELECT
71*142e30dfSdrh **         loop over the tables in the SELECT
72*142e30dfSdrh **           gosub C
73*142e30dfSdrh **         end loop
74*142e30dfSdrh **         cleanup after the SELECT
75*142e30dfSdrh **         goto D
76*142e30dfSdrh **      C: insert the select result into the intermediate table
77*142e30dfSdrh **         return
78*142e30dfSdrh **      B: open a cursor to an intermediate table
79*142e30dfSdrh **         goto A
80*142e30dfSdrh **      D: open write cursor to <table> and its indices
81*142e30dfSdrh **         loop over the intermediate table
82*142e30dfSdrh **           transfer values form intermediate table into <table>
83*142e30dfSdrh **         end the loop
84*142e30dfSdrh **         cleanup
85cce7d176Sdrh */
86cce7d176Sdrh void sqliteInsert(
87cce7d176Sdrh   Parse *pParse,        /* Parser context */
88cce7d176Sdrh   Token *pTableName,    /* Name of table into which we are inserting */
89cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
905974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
919cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
929cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
93cce7d176Sdrh ){
945974a30fSdrh   Table *pTab;          /* The table to insert into */
95c3f9bad2Sdanielk1977   char *zTab = 0;       /* Name of the table into which we are inserting */
965974a30fSdrh   int i, j, idx;        /* Loop counters */
975974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
985974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
99967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
1005974a30fSdrh   int base;             /* First available cursor */
1015974a30fSdrh   int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
102ecdc7530Sdrh   sqlite *db;           /* The main database structure */
103f57b3399Sdrh   int openOp;           /* Opcode used to open cursors */
1044a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
1050ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
106*142e30dfSdrh   int useTempTable;     /* Store SELECT results in intermediate table */
107*142e30dfSdrh   int srcTab;           /* Data comes from this temporary cursor if >=0 */
108*142e30dfSdrh   int iSelectLoop;      /* Address of code that implements the SELECT */
109*142e30dfSdrh   int iCleanup;         /* Address of the cleanup code */
110*142e30dfSdrh   int iInsertBlock;     /* Address of the subroutine used to insert data */
111*142e30dfSdrh   int iCntMem;          /* Memory cell used for the row counter */
112cce7d176Sdrh 
113c3f9bad2Sdanielk1977   int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
114c3f9bad2Sdanielk1977   int newIdx = -1;
115c3f9bad2Sdanielk1977 
116daffd0e5Sdrh   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
117ecdc7530Sdrh   db = pParse->db;
118daffd0e5Sdrh 
1191ccde15dSdrh   /* Locate the table into which we will be inserting new information.
1201ccde15dSdrh   */
121cce7d176Sdrh   zTab = sqliteTableNameFromToken(pTableName);
122daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
123c3f9bad2Sdanielk1977   pTab = sqliteFindTable(pParse->db, zTab);
124c3f9bad2Sdanielk1977   if( pTab==0 ){
125c3f9bad2Sdanielk1977     sqliteSetString(&pParse->zErrMsg, "no such table: ", zTab, 0);
126c3f9bad2Sdanielk1977     pParse->nErr++;
127c3f9bad2Sdanielk1977     goto insert_cleanup;
128c3f9bad2Sdanielk1977   }
129c3f9bad2Sdanielk1977 
130c3f9bad2Sdanielk1977   /* Ensure that:
131c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
132c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
133c3f9bad2Sdanielk1977   */
134c3f9bad2Sdanielk1977   row_triggers_exist =
135c3f9bad2Sdanielk1977     sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
136c3f9bad2Sdanielk1977         TK_BEFORE, TK_ROW, 0) ||
137c3f9bad2Sdanielk1977     sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT, TK_AFTER, TK_ROW, 0);
138c3f9bad2Sdanielk1977   if( pTab->readOnly || (pTab->pSelect && !row_triggers_exist) ){
139c3f9bad2Sdanielk1977     sqliteSetString(&pParse->zErrMsg,
140c3f9bad2Sdanielk1977       pTab->pSelect ? "view " : "table ",
141c3f9bad2Sdanielk1977       zTab,
142c3f9bad2Sdanielk1977       " may not be modified", 0);
143c3f9bad2Sdanielk1977     pParse->nErr++;
144c3f9bad2Sdanielk1977     goto insert_cleanup;
145c3f9bad2Sdanielk1977   }
146cce7d176Sdrh   sqliteFree(zTab);
147c3f9bad2Sdanielk1977   zTab = 0;
148c3f9bad2Sdanielk1977 
149a76b5dfcSdrh   if( pTab==0 ) goto insert_cleanup;
1501ccde15dSdrh 
151f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
152f573c99bSdrh   */
153f573c99bSdrh   if( pTab->pSelect ){
154f573c99bSdrh     if( sqliteViewGetColumnNames(pParse, pTab) ){
155f573c99bSdrh       goto insert_cleanup;
156f573c99bSdrh     }
157f573c99bSdrh   }
158f573c99bSdrh 
1591ccde15dSdrh   /* Allocate a VDBE
1601ccde15dSdrh   */
161d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1625974a30fSdrh   if( v==0 ) goto insert_cleanup;
163c977f7f5Sdrh   sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist);
1641ccde15dSdrh 
165c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
166f29ce559Sdanielk1977   if( row_triggers_exist ){
167c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
168f29ce559Sdanielk1977   }
169c3f9bad2Sdanielk1977 
1701ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
171*142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
172*142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
173*142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
174*142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
175*142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
176*142e30dfSdrh   ** results in a temporary table. (Template 3.)
1771ccde15dSdrh   */
1785974a30fSdrh   if( pSelect ){
179*142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
180*142e30dfSdrh     */
181*142e30dfSdrh     int rc, iInitCode;
182*142e30dfSdrh     int opCode;
183*142e30dfSdrh     iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
184*142e30dfSdrh     iSelectLoop = sqliteVdbeCurrentAddr(v);
185*142e30dfSdrh     iInsertBlock = sqliteVdbeMakeLabel(v);
186*142e30dfSdrh     rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
187daffd0e5Sdrh     if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
188*142e30dfSdrh     iCleanup = sqliteVdbeMakeLabel(v);
189*142e30dfSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
1905974a30fSdrh     assert( pSelect->pEList );
191967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
192*142e30dfSdrh 
193*142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
194*142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
195*142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
196*142e30dfSdrh     */
197*142e30dfSdrh     opCode = pTab->isTemp ? OP_OpenTemp : OP_Open;
198*142e30dfSdrh     useTempTable = row_triggers_exist || sqliteVdbeFindOp(v,opCode,pTab->tnum);
199*142e30dfSdrh 
200*142e30dfSdrh     if( useTempTable ){
201*142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
202*142e30dfSdrh       ** the result.  Store the result in a temporary table
203*142e30dfSdrh       */
204*142e30dfSdrh       srcTab = pParse->nTab++;
205*142e30dfSdrh       sqliteVdbeResolveLabel(v, iInsertBlock);
206*142e30dfSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
207*142e30dfSdrh       sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
208*142e30dfSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
209*142e30dfSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
210*142e30dfSdrh       sqliteVdbeAddOp(v, OP_Return, 0, 0);
211*142e30dfSdrh 
212*142e30dfSdrh       /* The following code runs first because the GOTO at the very top
213*142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
214*142e30dfSdrh       ** back up and execute the SELECT code above.
215*142e30dfSdrh       */
216*142e30dfSdrh       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
217*142e30dfSdrh       sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
218*142e30dfSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
219*142e30dfSdrh       sqliteVdbeResolveLabel(v, iCleanup);
2205974a30fSdrh     }else{
221*142e30dfSdrh       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
222*142e30dfSdrh     }
223*142e30dfSdrh   }else{
224*142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
225*142e30dfSdrh     ** clause
226*142e30dfSdrh     */
227ad3cab52Sdrh     SrcList dummy;
228daffd0e5Sdrh     assert( pList!=0 );
2295974a30fSdrh     srcTab = -1;
230*142e30dfSdrh     useTempTable = 0;
2315974a30fSdrh     assert( pList );
232967e8b73Sdrh     nColumn = pList->nExpr;
233ad3cab52Sdrh     dummy.nSrc = 0;
234e64e7b20Sdrh     for(i=0; i<nColumn; i++){
235832508b7Sdrh       if( sqliteExprResolveIds(pParse, 0, &dummy, 0, pList->a[i].pExpr) ){
236e64e7b20Sdrh         goto insert_cleanup;
237e64e7b20Sdrh       }
238b04a5d87Sdrh       if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
239b04a5d87Sdrh         goto insert_cleanup;
240b04a5d87Sdrh       }
241e64e7b20Sdrh     }
2425974a30fSdrh   }
2431ccde15dSdrh 
2441ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
2451ccde15dSdrh   ** of columns to be inserted into the table.
2461ccde15dSdrh   */
247967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
248cce7d176Sdrh     char zNum1[30];
249cce7d176Sdrh     char zNum2[30];
250967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
251cce7d176Sdrh     sprintf(zNum2,"%d", pTab->nCol);
252cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
253cce7d176Sdrh        " has ", zNum2, " columns but ",
254cce7d176Sdrh        zNum1, " values were supplied", 0);
255cce7d176Sdrh     pParse->nErr++;
256cce7d176Sdrh     goto insert_cleanup;
257cce7d176Sdrh   }
258967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
259cce7d176Sdrh     char zNum1[30];
260cce7d176Sdrh     char zNum2[30];
261967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
262967e8b73Sdrh     sprintf(zNum2,"%d", pColumn->nId);
263cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, zNum1, " values for ",
264cce7d176Sdrh        zNum2, " columns", 0);
265cce7d176Sdrh     pParse->nErr++;
266cce7d176Sdrh     goto insert_cleanup;
267cce7d176Sdrh   }
2681ccde15dSdrh 
2691ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
2701ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
2711ccde15dSdrh   ** remember the column indices.
272c8392586Sdrh   **
273c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
274c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
275c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
276c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
277c8392586Sdrh   ** is appears in the original table.  (The index of the primary
278c8392586Sdrh   ** key in the original table is pTab->iPKey.)
2791ccde15dSdrh   */
280967e8b73Sdrh   if( pColumn ){
281967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
282967e8b73Sdrh       pColumn->a[i].idx = -1;
283cce7d176Sdrh     }
284967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
285cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
286967e8b73Sdrh         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
287967e8b73Sdrh           pColumn->a[i].idx = j;
2884a32431cSdrh           if( j==pTab->iPKey ){
2899aa028daSdrh             keyColumn = i;
2904a32431cSdrh           }
291cce7d176Sdrh           break;
292cce7d176Sdrh         }
293cce7d176Sdrh       }
294cce7d176Sdrh       if( j>=pTab->nCol ){
295cce7d176Sdrh         sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
296967e8b73Sdrh            " has no column named ", pColumn->a[i].zName, 0);
297cce7d176Sdrh         pParse->nErr++;
298cce7d176Sdrh         goto insert_cleanup;
299cce7d176Sdrh       }
300cce7d176Sdrh     }
301cce7d176Sdrh   }
3021ccde15dSdrh 
303aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
304c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
305c8392586Sdrh   ** in the original table definition.
3064a32431cSdrh   */
3074a32431cSdrh   if( pColumn==0 ){
3084a32431cSdrh     keyColumn = pTab->iPKey;
3094a32431cSdrh   }
3104a32431cSdrh 
311*142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
312*142e30dfSdrh   */
313f29ce559Sdanielk1977   if( row_triggers_exist ){
314c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
315f29ce559Sdanielk1977   }
316c3f9bad2Sdanielk1977 
317c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
3181ccde15dSdrh   */
319*142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
320*142e30dfSdrh     iCntMem = pParse->nMem++;
321*142e30dfSdrh     sqliteVdbeAddOp(v, OP_Integer, 0, 0);
322*142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
323c3f9bad2Sdanielk1977   }
324c3f9bad2Sdanielk1977 
325c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
326c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
3275974a30fSdrh     base = pParse->nTab;
328f57b3399Sdrh     openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
32999fcd718Sdrh     sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
33099fcd718Sdrh     sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
331bed8690fSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
33299fcd718Sdrh       sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
33399fcd718Sdrh       sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
3345974a30fSdrh     }
335832508b7Sdrh     pParse->nTab += idx;
336feeb1394Sdrh   }
337feeb1394Sdrh 
338*142e30dfSdrh   /* If the data source is a temporary table, then we have to create
3391ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
340*142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
341*142e30dfSdrh   ** to launch the SELECT statement processing.
3421ccde15dSdrh   */
343*142e30dfSdrh   if( useTempTable ){
3445974a30fSdrh     iBreak = sqliteVdbeMakeLabel(v);
3456b56344dSdrh     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
3466b56344dSdrh     iCont = sqliteVdbeCurrentAddr(v);
347*142e30dfSdrh   }else if( pSelect ){
348*142e30dfSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
349*142e30dfSdrh     sqliteVdbeResolveLabel(v, iInsertBlock);
350bed8690fSdrh   }
3511ccde15dSdrh 
3526f34903eSdanielk1977   endOfLoop = sqliteVdbeMakeLabel(v);
353c3f9bad2Sdanielk1977   if( row_triggers_exist ){
354c3f9bad2Sdanielk1977 
355c3f9bad2Sdanielk1977     /* build the new.* reference row */
356c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Integer, 13, 0);
357c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
358c3f9bad2Sdanielk1977       if( pColumn==0 ){
359c3f9bad2Sdanielk1977         j = i;
360c3f9bad2Sdanielk1977       }else{
361c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
362c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
363c3f9bad2Sdanielk1977         }
364c3f9bad2Sdanielk1977       }
365c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
366c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_String, 0, 0);
367c3f9bad2Sdanielk1977         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
368*142e30dfSdrh       }else if( useTempTable ){
369c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
370*142e30dfSdrh       }else if( pSelect ){
371*142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
372c3f9bad2Sdanielk1977       }else{
373c3f9bad2Sdanielk1977         sqliteExprCode(pParse, pList->a[j].pExpr);
374c3f9bad2Sdanielk1977       }
375c3f9bad2Sdanielk1977     }
376c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
377c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
378c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
379c3f9bad2Sdanielk1977 
380c3f9bad2Sdanielk1977     /* Fire BEFORE triggers */
381f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab, newIdx, -1,
3826f34903eSdanielk1977         onError, endOfLoop) ){
383f29ce559Sdanielk1977       goto insert_cleanup;
384f29ce559Sdanielk1977     }
385c3f9bad2Sdanielk1977 
386c3f9bad2Sdanielk1977     /* Open the tables and indices for the INSERT */
387c3f9bad2Sdanielk1977     if( !pTab->pSelect ){
388c3f9bad2Sdanielk1977       base = pParse->nTab;
389c3f9bad2Sdanielk1977       openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
390c3f9bad2Sdanielk1977       sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
391c3f9bad2Sdanielk1977       sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
392c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
393c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
394c3f9bad2Sdanielk1977         sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
395c3f9bad2Sdanielk1977       }
396c3f9bad2Sdanielk1977       pParse->nTab += idx;
397c3f9bad2Sdanielk1977     }
398c3f9bad2Sdanielk1977   }
399c3f9bad2Sdanielk1977 
4004a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
4014a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
4024a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
403b419a926Sdrh   ** case the record number is the same as that column.
4041ccde15dSdrh   */
405c3f9bad2Sdanielk1977   if( !pTab->pSelect ){
4064a32431cSdrh     if( keyColumn>=0 ){
407*142e30dfSdrh       if( useTempTable ){
4084a32431cSdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
409*142e30dfSdrh       }else if( pSelect ){
410*142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
4114a32431cSdrh       }else{
4124a32431cSdrh         sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
41327a32783Sdrh       }
414e1e68f49Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
415e1e68f49Sdrh       ** to generate a unique primary key value.
416e1e68f49Sdrh       */
417f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
418e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
419e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
4208aff1015Sdrh       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
4214a32431cSdrh     }else{
42299fcd718Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
4234a32431cSdrh     }
4244a32431cSdrh 
425aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
4264a32431cSdrh     ** with the first column.
4274a32431cSdrh     */
428cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
4294a32431cSdrh       if( i==pTab->iPKey ){
4304a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
431aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
432aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
433aacc543eSdrh         ** taking up data space with information that will never be used. */
4344a32431cSdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
4354a32431cSdrh         continue;
4364a32431cSdrh       }
437967e8b73Sdrh       if( pColumn==0 ){
438cce7d176Sdrh         j = i;
439cce7d176Sdrh       }else{
440967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
441967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
442cce7d176Sdrh         }
443cce7d176Sdrh       }
444967e8b73Sdrh       if( pColumn && j>=pColumn->nId ){
44599fcd718Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
44699fcd718Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
447*142e30dfSdrh       }else if( useTempTable ){
44824e97df9Sdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
449*142e30dfSdrh       }else if( pSelect ){
450*142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
451cce7d176Sdrh       }else{
452cce7d176Sdrh         sqliteExprCode(pParse, pList->a[j].pExpr);
453cce7d176Sdrh       }
454cce7d176Sdrh     }
4551ccde15dSdrh 
4560ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
4570ca3e24bSdrh     ** do the insertion.
4584a32431cSdrh     */
459b419a926Sdrh     sqliteGenerateConstraintChecks(pParse, pTab, base, 0,0,0,onError,endOfLoop);
460b419a926Sdrh     sqliteCompleteInsertion(pParse, pTab, base, 0,0,0);
4611bee3d7bSdrh 
462feeb1394Sdrh     /* Update the count of rows that are inserted
4631bee3d7bSdrh     */
464*142e30dfSdrh     if( (db->flags & SQLITE_CountRows)!=0 ){
465*142e30dfSdrh       sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
4661bee3d7bSdrh     }
467c3f9bad2Sdanielk1977   }
468c3f9bad2Sdanielk1977 
469c3f9bad2Sdanielk1977   if( row_triggers_exist ){
470c3f9bad2Sdanielk1977     /* Close all tables opened */
471c3f9bad2Sdanielk1977     if( !pTab->pSelect ){
472c3f9bad2Sdanielk1977       sqliteVdbeAddOp(v, OP_Close, base, 0);
473c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
474c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
475c3f9bad2Sdanielk1977       }
476c3f9bad2Sdanielk1977     }
477c3f9bad2Sdanielk1977 
478c3f9bad2Sdanielk1977     /* Code AFTER triggers */
479f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
4806f34903eSdanielk1977           onError, endOfLoop) ){
481f29ce559Sdanielk1977       goto insert_cleanup;
482f29ce559Sdanielk1977     }
483c3f9bad2Sdanielk1977   }
4841bee3d7bSdrh 
4851ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
4861ccde15dSdrh   */
4870ca3e24bSdrh   sqliteVdbeResolveLabel(v, endOfLoop);
488*142e30dfSdrh   if( useTempTable ){
4896b56344dSdrh     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
49099fcd718Sdrh     sqliteVdbeResolveLabel(v, iBreak);
4916b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
492*142e30dfSdrh   }else if( pSelect ){
493*142e30dfSdrh     sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
494*142e30dfSdrh     sqliteVdbeAddOp(v, OP_Return, 0, 0);
495*142e30dfSdrh     sqliteVdbeResolveLabel(v, iCleanup);
4966b56344dSdrh   }
497c3f9bad2Sdanielk1977 
498c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
499c3f9bad2Sdanielk1977     /* Close all tables opened */
5006b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, base, 0);
5016b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
5026b56344dSdrh       sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
503cce7d176Sdrh     }
504c3f9bad2Sdanielk1977   }
505c3f9bad2Sdanielk1977 
5061c92853dSdrh   sqliteEndWriteOperation(pParse);
5075e00f6c7Sdrh 
5081bee3d7bSdrh   /*
5091bee3d7bSdrh   ** Return the number of rows inserted.
5101bee3d7bSdrh   */
511*142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
5121bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnCount, 1, 0);
5131bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
5141bee3d7bSdrh     sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
515*142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
5161bee3d7bSdrh     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
5171bee3d7bSdrh   }
518cce7d176Sdrh 
519cce7d176Sdrh insert_cleanup:
5205974a30fSdrh   if( pList ) sqliteExprListDelete(pList);
5215974a30fSdrh   if( pSelect ) sqliteSelectDelete(pSelect);
522c3f9bad2Sdanielk1977   if ( zTab ) sqliteFree(zTab);
523967e8b73Sdrh   sqliteIdListDelete(pColumn);
524cce7d176Sdrh }
5259cfcf5d4Sdrh 
5269cfcf5d4Sdrh /*
5279cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
5289cfcf5d4Sdrh **
5299cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
5300ca3e24bSdrh ** the following values:
5310ca3e24bSdrh **
532b419a926Sdrh **    1.  The recno of the row to be updated before it is updated.  This
533b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
534b419a926Sdrh **        change to the record number.
5350ca3e24bSdrh **
536b419a926Sdrh **    2.  The recno of the row after the update.
5370ca3e24bSdrh **
5380ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
5390ca3e24bSdrh **
5400ca3e24bSdrh **    i.  Data from middle columns...
5410ca3e24bSdrh **
5420ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
5430ca3e24bSdrh **
544b419a926Sdrh ** The old recno shown as entry (1) above is omitted unless both isUpdate
5451c92853dSdrh ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
5461c92853dSdrh ** INSERTs and recnoChng is true if the record number is being changed.
5470ca3e24bSdrh **
5480ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
5490ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
5500ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
5510ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
5520ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
5539cfcf5d4Sdrh **
5549cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
5559cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
5561c92853dSdrh ** then the appropriate action is performed.  There are five possible
5571c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
5589cfcf5d4Sdrh **
5599cfcf5d4Sdrh **  Constraint type  Action       What Happens
5609cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
5611c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
5629cfcf5d4Sdrh **                                sqlite_exec() returns immediately with a
5639cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
5649cfcf5d4Sdrh **
5651c92853dSdrh **  any              ABORT        Back out changes from the current command
5661c92853dSdrh **                                only (do not do a complete rollback) then
5671c92853dSdrh **                                cause sqlite_exec() to return immediately
5681c92853dSdrh **                                with SQLITE_CONSTRAINT.
5691c92853dSdrh **
5701c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
5711c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
5721c92853dSdrh **                                transaction is not rolled back and any
5731c92853dSdrh **                                prior changes are retained.
5741c92853dSdrh **
5759cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
5769cfcf5d4Sdrh **                                the stack and there is an immediate jump
5779cfcf5d4Sdrh **                                to label ignoreDest.
5789cfcf5d4Sdrh **
5799cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
5809cfcf5d4Sdrh **                                value for that column.  If the default value
5819cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
5829cfcf5d4Sdrh **
5839cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
5849cfcf5d4Sdrh **                                being inserted is removed.
5859cfcf5d4Sdrh **
5869cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
5879cfcf5d4Sdrh **
5881c92853dSdrh ** Which action to take is determined by the overrideError parameter.
5891c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
5901c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
5911c92853dSdrh ** for the constraint is used.
5929cfcf5d4Sdrh **
593aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
5949cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
5959cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
5969cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
5979cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
5989cfcf5d4Sdrh **
5999cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
6009cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
6019cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
6029cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
6039cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
6049cfcf5d4Sdrh */
6059cfcf5d4Sdrh void sqliteGenerateConstraintChecks(
6069cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
6079cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
6089cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
6099cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
6100ca3e24bSdrh   int recnoChng,      /* True if the record number will change */
611b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
6129cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
613b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
6149cfcf5d4Sdrh ){
6159cfcf5d4Sdrh   int i;
6169cfcf5d4Sdrh   Vdbe *v;
6179cfcf5d4Sdrh   int nCol;
6189cfcf5d4Sdrh   int onError;
6199cfcf5d4Sdrh   int addr;
6209cfcf5d4Sdrh   int extra;
6210ca3e24bSdrh   int iCur;
6220ca3e24bSdrh   Index *pIdx;
6230ca3e24bSdrh   int seenReplace = 0;
624f5905aa7Sdrh   int jumpInst1, jumpInst2;
6250ca3e24bSdrh   int contAddr;
626b419a926Sdrh   int hasTwoRecnos = (isUpdate && recnoChng);
6279cfcf5d4Sdrh 
6289cfcf5d4Sdrh   v = sqliteGetVdbe(pParse);
6299cfcf5d4Sdrh   assert( v!=0 );
630417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
6319cfcf5d4Sdrh   nCol = pTab->nCol;
6329cfcf5d4Sdrh 
6339cfcf5d4Sdrh   /* Test all NOT NULL constraints.
6349cfcf5d4Sdrh   */
6359cfcf5d4Sdrh   for(i=0; i<nCol; i++){
6360ca3e24bSdrh     if( i==pTab->iPKey ){
6370ca3e24bSdrh       /* Fix me: Make sure the INTEGER PRIMARY KEY is not NULL. */
6380ca3e24bSdrh       continue;
6390ca3e24bSdrh     }
6409cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
6410ca3e24bSdrh     if( onError==OE_None ) continue;
6429cfcf5d4Sdrh     if( overrideError!=OE_Default ){
6439cfcf5d4Sdrh       onError = overrideError;
6441c92853dSdrh     }else if( onError==OE_Default ){
6450d65dc0eSdrh       onError = pParse->db->onError;
6460d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
6479cfcf5d4Sdrh     }
6489cfcf5d4Sdrh     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
6499cfcf5d4Sdrh       onError = OE_Abort;
6509cfcf5d4Sdrh     }
651ef6764a1Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
652f5905aa7Sdrh     addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
6539cfcf5d4Sdrh     switch( onError ){
6541c92853dSdrh       case OE_Rollback:
6551c92853dSdrh       case OE_Abort:
6561c92853dSdrh       case OE_Fail: {
6571c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
6589cfcf5d4Sdrh         break;
6599cfcf5d4Sdrh       }
6609cfcf5d4Sdrh       case OE_Ignore: {
661b419a926Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
6620ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
6639cfcf5d4Sdrh         break;
6649cfcf5d4Sdrh       }
6659cfcf5d4Sdrh       case OE_Replace: {
6669cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
6679cfcf5d4Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
6689cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
6699cfcf5d4Sdrh         break;
6709cfcf5d4Sdrh       }
6710ca3e24bSdrh       default: assert(0);
6729cfcf5d4Sdrh     }
673ef6764a1Sdrh     sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
6749cfcf5d4Sdrh   }
6759cfcf5d4Sdrh 
6769cfcf5d4Sdrh   /* Test all CHECK constraints
6779cfcf5d4Sdrh   */
6780bd1f4eaSdrh   /**** TBD ****/
6799cfcf5d4Sdrh 
6800bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
6810bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
6820bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
6830bd1f4eaSdrh   ** Also, if the conflict resolution policy is REPLACE, then we
6840bd1f4eaSdrh   ** can skip this test.
6859cfcf5d4Sdrh   */
6860d65dc0eSdrh   if( (recnoChng || !isUpdate) && pTab->iPKey>=0 ){
6870ca3e24bSdrh     onError = pTab->keyConf;
6880ca3e24bSdrh     if( overrideError!=OE_Default ){
6890ca3e24bSdrh       onError = overrideError;
6901c92853dSdrh     }else if( onError==OE_Default ){
6910d65dc0eSdrh       onError = pParse->db->onError;
6920d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
6930ca3e24bSdrh     }
6940d65dc0eSdrh     if( onError!=OE_Replace ){
69579b0c956Sdrh       if( isUpdate ){
69679b0c956Sdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
69779b0c956Sdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
698f5905aa7Sdrh         jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
69979b0c956Sdrh       }
7000d65dc0eSdrh       sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
701f5905aa7Sdrh       jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
7020ca3e24bSdrh       switch( onError ){
7031c92853dSdrh         case OE_Rollback:
7041c92853dSdrh         case OE_Abort:
7051c92853dSdrh         case OE_Fail: {
7061c92853dSdrh           sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
7070ca3e24bSdrh           break;
7080ca3e24bSdrh         }
7090ca3e24bSdrh         case OE_Ignore: {
710b419a926Sdrh           sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
7110ca3e24bSdrh           sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
7120ca3e24bSdrh           break;
7130ca3e24bSdrh         }
7140ca3e24bSdrh         default: assert(0);
7150ca3e24bSdrh       }
7160ca3e24bSdrh       contAddr = sqliteVdbeCurrentAddr(v);
71779b0c956Sdrh       sqliteVdbeChangeP2(v, jumpInst2, contAddr);
718f5905aa7Sdrh       if( isUpdate ){
719f5905aa7Sdrh         sqliteVdbeChangeP2(v, jumpInst1, contAddr);
7200ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
7210ca3e24bSdrh         sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
7220ca3e24bSdrh       }
7230ca3e24bSdrh     }
7240d65dc0eSdrh   }
7250bd1f4eaSdrh 
7260bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
7270bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
7280bd1f4eaSdrh   ** Add the new records to the indices as we go.
7290bd1f4eaSdrh   */
7309cfcf5d4Sdrh   extra = 0;
7319cfcf5d4Sdrh   for(extra=(-1), iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
7329cfcf5d4Sdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;
7339cfcf5d4Sdrh     extra++;
7349cfcf5d4Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
7359cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
7369cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
7379cfcf5d4Sdrh       if( idx==pTab->iPKey ){
7380ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
7399cfcf5d4Sdrh       }else{
7400ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
7419cfcf5d4Sdrh       }
7429cfcf5d4Sdrh     }
743f5905aa7Sdrh     jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
744491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
7459cfcf5d4Sdrh     onError = pIdx->onError;
7469cfcf5d4Sdrh     if( onError==OE_None ) continue;
7479cfcf5d4Sdrh     if( overrideError!=OE_Default ){
7489cfcf5d4Sdrh       onError = overrideError;
7491c92853dSdrh     }else if( onError==OE_Default ){
7500d65dc0eSdrh       onError = pParse->db->onError;
7510d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
7529cfcf5d4Sdrh     }
753b419a926Sdrh     sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
754f5905aa7Sdrh     jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
7559cfcf5d4Sdrh     switch( onError ){
7561c92853dSdrh       case OE_Rollback:
7571c92853dSdrh       case OE_Abort:
7581c92853dSdrh       case OE_Fail: {
7591c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
7609cfcf5d4Sdrh         break;
7619cfcf5d4Sdrh       }
7629cfcf5d4Sdrh       case OE_Ignore: {
7630ca3e24bSdrh         assert( seenReplace==0 );
764fe1a1773Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
7659cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
7669cfcf5d4Sdrh         break;
7679cfcf5d4Sdrh       }
7689cfcf5d4Sdrh       case OE_Replace: {
76938640e15Sdrh         sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
7709cfcf5d4Sdrh         if( isUpdate ){
771b419a926Sdrh           sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
7720ca3e24bSdrh           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
7739cfcf5d4Sdrh         }
7740ca3e24bSdrh         seenReplace = 1;
7759cfcf5d4Sdrh         break;
7769cfcf5d4Sdrh       }
7770ca3e24bSdrh       default: assert(0);
7789cfcf5d4Sdrh     }
7799cfcf5d4Sdrh     contAddr = sqliteVdbeCurrentAddr(v);
7800bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
781f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst1, contAddr);
7820bd1f4eaSdrh #endif
783f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
7849cfcf5d4Sdrh   }
7859cfcf5d4Sdrh }
7860ca3e24bSdrh 
7870ca3e24bSdrh /*
7880ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
7890ca3e24bSdrh ** that was started by a prior call to sqliteGenerateConstraintChecks.
7900ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
7910ca3e24bSdrh ** and the recno for the new entry.  This routine creates the new
7920ca3e24bSdrh ** entries in all indices and in the main table.
7930ca3e24bSdrh **
794b419a926Sdrh ** The arguments to this routine should be the same as the first six
7950ca3e24bSdrh ** arguments to sqliteGenerateConstraintChecks.
7960ca3e24bSdrh */
7970ca3e24bSdrh void sqliteCompleteInsertion(
7980ca3e24bSdrh   Parse *pParse,      /* The parser context */
7990ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
8000ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
8010ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
802b419a926Sdrh   int recnoChng,      /* True if the record number will change */
803b419a926Sdrh   int isUpdate        /* True for UPDATE, False for INSERT */
8040ca3e24bSdrh ){
8050ca3e24bSdrh   int i;
8060ca3e24bSdrh   Vdbe *v;
8070ca3e24bSdrh   int nIdx;
8080ca3e24bSdrh   Index *pIdx;
8090ca3e24bSdrh 
8100ca3e24bSdrh   v = sqliteGetVdbe(pParse);
8110ca3e24bSdrh   assert( v!=0 );
812417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
8130ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
8140ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
8150ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
8160ca3e24bSdrh     sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
8170ca3e24bSdrh   }
8180ca3e24bSdrh   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
819c3f9bad2Sdanielk1977   sqliteVdbeAddOp(v, OP_PutIntKey, base, pParse->trigStack?0:1);
820b419a926Sdrh   if( isUpdate && recnoChng ){
8210ca3e24bSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
8220ca3e24bSdrh   }
8230ca3e24bSdrh }
824