xref: /sqlite-3.40.0/src/insert.c (revision da93d238)
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*da93d238Sdrh ** $Id: insert.c,v 1.77 2003/03/31 02:12:47 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.
33142e30dfSdrh **
34142e30dfSdrh ** The code generated follows one of three templates.  For a simple
35142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
36142e30dfSdrh ** once straight down through.  The template looks like this:
37142e30dfSdrh **
38142e30dfSdrh **         open write cursor to <table> and its indices
39142e30dfSdrh **         puts VALUES clause expressions onto the stack
40142e30dfSdrh **         write the resulting record into <table>
41142e30dfSdrh **         cleanup
42142e30dfSdrh **
43142e30dfSdrh ** If the statement is of the form
44142e30dfSdrh **
45142e30dfSdrh **   INSERT INTO <table> SELECT ...
46142e30dfSdrh **
47142e30dfSdrh ** And the SELECT clause does not read from <table> at any time, then
48142e30dfSdrh ** the generated code follows this template:
49142e30dfSdrh **
50142e30dfSdrh **         goto B
51142e30dfSdrh **      A: setup for the SELECT
52142e30dfSdrh **         loop over the tables in the SELECT
53142e30dfSdrh **           gosub C
54142e30dfSdrh **         end loop
55142e30dfSdrh **         cleanup after the SELECT
56142e30dfSdrh **         goto D
57142e30dfSdrh **      B: open write cursor to <table> and its indices
58142e30dfSdrh **         goto A
59142e30dfSdrh **      C: insert the select result into <table>
60142e30dfSdrh **         return
61142e30dfSdrh **      D: cleanup
62142e30dfSdrh **
63142e30dfSdrh ** The third template is used if the insert statement takes its
64142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
65142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
66142e30dfSdrh ** we have to use a intermediate table to store the results of
67142e30dfSdrh ** the select.  The template is like this:
68142e30dfSdrh **
69142e30dfSdrh **         goto B
70142e30dfSdrh **      A: setup for the SELECT
71142e30dfSdrh **         loop over the tables in the SELECT
72142e30dfSdrh **           gosub C
73142e30dfSdrh **         end loop
74142e30dfSdrh **         cleanup after the SELECT
75142e30dfSdrh **         goto D
76142e30dfSdrh **      C: insert the select result into the intermediate table
77142e30dfSdrh **         return
78142e30dfSdrh **      B: open a cursor to an intermediate table
79142e30dfSdrh **         goto A
80142e30dfSdrh **      D: open write cursor to <table> and its indices
81142e30dfSdrh **         loop over the intermediate table
82142e30dfSdrh **           transfer values form intermediate table into <table>
83142e30dfSdrh **         end the loop
84142e30dfSdrh **         cleanup
85cce7d176Sdrh */
86cce7d176Sdrh void sqliteInsert(
87cce7d176Sdrh   Parse *pParse,        /* Parser context */
88113088ecSdrh   SrcList *pTabList,    /* 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 */
95113088ecSdrh   char *zTab;           /* 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 */
1034a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
1040ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
105142e30dfSdrh   int useTempTable;     /* Store SELECT results in intermediate table */
106142e30dfSdrh   int srcTab;           /* Data comes from this temporary cursor if >=0 */
107142e30dfSdrh   int iSelectLoop;      /* Address of code that implements the SELECT */
108142e30dfSdrh   int iCleanup;         /* Address of the cleanup code */
109142e30dfSdrh   int iInsertBlock;     /* Address of the subroutine used to insert data */
110142e30dfSdrh   int iCntMem;          /* Memory cell used for the row counter */
111cce7d176Sdrh 
112c3f9bad2Sdanielk1977   int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
113c3f9bad2Sdanielk1977   int newIdx = -1;
114c3f9bad2Sdanielk1977 
115daffd0e5Sdrh   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
116ecdc7530Sdrh   db = pParse->db;
117daffd0e5Sdrh 
1181ccde15dSdrh   /* Locate the table into which we will be inserting new information.
1191ccde15dSdrh   */
120113088ecSdrh   assert( pTabList->nSrc==1 );
121113088ecSdrh   zTab = pTabList->a[0].zName;
122daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
123812d7a21Sdrh   pTab = sqliteSrcListLookup(pParse, pTabList);
124c3f9bad2Sdanielk1977   if( pTab==0 ){
125c3f9bad2Sdanielk1977     goto insert_cleanup;
126c3f9bad2Sdanielk1977   }
127e5f9c644Sdrh   if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0) ){
1281962bda7Sdrh     goto insert_cleanup;
1291962bda7Sdrh   }
130c3f9bad2Sdanielk1977 
131c3f9bad2Sdanielk1977   /* Ensure that:
132c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
133c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
134c3f9bad2Sdanielk1977   */
135c3f9bad2Sdanielk1977   row_triggers_exist =
136c3f9bad2Sdanielk1977     sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
137c3f9bad2Sdanielk1977         TK_BEFORE, TK_ROW, 0) ||
138c3f9bad2Sdanielk1977     sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT, TK_AFTER, TK_ROW, 0);
139c3f9bad2Sdanielk1977   if( pTab->readOnly || (pTab->pSelect && !row_triggers_exist) ){
140*da93d238Sdrh     sqliteErrorMsg(pParse, "%s %s may not be modified",
141c3f9bad2Sdanielk1977       pTab->pSelect ? "view" : "table",
142*da93d238Sdrh       zTab);
143c3f9bad2Sdanielk1977     goto insert_cleanup;
144c3f9bad2Sdanielk1977   }
145c3f9bad2Sdanielk1977 
146a76b5dfcSdrh   if( pTab==0 ) goto insert_cleanup;
1471ccde15dSdrh 
148f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
149f573c99bSdrh   */
150f573c99bSdrh   if( pTab->pSelect ){
151f573c99bSdrh     if( sqliteViewGetColumnNames(pParse, pTab) ){
152f573c99bSdrh       goto insert_cleanup;
153f573c99bSdrh     }
154f573c99bSdrh   }
155f573c99bSdrh 
1561ccde15dSdrh   /* Allocate a VDBE
1571ccde15dSdrh   */
158d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1595974a30fSdrh   if( v==0 ) goto insert_cleanup;
160cabb0819Sdrh   sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist,
161d24cc427Sdrh          !row_triggers_exist && pTab->iDb==1);
1621ccde15dSdrh 
163c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
164f29ce559Sdanielk1977   if( row_triggers_exist ){
165c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
166f29ce559Sdanielk1977   }
167c3f9bad2Sdanielk1977 
1681ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
169142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
170142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
171142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
172142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
173142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
174142e30dfSdrh   ** results in a temporary table. (Template 3.)
1751ccde15dSdrh   */
1765974a30fSdrh   if( pSelect ){
177142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
178142e30dfSdrh     */
179142e30dfSdrh     int rc, iInitCode;
180142e30dfSdrh     int opCode;
181142e30dfSdrh     iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
182142e30dfSdrh     iSelectLoop = sqliteVdbeCurrentAddr(v);
183142e30dfSdrh     iInsertBlock = sqliteVdbeMakeLabel(v);
184142e30dfSdrh     rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
185daffd0e5Sdrh     if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
186142e30dfSdrh     iCleanup = sqliteVdbeMakeLabel(v);
187142e30dfSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
1885974a30fSdrh     assert( pSelect->pEList );
189967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
190142e30dfSdrh 
191142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
192142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
193142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
194142e30dfSdrh     */
195d24cc427Sdrh     opCode = pTab->iDb==1 ? OP_OpenTemp : OP_OpenRead;
196142e30dfSdrh     useTempTable = row_triggers_exist || sqliteVdbeFindOp(v,opCode,pTab->tnum);
197142e30dfSdrh 
198142e30dfSdrh     if( useTempTable ){
199142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
200142e30dfSdrh       ** the result.  Store the result in a temporary table
201142e30dfSdrh       */
202142e30dfSdrh       srcTab = pParse->nTab++;
203142e30dfSdrh       sqliteVdbeResolveLabel(v, iInsertBlock);
204142e30dfSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
205142e30dfSdrh       sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
206142e30dfSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
207142e30dfSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
208142e30dfSdrh       sqliteVdbeAddOp(v, OP_Return, 0, 0);
209142e30dfSdrh 
210142e30dfSdrh       /* The following code runs first because the GOTO at the very top
211142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
212142e30dfSdrh       ** back up and execute the SELECT code above.
213142e30dfSdrh       */
214142e30dfSdrh       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
215142e30dfSdrh       sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
216142e30dfSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
217142e30dfSdrh       sqliteVdbeResolveLabel(v, iCleanup);
2185974a30fSdrh     }else{
219142e30dfSdrh       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
220142e30dfSdrh     }
221142e30dfSdrh   }else{
222142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
223142e30dfSdrh     ** clause
224142e30dfSdrh     */
225ad3cab52Sdrh     SrcList dummy;
226daffd0e5Sdrh     assert( pList!=0 );
2275974a30fSdrh     srcTab = -1;
228142e30dfSdrh     useTempTable = 0;
2295974a30fSdrh     assert( pList );
230967e8b73Sdrh     nColumn = pList->nExpr;
231ad3cab52Sdrh     dummy.nSrc = 0;
232e64e7b20Sdrh     for(i=0; i<nColumn; i++){
233832508b7Sdrh       if( sqliteExprResolveIds(pParse, 0, &dummy, 0, pList->a[i].pExpr) ){
234e64e7b20Sdrh         goto insert_cleanup;
235e64e7b20Sdrh       }
236b04a5d87Sdrh       if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
237b04a5d87Sdrh         goto insert_cleanup;
238b04a5d87Sdrh       }
239e64e7b20Sdrh     }
2405974a30fSdrh   }
2411ccde15dSdrh 
2421ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
2431ccde15dSdrh   ** of columns to be inserted into the table.
2441ccde15dSdrh   */
245967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
246*da93d238Sdrh     sqliteErrorMsg(pParse,
247*da93d238Sdrh        "table %S has %d columns but %d values were supplied",
248*da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
249cce7d176Sdrh     goto insert_cleanup;
250cce7d176Sdrh   }
251967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
252*da93d238Sdrh     sqliteErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
253cce7d176Sdrh     goto insert_cleanup;
254cce7d176Sdrh   }
2551ccde15dSdrh 
2561ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
2571ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
2581ccde15dSdrh   ** remember the column indices.
259c8392586Sdrh   **
260c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
261c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
262c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
263c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
264c8392586Sdrh   ** is appears in the original table.  (The index of the primary
265c8392586Sdrh   ** key in the original table is pTab->iPKey.)
2661ccde15dSdrh   */
267967e8b73Sdrh   if( pColumn ){
268967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
269967e8b73Sdrh       pColumn->a[i].idx = -1;
270cce7d176Sdrh     }
271967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
272cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
273967e8b73Sdrh         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
274967e8b73Sdrh           pColumn->a[i].idx = j;
2754a32431cSdrh           if( j==pTab->iPKey ){
2769aa028daSdrh             keyColumn = i;
2774a32431cSdrh           }
278cce7d176Sdrh           break;
279cce7d176Sdrh         }
280cce7d176Sdrh       }
281cce7d176Sdrh       if( j>=pTab->nCol ){
282*da93d238Sdrh         sqliteErrorMsg(pParse, "table %S has no column named %s",
283*da93d238Sdrh             pTabList, 0, pColumn->a[i].zName);
284cce7d176Sdrh         pParse->nErr++;
285cce7d176Sdrh         goto insert_cleanup;
286cce7d176Sdrh       }
287cce7d176Sdrh     }
288cce7d176Sdrh   }
2891ccde15dSdrh 
290aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
291c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
292c8392586Sdrh   ** in the original table definition.
2934a32431cSdrh   */
2944a32431cSdrh   if( pColumn==0 ){
2954a32431cSdrh     keyColumn = pTab->iPKey;
2964a32431cSdrh   }
2974a32431cSdrh 
298142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
299142e30dfSdrh   */
300f29ce559Sdanielk1977   if( row_triggers_exist ){
301c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
302f29ce559Sdanielk1977   }
303c3f9bad2Sdanielk1977 
304c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
3051ccde15dSdrh   */
306142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
307142e30dfSdrh     iCntMem = pParse->nMem++;
308142e30dfSdrh     sqliteVdbeAddOp(v, OP_Integer, 0, 0);
309142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
310c3f9bad2Sdanielk1977   }
311c3f9bad2Sdanielk1977 
312c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
313c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
3145974a30fSdrh     base = pParse->nTab;
315d24cc427Sdrh     sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
316001bbcbbSdrh     sqliteVdbeAddOp(v, OP_OpenWrite, base, pTab->tnum);
31799fcd718Sdrh     sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
318bed8690fSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
319d24cc427Sdrh       sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
320001bbcbbSdrh       sqliteVdbeAddOp(v, OP_OpenWrite, idx+base, pIdx->tnum);
32199fcd718Sdrh       sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
3225974a30fSdrh     }
323832508b7Sdrh     pParse->nTab += idx;
324feeb1394Sdrh   }
325feeb1394Sdrh 
326142e30dfSdrh   /* If the data source is a temporary table, then we have to create
3271ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
328142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
329142e30dfSdrh   ** to launch the SELECT statement processing.
3301ccde15dSdrh   */
331142e30dfSdrh   if( useTempTable ){
3325974a30fSdrh     iBreak = sqliteVdbeMakeLabel(v);
3336b56344dSdrh     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
3346b56344dSdrh     iCont = sqliteVdbeCurrentAddr(v);
335142e30dfSdrh   }else if( pSelect ){
336142e30dfSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
337142e30dfSdrh     sqliteVdbeResolveLabel(v, iInsertBlock);
338bed8690fSdrh   }
3391ccde15dSdrh 
3406f34903eSdanielk1977   endOfLoop = sqliteVdbeMakeLabel(v);
341c3f9bad2Sdanielk1977   if( row_triggers_exist ){
342c3f9bad2Sdanielk1977 
343c3f9bad2Sdanielk1977     /* build the new.* reference row */
344c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Integer, 13, 0);
345c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
346c3f9bad2Sdanielk1977       if( pColumn==0 ){
347c3f9bad2Sdanielk1977         j = i;
348c3f9bad2Sdanielk1977       }else{
349c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
350c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
351c3f9bad2Sdanielk1977         }
352c3f9bad2Sdanielk1977       }
353c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
354c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_String, 0, 0);
355c3f9bad2Sdanielk1977         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
356142e30dfSdrh       }else if( useTempTable ){
357c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
358142e30dfSdrh       }else if( pSelect ){
359142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
360c3f9bad2Sdanielk1977       }else{
361c3f9bad2Sdanielk1977         sqliteExprCode(pParse, pList->a[j].pExpr);
362c3f9bad2Sdanielk1977       }
363c3f9bad2Sdanielk1977     }
364c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
365c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
366c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
367c3f9bad2Sdanielk1977 
368c3f9bad2Sdanielk1977     /* Fire BEFORE triggers */
369f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab, newIdx, -1,
3706f34903eSdanielk1977         onError, endOfLoop) ){
371f29ce559Sdanielk1977       goto insert_cleanup;
372f29ce559Sdanielk1977     }
373c3f9bad2Sdanielk1977 
374c3f9bad2Sdanielk1977     /* Open the tables and indices for the INSERT */
375c3f9bad2Sdanielk1977     if( !pTab->pSelect ){
376c3f9bad2Sdanielk1977       base = pParse->nTab;
377d24cc427Sdrh       sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
378001bbcbbSdrh       sqliteVdbeAddOp(v, OP_OpenWrite, base, pTab->tnum);
379c3f9bad2Sdanielk1977       sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
380c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
381d24cc427Sdrh         sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
382001bbcbbSdrh         sqliteVdbeAddOp(v, OP_OpenWrite, idx+base, pIdx->tnum);
383c3f9bad2Sdanielk1977         sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
384c3f9bad2Sdanielk1977       }
385c3f9bad2Sdanielk1977       pParse->nTab += idx;
386c3f9bad2Sdanielk1977     }
387c3f9bad2Sdanielk1977   }
388c3f9bad2Sdanielk1977 
3894a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
3904a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
3914a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
392b419a926Sdrh   ** case the record number is the same as that column.
3931ccde15dSdrh   */
394c3f9bad2Sdanielk1977   if( !pTab->pSelect ){
3954a32431cSdrh     if( keyColumn>=0 ){
396142e30dfSdrh       if( useTempTable ){
3974a32431cSdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
398142e30dfSdrh       }else if( pSelect ){
399142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
4004a32431cSdrh       }else{
4014a32431cSdrh         sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
40227a32783Sdrh       }
403e1e68f49Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
404e1e68f49Sdrh       ** to generate a unique primary key value.
405e1e68f49Sdrh       */
406f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
407e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
408e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
4098aff1015Sdrh       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
4104a32431cSdrh     }else{
41199fcd718Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
4124a32431cSdrh     }
4134a32431cSdrh 
414aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
4154a32431cSdrh     ** with the first column.
4164a32431cSdrh     */
417cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
4184a32431cSdrh       if( i==pTab->iPKey ){
4194a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
420aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
421aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
422aacc543eSdrh         ** taking up data space with information that will never be used. */
4234a32431cSdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
4244a32431cSdrh         continue;
4254a32431cSdrh       }
426967e8b73Sdrh       if( pColumn==0 ){
427cce7d176Sdrh         j = i;
428cce7d176Sdrh       }else{
429967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
430967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
431cce7d176Sdrh         }
432cce7d176Sdrh       }
433967e8b73Sdrh       if( pColumn && j>=pColumn->nId ){
43499fcd718Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
43599fcd718Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
436142e30dfSdrh       }else if( useTempTable ){
43724e97df9Sdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
438142e30dfSdrh       }else if( pSelect ){
439142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
440cce7d176Sdrh       }else{
441cce7d176Sdrh         sqliteExprCode(pParse, pList->a[j].pExpr);
442cce7d176Sdrh       }
443cce7d176Sdrh     }
4441ccde15dSdrh 
4450ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
4460ca3e24bSdrh     ** do the insertion.
4474a32431cSdrh     */
448b419a926Sdrh     sqliteGenerateConstraintChecks(pParse, pTab, base, 0,0,0,onError,endOfLoop);
449b419a926Sdrh     sqliteCompleteInsertion(pParse, pTab, base, 0,0,0);
4501bee3d7bSdrh 
451feeb1394Sdrh     /* Update the count of rows that are inserted
4521bee3d7bSdrh     */
453142e30dfSdrh     if( (db->flags & SQLITE_CountRows)!=0 ){
454142e30dfSdrh       sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
4551bee3d7bSdrh     }
456c3f9bad2Sdanielk1977   }
457c3f9bad2Sdanielk1977 
458c3f9bad2Sdanielk1977   if( row_triggers_exist ){
459c3f9bad2Sdanielk1977     /* Close all tables opened */
460c3f9bad2Sdanielk1977     if( !pTab->pSelect ){
461c3f9bad2Sdanielk1977       sqliteVdbeAddOp(v, OP_Close, base, 0);
462c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
463c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
464c3f9bad2Sdanielk1977       }
465c3f9bad2Sdanielk1977     }
466c3f9bad2Sdanielk1977 
467c3f9bad2Sdanielk1977     /* Code AFTER triggers */
468f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
4696f34903eSdanielk1977           onError, endOfLoop) ){
470f29ce559Sdanielk1977       goto insert_cleanup;
471f29ce559Sdanielk1977     }
472c3f9bad2Sdanielk1977   }
4731bee3d7bSdrh 
4741ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
4751ccde15dSdrh   */
4760ca3e24bSdrh   sqliteVdbeResolveLabel(v, endOfLoop);
477142e30dfSdrh   if( useTempTable ){
4786b56344dSdrh     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
47999fcd718Sdrh     sqliteVdbeResolveLabel(v, iBreak);
4806b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
481142e30dfSdrh   }else if( pSelect ){
482142e30dfSdrh     sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
483142e30dfSdrh     sqliteVdbeAddOp(v, OP_Return, 0, 0);
484142e30dfSdrh     sqliteVdbeResolveLabel(v, iCleanup);
4856b56344dSdrh   }
486c3f9bad2Sdanielk1977 
487c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
488c3f9bad2Sdanielk1977     /* Close all tables opened */
4896b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, base, 0);
4906b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
4916b56344dSdrh       sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
492cce7d176Sdrh     }
493c3f9bad2Sdanielk1977   }
494c3f9bad2Sdanielk1977 
4951c92853dSdrh   sqliteEndWriteOperation(pParse);
4965e00f6c7Sdrh 
4971bee3d7bSdrh   /*
4981bee3d7bSdrh   ** Return the number of rows inserted.
4991bee3d7bSdrh   */
500142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
5011bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
5021bee3d7bSdrh     sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
503142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
5041bee3d7bSdrh     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
5051bee3d7bSdrh   }
506cce7d176Sdrh 
507cce7d176Sdrh insert_cleanup:
508113088ecSdrh   sqliteSrcListDelete(pTabList);
5095974a30fSdrh   if( pList ) sqliteExprListDelete(pList);
5105974a30fSdrh   if( pSelect ) sqliteSelectDelete(pSelect);
511967e8b73Sdrh   sqliteIdListDelete(pColumn);
512cce7d176Sdrh }
5139cfcf5d4Sdrh 
5149cfcf5d4Sdrh /*
5159cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
5169cfcf5d4Sdrh **
5179cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
5180ca3e24bSdrh ** the following values:
5190ca3e24bSdrh **
520b419a926Sdrh **    1.  The recno of the row to be updated before it is updated.  This
521b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
522b419a926Sdrh **        change to the record number.
5230ca3e24bSdrh **
524b419a926Sdrh **    2.  The recno of the row after the update.
5250ca3e24bSdrh **
5260ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
5270ca3e24bSdrh **
5280ca3e24bSdrh **    i.  Data from middle columns...
5290ca3e24bSdrh **
5300ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
5310ca3e24bSdrh **
532b419a926Sdrh ** The old recno shown as entry (1) above is omitted unless both isUpdate
5331c92853dSdrh ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
5341c92853dSdrh ** INSERTs and recnoChng is true if the record number is being changed.
5350ca3e24bSdrh **
5360ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
5370ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
5380ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
5390ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
5400ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
5419cfcf5d4Sdrh **
5429cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
5439cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
5441c92853dSdrh ** then the appropriate action is performed.  There are five possible
5451c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
5469cfcf5d4Sdrh **
5479cfcf5d4Sdrh **  Constraint type  Action       What Happens
5489cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
5491c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
5509cfcf5d4Sdrh **                                sqlite_exec() returns immediately with a
5519cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
5529cfcf5d4Sdrh **
5531c92853dSdrh **  any              ABORT        Back out changes from the current command
5541c92853dSdrh **                                only (do not do a complete rollback) then
5551c92853dSdrh **                                cause sqlite_exec() to return immediately
5561c92853dSdrh **                                with SQLITE_CONSTRAINT.
5571c92853dSdrh **
5581c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
5591c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
5601c92853dSdrh **                                transaction is not rolled back and any
5611c92853dSdrh **                                prior changes are retained.
5621c92853dSdrh **
5639cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
5649cfcf5d4Sdrh **                                the stack and there is an immediate jump
5659cfcf5d4Sdrh **                                to label ignoreDest.
5669cfcf5d4Sdrh **
5679cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
5689cfcf5d4Sdrh **                                value for that column.  If the default value
5699cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
5709cfcf5d4Sdrh **
5719cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
5729cfcf5d4Sdrh **                                being inserted is removed.
5739cfcf5d4Sdrh **
5749cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
5759cfcf5d4Sdrh **
5761c92853dSdrh ** Which action to take is determined by the overrideError parameter.
5771c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
5781c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
5791c92853dSdrh ** for the constraint is used.
5809cfcf5d4Sdrh **
581aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
5829cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
5839cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
5849cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
5859cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
5869cfcf5d4Sdrh **
5879cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
5889cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
5899cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
5909cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
5919cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
5929cfcf5d4Sdrh */
5939cfcf5d4Sdrh void sqliteGenerateConstraintChecks(
5949cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
5959cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
5969cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
5979cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
5980ca3e24bSdrh   int recnoChng,      /* True if the record number will change */
599b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
6009cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
601b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
6029cfcf5d4Sdrh ){
6039cfcf5d4Sdrh   int i;
6049cfcf5d4Sdrh   Vdbe *v;
6059cfcf5d4Sdrh   int nCol;
6069cfcf5d4Sdrh   int onError;
6079cfcf5d4Sdrh   int addr;
6089cfcf5d4Sdrh   int extra;
6090ca3e24bSdrh   int iCur;
6100ca3e24bSdrh   Index *pIdx;
6110ca3e24bSdrh   int seenReplace = 0;
612f5905aa7Sdrh   int jumpInst1, jumpInst2;
6130ca3e24bSdrh   int contAddr;
614b419a926Sdrh   int hasTwoRecnos = (isUpdate && recnoChng);
6159cfcf5d4Sdrh 
6169cfcf5d4Sdrh   v = sqliteGetVdbe(pParse);
6179cfcf5d4Sdrh   assert( v!=0 );
618417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
6199cfcf5d4Sdrh   nCol = pTab->nCol;
6209cfcf5d4Sdrh 
6219cfcf5d4Sdrh   /* Test all NOT NULL constraints.
6229cfcf5d4Sdrh   */
6239cfcf5d4Sdrh   for(i=0; i<nCol; i++){
6240ca3e24bSdrh     if( i==pTab->iPKey ){
6250ca3e24bSdrh       /* Fix me: Make sure the INTEGER PRIMARY KEY is not NULL. */
6260ca3e24bSdrh       continue;
6270ca3e24bSdrh     }
6289cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
6290ca3e24bSdrh     if( onError==OE_None ) continue;
6309cfcf5d4Sdrh     if( overrideError!=OE_Default ){
6319cfcf5d4Sdrh       onError = overrideError;
6321c92853dSdrh     }else if( onError==OE_Default ){
6330d65dc0eSdrh       onError = pParse->db->onError;
6340d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
6359cfcf5d4Sdrh     }
6369cfcf5d4Sdrh     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
6379cfcf5d4Sdrh       onError = OE_Abort;
6389cfcf5d4Sdrh     }
639ef6764a1Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
640f5905aa7Sdrh     addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
6419cfcf5d4Sdrh     switch( onError ){
6421c92853dSdrh       case OE_Rollback:
6431c92853dSdrh       case OE_Abort:
6441c92853dSdrh       case OE_Fail: {
645483750baSdrh         char *zMsg = 0;
6461c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
647483750baSdrh         sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
648483750baSdrh                         " may not be NULL", 0);
649483750baSdrh         sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
6509cfcf5d4Sdrh         break;
6519cfcf5d4Sdrh       }
6529cfcf5d4Sdrh       case OE_Ignore: {
653b419a926Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
6540ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
6559cfcf5d4Sdrh         break;
6569cfcf5d4Sdrh       }
6579cfcf5d4Sdrh       case OE_Replace: {
6589cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
6599cfcf5d4Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
6609cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
6619cfcf5d4Sdrh         break;
6629cfcf5d4Sdrh       }
6630ca3e24bSdrh       default: assert(0);
6649cfcf5d4Sdrh     }
665ef6764a1Sdrh     sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
6669cfcf5d4Sdrh   }
6679cfcf5d4Sdrh 
6689cfcf5d4Sdrh   /* Test all CHECK constraints
6699cfcf5d4Sdrh   */
6700bd1f4eaSdrh   /**** TBD ****/
6719cfcf5d4Sdrh 
6720bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
6730bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
6740bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
6750bd1f4eaSdrh   ** Also, if the conflict resolution policy is REPLACE, then we
6760bd1f4eaSdrh   ** can skip this test.
6779cfcf5d4Sdrh   */
6780d65dc0eSdrh   if( (recnoChng || !isUpdate) && pTab->iPKey>=0 ){
6790ca3e24bSdrh     onError = pTab->keyConf;
6800ca3e24bSdrh     if( overrideError!=OE_Default ){
6810ca3e24bSdrh       onError = overrideError;
6821c92853dSdrh     }else if( onError==OE_Default ){
6830d65dc0eSdrh       onError = pParse->db->onError;
6840d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
6850ca3e24bSdrh     }
6860d65dc0eSdrh     if( onError!=OE_Replace ){
68779b0c956Sdrh       if( isUpdate ){
68879b0c956Sdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
68979b0c956Sdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
690f5905aa7Sdrh         jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
69179b0c956Sdrh       }
6920d65dc0eSdrh       sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
693f5905aa7Sdrh       jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
6940ca3e24bSdrh       switch( onError ){
6951c92853dSdrh         case OE_Rollback:
6961c92853dSdrh         case OE_Abort:
6971c92853dSdrh         case OE_Fail: {
6981c92853dSdrh           sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
699483750baSdrh           sqliteVdbeChangeP3(v, -1, "PRIMARY KEY must be unique", P3_STATIC);
7000ca3e24bSdrh           break;
7010ca3e24bSdrh         }
7020ca3e24bSdrh         case OE_Ignore: {
703b419a926Sdrh           sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
7040ca3e24bSdrh           sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
7050ca3e24bSdrh           break;
7060ca3e24bSdrh         }
7070ca3e24bSdrh         default: assert(0);
7080ca3e24bSdrh       }
7090ca3e24bSdrh       contAddr = sqliteVdbeCurrentAddr(v);
71079b0c956Sdrh       sqliteVdbeChangeP2(v, jumpInst2, contAddr);
711f5905aa7Sdrh       if( isUpdate ){
712f5905aa7Sdrh         sqliteVdbeChangeP2(v, jumpInst1, contAddr);
7130ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
7140ca3e24bSdrh         sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
7150ca3e24bSdrh       }
7160ca3e24bSdrh     }
7170d65dc0eSdrh   }
7180bd1f4eaSdrh 
7190bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
7200bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
7210bd1f4eaSdrh   ** Add the new records to the indices as we go.
7220bd1f4eaSdrh   */
7239cfcf5d4Sdrh   extra = 0;
7249cfcf5d4Sdrh   for(extra=(-1), iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
7259cfcf5d4Sdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;
7269cfcf5d4Sdrh     extra++;
7279cfcf5d4Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
7289cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
7299cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
7309cfcf5d4Sdrh       if( idx==pTab->iPKey ){
7310ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
7329cfcf5d4Sdrh       }else{
7330ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
7349cfcf5d4Sdrh       }
7359cfcf5d4Sdrh     }
736f5905aa7Sdrh     jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
737491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
7389cfcf5d4Sdrh     onError = pIdx->onError;
7399cfcf5d4Sdrh     if( onError==OE_None ) continue;
7409cfcf5d4Sdrh     if( overrideError!=OE_Default ){
7419cfcf5d4Sdrh       onError = overrideError;
7421c92853dSdrh     }else if( onError==OE_Default ){
7430d65dc0eSdrh       onError = pParse->db->onError;
7440d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
7459cfcf5d4Sdrh     }
746b419a926Sdrh     sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
747f5905aa7Sdrh     jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
7489cfcf5d4Sdrh     switch( onError ){
7491c92853dSdrh       case OE_Rollback:
7501c92853dSdrh       case OE_Abort:
7511c92853dSdrh       case OE_Fail: {
7521c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
753483750baSdrh         sqliteVdbeChangeP3(v, -1, "uniqueness constraint failed", P3_STATIC);
7549cfcf5d4Sdrh         break;
7559cfcf5d4Sdrh       }
7569cfcf5d4Sdrh       case OE_Ignore: {
7570ca3e24bSdrh         assert( seenReplace==0 );
758fe1a1773Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
7599cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
7609cfcf5d4Sdrh         break;
7619cfcf5d4Sdrh       }
7629cfcf5d4Sdrh       case OE_Replace: {
76338640e15Sdrh         sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
7649cfcf5d4Sdrh         if( isUpdate ){
765b419a926Sdrh           sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
7660ca3e24bSdrh           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
7679cfcf5d4Sdrh         }
7680ca3e24bSdrh         seenReplace = 1;
7699cfcf5d4Sdrh         break;
7709cfcf5d4Sdrh       }
7710ca3e24bSdrh       default: assert(0);
7729cfcf5d4Sdrh     }
7739cfcf5d4Sdrh     contAddr = sqliteVdbeCurrentAddr(v);
7740bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
775f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst1, contAddr);
7760bd1f4eaSdrh #endif
777f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
7789cfcf5d4Sdrh   }
7799cfcf5d4Sdrh }
7800ca3e24bSdrh 
7810ca3e24bSdrh /*
7820ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
7830ca3e24bSdrh ** that was started by a prior call to sqliteGenerateConstraintChecks.
7840ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
7850ca3e24bSdrh ** and the recno for the new entry.  This routine creates the new
7860ca3e24bSdrh ** entries in all indices and in the main table.
7870ca3e24bSdrh **
788b419a926Sdrh ** The arguments to this routine should be the same as the first six
7890ca3e24bSdrh ** arguments to sqliteGenerateConstraintChecks.
7900ca3e24bSdrh */
7910ca3e24bSdrh void sqliteCompleteInsertion(
7920ca3e24bSdrh   Parse *pParse,      /* The parser context */
7930ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
7940ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
7950ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
796b419a926Sdrh   int recnoChng,      /* True if the record number will change */
797b419a926Sdrh   int isUpdate        /* True for UPDATE, False for INSERT */
7980ca3e24bSdrh ){
7990ca3e24bSdrh   int i;
8000ca3e24bSdrh   Vdbe *v;
8010ca3e24bSdrh   int nIdx;
8020ca3e24bSdrh   Index *pIdx;
8030ca3e24bSdrh 
8040ca3e24bSdrh   v = sqliteGetVdbe(pParse);
8050ca3e24bSdrh   assert( v!=0 );
806417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
8070ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
8080ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
8090ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
8100ca3e24bSdrh     sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
8110ca3e24bSdrh   }
8120ca3e24bSdrh   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
813c3f9bad2Sdanielk1977   sqliteVdbeAddOp(v, OP_PutIntKey, base, pParse->trigStack?0:1);
814b419a926Sdrh   if( isUpdate && recnoChng ){
8150ca3e24bSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
8160ca3e24bSdrh   }
8170ca3e24bSdrh }
818