xref: /sqlite-3.40.0/src/insert.c (revision 0bd1f4ea)
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*0bd1f4eaSdrh ** $Id: insert.c,v 1.60 2002/06/06 18:54:40 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.
33cce7d176Sdrh */
34cce7d176Sdrh void sqliteInsert(
35cce7d176Sdrh   Parse *pParse,        /* Parser context */
36cce7d176Sdrh   Token *pTableName,    /* Name of table into which we are inserting */
37cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
385974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
399cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
409cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
41cce7d176Sdrh ){
425974a30fSdrh   Table *pTab;          /* The table to insert into */
43c3f9bad2Sdanielk1977   char *zTab = 0;       /* Name of the table into which we are inserting */
445974a30fSdrh   int i, j, idx;        /* Loop counters */
455974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
465974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
475974a30fSdrh   int srcTab;           /* Date comes from this temporary cursor if >=0 */
48967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
495974a30fSdrh   int base;             /* First available cursor */
505974a30fSdrh   int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
51ecdc7530Sdrh   sqlite *db;           /* The main database structure */
52f57b3399Sdrh   int openOp;           /* Opcode used to open cursors */
534a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
540ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
55cce7d176Sdrh 
56c3f9bad2Sdanielk1977   int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
57c3f9bad2Sdanielk1977   int newIdx = -1;
58c3f9bad2Sdanielk1977 
59daffd0e5Sdrh   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
60ecdc7530Sdrh   db = pParse->db;
61daffd0e5Sdrh 
621ccde15dSdrh   /* Locate the table into which we will be inserting new information.
631ccde15dSdrh   */
64cce7d176Sdrh   zTab = sqliteTableNameFromToken(pTableName);
65daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
66c3f9bad2Sdanielk1977   pTab = sqliteFindTable(pParse->db, zTab);
67c3f9bad2Sdanielk1977   if( pTab==0 ){
68c3f9bad2Sdanielk1977     sqliteSetString(&pParse->zErrMsg, "no such table: ", zTab, 0);
69c3f9bad2Sdanielk1977     pParse->nErr++;
70c3f9bad2Sdanielk1977     goto insert_cleanup;
71c3f9bad2Sdanielk1977   }
72c3f9bad2Sdanielk1977 
73c3f9bad2Sdanielk1977   /* Ensure that:
74c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
75c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
76c3f9bad2Sdanielk1977   */
77c3f9bad2Sdanielk1977   row_triggers_exist =
78c3f9bad2Sdanielk1977     sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
79c3f9bad2Sdanielk1977         TK_BEFORE, TK_ROW, 0) ||
80c3f9bad2Sdanielk1977     sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT, TK_AFTER, TK_ROW, 0);
81c3f9bad2Sdanielk1977   if( pTab->readOnly || (pTab->pSelect && !row_triggers_exist) ){
82c3f9bad2Sdanielk1977     sqliteSetString(&pParse->zErrMsg,
83c3f9bad2Sdanielk1977       pTab->pSelect ? "view " : "table ",
84c3f9bad2Sdanielk1977       zTab,
85c3f9bad2Sdanielk1977       " may not be modified", 0);
86c3f9bad2Sdanielk1977     pParse->nErr++;
87c3f9bad2Sdanielk1977     goto insert_cleanup;
88c3f9bad2Sdanielk1977   }
89cce7d176Sdrh   sqliteFree(zTab);
90c3f9bad2Sdanielk1977   zTab = 0;
91c3f9bad2Sdanielk1977 
92a76b5dfcSdrh   if( pTab==0 ) goto insert_cleanup;
931ccde15dSdrh 
941ccde15dSdrh   /* Allocate a VDBE
951ccde15dSdrh   */
96d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
975974a30fSdrh   if( v==0 ) goto insert_cleanup;
98c977f7f5Sdrh   sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist);
991ccde15dSdrh 
100c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
101f29ce559Sdanielk1977   if( row_triggers_exist ){
102c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
103f29ce559Sdanielk1977   }
104c3f9bad2Sdanielk1977 
1051ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
106c6b52df3Sdrh   ** is coming from a SELECT statement, then this step has to generate
1071ccde15dSdrh   ** all the code to implement the SELECT statement and leave the data
1081ccde15dSdrh   ** in a temporary table.  If data is coming from an expression list,
1091ccde15dSdrh   ** then we just have to count the number of expressions.
1101ccde15dSdrh   */
1115974a30fSdrh   if( pSelect ){
1125974a30fSdrh     int rc;
1135974a30fSdrh     srcTab = pParse->nTab++;
11499fcd718Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
115832508b7Sdrh     rc = sqliteSelect(pParse, pSelect, SRT_Table, srcTab, 0,0,0);
116daffd0e5Sdrh     if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
1175974a30fSdrh     assert( pSelect->pEList );
118967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
1195974a30fSdrh   }else{
120ad3cab52Sdrh     SrcList dummy;
121daffd0e5Sdrh     assert( pList!=0 );
1225974a30fSdrh     srcTab = -1;
1235974a30fSdrh     assert( pList );
124967e8b73Sdrh     nColumn = pList->nExpr;
125ad3cab52Sdrh     dummy.nSrc = 0;
126e64e7b20Sdrh     for(i=0; i<nColumn; i++){
127832508b7Sdrh       if( sqliteExprResolveIds(pParse, 0, &dummy, 0, pList->a[i].pExpr) ){
128e64e7b20Sdrh         goto insert_cleanup;
129e64e7b20Sdrh       }
130b04a5d87Sdrh       if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
131b04a5d87Sdrh         goto insert_cleanup;
132b04a5d87Sdrh       }
133e64e7b20Sdrh     }
1345974a30fSdrh   }
1351ccde15dSdrh 
1361ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
1371ccde15dSdrh   ** of columns to be inserted into the table.
1381ccde15dSdrh   */
139967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
140cce7d176Sdrh     char zNum1[30];
141cce7d176Sdrh     char zNum2[30];
142967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
143cce7d176Sdrh     sprintf(zNum2,"%d", pTab->nCol);
144cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
145cce7d176Sdrh        " has ", zNum2, " columns but ",
146cce7d176Sdrh        zNum1, " values were supplied", 0);
147cce7d176Sdrh     pParse->nErr++;
148cce7d176Sdrh     goto insert_cleanup;
149cce7d176Sdrh   }
150967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
151cce7d176Sdrh     char zNum1[30];
152cce7d176Sdrh     char zNum2[30];
153967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
154967e8b73Sdrh     sprintf(zNum2,"%d", pColumn->nId);
155cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, zNum1, " values for ",
156cce7d176Sdrh        zNum2, " columns", 0);
157cce7d176Sdrh     pParse->nErr++;
158cce7d176Sdrh     goto insert_cleanup;
159cce7d176Sdrh   }
1601ccde15dSdrh 
1611ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
1621ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
1631ccde15dSdrh   ** remember the column indices.
164c8392586Sdrh   **
165c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
166c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
167c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
168c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
169c8392586Sdrh   ** is appears in the original table.  (The index of the primary
170c8392586Sdrh   ** key in the original table is pTab->iPKey.)
1711ccde15dSdrh   */
172967e8b73Sdrh   if( pColumn ){
173967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
174967e8b73Sdrh       pColumn->a[i].idx = -1;
175cce7d176Sdrh     }
176967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
177cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
178967e8b73Sdrh         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
179967e8b73Sdrh           pColumn->a[i].idx = j;
1804a32431cSdrh           if( j==pTab->iPKey ){
1819aa028daSdrh             keyColumn = i;
1824a32431cSdrh           }
183cce7d176Sdrh           break;
184cce7d176Sdrh         }
185cce7d176Sdrh       }
186cce7d176Sdrh       if( j>=pTab->nCol ){
187cce7d176Sdrh         sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
188967e8b73Sdrh            " has no column named ", pColumn->a[i].zName, 0);
189cce7d176Sdrh         pParse->nErr++;
190cce7d176Sdrh         goto insert_cleanup;
191cce7d176Sdrh       }
192cce7d176Sdrh     }
193cce7d176Sdrh   }
1941ccde15dSdrh 
195aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
196c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
197c8392586Sdrh   ** in the original table definition.
1984a32431cSdrh   */
1994a32431cSdrh   if( pColumn==0 ){
2004a32431cSdrh     keyColumn = pTab->iPKey;
2014a32431cSdrh   }
2024a32431cSdrh 
203c3f9bad2Sdanielk1977   /* Open the temp table for FOR EACH ROW triggers */
204f29ce559Sdanielk1977   if( row_triggers_exist ){
205c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
206f29ce559Sdanielk1977   }
207c3f9bad2Sdanielk1977 
208c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
2091ccde15dSdrh   */
210c3f9bad2Sdanielk1977   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
211c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Integer, 0, 0);  /* Initialize the row count */
212c3f9bad2Sdanielk1977   }
213c3f9bad2Sdanielk1977 
214c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
215c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
2165974a30fSdrh     base = pParse->nTab;
217f57b3399Sdrh     openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
21899fcd718Sdrh     sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
21999fcd718Sdrh     sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
220bed8690fSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
22199fcd718Sdrh       sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
22299fcd718Sdrh       sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
2235974a30fSdrh     }
224832508b7Sdrh     pParse->nTab += idx;
225feeb1394Sdrh   }
226feeb1394Sdrh 
2271ccde15dSdrh   /* If the data source is a SELECT statement, then we have to create
2281ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
2291ccde15dSdrh   ** source is an expression list, then exactly one row will be inserted
2301ccde15dSdrh   ** and the loop is not used.
2311ccde15dSdrh   */
2325974a30fSdrh   if( srcTab>=0 ){
2335974a30fSdrh     iBreak = sqliteVdbeMakeLabel(v);
2346b56344dSdrh     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
2356b56344dSdrh     iCont = sqliteVdbeCurrentAddr(v);
236bed8690fSdrh   }
2371ccde15dSdrh 
238c3f9bad2Sdanielk1977   if( row_triggers_exist ){
239c3f9bad2Sdanielk1977 
240c3f9bad2Sdanielk1977     /* build the new.* reference row */
241c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Integer, 13, 0);
242c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
243c3f9bad2Sdanielk1977       if( pColumn==0 ){
244c3f9bad2Sdanielk1977         j = i;
245c3f9bad2Sdanielk1977       }else{
246c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
247c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
248c3f9bad2Sdanielk1977         }
249c3f9bad2Sdanielk1977       }
250c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
251c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_String, 0, 0);
252c3f9bad2Sdanielk1977         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
253c3f9bad2Sdanielk1977       }else if( srcTab>=0 ){
254c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
255c3f9bad2Sdanielk1977       }else{
256c3f9bad2Sdanielk1977         sqliteExprCode(pParse, pList->a[j].pExpr);
257c3f9bad2Sdanielk1977       }
258c3f9bad2Sdanielk1977     }
259c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
260c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
261c3f9bad2Sdanielk1977     sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
262c3f9bad2Sdanielk1977 
263c3f9bad2Sdanielk1977     /* Fire BEFORE triggers */
264f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab, newIdx, -1,
265f29ce559Sdanielk1977         onError) ){
266f29ce559Sdanielk1977       goto insert_cleanup;
267f29ce559Sdanielk1977     }
268c3f9bad2Sdanielk1977 
269c3f9bad2Sdanielk1977     /* Open the tables and indices for the INSERT */
270c3f9bad2Sdanielk1977     if( !pTab->pSelect ){
271c3f9bad2Sdanielk1977       base = pParse->nTab;
272c3f9bad2Sdanielk1977       openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
273c3f9bad2Sdanielk1977       sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
274c3f9bad2Sdanielk1977       sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
275c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
276c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
277c3f9bad2Sdanielk1977         sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
278c3f9bad2Sdanielk1977       }
279c3f9bad2Sdanielk1977       pParse->nTab += idx;
280c3f9bad2Sdanielk1977     }
281c3f9bad2Sdanielk1977   }
282c3f9bad2Sdanielk1977 
2834a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
2844a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
2854a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
286b419a926Sdrh   ** case the record number is the same as that column.
2871ccde15dSdrh   */
288c3f9bad2Sdanielk1977   if( !pTab->pSelect ){
2894a32431cSdrh     if( keyColumn>=0 ){
2904a32431cSdrh       if( srcTab>=0 ){
2914a32431cSdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
2924a32431cSdrh       }else{
2934a32431cSdrh         sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
294e1e68f49Sdrh 
295e1e68f49Sdrh         /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
296e1e68f49Sdrh         ** to generate a unique primary key value.
297e1e68f49Sdrh         */
298f5905aa7Sdrh         sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
299e1e68f49Sdrh         sqliteVdbeAddOp(v, OP_Pop, 1, 0);
300e1e68f49Sdrh         sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
3014a32431cSdrh       }
3028aff1015Sdrh       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
3034a32431cSdrh     }else{
30499fcd718Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
3054a32431cSdrh     }
3064a32431cSdrh 
307aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
3084a32431cSdrh     ** with the first column.
3094a32431cSdrh     */
310cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
3114a32431cSdrh       if( i==pTab->iPKey ){
3124a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
313aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
314aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
315aacc543eSdrh         ** taking up data space with information that will never be used. */
3164a32431cSdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
3174a32431cSdrh         continue;
3184a32431cSdrh       }
319967e8b73Sdrh       if( pColumn==0 ){
320cce7d176Sdrh         j = i;
321cce7d176Sdrh       }else{
322967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
323967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
324cce7d176Sdrh         }
325cce7d176Sdrh       }
326967e8b73Sdrh       if( pColumn && j>=pColumn->nId ){
32799fcd718Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
32899fcd718Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
3295974a30fSdrh       }else if( srcTab>=0 ){
33024e97df9Sdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
331cce7d176Sdrh       }else{
332cce7d176Sdrh         sqliteExprCode(pParse, pList->a[j].pExpr);
333cce7d176Sdrh       }
334cce7d176Sdrh     }
3351ccde15dSdrh 
3360ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
3370ca3e24bSdrh     ** do the insertion.
3384a32431cSdrh     */
3390ca3e24bSdrh     endOfLoop = sqliteVdbeMakeLabel(v);
340b419a926Sdrh     sqliteGenerateConstraintChecks(pParse, pTab, base, 0,0,0,onError,endOfLoop);
341b419a926Sdrh     sqliteCompleteInsertion(pParse, pTab, base, 0,0,0);
3421bee3d7bSdrh 
343feeb1394Sdrh     /* Update the count of rows that are inserted
3441bee3d7bSdrh     */
345c3f9bad2Sdanielk1977     if( (db->flags & SQLITE_CountRows)!=0 && !pParse->trigStack){
3461bee3d7bSdrh       sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
3471bee3d7bSdrh     }
348c3f9bad2Sdanielk1977   }
349c3f9bad2Sdanielk1977 
350c3f9bad2Sdanielk1977   if( row_triggers_exist ){
351c3f9bad2Sdanielk1977     /* Close all tables opened */
352c3f9bad2Sdanielk1977     if( !pTab->pSelect ){
353c3f9bad2Sdanielk1977       sqliteVdbeAddOp(v, OP_Close, base, 0);
354c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
355c3f9bad2Sdanielk1977         sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
356c3f9bad2Sdanielk1977       }
357c3f9bad2Sdanielk1977     }
358c3f9bad2Sdanielk1977 
359c3f9bad2Sdanielk1977     /* Code AFTER triggers */
360f29ce559Sdanielk1977     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
361f29ce559Sdanielk1977           onError) ){
362f29ce559Sdanielk1977       goto insert_cleanup;
363f29ce559Sdanielk1977     }
364c3f9bad2Sdanielk1977   }
3651bee3d7bSdrh 
3661ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
3671ccde15dSdrh   */
3680ca3e24bSdrh   sqliteVdbeResolveLabel(v, endOfLoop);
3695974a30fSdrh   if( srcTab>=0 ){
3706b56344dSdrh     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
37199fcd718Sdrh     sqliteVdbeResolveLabel(v, iBreak);
3726b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
3736b56344dSdrh   }
374c3f9bad2Sdanielk1977 
375c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
376c3f9bad2Sdanielk1977     /* Close all tables opened */
3776b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, base, 0);
3786b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
3796b56344dSdrh       sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
380cce7d176Sdrh     }
381c3f9bad2Sdanielk1977   }
382c3f9bad2Sdanielk1977 
3831c92853dSdrh   sqliteEndWriteOperation(pParse);
3845e00f6c7Sdrh 
3851bee3d7bSdrh   /*
3861bee3d7bSdrh   ** Return the number of rows inserted.
3871bee3d7bSdrh   */
388c3f9bad2Sdanielk1977   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
3891bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnCount, 1, 0);
3901bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
3911bee3d7bSdrh     sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
3921bee3d7bSdrh     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
3931bee3d7bSdrh   }
394cce7d176Sdrh 
395cce7d176Sdrh insert_cleanup:
3965974a30fSdrh   if( pList ) sqliteExprListDelete(pList);
3975974a30fSdrh   if( pSelect ) sqliteSelectDelete(pSelect);
398c3f9bad2Sdanielk1977   if ( zTab ) sqliteFree(zTab);
399967e8b73Sdrh   sqliteIdListDelete(pColumn);
400cce7d176Sdrh }
4019cfcf5d4Sdrh 
4029cfcf5d4Sdrh /*
4039cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
4049cfcf5d4Sdrh **
4059cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
4060ca3e24bSdrh ** the following values:
4070ca3e24bSdrh **
408b419a926Sdrh **    1.  The recno of the row to be updated before it is updated.  This
409b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
410b419a926Sdrh **        change to the record number.
4110ca3e24bSdrh **
412b419a926Sdrh **    2.  The recno of the row after the update.
4130ca3e24bSdrh **
4140ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
4150ca3e24bSdrh **
4160ca3e24bSdrh **    i.  Data from middle columns...
4170ca3e24bSdrh **
4180ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
4190ca3e24bSdrh **
420b419a926Sdrh ** The old recno shown as entry (1) above is omitted unless both isUpdate
4211c92853dSdrh ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
4221c92853dSdrh ** INSERTs and recnoChng is true if the record number is being changed.
4230ca3e24bSdrh **
4240ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
4250ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
4260ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
4270ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
4280ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
4299cfcf5d4Sdrh **
4309cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
4319cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
4321c92853dSdrh ** then the appropriate action is performed.  There are five possible
4331c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
4349cfcf5d4Sdrh **
4359cfcf5d4Sdrh **  Constraint type  Action       What Happens
4369cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
4371c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
4389cfcf5d4Sdrh **                                sqlite_exec() returns immediately with a
4399cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
4409cfcf5d4Sdrh **
4411c92853dSdrh **  any              ABORT        Back out changes from the current command
4421c92853dSdrh **                                only (do not do a complete rollback) then
4431c92853dSdrh **                                cause sqlite_exec() to return immediately
4441c92853dSdrh **                                with SQLITE_CONSTRAINT.
4451c92853dSdrh **
4461c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
4471c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
4481c92853dSdrh **                                transaction is not rolled back and any
4491c92853dSdrh **                                prior changes are retained.
4501c92853dSdrh **
4519cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
4529cfcf5d4Sdrh **                                the stack and there is an immediate jump
4539cfcf5d4Sdrh **                                to label ignoreDest.
4549cfcf5d4Sdrh **
4559cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
4569cfcf5d4Sdrh **                                value for that column.  If the default value
4579cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
4589cfcf5d4Sdrh **
4599cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
4609cfcf5d4Sdrh **                                being inserted is removed.
4619cfcf5d4Sdrh **
4629cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
4639cfcf5d4Sdrh **
4641c92853dSdrh ** Which action to take is determined by the overrideError parameter.
4651c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
4661c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
4671c92853dSdrh ** for the constraint is used.
4689cfcf5d4Sdrh **
469aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
4709cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
4719cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
4729cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
4739cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
4749cfcf5d4Sdrh **
4759cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
4769cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
4779cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
4789cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
4799cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
4809cfcf5d4Sdrh */
4819cfcf5d4Sdrh void sqliteGenerateConstraintChecks(
4829cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
4839cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
4849cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
4859cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
4860ca3e24bSdrh   int recnoChng,      /* True if the record number will change */
487b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
4889cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
489b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
4909cfcf5d4Sdrh ){
4919cfcf5d4Sdrh   int i;
4929cfcf5d4Sdrh   Vdbe *v;
4939cfcf5d4Sdrh   int nCol;
4949cfcf5d4Sdrh   int onError;
4959cfcf5d4Sdrh   int addr;
4969cfcf5d4Sdrh   int extra;
4970ca3e24bSdrh   int iCur;
4980ca3e24bSdrh   Index *pIdx;
4990ca3e24bSdrh   int seenReplace = 0;
500f5905aa7Sdrh   int jumpInst1, jumpInst2;
5010ca3e24bSdrh   int contAddr;
502b419a926Sdrh   int hasTwoRecnos = (isUpdate && recnoChng);
5039cfcf5d4Sdrh 
5049cfcf5d4Sdrh   v = sqliteGetVdbe(pParse);
5059cfcf5d4Sdrh   assert( v!=0 );
506417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
5079cfcf5d4Sdrh   nCol = pTab->nCol;
5089cfcf5d4Sdrh 
5099cfcf5d4Sdrh   /* Test all NOT NULL constraints.
5109cfcf5d4Sdrh   */
5119cfcf5d4Sdrh   for(i=0; i<nCol; i++){
5120ca3e24bSdrh     if( i==pTab->iPKey ){
5130ca3e24bSdrh       /* Fix me: Make sure the INTEGER PRIMARY KEY is not NULL. */
5140ca3e24bSdrh       continue;
5150ca3e24bSdrh     }
5169cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
5170ca3e24bSdrh     if( onError==OE_None ) continue;
5189cfcf5d4Sdrh     if( overrideError!=OE_Default ){
5199cfcf5d4Sdrh       onError = overrideError;
5201c92853dSdrh     }else if( onError==OE_Default ){
5210d65dc0eSdrh       onError = pParse->db->onError;
5220d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
5239cfcf5d4Sdrh     }
5249cfcf5d4Sdrh     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
5259cfcf5d4Sdrh       onError = OE_Abort;
5269cfcf5d4Sdrh     }
527ef6764a1Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
528f5905aa7Sdrh     addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
5299cfcf5d4Sdrh     switch( onError ){
5301c92853dSdrh       case OE_Rollback:
5311c92853dSdrh       case OE_Abort:
5321c92853dSdrh       case OE_Fail: {
5331c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
5349cfcf5d4Sdrh         break;
5359cfcf5d4Sdrh       }
5369cfcf5d4Sdrh       case OE_Ignore: {
537b419a926Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
5380ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
5399cfcf5d4Sdrh         break;
5409cfcf5d4Sdrh       }
5419cfcf5d4Sdrh       case OE_Replace: {
5429cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
5439cfcf5d4Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
5449cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
5459cfcf5d4Sdrh         break;
5469cfcf5d4Sdrh       }
5470ca3e24bSdrh       default: assert(0);
5489cfcf5d4Sdrh     }
549ef6764a1Sdrh     sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
5509cfcf5d4Sdrh   }
5519cfcf5d4Sdrh 
5529cfcf5d4Sdrh   /* Test all CHECK constraints
5539cfcf5d4Sdrh   */
554*0bd1f4eaSdrh   /**** TBD ****/
5559cfcf5d4Sdrh 
556*0bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
557*0bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
558*0bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
559*0bd1f4eaSdrh   ** Also, if the conflict resolution policy is REPLACE, then we
560*0bd1f4eaSdrh   ** can skip this test.
5619cfcf5d4Sdrh   */
5620d65dc0eSdrh   if( (recnoChng || !isUpdate) && pTab->iPKey>=0 ){
5630ca3e24bSdrh     onError = pTab->keyConf;
5640ca3e24bSdrh     if( overrideError!=OE_Default ){
5650ca3e24bSdrh       onError = overrideError;
5661c92853dSdrh     }else if( onError==OE_Default ){
5670d65dc0eSdrh       onError = pParse->db->onError;
5680d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
5690ca3e24bSdrh     }
5700d65dc0eSdrh     if( onError!=OE_Replace ){
57179b0c956Sdrh       if( isUpdate ){
57279b0c956Sdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
57379b0c956Sdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
574f5905aa7Sdrh         jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
57579b0c956Sdrh       }
5760d65dc0eSdrh       sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
577f5905aa7Sdrh       jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
5780ca3e24bSdrh       switch( onError ){
5791c92853dSdrh         case OE_Rollback:
5801c92853dSdrh         case OE_Abort:
5811c92853dSdrh         case OE_Fail: {
5821c92853dSdrh           sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
5830ca3e24bSdrh           break;
5840ca3e24bSdrh         }
5850ca3e24bSdrh         case OE_Ignore: {
586b419a926Sdrh           sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
5870ca3e24bSdrh           sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
5880ca3e24bSdrh           break;
5890ca3e24bSdrh         }
5900ca3e24bSdrh         default: assert(0);
5910ca3e24bSdrh       }
5920ca3e24bSdrh       contAddr = sqliteVdbeCurrentAddr(v);
59379b0c956Sdrh       sqliteVdbeChangeP2(v, jumpInst2, contAddr);
594f5905aa7Sdrh       if( isUpdate ){
595f5905aa7Sdrh         sqliteVdbeChangeP2(v, jumpInst1, contAddr);
5960ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
5970ca3e24bSdrh         sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
5980ca3e24bSdrh       }
5990ca3e24bSdrh     }
6000d65dc0eSdrh   }
601*0bd1f4eaSdrh 
602*0bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
603*0bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
604*0bd1f4eaSdrh   ** Add the new records to the indices as we go.
605*0bd1f4eaSdrh   */
6069cfcf5d4Sdrh   extra = 0;
6079cfcf5d4Sdrh   for(extra=(-1), iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
6089cfcf5d4Sdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;
6099cfcf5d4Sdrh     extra++;
6109cfcf5d4Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
6119cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
6129cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
6139cfcf5d4Sdrh       if( idx==pTab->iPKey ){
6140ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
6159cfcf5d4Sdrh       }else{
6160ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
6179cfcf5d4Sdrh       }
6189cfcf5d4Sdrh     }
619f5905aa7Sdrh     jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
6209cfcf5d4Sdrh     onError = pIdx->onError;
6219cfcf5d4Sdrh     if( onError==OE_None ) continue;
6229cfcf5d4Sdrh     if( overrideError!=OE_Default ){
6239cfcf5d4Sdrh       onError = overrideError;
6241c92853dSdrh     }else if( onError==OE_Default ){
6250d65dc0eSdrh       onError = pParse->db->onError;
6260d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
6279cfcf5d4Sdrh     }
628b419a926Sdrh     sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
629f5905aa7Sdrh     jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
6309cfcf5d4Sdrh     switch( onError ){
6311c92853dSdrh       case OE_Rollback:
6321c92853dSdrh       case OE_Abort:
6331c92853dSdrh       case OE_Fail: {
6341c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
6359cfcf5d4Sdrh         break;
6369cfcf5d4Sdrh       }
6379cfcf5d4Sdrh       case OE_Ignore: {
6380ca3e24bSdrh         assert( seenReplace==0 );
639fe1a1773Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
6409cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
6419cfcf5d4Sdrh         break;
6429cfcf5d4Sdrh       }
6439cfcf5d4Sdrh       case OE_Replace: {
644c8d30ac1Sdrh         sqliteGenerateRowDelete(v, pTab, base, 0);
6459cfcf5d4Sdrh         if( isUpdate ){
646b419a926Sdrh           sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
6470ca3e24bSdrh           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
6489cfcf5d4Sdrh         }
6490ca3e24bSdrh         seenReplace = 1;
6509cfcf5d4Sdrh         break;
6519cfcf5d4Sdrh       }
6520ca3e24bSdrh       default: assert(0);
6539cfcf5d4Sdrh     }
6549cfcf5d4Sdrh     contAddr = sqliteVdbeCurrentAddr(v);
655*0bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
656f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst1, contAddr);
657*0bd1f4eaSdrh #endif
658f5905aa7Sdrh     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
6599cfcf5d4Sdrh   }
6609cfcf5d4Sdrh }
6610ca3e24bSdrh 
6620ca3e24bSdrh /*
6630ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
6640ca3e24bSdrh ** that was started by a prior call to sqliteGenerateConstraintChecks.
6650ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
6660ca3e24bSdrh ** and the recno for the new entry.  This routine creates the new
6670ca3e24bSdrh ** entries in all indices and in the main table.
6680ca3e24bSdrh **
669b419a926Sdrh ** The arguments to this routine should be the same as the first six
6700ca3e24bSdrh ** arguments to sqliteGenerateConstraintChecks.
6710ca3e24bSdrh */
6720ca3e24bSdrh void sqliteCompleteInsertion(
6730ca3e24bSdrh   Parse *pParse,      /* The parser context */
6740ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
6750ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
6760ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
677b419a926Sdrh   int recnoChng,      /* True if the record number will change */
678b419a926Sdrh   int isUpdate        /* True for UPDATE, False for INSERT */
6790ca3e24bSdrh ){
6800ca3e24bSdrh   int i;
6810ca3e24bSdrh   Vdbe *v;
6820ca3e24bSdrh   int nIdx;
6830ca3e24bSdrh   Index *pIdx;
6840ca3e24bSdrh 
6850ca3e24bSdrh   v = sqliteGetVdbe(pParse);
6860ca3e24bSdrh   assert( v!=0 );
687417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
6880ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
6890ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
6900ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
6910ca3e24bSdrh     sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
6920ca3e24bSdrh   }
6930ca3e24bSdrh   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
694c3f9bad2Sdanielk1977   sqliteVdbeAddOp(v, OP_PutIntKey, base, pParse->trigStack?0:1);
695b419a926Sdrh   if( isUpdate && recnoChng ){
6960ca3e24bSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
6970ca3e24bSdrh   }
6980ca3e24bSdrh }
699