xref: /sqlite-3.40.0/src/insert.c (revision cd44690a)
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*cd44690aSdrh ** $Id: insert.c,v 1.94 2004/02/24 01:05:33 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 */
96e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
975974a30fSdrh   int i, j, idx;        /* Loop counters */
985974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
995974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
100967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
1016a3ea0e6Sdrh   int base;             /* VDBE Cursor number for pTab */
1025974a30fSdrh   int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
103ecdc7530Sdrh   sqlite *db;           /* The main database structure */
1044a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
1050ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
106142e30dfSdrh   int useTempTable;     /* Store SELECT results in intermediate table */
107142e30dfSdrh   int srcTab;           /* Data comes from this temporary cursor if >=0 */
108142e30dfSdrh   int iSelectLoop;      /* Address of code that implements the SELECT */
109142e30dfSdrh   int iCleanup;         /* Address of the cleanup code */
110142e30dfSdrh   int iInsertBlock;     /* Address of the subroutine used to insert data */
111142e30dfSdrh   int iCntMem;          /* Memory cell used for the row counter */
1125cf590c1Sdrh   int isView;           /* True if attempting to insert into a view */
113cce7d176Sdrh 
114c3f9bad2Sdanielk1977   int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
11570ce3f0cSdrh   int before_triggers;        /* True if there are BEFORE triggers */
11670ce3f0cSdrh   int after_triggers;         /* True if there are AFTER triggers */
11770ce3f0cSdrh   int newIdx = -1;            /* Cursor for the NEW table */
118c3f9bad2Sdanielk1977 
119daffd0e5Sdrh   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
120ecdc7530Sdrh   db = pParse->db;
121daffd0e5Sdrh 
1221ccde15dSdrh   /* Locate the table into which we will be inserting new information.
1231ccde15dSdrh   */
124113088ecSdrh   assert( pTabList->nSrc==1 );
125113088ecSdrh   zTab = pTabList->a[0].zName;
126daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
127812d7a21Sdrh   pTab = sqliteSrcListLookup(pParse, pTabList);
128c3f9bad2Sdanielk1977   if( pTab==0 ){
129c3f9bad2Sdanielk1977     goto insert_cleanup;
130c3f9bad2Sdanielk1977   }
131e22a334bSdrh   assert( pTab->iDb<db->nDb );
132e22a334bSdrh   zDb = db->aDb[pTab->iDb].zName;
133e22a334bSdrh   if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
1341962bda7Sdrh     goto insert_cleanup;
1351962bda7Sdrh   }
136c3f9bad2Sdanielk1977 
137c3f9bad2Sdanielk1977   /* Ensure that:
138c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
139c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
140c3f9bad2Sdanielk1977   */
14170ce3f0cSdrh   before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
14270ce3f0cSdrh                                        TK_BEFORE, TK_ROW, 0);
14370ce3f0cSdrh   after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
14470ce3f0cSdrh                                        TK_AFTER, TK_ROW, 0);
14570ce3f0cSdrh   row_triggers_exist = before_triggers || after_triggers;
1465cf590c1Sdrh   isView = pTab->pSelect!=0;
1475cf590c1Sdrh   if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
148c3f9bad2Sdanielk1977     goto insert_cleanup;
149c3f9bad2Sdanielk1977   }
150a76b5dfcSdrh   if( pTab==0 ) goto insert_cleanup;
1511ccde15dSdrh 
152f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
153f573c99bSdrh   */
1545cf590c1Sdrh   if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
155f573c99bSdrh     goto insert_cleanup;
156f573c99bSdrh   }
157f573c99bSdrh 
1581ccde15dSdrh   /* Allocate a VDBE
1591ccde15dSdrh   */
160d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
1615974a30fSdrh   if( v==0 ) goto insert_cleanup;
1628bf8dc92Sdrh   sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist, pTab->iDb);
1631ccde15dSdrh 
164c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
165f29ce559Sdanielk1977   if( row_triggers_exist ){
166c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
167f29ce559Sdanielk1977   }
168c3f9bad2Sdanielk1977 
1691ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
170142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
171142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
172142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
173142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
174142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
175142e30dfSdrh   ** results in a temporary table. (Template 3.)
1761ccde15dSdrh   */
1775974a30fSdrh   if( pSelect ){
178142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
179142e30dfSdrh     */
180142e30dfSdrh     int rc, iInitCode;
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.
194048c530cSdrh     **
195048c530cSdrh     ** A temp table must be used if the table being updated is also one
196048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
197048c530cSdrh     ** temp table in the case of row triggers.
198142e30dfSdrh     */
199048c530cSdrh     if( row_triggers_exist ){
200048c530cSdrh       useTempTable = 1;
201048c530cSdrh     }else{
202048c530cSdrh       int addr = sqliteVdbeFindOp(v, OP_OpenRead, pTab->tnum);
203048c530cSdrh       useTempTable = 0;
204048c530cSdrh       if( addr>0 ){
205048c530cSdrh         VdbeOp *pOp = sqliteVdbeGetOp(v, addr-2);
206048c530cSdrh         if( pOp->opcode==OP_Integer && pOp->p1==pTab->iDb ){
207048c530cSdrh           useTempTable = 1;
208048c530cSdrh         }
209048c530cSdrh       }
210048c530cSdrh     }
211142e30dfSdrh 
212142e30dfSdrh     if( useTempTable ){
213142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
214142e30dfSdrh       ** the result.  Store the result in a temporary table
215142e30dfSdrh       */
216142e30dfSdrh       srcTab = pParse->nTab++;
217142e30dfSdrh       sqliteVdbeResolveLabel(v, iInsertBlock);
218142e30dfSdrh       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
219142e30dfSdrh       sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
220142e30dfSdrh       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
221142e30dfSdrh       sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
222142e30dfSdrh       sqliteVdbeAddOp(v, OP_Return, 0, 0);
223142e30dfSdrh 
224142e30dfSdrh       /* The following code runs first because the GOTO at the very top
225142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
226142e30dfSdrh       ** back up and execute the SELECT code above.
227142e30dfSdrh       */
228142e30dfSdrh       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
229142e30dfSdrh       sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
230142e30dfSdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
231142e30dfSdrh       sqliteVdbeResolveLabel(v, iCleanup);
2325974a30fSdrh     }else{
233142e30dfSdrh       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
234142e30dfSdrh     }
235142e30dfSdrh   }else{
236142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
237142e30dfSdrh     ** clause
238142e30dfSdrh     */
239ad3cab52Sdrh     SrcList dummy;
240daffd0e5Sdrh     assert( pList!=0 );
2415974a30fSdrh     srcTab = -1;
242142e30dfSdrh     useTempTable = 0;
2435974a30fSdrh     assert( pList );
244967e8b73Sdrh     nColumn = pList->nExpr;
245ad3cab52Sdrh     dummy.nSrc = 0;
246e64e7b20Sdrh     for(i=0; i<nColumn; i++){
2476a3ea0e6Sdrh       if( sqliteExprResolveIds(pParse, &dummy, 0, pList->a[i].pExpr) ){
248e64e7b20Sdrh         goto insert_cleanup;
249e64e7b20Sdrh       }
250b04a5d87Sdrh       if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
251b04a5d87Sdrh         goto insert_cleanup;
252b04a5d87Sdrh       }
253e64e7b20Sdrh     }
2545974a30fSdrh   }
2551ccde15dSdrh 
2561ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
2571ccde15dSdrh   ** of columns to be inserted into the table.
2581ccde15dSdrh   */
259967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
260da93d238Sdrh     sqliteErrorMsg(pParse,
261da93d238Sdrh        "table %S has %d columns but %d values were supplied",
262da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
263cce7d176Sdrh     goto insert_cleanup;
264cce7d176Sdrh   }
265967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
266da93d238Sdrh     sqliteErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
267cce7d176Sdrh     goto insert_cleanup;
268cce7d176Sdrh   }
2691ccde15dSdrh 
2701ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
2711ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
2721ccde15dSdrh   ** remember the column indices.
273c8392586Sdrh   **
274c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
275c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
276c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
277c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
278c8392586Sdrh   ** is appears in the original table.  (The index of the primary
279c8392586Sdrh   ** key in the original table is pTab->iPKey.)
2801ccde15dSdrh   */
281967e8b73Sdrh   if( pColumn ){
282967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
283967e8b73Sdrh       pColumn->a[i].idx = -1;
284cce7d176Sdrh     }
285967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
286cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
287967e8b73Sdrh         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
288967e8b73Sdrh           pColumn->a[i].idx = j;
2894a32431cSdrh           if( j==pTab->iPKey ){
2909aa028daSdrh             keyColumn = i;
2914a32431cSdrh           }
292cce7d176Sdrh           break;
293cce7d176Sdrh         }
294cce7d176Sdrh       }
295cce7d176Sdrh       if( j>=pTab->nCol ){
296a0217ba7Sdrh         if( sqliteIsRowid(pColumn->a[i].zName) ){
297a0217ba7Sdrh           keyColumn = i;
298a0217ba7Sdrh         }else{
299da93d238Sdrh           sqliteErrorMsg(pParse, "table %S has no column named %s",
300da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
301cce7d176Sdrh           pParse->nErr++;
302cce7d176Sdrh           goto insert_cleanup;
303cce7d176Sdrh         }
304cce7d176Sdrh       }
305cce7d176Sdrh     }
306a0217ba7Sdrh   }
3071ccde15dSdrh 
308aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
309c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
310c8392586Sdrh   ** in the original table definition.
3114a32431cSdrh   */
3124a32431cSdrh   if( pColumn==0 ){
3134a32431cSdrh     keyColumn = pTab->iPKey;
3144a32431cSdrh   }
3154a32431cSdrh 
316142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
317142e30dfSdrh   */
318f29ce559Sdanielk1977   if( row_triggers_exist ){
31970ce3f0cSdrh     sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
320f29ce559Sdanielk1977   }
321c3f9bad2Sdanielk1977 
322c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
3231ccde15dSdrh   */
324142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
325142e30dfSdrh     iCntMem = pParse->nMem++;
326142e30dfSdrh     sqliteVdbeAddOp(v, OP_Integer, 0, 0);
327142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
328c3f9bad2Sdanielk1977   }
329c3f9bad2Sdanielk1977 
330c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
331c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
3325974a30fSdrh     base = pParse->nTab;
333*cd44690aSdrh     idx = sqliteOpenTableAndIndices(pParse, pTab, base);
334832508b7Sdrh     pParse->nTab += idx;
335feeb1394Sdrh   }
336feeb1394Sdrh 
337142e30dfSdrh   /* If the data source is a temporary table, then we have to create
3381ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
339142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
340142e30dfSdrh   ** to launch the SELECT statement processing.
3411ccde15dSdrh   */
342142e30dfSdrh   if( useTempTable ){
3435974a30fSdrh     iBreak = sqliteVdbeMakeLabel(v);
3446b56344dSdrh     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
3456b56344dSdrh     iCont = sqliteVdbeCurrentAddr(v);
346142e30dfSdrh   }else if( pSelect ){
347142e30dfSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
348142e30dfSdrh     sqliteVdbeResolveLabel(v, iInsertBlock);
349bed8690fSdrh   }
3501ccde15dSdrh 
3515cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
35270ce3f0cSdrh   */
3536f34903eSdanielk1977   endOfLoop = sqliteVdbeMakeLabel(v);
35470ce3f0cSdrh   if( before_triggers ){
355c3f9bad2Sdanielk1977 
35670ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
35770ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
35870ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
35970ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
36070ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
36170ce3f0cSdrh     */
36270ce3f0cSdrh     if( keyColumn<0 ){
36370ce3f0cSdrh       sqliteVdbeAddOp(v, OP_Integer, -1, 0);
36470ce3f0cSdrh     }else if( useTempTable ){
36570ce3f0cSdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
36670ce3f0cSdrh     }else if( pSelect ){
36770ce3f0cSdrh       sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
36870ce3f0cSdrh     }else{
36970ce3f0cSdrh       sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
37070ce3f0cSdrh       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
37170ce3f0cSdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
37270ce3f0cSdrh       sqliteVdbeAddOp(v, OP_Integer, -1, 0);
37370ce3f0cSdrh       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
37470ce3f0cSdrh     }
37570ce3f0cSdrh 
37670ce3f0cSdrh     /* Create the new column data
37770ce3f0cSdrh     */
378c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
379c3f9bad2Sdanielk1977       if( pColumn==0 ){
380c3f9bad2Sdanielk1977         j = i;
381c3f9bad2Sdanielk1977       }else{
382c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
383c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
384c3f9bad2Sdanielk1977         }
385c3f9bad2Sdanielk1977       }
386c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
387701a0aebSdrh         sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
388142e30dfSdrh       }else if( useTempTable ){
389c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
390142e30dfSdrh       }else if( pSelect ){
391142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
392c3f9bad2Sdanielk1977       }else{
393c3f9bad2Sdanielk1977         sqliteExprCode(pParse, pList->a[j].pExpr);
394c3f9bad2Sdanielk1977       }
395c3f9bad2Sdanielk1977     }
396c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
397c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
398c3f9bad2Sdanielk1977 
3995cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
400b2fe7d8cSdrh     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab,
401b2fe7d8cSdrh         newIdx, -1, onError, endOfLoop) ){
402f29ce559Sdanielk1977       goto insert_cleanup;
403f29ce559Sdanielk1977     }
40470ce3f0cSdrh   }
405c3f9bad2Sdanielk1977 
40670ce3f0cSdrh   /* If any triggers exists, the opening of tables and indices is deferred
40770ce3f0cSdrh   ** until now.
40870ce3f0cSdrh   */
4095cf590c1Sdrh   if( row_triggers_exist && !isView ){
410c3f9bad2Sdanielk1977     base = pParse->nTab;
411*cd44690aSdrh     idx = sqliteOpenTableAndIndices(pParse, pTab, base);
412c3f9bad2Sdanielk1977     pParse->nTab += idx;
413c3f9bad2Sdanielk1977   }
414c3f9bad2Sdanielk1977 
4154a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
4164a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
4174a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
418b419a926Sdrh   ** case the record number is the same as that column.
4191ccde15dSdrh   */
4205cf590c1Sdrh   if( !isView ){
4214a32431cSdrh     if( keyColumn>=0 ){
422142e30dfSdrh       if( useTempTable ){
4234a32431cSdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
424142e30dfSdrh       }else if( pSelect ){
425142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
4264a32431cSdrh       }else{
4274a32431cSdrh         sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
42827a32783Sdrh       }
429e1e68f49Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
430e1e68f49Sdrh       ** to generate a unique primary key value.
431e1e68f49Sdrh       */
432f5905aa7Sdrh       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
433e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
434e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
4358aff1015Sdrh       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
4364a32431cSdrh     }else{
43799fcd718Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
4384a32431cSdrh     }
4394a32431cSdrh 
440aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
4414a32431cSdrh     ** with the first column.
4424a32431cSdrh     */
443cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
4444a32431cSdrh       if( i==pTab->iPKey ){
4454a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
446aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
447aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
448aacc543eSdrh         ** taking up data space with information that will never be used. */
4494a32431cSdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
4504a32431cSdrh         continue;
4514a32431cSdrh       }
452967e8b73Sdrh       if( pColumn==0 ){
453cce7d176Sdrh         j = i;
454cce7d176Sdrh       }else{
455967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
456967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
457cce7d176Sdrh         }
458cce7d176Sdrh       }
459967e8b73Sdrh       if( pColumn && j>=pColumn->nId ){
460701a0aebSdrh         sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
461142e30dfSdrh       }else if( useTempTable ){
46224e97df9Sdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
463142e30dfSdrh       }else if( pSelect ){
464142e30dfSdrh         sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
465cce7d176Sdrh       }else{
466cce7d176Sdrh         sqliteExprCode(pParse, pList->a[j].pExpr);
467cce7d176Sdrh       }
468cce7d176Sdrh     }
4691ccde15dSdrh 
4700ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
4710ca3e24bSdrh     ** do the insertion.
4724a32431cSdrh     */
473a0217ba7Sdrh     sqliteGenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
474a0217ba7Sdrh                                    0, onError, endOfLoop);
47570ce3f0cSdrh     sqliteCompleteInsertion(pParse, pTab, base, 0,0,0,
47670ce3f0cSdrh                             after_triggers ? newIdx : -1);
4775cf590c1Sdrh   }
4781bee3d7bSdrh 
479feeb1394Sdrh   /* Update the count of rows that are inserted
4801bee3d7bSdrh   */
481142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
482142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
4831bee3d7bSdrh   }
484c3f9bad2Sdanielk1977 
485c3f9bad2Sdanielk1977   if( row_triggers_exist ){
486c3f9bad2Sdanielk1977     /* Close all tables opened */
4875cf590c1Sdrh     if( !isView ){
488c3f9bad2Sdanielk1977       sqliteVdbeAddOp(v, OP_Close, base, 0);
489c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
490c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
491c3f9bad2Sdanielk1977       }
492c3f9bad2Sdanielk1977     }
493c3f9bad2Sdanielk1977 
494c3f9bad2Sdanielk1977     /* Code AFTER triggers */
495f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
4966f34903eSdanielk1977           onError, endOfLoop) ){
497f29ce559Sdanielk1977       goto insert_cleanup;
498f29ce559Sdanielk1977     }
499c3f9bad2Sdanielk1977   }
5001bee3d7bSdrh 
5011ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
5021ccde15dSdrh   */
5030ca3e24bSdrh   sqliteVdbeResolveLabel(v, endOfLoop);
504142e30dfSdrh   if( useTempTable ){
5056b56344dSdrh     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
50699fcd718Sdrh     sqliteVdbeResolveLabel(v, iBreak);
5076b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
508142e30dfSdrh   }else if( pSelect ){
509142e30dfSdrh     sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
510142e30dfSdrh     sqliteVdbeAddOp(v, OP_Return, 0, 0);
511142e30dfSdrh     sqliteVdbeResolveLabel(v, iCleanup);
5126b56344dSdrh   }
513c3f9bad2Sdanielk1977 
514c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
515c3f9bad2Sdanielk1977     /* Close all tables opened */
5166b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, base, 0);
5176b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
5186b56344dSdrh       sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
519cce7d176Sdrh     }
520c3f9bad2Sdanielk1977   }
521c3f9bad2Sdanielk1977 
522b0c374ffSrdc   sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
5231c92853dSdrh   sqliteEndWriteOperation(pParse);
5245e00f6c7Sdrh 
5251bee3d7bSdrh   /*
5261bee3d7bSdrh   ** Return the number of rows inserted.
5271bee3d7bSdrh   */
528142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
529701a0aebSdrh     sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows inserted", P3_STATIC);
530142e30dfSdrh     sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
5311bee3d7bSdrh     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
5321bee3d7bSdrh   }
533cce7d176Sdrh 
534cce7d176Sdrh insert_cleanup:
535113088ecSdrh   sqliteSrcListDelete(pTabList);
5365974a30fSdrh   if( pList ) sqliteExprListDelete(pList);
5375974a30fSdrh   if( pSelect ) sqliteSelectDelete(pSelect);
538967e8b73Sdrh   sqliteIdListDelete(pColumn);
539cce7d176Sdrh }
5409cfcf5d4Sdrh 
5419cfcf5d4Sdrh /*
5429cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
5439cfcf5d4Sdrh **
5449cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
5450ca3e24bSdrh ** the following values:
5460ca3e24bSdrh **
547b2fe7d8cSdrh **    1.  The recno of the row to be updated before the update.  This
548b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
549b419a926Sdrh **        change to the record number.
5500ca3e24bSdrh **
551b419a926Sdrh **    2.  The recno of the row after the update.
5520ca3e24bSdrh **
5530ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
5540ca3e24bSdrh **
5550ca3e24bSdrh **    i.  Data from middle columns...
5560ca3e24bSdrh **
5570ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
5580ca3e24bSdrh **
559b419a926Sdrh ** The old recno shown as entry (1) above is omitted unless both isUpdate
5601c92853dSdrh ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
5611c92853dSdrh ** INSERTs and recnoChng is true if the record number is being changed.
5620ca3e24bSdrh **
5630ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
5640ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
5650ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
5660ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
5670ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
5689cfcf5d4Sdrh **
5699cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
5709cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
5711c92853dSdrh ** then the appropriate action is performed.  There are five possible
5721c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
5739cfcf5d4Sdrh **
5749cfcf5d4Sdrh **  Constraint type  Action       What Happens
5759cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
5761c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
5779cfcf5d4Sdrh **                                sqlite_exec() returns immediately with a
5789cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
5799cfcf5d4Sdrh **
5801c92853dSdrh **  any              ABORT        Back out changes from the current command
5811c92853dSdrh **                                only (do not do a complete rollback) then
5821c92853dSdrh **                                cause sqlite_exec() to return immediately
5831c92853dSdrh **                                with SQLITE_CONSTRAINT.
5841c92853dSdrh **
5851c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
5861c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
5871c92853dSdrh **                                transaction is not rolled back and any
5881c92853dSdrh **                                prior changes are retained.
5891c92853dSdrh **
5909cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
5919cfcf5d4Sdrh **                                the stack and there is an immediate jump
5929cfcf5d4Sdrh **                                to label ignoreDest.
5939cfcf5d4Sdrh **
5949cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
5959cfcf5d4Sdrh **                                value for that column.  If the default value
5969cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
5979cfcf5d4Sdrh **
5989cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
5999cfcf5d4Sdrh **                                being inserted is removed.
6009cfcf5d4Sdrh **
6019cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
6029cfcf5d4Sdrh **
6031c92853dSdrh ** Which action to take is determined by the overrideError parameter.
6041c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
6051c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
6061c92853dSdrh ** for the constraint is used.
6079cfcf5d4Sdrh **
608aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
6099cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
6109cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
6119cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
6129cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
6139cfcf5d4Sdrh **
6149cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
6159cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
6169cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
6179cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
6189cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
6199cfcf5d4Sdrh */
6209cfcf5d4Sdrh void sqliteGenerateConstraintChecks(
6219cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
6229cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
6239cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
6249cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
6250ca3e24bSdrh   int recnoChng,      /* True if the record number will change */
626b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
6279cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
628b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
6299cfcf5d4Sdrh ){
6309cfcf5d4Sdrh   int i;
6319cfcf5d4Sdrh   Vdbe *v;
6329cfcf5d4Sdrh   int nCol;
6339cfcf5d4Sdrh   int onError;
6349cfcf5d4Sdrh   int addr;
6359cfcf5d4Sdrh   int extra;
6360ca3e24bSdrh   int iCur;
6370ca3e24bSdrh   Index *pIdx;
6380ca3e24bSdrh   int seenReplace = 0;
639f5905aa7Sdrh   int jumpInst1, jumpInst2;
6400ca3e24bSdrh   int contAddr;
641b419a926Sdrh   int hasTwoRecnos = (isUpdate && recnoChng);
6429cfcf5d4Sdrh 
6439cfcf5d4Sdrh   v = sqliteGetVdbe(pParse);
6449cfcf5d4Sdrh   assert( v!=0 );
645417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
6469cfcf5d4Sdrh   nCol = pTab->nCol;
6479cfcf5d4Sdrh 
6489cfcf5d4Sdrh   /* Test all NOT NULL constraints.
6499cfcf5d4Sdrh   */
6509cfcf5d4Sdrh   for(i=0; i<nCol; i++){
6510ca3e24bSdrh     if( i==pTab->iPKey ){
6520ca3e24bSdrh       continue;
6530ca3e24bSdrh     }
6549cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
6550ca3e24bSdrh     if( onError==OE_None ) continue;
6569cfcf5d4Sdrh     if( overrideError!=OE_Default ){
6579cfcf5d4Sdrh       onError = overrideError;
658a996e477Sdrh     }else if( pParse->db->onError!=OE_Default ){
6590d65dc0eSdrh       onError = pParse->db->onError;
660a996e477Sdrh     }else if( onError==OE_Default ){
661a996e477Sdrh       onError = OE_Abort;
6629cfcf5d4Sdrh     }
6639cfcf5d4Sdrh     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
6649cfcf5d4Sdrh       onError = OE_Abort;
6659cfcf5d4Sdrh     }
666ef6764a1Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
667f5905aa7Sdrh     addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
6689cfcf5d4Sdrh     switch( onError ){
6691c92853dSdrh       case OE_Rollback:
6701c92853dSdrh       case OE_Abort:
6711c92853dSdrh       case OE_Fail: {
672483750baSdrh         char *zMsg = 0;
6731c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
674483750baSdrh         sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
67541743984Sdrh                         " may not be NULL", (char*)0);
676483750baSdrh         sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
6779cfcf5d4Sdrh         break;
6789cfcf5d4Sdrh       }
6799cfcf5d4Sdrh       case OE_Ignore: {
680b419a926Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
6810ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
6829cfcf5d4Sdrh         break;
6839cfcf5d4Sdrh       }
6849cfcf5d4Sdrh       case OE_Replace: {
685701a0aebSdrh         sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
6869cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
6879cfcf5d4Sdrh         break;
6889cfcf5d4Sdrh       }
6890ca3e24bSdrh       default: assert(0);
6909cfcf5d4Sdrh     }
691ef6764a1Sdrh     sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
6929cfcf5d4Sdrh   }
6939cfcf5d4Sdrh 
6949cfcf5d4Sdrh   /* Test all CHECK constraints
6959cfcf5d4Sdrh   */
6960bd1f4eaSdrh   /**** TBD ****/
6979cfcf5d4Sdrh 
6980bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
6990bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
7000bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
7019cfcf5d4Sdrh   */
7025383ae5cSdrh   if( recnoChng ){
7030ca3e24bSdrh     onError = pTab->keyConf;
7040ca3e24bSdrh     if( overrideError!=OE_Default ){
7050ca3e24bSdrh       onError = overrideError;
706a996e477Sdrh     }else if( pParse->db->onError!=OE_Default ){
7070d65dc0eSdrh       onError = pParse->db->onError;
708a996e477Sdrh     }else if( onError==OE_Default ){
709a996e477Sdrh       onError = OE_Abort;
7100ca3e24bSdrh     }
711a0217ba7Sdrh 
71279b0c956Sdrh     if( isUpdate ){
71379b0c956Sdrh       sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
71479b0c956Sdrh       sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
715f5905aa7Sdrh       jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
71679b0c956Sdrh     }
7170d65dc0eSdrh     sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
718f5905aa7Sdrh     jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
7190ca3e24bSdrh     switch( onError ){
720a0217ba7Sdrh       default: {
721a0217ba7Sdrh         onError = OE_Abort;
722a0217ba7Sdrh         /* Fall thru into the next case */
723a0217ba7Sdrh       }
7241c92853dSdrh       case OE_Rollback:
7251c92853dSdrh       case OE_Abort:
7261c92853dSdrh       case OE_Fail: {
727701a0aebSdrh         sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
728701a0aebSdrh                          "PRIMARY KEY must be unique", P3_STATIC);
7290ca3e24bSdrh         break;
7300ca3e24bSdrh       }
7315383ae5cSdrh       case OE_Replace: {
7325383ae5cSdrh         sqliteGenerateRowIndexDelete(pParse->db, v, pTab, base, 0);
7335383ae5cSdrh         if( isUpdate ){
7347d02cb73Sdrh           sqliteVdbeAddOp(v, OP_Dup, nCol+hasTwoRecnos, 1);
7355383ae5cSdrh           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
7365383ae5cSdrh         }
7375383ae5cSdrh         seenReplace = 1;
7385383ae5cSdrh         break;
7395383ae5cSdrh       }
7400ca3e24bSdrh       case OE_Ignore: {
7415383ae5cSdrh         assert( seenReplace==0 );
742b419a926Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
7430ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
7440ca3e24bSdrh         break;
7450ca3e24bSdrh       }
7460ca3e24bSdrh     }
7470ca3e24bSdrh     contAddr = sqliteVdbeCurrentAddr(v);
74879b0c956Sdrh     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
749f5905aa7Sdrh     if( isUpdate ){
750f5905aa7Sdrh       sqliteVdbeChangeP2(v, jumpInst1, contAddr);
7510ca3e24bSdrh       sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
7520ca3e24bSdrh       sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
7530ca3e24bSdrh     }
7540ca3e24bSdrh   }
7550bd1f4eaSdrh 
7560bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
7570bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
7580bd1f4eaSdrh   ** Add the new records to the indices as we go.
7590bd1f4eaSdrh   */
760b2fe7d8cSdrh   extra = -1;
761b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
762b2fe7d8cSdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
7639cfcf5d4Sdrh     extra++;
764b2fe7d8cSdrh 
765b2fe7d8cSdrh     /* Create a key for accessing the index entry */
7669cfcf5d4Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
7679cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
7689cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
7699cfcf5d4Sdrh       if( idx==pTab->iPKey ){
7700ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
7719cfcf5d4Sdrh       }else{
7720ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
7739cfcf5d4Sdrh       }
7749cfcf5d4Sdrh     }
775f5905aa7Sdrh     jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
776491791a8Sdrh     if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
777b2fe7d8cSdrh 
778b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
7799cfcf5d4Sdrh     onError = pIdx->onError;
780b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
7819cfcf5d4Sdrh     if( overrideError!=OE_Default ){
7829cfcf5d4Sdrh       onError = overrideError;
783a996e477Sdrh     }else if( pParse->db->onError!=OE_Default ){
7840d65dc0eSdrh       onError = pParse->db->onError;
785a996e477Sdrh     }else if( onError==OE_Default ){
786a996e477Sdrh       onError = OE_Abort;
7879cfcf5d4Sdrh     }
7885383ae5cSdrh     if( seenReplace ){
7895383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
7905383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
7915383ae5cSdrh     }
7925383ae5cSdrh 
793b2fe7d8cSdrh 
794b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
795b419a926Sdrh     sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
796f5905aa7Sdrh     jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
797b2fe7d8cSdrh 
798b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
7999cfcf5d4Sdrh     switch( onError ){
8001c92853dSdrh       case OE_Rollback:
8011c92853dSdrh       case OE_Abort:
8021c92853dSdrh       case OE_Fail: {
80337ed48edSdrh         int j, n1, n2;
80437ed48edSdrh         char zErrMsg[200];
80537ed48edSdrh         strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
80637ed48edSdrh         n1 = strlen(zErrMsg);
80737ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
80837ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
80937ed48edSdrh           n2 = strlen(zCol);
81037ed48edSdrh           if( j>0 ){
81137ed48edSdrh             strcpy(&zErrMsg[n1], ", ");
81237ed48edSdrh             n1 += 2;
81337ed48edSdrh           }
81437ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
81537ed48edSdrh             strcpy(&zErrMsg[n1], "...");
81637ed48edSdrh             n1 += 3;
81737ed48edSdrh             break;
81837ed48edSdrh           }else{
81937ed48edSdrh             strcpy(&zErrMsg[n1], zCol);
82037ed48edSdrh             n1 += n2;
82137ed48edSdrh           }
82237ed48edSdrh         }
82337ed48edSdrh         strcpy(&zErrMsg[n1],
82437ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
825701a0aebSdrh         sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
8269cfcf5d4Sdrh         break;
8279cfcf5d4Sdrh       }
8289cfcf5d4Sdrh       case OE_Ignore: {
8290ca3e24bSdrh         assert( seenReplace==0 );
830fe1a1773Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
8319cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
8329cfcf5d4Sdrh         break;
8339cfcf5d4Sdrh       }
8349cfcf5d4Sdrh       case OE_Replace: {
83538640e15Sdrh         sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
8369cfcf5d4Sdrh         if( isUpdate ){
837b419a926Sdrh           sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
8380ca3e24bSdrh           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
8399cfcf5d4Sdrh         }
8400ca3e24bSdrh         seenReplace = 1;
8419cfcf5d4Sdrh         break;
8429cfcf5d4Sdrh       }
8430ca3e24bSdrh       default: assert(0);
8449cfcf5d4Sdrh     }
8459cfcf5d4Sdrh     contAddr = sqliteVdbeCurrentAddr(v);
8460bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
847f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst1, contAddr);
8480bd1f4eaSdrh #endif
849f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
8509cfcf5d4Sdrh   }
8519cfcf5d4Sdrh }
8520ca3e24bSdrh 
8530ca3e24bSdrh /*
8540ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
8550ca3e24bSdrh ** that was started by a prior call to sqliteGenerateConstraintChecks.
8560ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
8570ca3e24bSdrh ** and the recno for the new entry.  This routine creates the new
8580ca3e24bSdrh ** entries in all indices and in the main table.
8590ca3e24bSdrh **
860b419a926Sdrh ** The arguments to this routine should be the same as the first six
8610ca3e24bSdrh ** arguments to sqliteGenerateConstraintChecks.
8620ca3e24bSdrh */
8630ca3e24bSdrh void sqliteCompleteInsertion(
8640ca3e24bSdrh   Parse *pParse,      /* The parser context */
8650ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
8660ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
8670ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
868b419a926Sdrh   int recnoChng,      /* True if the record number will change */
86970ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
87070ce3f0cSdrh   int newIdx          /* Index of NEW table for triggers.  -1 if none */
8710ca3e24bSdrh ){
8720ca3e24bSdrh   int i;
8730ca3e24bSdrh   Vdbe *v;
8740ca3e24bSdrh   int nIdx;
8750ca3e24bSdrh   Index *pIdx;
8760ca3e24bSdrh 
8770ca3e24bSdrh   v = sqliteGetVdbe(pParse);
8780ca3e24bSdrh   assert( v!=0 );
879417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
8800ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
8810ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
8820ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
8830ca3e24bSdrh     sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
8840ca3e24bSdrh   }
8850ca3e24bSdrh   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
88670ce3f0cSdrh   if( newIdx>=0 ){
88770ce3f0cSdrh     sqliteVdbeAddOp(v, OP_Dup, 1, 0);
88870ce3f0cSdrh     sqliteVdbeAddOp(v, OP_Dup, 1, 0);
88970ce3f0cSdrh     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
89070ce3f0cSdrh   }
891b0c374ffSrdc   sqliteVdbeAddOp(v, OP_PutIntKey, base,
892b0c374ffSrdc     (pParse->trigStack?0:OPFLAG_NCHANGE) |
893b0c374ffSrdc     (isUpdate?0:OPFLAG_LASTROWID) | OPFLAG_CSCHANGE);
894b419a926Sdrh   if( isUpdate && recnoChng ){
8950ca3e24bSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
8960ca3e24bSdrh   }
8970ca3e24bSdrh }
898*cd44690aSdrh 
899*cd44690aSdrh /*
900*cd44690aSdrh ** Generate code that will open write cursors for a table and for all
901*cd44690aSdrh ** indices of that table.  The "base" parameter is the cursor number used
902*cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
903*cd44690aSdrh **
904*cd44690aSdrh ** Return the total number of cursors opened.  This is always at least
905*cd44690aSdrh ** 1 (for the main table) plus more for each cursor.
906*cd44690aSdrh */
907*cd44690aSdrh int sqliteOpenTableAndIndices(Parse *pParse, Table *pTab, int base){
908*cd44690aSdrh   int i;
909*cd44690aSdrh   Index *pIdx;
910*cd44690aSdrh   Vdbe *v = sqliteGetVdbe(pParse);
911*cd44690aSdrh   assert( v!=0 );
912*cd44690aSdrh   sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
913*cd44690aSdrh   sqliteVdbeOp3(v, OP_OpenWrite, base, pTab->tnum, pTab->zName, P3_STATIC);
914*cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
915*cd44690aSdrh     sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
916*cd44690aSdrh     sqliteVdbeOp3(v, OP_OpenWrite, i+base, pIdx->tnum, pIdx->zName, P3_STATIC);
917*cd44690aSdrh   }
918*cd44690aSdrh   return i;
919*cd44690aSdrh }
920