xref: /sqlite-3.40.0/src/insert.c (revision c8d30ac1)
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*c8d30ac1Sdrh ** $Id: insert.c,v 1.52 2002/04/12 10:08:59 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 */
435974a30fSdrh   char *zTab;           /* 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 
56daffd0e5Sdrh   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
57ecdc7530Sdrh   db = pParse->db;
58daffd0e5Sdrh 
591ccde15dSdrh   /* Locate the table into which we will be inserting new information.
601ccde15dSdrh   */
61cce7d176Sdrh   zTab = sqliteTableNameFromToken(pTableName);
62daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
63a76b5dfcSdrh   pTab = sqliteTableNameToTable(pParse, zTab);
64cce7d176Sdrh   sqliteFree(zTab);
65a76b5dfcSdrh   if( pTab==0 ) goto insert_cleanup;
66417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
671ccde15dSdrh 
681ccde15dSdrh   /* Allocate a VDBE
691ccde15dSdrh   */
70d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
715974a30fSdrh   if( v==0 ) goto insert_cleanup;
72663fc63aSdrh   if( pSelect ){
73663fc63aSdrh     sqliteBeginMultiWriteOperation(pParse);
74663fc63aSdrh   }else{
751c92853dSdrh     sqliteBeginWriteOperation(pParse);
76663fc63aSdrh   }
771ccde15dSdrh 
781ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
79c6b52df3Sdrh   ** is coming from a SELECT statement, then this step has to generate
801ccde15dSdrh   ** all the code to implement the SELECT statement and leave the data
811ccde15dSdrh   ** in a temporary table.  If data is coming from an expression list,
821ccde15dSdrh   ** then we just have to count the number of expressions.
831ccde15dSdrh   */
845974a30fSdrh   if( pSelect ){
855974a30fSdrh     int rc;
865974a30fSdrh     srcTab = pParse->nTab++;
8799fcd718Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
88832508b7Sdrh     rc = sqliteSelect(pParse, pSelect, SRT_Table, srcTab, 0,0,0);
89daffd0e5Sdrh     if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
905974a30fSdrh     assert( pSelect->pEList );
91967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
925974a30fSdrh   }else{
93e64e7b20Sdrh     IdList dummy;
94daffd0e5Sdrh     assert( pList!=0 );
955974a30fSdrh     srcTab = -1;
965974a30fSdrh     assert( pList );
97967e8b73Sdrh     nColumn = pList->nExpr;
98e64e7b20Sdrh     dummy.nId = 0;
99e64e7b20Sdrh     for(i=0; i<nColumn; i++){
100832508b7Sdrh       if( sqliteExprResolveIds(pParse, 0, &dummy, 0, pList->a[i].pExpr) ){
101e64e7b20Sdrh         goto insert_cleanup;
102e64e7b20Sdrh       }
103b04a5d87Sdrh       if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
104b04a5d87Sdrh         goto insert_cleanup;
105b04a5d87Sdrh       }
106e64e7b20Sdrh     }
1075974a30fSdrh   }
1081ccde15dSdrh 
1091ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
1101ccde15dSdrh   ** of columns to be inserted into the table.
1111ccde15dSdrh   */
112967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
113cce7d176Sdrh     char zNum1[30];
114cce7d176Sdrh     char zNum2[30];
115967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
116cce7d176Sdrh     sprintf(zNum2,"%d", pTab->nCol);
117cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
118cce7d176Sdrh        " has ", zNum2, " columns but ",
119cce7d176Sdrh        zNum1, " values were supplied", 0);
120cce7d176Sdrh     pParse->nErr++;
121cce7d176Sdrh     goto insert_cleanup;
122cce7d176Sdrh   }
123967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
124cce7d176Sdrh     char zNum1[30];
125cce7d176Sdrh     char zNum2[30];
126967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
127967e8b73Sdrh     sprintf(zNum2,"%d", pColumn->nId);
128cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, zNum1, " values for ",
129cce7d176Sdrh        zNum2, " columns", 0);
130cce7d176Sdrh     pParse->nErr++;
131cce7d176Sdrh     goto insert_cleanup;
132cce7d176Sdrh   }
1331ccde15dSdrh 
1341ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
1351ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
1361ccde15dSdrh   ** remember the column indices.
137c8392586Sdrh   **
138c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
139c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
140c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
141c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
142c8392586Sdrh   ** is appears in the original table.  (The index of the primary
143c8392586Sdrh   ** key in the original table is pTab->iPKey.)
1441ccde15dSdrh   */
145967e8b73Sdrh   if( pColumn ){
146967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
147967e8b73Sdrh       pColumn->a[i].idx = -1;
148cce7d176Sdrh     }
149967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
150cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
151967e8b73Sdrh         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
152967e8b73Sdrh           pColumn->a[i].idx = j;
1534a32431cSdrh           if( j==pTab->iPKey ){
1549aa028daSdrh             keyColumn = i;
1554a32431cSdrh           }
156cce7d176Sdrh           break;
157cce7d176Sdrh         }
158cce7d176Sdrh       }
159cce7d176Sdrh       if( j>=pTab->nCol ){
160cce7d176Sdrh         sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
161967e8b73Sdrh            " has no column named ", pColumn->a[i].zName, 0);
162cce7d176Sdrh         pParse->nErr++;
163cce7d176Sdrh         goto insert_cleanup;
164cce7d176Sdrh       }
165cce7d176Sdrh     }
166cce7d176Sdrh   }
1671ccde15dSdrh 
168aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
169c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
170c8392586Sdrh   ** in the original table definition.
1714a32431cSdrh   */
1724a32431cSdrh   if( pColumn==0 ){
1734a32431cSdrh     keyColumn = pTab->iPKey;
1744a32431cSdrh   }
1754a32431cSdrh 
1761ccde15dSdrh   /* Open cursors into the table that is received the new data and
1771ccde15dSdrh   ** all indices of that table.
1781ccde15dSdrh   */
1795974a30fSdrh   base = pParse->nTab;
180f57b3399Sdrh   openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
18199fcd718Sdrh   sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
18299fcd718Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
183bed8690fSdrh   for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
18499fcd718Sdrh     sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
18599fcd718Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
1865974a30fSdrh   }
187832508b7Sdrh   pParse->nTab += idx;
1881ccde15dSdrh 
189feeb1394Sdrh   /* Initialize the count of rows to be inserted
190feeb1394Sdrh   */
191feeb1394Sdrh   if( db->flags & SQLITE_CountRows ){
192feeb1394Sdrh     sqliteVdbeAddOp(v, OP_Integer, 0, 0);  /* Initialize the row count */
193feeb1394Sdrh   }
194feeb1394Sdrh 
1951ccde15dSdrh   /* If the data source is a SELECT statement, then we have to create
1961ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
1971ccde15dSdrh   ** source is an expression list, then exactly one row will be inserted
1981ccde15dSdrh   ** and the loop is not used.
1991ccde15dSdrh   */
2005974a30fSdrh   if( srcTab>=0 ){
2015974a30fSdrh     iBreak = sqliteVdbeMakeLabel(v);
2026b56344dSdrh     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
2036b56344dSdrh     iCont = sqliteVdbeCurrentAddr(v);
204bed8690fSdrh   }
2051ccde15dSdrh 
2064a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
2074a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
2084a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
209b419a926Sdrh   ** case the record number is the same as that column.
2101ccde15dSdrh   */
2114a32431cSdrh   if( keyColumn>=0 ){
2124a32431cSdrh     if( srcTab>=0 ){
2134a32431cSdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
2144a32431cSdrh     }else{
215e1e68f49Sdrh       int addr;
2164a32431cSdrh       sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
217e1e68f49Sdrh 
218e1e68f49Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
219e1e68f49Sdrh       ** to generate a unique primary key value.
220e1e68f49Sdrh       */
221e1e68f49Sdrh       addr = sqliteVdbeAddOp(v, OP_Dup, 0, 1);
222e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_NotNull, 0, addr+4);
223e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
224e1e68f49Sdrh       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
2254a32431cSdrh     }
2268aff1015Sdrh     sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
2274a32431cSdrh   }else{
22899fcd718Sdrh     sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
2294a32431cSdrh   }
2304a32431cSdrh 
231aacc543eSdrh   /* Push onto the stack, data for all columns of the new entry, beginning
2324a32431cSdrh   ** with the first column.
2334a32431cSdrh   */
234cce7d176Sdrh   for(i=0; i<pTab->nCol; i++){
2354a32431cSdrh     if( i==pTab->iPKey ){
2364a32431cSdrh       /* The value of the INTEGER PRIMARY KEY column is always a NULL.
237aacc543eSdrh       ** Whenever this column is read, the record number will be substituted
238aacc543eSdrh       ** in its place.  So will fill this column with a NULL to avoid
239aacc543eSdrh       ** taking up data space with information that will never be used. */
2404a32431cSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
2414a32431cSdrh       continue;
2424a32431cSdrh     }
243967e8b73Sdrh     if( pColumn==0 ){
244cce7d176Sdrh       j = i;
245cce7d176Sdrh     }else{
246967e8b73Sdrh       for(j=0; j<pColumn->nId; j++){
247967e8b73Sdrh         if( pColumn->a[j].idx==i ) break;
248cce7d176Sdrh       }
249cce7d176Sdrh     }
250967e8b73Sdrh     if( pColumn && j>=pColumn->nId ){
25199fcd718Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
25299fcd718Sdrh       sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
2535974a30fSdrh     }else if( srcTab>=0 ){
25424e97df9Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, j);
255cce7d176Sdrh     }else{
256cce7d176Sdrh       sqliteExprCode(pParse, pList->a[j].pExpr);
257cce7d176Sdrh     }
258cce7d176Sdrh   }
2591ccde15dSdrh 
2600ca3e24bSdrh   /* Generate code to check constraints and generate index keys and
2610ca3e24bSdrh   ** do the insertion.
2624a32431cSdrh   */
2630ca3e24bSdrh   endOfLoop = sqliteVdbeMakeLabel(v);
264b419a926Sdrh   sqliteGenerateConstraintChecks(pParse, pTab, base, 0,0,0, onError, endOfLoop);
265b419a926Sdrh   sqliteCompleteInsertion(pParse, pTab, base, 0,0,0);
2661bee3d7bSdrh 
267feeb1394Sdrh   /* Update the count of rows that are inserted
2681bee3d7bSdrh   */
269feeb1394Sdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
2701bee3d7bSdrh     sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
2711bee3d7bSdrh   }
2721bee3d7bSdrh 
2731ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
2741ccde15dSdrh   */
2750ca3e24bSdrh   sqliteVdbeResolveLabel(v, endOfLoop);
2765974a30fSdrh   if( srcTab>=0 ){
2776b56344dSdrh     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
27899fcd718Sdrh     sqliteVdbeResolveLabel(v, iBreak);
2796b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
2806b56344dSdrh   }
2816b56344dSdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
2826b56344dSdrh   for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
2836b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
284cce7d176Sdrh   }
2851c92853dSdrh   sqliteEndWriteOperation(pParse);
2865e00f6c7Sdrh 
2871bee3d7bSdrh   /*
2881bee3d7bSdrh   ** Return the number of rows inserted.
2891bee3d7bSdrh   */
2901bee3d7bSdrh   if( db->flags & SQLITE_CountRows ){
2911bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnCount, 1, 0);
2921bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
2931bee3d7bSdrh     sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
2941bee3d7bSdrh     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
2951bee3d7bSdrh   }
296cce7d176Sdrh 
297cce7d176Sdrh insert_cleanup:
2985974a30fSdrh   if( pList ) sqliteExprListDelete(pList);
2995974a30fSdrh   if( pSelect ) sqliteSelectDelete(pSelect);
300967e8b73Sdrh   sqliteIdListDelete(pColumn);
301cce7d176Sdrh }
3029cfcf5d4Sdrh 
3039cfcf5d4Sdrh /*
3049cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
3059cfcf5d4Sdrh **
3069cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
3070ca3e24bSdrh ** the following values:
3080ca3e24bSdrh **
309b419a926Sdrh **    1.  The recno of the row to be updated before it is updated.  This
310b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
311b419a926Sdrh **        change to the record number.
3120ca3e24bSdrh **
313b419a926Sdrh **    2.  The recno of the row after the update.
3140ca3e24bSdrh **
3150ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
3160ca3e24bSdrh **
3170ca3e24bSdrh **    i.  Data from middle columns...
3180ca3e24bSdrh **
3190ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
3200ca3e24bSdrh **
321b419a926Sdrh ** The old recno shown as entry (1) above is omitted unless both isUpdate
3221c92853dSdrh ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
3231c92853dSdrh ** INSERTs and recnoChng is true if the record number is being changed.
3240ca3e24bSdrh **
3250ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
3260ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
3270ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
3280ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
3290ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
3309cfcf5d4Sdrh **
3319cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
3329cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
3331c92853dSdrh ** then the appropriate action is performed.  There are five possible
3341c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
3359cfcf5d4Sdrh **
3369cfcf5d4Sdrh **  Constraint type  Action       What Happens
3379cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
3381c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
3399cfcf5d4Sdrh **                                sqlite_exec() returns immediately with a
3409cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
3419cfcf5d4Sdrh **
3421c92853dSdrh **  any              ABORT        Back out changes from the current command
3431c92853dSdrh **                                only (do not do a complete rollback) then
3441c92853dSdrh **                                cause sqlite_exec() to return immediately
3451c92853dSdrh **                                with SQLITE_CONSTRAINT.
3461c92853dSdrh **
3471c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
3481c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
3491c92853dSdrh **                                transaction is not rolled back and any
3501c92853dSdrh **                                prior changes are retained.
3511c92853dSdrh **
3529cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
3539cfcf5d4Sdrh **                                the stack and there is an immediate jump
3549cfcf5d4Sdrh **                                to label ignoreDest.
3559cfcf5d4Sdrh **
3569cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
3579cfcf5d4Sdrh **                                value for that column.  If the default value
3589cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
3599cfcf5d4Sdrh **
3609cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
3619cfcf5d4Sdrh **                                being inserted is removed.
3629cfcf5d4Sdrh **
3639cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
3649cfcf5d4Sdrh **
3651c92853dSdrh ** Which action to take is determined by the overrideError parameter.
3661c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
3671c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
3681c92853dSdrh ** for the constraint is used.
3699cfcf5d4Sdrh **
370aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
3719cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
3729cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
3739cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
3749cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
3759cfcf5d4Sdrh **
3769cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
3779cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
3789cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
3799cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
3809cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
3819cfcf5d4Sdrh */
3829cfcf5d4Sdrh void sqliteGenerateConstraintChecks(
3839cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
3849cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
3859cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
3869cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
3870ca3e24bSdrh   int recnoChng,      /* True if the record number will change */
388b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
3899cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
390b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
3919cfcf5d4Sdrh ){
3929cfcf5d4Sdrh   int i;
3939cfcf5d4Sdrh   Vdbe *v;
3949cfcf5d4Sdrh   int nCol;
3959cfcf5d4Sdrh   int onError;
3969cfcf5d4Sdrh   int addr;
3979cfcf5d4Sdrh   int extra;
3980ca3e24bSdrh   int iCur;
3990ca3e24bSdrh   Index *pIdx;
4000ca3e24bSdrh   int seenReplace = 0;
4010ca3e24bSdrh   int jumpInst;
4020ca3e24bSdrh   int contAddr;
403b419a926Sdrh   int hasTwoRecnos = (isUpdate && recnoChng);
4049cfcf5d4Sdrh 
4059cfcf5d4Sdrh   v = sqliteGetVdbe(pParse);
4069cfcf5d4Sdrh   assert( v!=0 );
407417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
4089cfcf5d4Sdrh   nCol = pTab->nCol;
4099cfcf5d4Sdrh 
4109cfcf5d4Sdrh   /* Test all NOT NULL constraints.
4119cfcf5d4Sdrh   */
4129cfcf5d4Sdrh   for(i=0; i<nCol; i++){
4130ca3e24bSdrh     if( i==pTab->iPKey ){
4140ca3e24bSdrh       /* Fix me: Make sure the INTEGER PRIMARY KEY is not NULL. */
4150ca3e24bSdrh       continue;
4160ca3e24bSdrh     }
4179cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
4180ca3e24bSdrh     if( onError==OE_None ) continue;
4199cfcf5d4Sdrh     if( overrideError!=OE_Default ){
4209cfcf5d4Sdrh       onError = overrideError;
4211c92853dSdrh     }else if( onError==OE_Default ){
4220d65dc0eSdrh       onError = pParse->db->onError;
4230d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
4249cfcf5d4Sdrh     }
4259cfcf5d4Sdrh     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
4269cfcf5d4Sdrh       onError = OE_Abort;
4279cfcf5d4Sdrh     }
428ef6764a1Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
429ef6764a1Sdrh     addr = sqliteVdbeAddOp(v, OP_NotNull, 0, 0);
4309cfcf5d4Sdrh     switch( onError ){
4311c92853dSdrh       case OE_Rollback:
4321c92853dSdrh       case OE_Abort:
4331c92853dSdrh       case OE_Fail: {
4341c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
4359cfcf5d4Sdrh         break;
4369cfcf5d4Sdrh       }
4379cfcf5d4Sdrh       case OE_Ignore: {
438b419a926Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
4390ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
4409cfcf5d4Sdrh         break;
4419cfcf5d4Sdrh       }
4429cfcf5d4Sdrh       case OE_Replace: {
4439cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
4449cfcf5d4Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
4459cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
4469cfcf5d4Sdrh         break;
4479cfcf5d4Sdrh       }
4480ca3e24bSdrh       default: assert(0);
4499cfcf5d4Sdrh     }
450ef6764a1Sdrh     sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
4519cfcf5d4Sdrh   }
4529cfcf5d4Sdrh 
4539cfcf5d4Sdrh   /* Test all CHECK constraints
4549cfcf5d4Sdrh   */
4559cfcf5d4Sdrh 
4569cfcf5d4Sdrh   /* Test all UNIQUE constraints.  Add index records as we go.
4579cfcf5d4Sdrh   */
4580d65dc0eSdrh   if( (recnoChng || !isUpdate) && pTab->iPKey>=0 ){
4590ca3e24bSdrh     onError = pTab->keyConf;
4600ca3e24bSdrh     if( overrideError!=OE_Default ){
4610ca3e24bSdrh       onError = overrideError;
4621c92853dSdrh     }else if( onError==OE_Default ){
4630d65dc0eSdrh       onError = pParse->db->onError;
4640d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
4650ca3e24bSdrh     }
4660d65dc0eSdrh     if( onError!=OE_Replace ){
4670d65dc0eSdrh       sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
4680d65dc0eSdrh       jumpInst = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
4690ca3e24bSdrh       switch( onError ){
4701c92853dSdrh         case OE_Rollback:
4711c92853dSdrh         case OE_Abort:
4721c92853dSdrh         case OE_Fail: {
4731c92853dSdrh           sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
4740ca3e24bSdrh           break;
4750ca3e24bSdrh         }
4760ca3e24bSdrh         case OE_Ignore: {
477b419a926Sdrh           sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
4780ca3e24bSdrh           sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
4790ca3e24bSdrh           break;
4800ca3e24bSdrh         }
4810ca3e24bSdrh         default: assert(0);
4820ca3e24bSdrh       }
4830ca3e24bSdrh       contAddr = sqliteVdbeCurrentAddr(v);
4840ca3e24bSdrh       sqliteVdbeChangeP2(v, jumpInst, contAddr);
4850ca3e24bSdrh       if( isUpdate ){
4860ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
4870ca3e24bSdrh         sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
4880ca3e24bSdrh       }
4890ca3e24bSdrh     }
4900d65dc0eSdrh   }
4919cfcf5d4Sdrh   extra = 0;
4929cfcf5d4Sdrh   for(extra=(-1), iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
4939cfcf5d4Sdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;
4949cfcf5d4Sdrh     extra++;
4959cfcf5d4Sdrh     sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
4969cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
4979cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
4989cfcf5d4Sdrh       if( idx==pTab->iPKey ){
4990ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
5009cfcf5d4Sdrh       }else{
5010ca3e24bSdrh         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
5029cfcf5d4Sdrh       }
5039cfcf5d4Sdrh     }
5049cfcf5d4Sdrh     sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
5059cfcf5d4Sdrh     onError = pIdx->onError;
5069cfcf5d4Sdrh     if( onError==OE_None ) continue;
5079cfcf5d4Sdrh     if( overrideError!=OE_Default ){
5089cfcf5d4Sdrh       onError = overrideError;
5091c92853dSdrh     }else if( onError==OE_Default ){
5100d65dc0eSdrh       onError = pParse->db->onError;
5110d65dc0eSdrh       if( onError==OE_Default ) onError = OE_Abort;
5129cfcf5d4Sdrh     }
513b419a926Sdrh     sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
5140ca3e24bSdrh     jumpInst = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
5159cfcf5d4Sdrh     switch( onError ){
5161c92853dSdrh       case OE_Rollback:
5171c92853dSdrh       case OE_Abort:
5181c92853dSdrh       case OE_Fail: {
5191c92853dSdrh         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
5209cfcf5d4Sdrh         break;
5219cfcf5d4Sdrh       }
5229cfcf5d4Sdrh       case OE_Ignore: {
5230ca3e24bSdrh         assert( seenReplace==0 );
524fe1a1773Sdrh         sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
5259cfcf5d4Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
5269cfcf5d4Sdrh         break;
5279cfcf5d4Sdrh       }
5289cfcf5d4Sdrh       case OE_Replace: {
529*c8d30ac1Sdrh         sqliteGenerateRowDelete(v, pTab, base, 0);
5309cfcf5d4Sdrh         if( isUpdate ){
531b419a926Sdrh           sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
5320ca3e24bSdrh           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
5339cfcf5d4Sdrh         }
5340ca3e24bSdrh         seenReplace = 1;
5359cfcf5d4Sdrh         break;
5369cfcf5d4Sdrh       }
5370ca3e24bSdrh       default: assert(0);
5389cfcf5d4Sdrh     }
5399cfcf5d4Sdrh     contAddr = sqliteVdbeCurrentAddr(v);
5409cfcf5d4Sdrh     sqliteVdbeChangeP2(v, jumpInst, contAddr);
5419cfcf5d4Sdrh   }
5429cfcf5d4Sdrh }
5430ca3e24bSdrh 
5440ca3e24bSdrh /*
5450ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
5460ca3e24bSdrh ** that was started by a prior call to sqliteGenerateConstraintChecks.
5470ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
5480ca3e24bSdrh ** and the recno for the new entry.  This routine creates the new
5490ca3e24bSdrh ** entries in all indices and in the main table.
5500ca3e24bSdrh **
551b419a926Sdrh ** The arguments to this routine should be the same as the first six
5520ca3e24bSdrh ** arguments to sqliteGenerateConstraintChecks.
5530ca3e24bSdrh */
5540ca3e24bSdrh void sqliteCompleteInsertion(
5550ca3e24bSdrh   Parse *pParse,      /* The parser context */
5560ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
5570ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
5580ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
559b419a926Sdrh   int recnoChng,      /* True if the record number will change */
560b419a926Sdrh   int isUpdate        /* True for UPDATE, False for INSERT */
5610ca3e24bSdrh ){
5620ca3e24bSdrh   int i;
5630ca3e24bSdrh   Vdbe *v;
5640ca3e24bSdrh   int nIdx;
5650ca3e24bSdrh   Index *pIdx;
5660ca3e24bSdrh 
5670ca3e24bSdrh   v = sqliteGetVdbe(pParse);
5680ca3e24bSdrh   assert( v!=0 );
569417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
5700ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
5710ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
5720ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
5730ca3e24bSdrh     sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
5740ca3e24bSdrh   }
5750ca3e24bSdrh   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
576*c8d30ac1Sdrh   sqliteVdbeAddOp(v, OP_PutIntKey, base, 1);
577b419a926Sdrh   if( isUpdate && recnoChng ){
5780ca3e24bSdrh     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
5790ca3e24bSdrh   }
5800ca3e24bSdrh }
581