xref: /titanic_53/usr/src/lib/libsqlite/src/insert.c (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
1*c5c4113dSnw141292 
2*c5c4113dSnw141292 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3*c5c4113dSnw141292 
4*c5c4113dSnw141292 /*
5*c5c4113dSnw141292 ** 2001 September 15
6*c5c4113dSnw141292 **
7*c5c4113dSnw141292 ** The author disclaims copyright to this source code.  In place of
8*c5c4113dSnw141292 ** a legal notice, here is a blessing:
9*c5c4113dSnw141292 **
10*c5c4113dSnw141292 **    May you do good and not evil.
11*c5c4113dSnw141292 **    May you find forgiveness for yourself and forgive others.
12*c5c4113dSnw141292 **    May you share freely, never taking more than you give.
13*c5c4113dSnw141292 **
14*c5c4113dSnw141292 *************************************************************************
15*c5c4113dSnw141292 ** This file contains C code routines that are called by the parser
16*c5c4113dSnw141292 ** to handle INSERT statements in SQLite.
17*c5c4113dSnw141292 **
18*c5c4113dSnw141292 ** $Id: insert.c,v 1.94 2004/02/24 01:05:33 drh Exp $
19*c5c4113dSnw141292 */
20*c5c4113dSnw141292 #include "sqliteInt.h"
21*c5c4113dSnw141292 
22*c5c4113dSnw141292 /*
23*c5c4113dSnw141292 ** This routine is call to handle SQL of the following forms:
24*c5c4113dSnw141292 **
25*c5c4113dSnw141292 **    insert into TABLE (IDLIST) values(EXPRLIST)
26*c5c4113dSnw141292 **    insert into TABLE (IDLIST) select
27*c5c4113dSnw141292 **
28*c5c4113dSnw141292 ** The IDLIST following the table name is always optional.  If omitted,
29*c5c4113dSnw141292 ** then a list of all columns for the table is substituted.  The IDLIST
30*c5c4113dSnw141292 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
31*c5c4113dSnw141292 **
32*c5c4113dSnw141292 ** The pList parameter holds EXPRLIST in the first form of the INSERT
33*c5c4113dSnw141292 ** statement above, and pSelect is NULL.  For the second form, pList is
34*c5c4113dSnw141292 ** NULL and pSelect is a pointer to the select statement used to generate
35*c5c4113dSnw141292 ** data for the insert.
36*c5c4113dSnw141292 **
37*c5c4113dSnw141292 ** The code generated follows one of three templates.  For a simple
38*c5c4113dSnw141292 ** select with data coming from a VALUES clause, the code executes
39*c5c4113dSnw141292 ** once straight down through.  The template looks like this:
40*c5c4113dSnw141292 **
41*c5c4113dSnw141292 **         open write cursor to <table> and its indices
42*c5c4113dSnw141292 **         puts VALUES clause expressions onto the stack
43*c5c4113dSnw141292 **         write the resulting record into <table>
44*c5c4113dSnw141292 **         cleanup
45*c5c4113dSnw141292 **
46*c5c4113dSnw141292 ** If the statement is of the form
47*c5c4113dSnw141292 **
48*c5c4113dSnw141292 **   INSERT INTO <table> SELECT ...
49*c5c4113dSnw141292 **
50*c5c4113dSnw141292 ** And the SELECT clause does not read from <table> at any time, then
51*c5c4113dSnw141292 ** the generated code follows this template:
52*c5c4113dSnw141292 **
53*c5c4113dSnw141292 **         goto B
54*c5c4113dSnw141292 **      A: setup for the SELECT
55*c5c4113dSnw141292 **         loop over the tables in the SELECT
56*c5c4113dSnw141292 **           gosub C
57*c5c4113dSnw141292 **         end loop
58*c5c4113dSnw141292 **         cleanup after the SELECT
59*c5c4113dSnw141292 **         goto D
60*c5c4113dSnw141292 **      B: open write cursor to <table> and its indices
61*c5c4113dSnw141292 **         goto A
62*c5c4113dSnw141292 **      C: insert the select result into <table>
63*c5c4113dSnw141292 **         return
64*c5c4113dSnw141292 **      D: cleanup
65*c5c4113dSnw141292 **
66*c5c4113dSnw141292 ** The third template is used if the insert statement takes its
67*c5c4113dSnw141292 ** values from a SELECT but the data is being inserted into a table
68*c5c4113dSnw141292 ** that is also read as part of the SELECT.  In the third form,
69*c5c4113dSnw141292 ** we have to use a intermediate table to store the results of
70*c5c4113dSnw141292 ** the select.  The template is like this:
71*c5c4113dSnw141292 **
72*c5c4113dSnw141292 **         goto B
73*c5c4113dSnw141292 **      A: setup for the SELECT
74*c5c4113dSnw141292 **         loop over the tables in the SELECT
75*c5c4113dSnw141292 **           gosub C
76*c5c4113dSnw141292 **         end loop
77*c5c4113dSnw141292 **         cleanup after the SELECT
78*c5c4113dSnw141292 **         goto D
79*c5c4113dSnw141292 **      C: insert the select result into the intermediate table
80*c5c4113dSnw141292 **         return
81*c5c4113dSnw141292 **      B: open a cursor to an intermediate table
82*c5c4113dSnw141292 **         goto A
83*c5c4113dSnw141292 **      D: open write cursor to <table> and its indices
84*c5c4113dSnw141292 **         loop over the intermediate table
85*c5c4113dSnw141292 **           transfer values form intermediate table into <table>
86*c5c4113dSnw141292 **         end the loop
87*c5c4113dSnw141292 **         cleanup
88*c5c4113dSnw141292 */
sqliteInsert(Parse * pParse,SrcList * pTabList,ExprList * pList,Select * pSelect,IdList * pColumn,int onError)89*c5c4113dSnw141292 void sqliteInsert(
90*c5c4113dSnw141292   Parse *pParse,        /* Parser context */
91*c5c4113dSnw141292   SrcList *pTabList,    /* Name of table into which we are inserting */
92*c5c4113dSnw141292   ExprList *pList,      /* List of values to be inserted */
93*c5c4113dSnw141292   Select *pSelect,      /* A SELECT statement to use as the data source */
94*c5c4113dSnw141292   IdList *pColumn,      /* Column names corresponding to IDLIST. */
95*c5c4113dSnw141292   int onError           /* How to handle constraint errors */
96*c5c4113dSnw141292 ){
97*c5c4113dSnw141292   Table *pTab;          /* The table to insert into */
98*c5c4113dSnw141292   char *zTab;           /* Name of the table into which we are inserting */
99*c5c4113dSnw141292   const char *zDb;      /* Name of the database holding this table */
100*c5c4113dSnw141292   int i, j, idx;        /* Loop counters */
101*c5c4113dSnw141292   Vdbe *v;              /* Generate code into this virtual machine */
102*c5c4113dSnw141292   Index *pIdx;          /* For looping over indices of the table */
103*c5c4113dSnw141292   int nColumn;          /* Number of columns in the data */
104*c5c4113dSnw141292   int base;             /* VDBE Cursor number for pTab */
105*c5c4113dSnw141292   int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
106*c5c4113dSnw141292   sqlite *db;           /* The main database structure */
107*c5c4113dSnw141292   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
108*c5c4113dSnw141292   int endOfLoop;        /* Label for the end of the insertion loop */
109*c5c4113dSnw141292   int useTempTable;     /* Store SELECT results in intermediate table */
110*c5c4113dSnw141292   int srcTab;           /* Data comes from this temporary cursor if >=0 */
111*c5c4113dSnw141292   int iSelectLoop;      /* Address of code that implements the SELECT */
112*c5c4113dSnw141292   int iCleanup;         /* Address of the cleanup code */
113*c5c4113dSnw141292   int iInsertBlock;     /* Address of the subroutine used to insert data */
114*c5c4113dSnw141292   int iCntMem;          /* Memory cell used for the row counter */
115*c5c4113dSnw141292   int isView;           /* True if attempting to insert into a view */
116*c5c4113dSnw141292 
117*c5c4113dSnw141292   int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
118*c5c4113dSnw141292   int before_triggers;        /* True if there are BEFORE triggers */
119*c5c4113dSnw141292   int after_triggers;         /* True if there are AFTER triggers */
120*c5c4113dSnw141292   int newIdx = -1;            /* Cursor for the NEW table */
121*c5c4113dSnw141292 
122*c5c4113dSnw141292   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
123*c5c4113dSnw141292   db = pParse->db;
124*c5c4113dSnw141292 
125*c5c4113dSnw141292   /* Locate the table into which we will be inserting new information.
126*c5c4113dSnw141292   */
127*c5c4113dSnw141292   assert( pTabList->nSrc==1 );
128*c5c4113dSnw141292   zTab = pTabList->a[0].zName;
129*c5c4113dSnw141292   if( zTab==0 ) goto insert_cleanup;
130*c5c4113dSnw141292   pTab = sqliteSrcListLookup(pParse, pTabList);
131*c5c4113dSnw141292   if( pTab==0 ){
132*c5c4113dSnw141292     goto insert_cleanup;
133*c5c4113dSnw141292   }
134*c5c4113dSnw141292   assert( pTab->iDb<db->nDb );
135*c5c4113dSnw141292   zDb = db->aDb[pTab->iDb].zName;
136*c5c4113dSnw141292   if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
137*c5c4113dSnw141292     goto insert_cleanup;
138*c5c4113dSnw141292   }
139*c5c4113dSnw141292 
140*c5c4113dSnw141292   /* Ensure that:
141*c5c4113dSnw141292   *  (a) the table is not read-only,
142*c5c4113dSnw141292   *  (b) that if it is a view then ON INSERT triggers exist
143*c5c4113dSnw141292   */
144*c5c4113dSnw141292   before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
145*c5c4113dSnw141292                                        TK_BEFORE, TK_ROW, 0);
146*c5c4113dSnw141292   after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
147*c5c4113dSnw141292                                        TK_AFTER, TK_ROW, 0);
148*c5c4113dSnw141292   row_triggers_exist = before_triggers || after_triggers;
149*c5c4113dSnw141292   isView = pTab->pSelect!=0;
150*c5c4113dSnw141292   if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
151*c5c4113dSnw141292     goto insert_cleanup;
152*c5c4113dSnw141292   }
153*c5c4113dSnw141292   if( pTab==0 ) goto insert_cleanup;
154*c5c4113dSnw141292 
155*c5c4113dSnw141292   /* If pTab is really a view, make sure it has been initialized.
156*c5c4113dSnw141292   */
157*c5c4113dSnw141292   if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
158*c5c4113dSnw141292     goto insert_cleanup;
159*c5c4113dSnw141292   }
160*c5c4113dSnw141292 
161*c5c4113dSnw141292   /* Allocate a VDBE
162*c5c4113dSnw141292   */
163*c5c4113dSnw141292   v = sqliteGetVdbe(pParse);
164*c5c4113dSnw141292   if( v==0 ) goto insert_cleanup;
165*c5c4113dSnw141292   sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist, pTab->iDb);
166*c5c4113dSnw141292 
167*c5c4113dSnw141292   /* if there are row triggers, allocate a temp table for new.* references. */
168*c5c4113dSnw141292   if( row_triggers_exist ){
169*c5c4113dSnw141292     newIdx = pParse->nTab++;
170*c5c4113dSnw141292   }
171*c5c4113dSnw141292 
172*c5c4113dSnw141292   /* Figure out how many columns of data are supplied.  If the data
173*c5c4113dSnw141292   ** is coming from a SELECT statement, then this step also generates
174*c5c4113dSnw141292   ** all the code to implement the SELECT statement and invoke a subroutine
175*c5c4113dSnw141292   ** to process each row of the result. (Template 2.) If the SELECT
176*c5c4113dSnw141292   ** statement uses the the table that is being inserted into, then the
177*c5c4113dSnw141292   ** subroutine is also coded here.  That subroutine stores the SELECT
178*c5c4113dSnw141292   ** results in a temporary table. (Template 3.)
179*c5c4113dSnw141292   */
180*c5c4113dSnw141292   if( pSelect ){
181*c5c4113dSnw141292     /* Data is coming from a SELECT.  Generate code to implement that SELECT
182*c5c4113dSnw141292     */
183*c5c4113dSnw141292     int rc, iInitCode;
184*c5c4113dSnw141292     iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
185*c5c4113dSnw141292     iSelectLoop = sqliteVdbeCurrentAddr(v);
186*c5c4113dSnw141292     iInsertBlock = sqliteVdbeMakeLabel(v);
187*c5c4113dSnw141292     rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
188*c5c4113dSnw141292     if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
189*c5c4113dSnw141292     iCleanup = sqliteVdbeMakeLabel(v);
190*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
191*c5c4113dSnw141292     assert( pSelect->pEList );
192*c5c4113dSnw141292     nColumn = pSelect->pEList->nExpr;
193*c5c4113dSnw141292 
194*c5c4113dSnw141292     /* Set useTempTable to TRUE if the result of the SELECT statement
195*c5c4113dSnw141292     ** should be written into a temporary table.  Set to FALSE if each
196*c5c4113dSnw141292     ** row of the SELECT can be written directly into the result table.
197*c5c4113dSnw141292     **
198*c5c4113dSnw141292     ** A temp table must be used if the table being updated is also one
199*c5c4113dSnw141292     ** of the tables being read by the SELECT statement.  Also use a
200*c5c4113dSnw141292     ** temp table in the case of row triggers.
201*c5c4113dSnw141292     */
202*c5c4113dSnw141292     if( row_triggers_exist ){
203*c5c4113dSnw141292       useTempTable = 1;
204*c5c4113dSnw141292     }else{
205*c5c4113dSnw141292       int addr = sqliteVdbeFindOp(v, OP_OpenRead, pTab->tnum);
206*c5c4113dSnw141292       useTempTable = 0;
207*c5c4113dSnw141292       if( addr>0 ){
208*c5c4113dSnw141292         VdbeOp *pOp = sqliteVdbeGetOp(v, addr-2);
209*c5c4113dSnw141292         if( pOp->opcode==OP_Integer && pOp->p1==pTab->iDb ){
210*c5c4113dSnw141292           useTempTable = 1;
211*c5c4113dSnw141292         }
212*c5c4113dSnw141292       }
213*c5c4113dSnw141292     }
214*c5c4113dSnw141292 
215*c5c4113dSnw141292     if( useTempTable ){
216*c5c4113dSnw141292       /* Generate the subroutine that SELECT calls to process each row of
217*c5c4113dSnw141292       ** the result.  Store the result in a temporary table
218*c5c4113dSnw141292       */
219*c5c4113dSnw141292       srcTab = pParse->nTab++;
220*c5c4113dSnw141292       sqliteVdbeResolveLabel(v, iInsertBlock);
221*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
222*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
223*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
224*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
225*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Return, 0, 0);
226*c5c4113dSnw141292 
227*c5c4113dSnw141292       /* The following code runs first because the GOTO at the very top
228*c5c4113dSnw141292       ** of the program jumps to it.  Create the temporary table, then jump
229*c5c4113dSnw141292       ** back up and execute the SELECT code above.
230*c5c4113dSnw141292       */
231*c5c4113dSnw141292       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
232*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
233*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
234*c5c4113dSnw141292       sqliteVdbeResolveLabel(v, iCleanup);
235*c5c4113dSnw141292     }else{
236*c5c4113dSnw141292       sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
237*c5c4113dSnw141292     }
238*c5c4113dSnw141292   }else{
239*c5c4113dSnw141292     /* This is the case if the data for the INSERT is coming from a VALUES
240*c5c4113dSnw141292     ** clause
241*c5c4113dSnw141292     */
242*c5c4113dSnw141292     SrcList dummy;
243*c5c4113dSnw141292     assert( pList!=0 );
244*c5c4113dSnw141292     srcTab = -1;
245*c5c4113dSnw141292     useTempTable = 0;
246*c5c4113dSnw141292     assert( pList );
247*c5c4113dSnw141292     nColumn = pList->nExpr;
248*c5c4113dSnw141292     dummy.nSrc = 0;
249*c5c4113dSnw141292     for(i=0; i<nColumn; i++){
250*c5c4113dSnw141292       if( sqliteExprResolveIds(pParse, &dummy, 0, pList->a[i].pExpr) ){
251*c5c4113dSnw141292         goto insert_cleanup;
252*c5c4113dSnw141292       }
253*c5c4113dSnw141292       if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
254*c5c4113dSnw141292         goto insert_cleanup;
255*c5c4113dSnw141292       }
256*c5c4113dSnw141292     }
257*c5c4113dSnw141292   }
258*c5c4113dSnw141292 
259*c5c4113dSnw141292   /* Make sure the number of columns in the source data matches the number
260*c5c4113dSnw141292   ** of columns to be inserted into the table.
261*c5c4113dSnw141292   */
262*c5c4113dSnw141292   if( pColumn==0 && nColumn!=pTab->nCol ){
263*c5c4113dSnw141292     sqliteErrorMsg(pParse,
264*c5c4113dSnw141292        "table %S has %d columns but %d values were supplied",
265*c5c4113dSnw141292        pTabList, 0, pTab->nCol, nColumn);
266*c5c4113dSnw141292     goto insert_cleanup;
267*c5c4113dSnw141292   }
268*c5c4113dSnw141292   if( pColumn!=0 && nColumn!=pColumn->nId ){
269*c5c4113dSnw141292     sqliteErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
270*c5c4113dSnw141292     goto insert_cleanup;
271*c5c4113dSnw141292   }
272*c5c4113dSnw141292 
273*c5c4113dSnw141292   /* If the INSERT statement included an IDLIST term, then make sure
274*c5c4113dSnw141292   ** all elements of the IDLIST really are columns of the table and
275*c5c4113dSnw141292   ** remember the column indices.
276*c5c4113dSnw141292   **
277*c5c4113dSnw141292   ** If the table has an INTEGER PRIMARY KEY column and that column
278*c5c4113dSnw141292   ** is named in the IDLIST, then record in the keyColumn variable
279*c5c4113dSnw141292   ** the index into IDLIST of the primary key column.  keyColumn is
280*c5c4113dSnw141292   ** the index of the primary key as it appears in IDLIST, not as
281*c5c4113dSnw141292   ** is appears in the original table.  (The index of the primary
282*c5c4113dSnw141292   ** key in the original table is pTab->iPKey.)
283*c5c4113dSnw141292   */
284*c5c4113dSnw141292   if( pColumn ){
285*c5c4113dSnw141292     for(i=0; i<pColumn->nId; i++){
286*c5c4113dSnw141292       pColumn->a[i].idx = -1;
287*c5c4113dSnw141292     }
288*c5c4113dSnw141292     for(i=0; i<pColumn->nId; i++){
289*c5c4113dSnw141292       for(j=0; j<pTab->nCol; j++){
290*c5c4113dSnw141292         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
291*c5c4113dSnw141292           pColumn->a[i].idx = j;
292*c5c4113dSnw141292           if( j==pTab->iPKey ){
293*c5c4113dSnw141292             keyColumn = i;
294*c5c4113dSnw141292           }
295*c5c4113dSnw141292           break;
296*c5c4113dSnw141292         }
297*c5c4113dSnw141292       }
298*c5c4113dSnw141292       if( j>=pTab->nCol ){
299*c5c4113dSnw141292         if( sqliteIsRowid(pColumn->a[i].zName) ){
300*c5c4113dSnw141292           keyColumn = i;
301*c5c4113dSnw141292         }else{
302*c5c4113dSnw141292           sqliteErrorMsg(pParse, "table %S has no column named %s",
303*c5c4113dSnw141292               pTabList, 0, pColumn->a[i].zName);
304*c5c4113dSnw141292           pParse->nErr++;
305*c5c4113dSnw141292           goto insert_cleanup;
306*c5c4113dSnw141292         }
307*c5c4113dSnw141292       }
308*c5c4113dSnw141292     }
309*c5c4113dSnw141292   }
310*c5c4113dSnw141292 
311*c5c4113dSnw141292   /* If there is no IDLIST term but the table has an integer primary
312*c5c4113dSnw141292   ** key, the set the keyColumn variable to the primary key column index
313*c5c4113dSnw141292   ** in the original table definition.
314*c5c4113dSnw141292   */
315*c5c4113dSnw141292   if( pColumn==0 ){
316*c5c4113dSnw141292     keyColumn = pTab->iPKey;
317*c5c4113dSnw141292   }
318*c5c4113dSnw141292 
319*c5c4113dSnw141292   /* Open the temp table for FOR EACH ROW triggers
320*c5c4113dSnw141292   */
321*c5c4113dSnw141292   if( row_triggers_exist ){
322*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
323*c5c4113dSnw141292   }
324*c5c4113dSnw141292 
325*c5c4113dSnw141292   /* Initialize the count of rows to be inserted
326*c5c4113dSnw141292   */
327*c5c4113dSnw141292   if( db->flags & SQLITE_CountRows ){
328*c5c4113dSnw141292     iCntMem = pParse->nMem++;
329*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Integer, 0, 0);
330*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
331*c5c4113dSnw141292   }
332*c5c4113dSnw141292 
333*c5c4113dSnw141292   /* Open tables and indices if there are no row triggers */
334*c5c4113dSnw141292   if( !row_triggers_exist ){
335*c5c4113dSnw141292     base = pParse->nTab;
336*c5c4113dSnw141292     idx = sqliteOpenTableAndIndices(pParse, pTab, base);
337*c5c4113dSnw141292     pParse->nTab += idx;
338*c5c4113dSnw141292   }
339*c5c4113dSnw141292 
340*c5c4113dSnw141292   /* If the data source is a temporary table, then we have to create
341*c5c4113dSnw141292   ** a loop because there might be multiple rows of data.  If the data
342*c5c4113dSnw141292   ** source is a subroutine call from the SELECT statement, then we need
343*c5c4113dSnw141292   ** to launch the SELECT statement processing.
344*c5c4113dSnw141292   */
345*c5c4113dSnw141292   if( useTempTable ){
346*c5c4113dSnw141292     iBreak = sqliteVdbeMakeLabel(v);
347*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
348*c5c4113dSnw141292     iCont = sqliteVdbeCurrentAddr(v);
349*c5c4113dSnw141292   }else if( pSelect ){
350*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
351*c5c4113dSnw141292     sqliteVdbeResolveLabel(v, iInsertBlock);
352*c5c4113dSnw141292   }
353*c5c4113dSnw141292 
354*c5c4113dSnw141292   /* Run the BEFORE and INSTEAD OF triggers, if there are any
355*c5c4113dSnw141292   */
356*c5c4113dSnw141292   endOfLoop = sqliteVdbeMakeLabel(v);
357*c5c4113dSnw141292   if( before_triggers ){
358*c5c4113dSnw141292 
359*c5c4113dSnw141292     /* build the NEW.* reference row.  Note that if there is an INTEGER
360*c5c4113dSnw141292     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
361*c5c4113dSnw141292     ** translated into a unique ID for the row.  But on a BEFORE trigger,
362*c5c4113dSnw141292     ** we do not know what the unique ID will be (because the insert has
363*c5c4113dSnw141292     ** not happened yet) so we substitute a rowid of -1
364*c5c4113dSnw141292     */
365*c5c4113dSnw141292     if( keyColumn<0 ){
366*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Integer, -1, 0);
367*c5c4113dSnw141292     }else if( useTempTable ){
368*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
369*c5c4113dSnw141292     }else if( pSelect ){
370*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
371*c5c4113dSnw141292     }else{
372*c5c4113dSnw141292       sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
373*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
374*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
375*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Integer, -1, 0);
376*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
377*c5c4113dSnw141292     }
378*c5c4113dSnw141292 
379*c5c4113dSnw141292     /* Create the new column data
380*c5c4113dSnw141292     */
381*c5c4113dSnw141292     for(i=0; i<pTab->nCol; i++){
382*c5c4113dSnw141292       if( pColumn==0 ){
383*c5c4113dSnw141292         j = i;
384*c5c4113dSnw141292       }else{
385*c5c4113dSnw141292         for(j=0; j<pColumn->nId; j++){
386*c5c4113dSnw141292           if( pColumn->a[j].idx==i ) break;
387*c5c4113dSnw141292         }
388*c5c4113dSnw141292       }
389*c5c4113dSnw141292       if( pColumn && j>=pColumn->nId ){
390*c5c4113dSnw141292         sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
391*c5c4113dSnw141292       }else if( useTempTable ){
392*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
393*c5c4113dSnw141292       }else if( pSelect ){
394*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
395*c5c4113dSnw141292       }else{
396*c5c4113dSnw141292         sqliteExprCode(pParse, pList->a[j].pExpr);
397*c5c4113dSnw141292       }
398*c5c4113dSnw141292     }
399*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
400*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
401*c5c4113dSnw141292 
402*c5c4113dSnw141292     /* Fire BEFORE or INSTEAD OF triggers */
403*c5c4113dSnw141292     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab,
404*c5c4113dSnw141292         newIdx, -1, onError, endOfLoop) ){
405*c5c4113dSnw141292       goto insert_cleanup;
406*c5c4113dSnw141292     }
407*c5c4113dSnw141292   }
408*c5c4113dSnw141292 
409*c5c4113dSnw141292   /* If any triggers exists, the opening of tables and indices is deferred
410*c5c4113dSnw141292   ** until now.
411*c5c4113dSnw141292   */
412*c5c4113dSnw141292   if( row_triggers_exist && !isView ){
413*c5c4113dSnw141292     base = pParse->nTab;
414*c5c4113dSnw141292     idx = sqliteOpenTableAndIndices(pParse, pTab, base);
415*c5c4113dSnw141292     pParse->nTab += idx;
416*c5c4113dSnw141292   }
417*c5c4113dSnw141292 
418*c5c4113dSnw141292   /* Push the record number for the new entry onto the stack.  The
419*c5c4113dSnw141292   ** record number is a randomly generate integer created by NewRecno
420*c5c4113dSnw141292   ** except when the table has an INTEGER PRIMARY KEY column, in which
421*c5c4113dSnw141292   ** case the record number is the same as that column.
422*c5c4113dSnw141292   */
423*c5c4113dSnw141292   if( !isView ){
424*c5c4113dSnw141292     if( keyColumn>=0 ){
425*c5c4113dSnw141292       if( useTempTable ){
426*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
427*c5c4113dSnw141292       }else if( pSelect ){
428*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
429*c5c4113dSnw141292       }else{
430*c5c4113dSnw141292         sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
431*c5c4113dSnw141292       }
432*c5c4113dSnw141292       /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
433*c5c4113dSnw141292       ** to generate a unique primary key value.
434*c5c4113dSnw141292       */
435*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
436*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
437*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
438*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
439*c5c4113dSnw141292     }else{
440*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
441*c5c4113dSnw141292     }
442*c5c4113dSnw141292 
443*c5c4113dSnw141292     /* Push onto the stack, data for all columns of the new entry, beginning
444*c5c4113dSnw141292     ** with the first column.
445*c5c4113dSnw141292     */
446*c5c4113dSnw141292     for(i=0; i<pTab->nCol; i++){
447*c5c4113dSnw141292       if( i==pTab->iPKey ){
448*c5c4113dSnw141292         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
449*c5c4113dSnw141292         ** Whenever this column is read, the record number will be substituted
450*c5c4113dSnw141292         ** in its place.  So will fill this column with a NULL to avoid
451*c5c4113dSnw141292         ** taking up data space with information that will never be used. */
452*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_String, 0, 0);
453*c5c4113dSnw141292         continue;
454*c5c4113dSnw141292       }
455*c5c4113dSnw141292       if( pColumn==0 ){
456*c5c4113dSnw141292         j = i;
457*c5c4113dSnw141292       }else{
458*c5c4113dSnw141292         for(j=0; j<pColumn->nId; j++){
459*c5c4113dSnw141292           if( pColumn->a[j].idx==i ) break;
460*c5c4113dSnw141292         }
461*c5c4113dSnw141292       }
462*c5c4113dSnw141292       if( pColumn && j>=pColumn->nId ){
463*c5c4113dSnw141292         sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
464*c5c4113dSnw141292       }else if( useTempTable ){
465*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Column, srcTab, j);
466*c5c4113dSnw141292       }else if( pSelect ){
467*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
468*c5c4113dSnw141292       }else{
469*c5c4113dSnw141292         sqliteExprCode(pParse, pList->a[j].pExpr);
470*c5c4113dSnw141292       }
471*c5c4113dSnw141292     }
472*c5c4113dSnw141292 
473*c5c4113dSnw141292     /* Generate code to check constraints and generate index keys and
474*c5c4113dSnw141292     ** do the insertion.
475*c5c4113dSnw141292     */
476*c5c4113dSnw141292     sqliteGenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
477*c5c4113dSnw141292                                    0, onError, endOfLoop);
478*c5c4113dSnw141292     sqliteCompleteInsertion(pParse, pTab, base, 0,0,0,
479*c5c4113dSnw141292                             after_triggers ? newIdx : -1);
480*c5c4113dSnw141292   }
481*c5c4113dSnw141292 
482*c5c4113dSnw141292   /* Update the count of rows that are inserted
483*c5c4113dSnw141292   */
484*c5c4113dSnw141292   if( (db->flags & SQLITE_CountRows)!=0 ){
485*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
486*c5c4113dSnw141292   }
487*c5c4113dSnw141292 
488*c5c4113dSnw141292   if( row_triggers_exist ){
489*c5c4113dSnw141292     /* Close all tables opened */
490*c5c4113dSnw141292     if( !isView ){
491*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Close, base, 0);
492*c5c4113dSnw141292       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
493*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
494*c5c4113dSnw141292       }
495*c5c4113dSnw141292     }
496*c5c4113dSnw141292 
497*c5c4113dSnw141292     /* Code AFTER triggers */
498*c5c4113dSnw141292     if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
499*c5c4113dSnw141292           onError, endOfLoop) ){
500*c5c4113dSnw141292       goto insert_cleanup;
501*c5c4113dSnw141292     }
502*c5c4113dSnw141292   }
503*c5c4113dSnw141292 
504*c5c4113dSnw141292   /* The bottom of the loop, if the data source is a SELECT statement
505*c5c4113dSnw141292   */
506*c5c4113dSnw141292   sqliteVdbeResolveLabel(v, endOfLoop);
507*c5c4113dSnw141292   if( useTempTable ){
508*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
509*c5c4113dSnw141292     sqliteVdbeResolveLabel(v, iBreak);
510*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
511*c5c4113dSnw141292   }else if( pSelect ){
512*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
513*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Return, 0, 0);
514*c5c4113dSnw141292     sqliteVdbeResolveLabel(v, iCleanup);
515*c5c4113dSnw141292   }
516*c5c4113dSnw141292 
517*c5c4113dSnw141292   if( !row_triggers_exist ){
518*c5c4113dSnw141292     /* Close all tables opened */
519*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Close, base, 0);
520*c5c4113dSnw141292     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
521*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
522*c5c4113dSnw141292     }
523*c5c4113dSnw141292   }
524*c5c4113dSnw141292 
525*c5c4113dSnw141292   sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
526*c5c4113dSnw141292   sqliteEndWriteOperation(pParse);
527*c5c4113dSnw141292 
528*c5c4113dSnw141292   /*
529*c5c4113dSnw141292   ** Return the number of rows inserted.
530*c5c4113dSnw141292   */
531*c5c4113dSnw141292   if( db->flags & SQLITE_CountRows ){
532*c5c4113dSnw141292     sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows inserted", P3_STATIC);
533*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
534*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
535*c5c4113dSnw141292   }
536*c5c4113dSnw141292 
537*c5c4113dSnw141292 insert_cleanup:
538*c5c4113dSnw141292   sqliteSrcListDelete(pTabList);
539*c5c4113dSnw141292   if( pList ) sqliteExprListDelete(pList);
540*c5c4113dSnw141292   if( pSelect ) sqliteSelectDelete(pSelect);
541*c5c4113dSnw141292   sqliteIdListDelete(pColumn);
542*c5c4113dSnw141292 }
543*c5c4113dSnw141292 
544*c5c4113dSnw141292 /*
545*c5c4113dSnw141292 ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
546*c5c4113dSnw141292 **
547*c5c4113dSnw141292 ** When this routine is called, the stack contains (from bottom to top)
548*c5c4113dSnw141292 ** the following values:
549*c5c4113dSnw141292 **
550*c5c4113dSnw141292 **    1.  The recno of the row to be updated before the update.  This
551*c5c4113dSnw141292 **        value is omitted unless we are doing an UPDATE that involves a
552*c5c4113dSnw141292 **        change to the record number.
553*c5c4113dSnw141292 **
554*c5c4113dSnw141292 **    2.  The recno of the row after the update.
555*c5c4113dSnw141292 **
556*c5c4113dSnw141292 **    3.  The data in the first column of the entry after the update.
557*c5c4113dSnw141292 **
558*c5c4113dSnw141292 **    i.  Data from middle columns...
559*c5c4113dSnw141292 **
560*c5c4113dSnw141292 **    N.  The data in the last column of the entry after the update.
561*c5c4113dSnw141292 **
562*c5c4113dSnw141292 ** The old recno shown as entry (1) above is omitted unless both isUpdate
563*c5c4113dSnw141292 ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
564*c5c4113dSnw141292 ** INSERTs and recnoChng is true if the record number is being changed.
565*c5c4113dSnw141292 **
566*c5c4113dSnw141292 ** The code generated by this routine pushes additional entries onto
567*c5c4113dSnw141292 ** the stack which are the keys for new index entries for the new record.
568*c5c4113dSnw141292 ** The order of index keys is the same as the order of the indices on
569*c5c4113dSnw141292 ** the pTable->pIndex list.  A key is only created for index i if
570*c5c4113dSnw141292 ** aIdxUsed!=0 and aIdxUsed[i]!=0.
571*c5c4113dSnw141292 **
572*c5c4113dSnw141292 ** This routine also generates code to check constraints.  NOT NULL,
573*c5c4113dSnw141292 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
574*c5c4113dSnw141292 ** then the appropriate action is performed.  There are five possible
575*c5c4113dSnw141292 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
576*c5c4113dSnw141292 **
577*c5c4113dSnw141292 **  Constraint type  Action       What Happens
578*c5c4113dSnw141292 **  ---------------  ----------   ----------------------------------------
579*c5c4113dSnw141292 **  any              ROLLBACK     The current transaction is rolled back and
580*c5c4113dSnw141292 **                                sqlite_exec() returns immediately with a
581*c5c4113dSnw141292 **                                return code of SQLITE_CONSTRAINT.
582*c5c4113dSnw141292 **
583*c5c4113dSnw141292 **  any              ABORT        Back out changes from the current command
584*c5c4113dSnw141292 **                                only (do not do a complete rollback) then
585*c5c4113dSnw141292 **                                cause sqlite_exec() to return immediately
586*c5c4113dSnw141292 **                                with SQLITE_CONSTRAINT.
587*c5c4113dSnw141292 **
588*c5c4113dSnw141292 **  any              FAIL         Sqlite_exec() returns immediately with a
589*c5c4113dSnw141292 **                                return code of SQLITE_CONSTRAINT.  The
590*c5c4113dSnw141292 **                                transaction is not rolled back and any
591*c5c4113dSnw141292 **                                prior changes are retained.
592*c5c4113dSnw141292 **
593*c5c4113dSnw141292 **  any              IGNORE       The record number and data is popped from
594*c5c4113dSnw141292 **                                the stack and there is an immediate jump
595*c5c4113dSnw141292 **                                to label ignoreDest.
596*c5c4113dSnw141292 **
597*c5c4113dSnw141292 **  NOT NULL         REPLACE      The NULL value is replace by the default
598*c5c4113dSnw141292 **                                value for that column.  If the default value
599*c5c4113dSnw141292 **                                is NULL, the action is the same as ABORT.
600*c5c4113dSnw141292 **
601*c5c4113dSnw141292 **  UNIQUE           REPLACE      The other row that conflicts with the row
602*c5c4113dSnw141292 **                                being inserted is removed.
603*c5c4113dSnw141292 **
604*c5c4113dSnw141292 **  CHECK            REPLACE      Illegal.  The results in an exception.
605*c5c4113dSnw141292 **
606*c5c4113dSnw141292 ** Which action to take is determined by the overrideError parameter.
607*c5c4113dSnw141292 ** Or if overrideError==OE_Default, then the pParse->onError parameter
608*c5c4113dSnw141292 ** is used.  Or if pParse->onError==OE_Default then the onError value
609*c5c4113dSnw141292 ** for the constraint is used.
610*c5c4113dSnw141292 **
611*c5c4113dSnw141292 ** The calling routine must open a read/write cursor for pTab with
612*c5c4113dSnw141292 ** cursor number "base".  All indices of pTab must also have open
613*c5c4113dSnw141292 ** read/write cursors with cursor number base+i for the i-th cursor.
614*c5c4113dSnw141292 ** Except, if there is no possibility of a REPLACE action then
615*c5c4113dSnw141292 ** cursors do not need to be open for indices where aIdxUsed[i]==0.
616*c5c4113dSnw141292 **
617*c5c4113dSnw141292 ** If the isUpdate flag is true, it means that the "base" cursor is
618*c5c4113dSnw141292 ** initially pointing to an entry that is being updated.  The isUpdate
619*c5c4113dSnw141292 ** flag causes extra code to be generated so that the "base" cursor
620*c5c4113dSnw141292 ** is still pointing at the same entry after the routine returns.
621*c5c4113dSnw141292 ** Without the isUpdate flag, the "base" cursor might be moved.
622*c5c4113dSnw141292 */
sqliteGenerateConstraintChecks(Parse * pParse,Table * pTab,int base,char * aIdxUsed,int recnoChng,int isUpdate,int overrideError,int ignoreDest)623*c5c4113dSnw141292 void sqliteGenerateConstraintChecks(
624*c5c4113dSnw141292   Parse *pParse,      /* The parser context */
625*c5c4113dSnw141292   Table *pTab,        /* the table into which we are inserting */
626*c5c4113dSnw141292   int base,           /* Index of a read/write cursor pointing at pTab */
627*c5c4113dSnw141292   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
628*c5c4113dSnw141292   int recnoChng,      /* True if the record number will change */
629*c5c4113dSnw141292   int isUpdate,       /* True for UPDATE, False for INSERT */
630*c5c4113dSnw141292   int overrideError,  /* Override onError to this if not OE_Default */
631*c5c4113dSnw141292   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
632*c5c4113dSnw141292 ){
633*c5c4113dSnw141292   int i;
634*c5c4113dSnw141292   Vdbe *v;
635*c5c4113dSnw141292   int nCol;
636*c5c4113dSnw141292   int onError;
637*c5c4113dSnw141292   int addr;
638*c5c4113dSnw141292   int extra;
639*c5c4113dSnw141292   int iCur;
640*c5c4113dSnw141292   Index *pIdx;
641*c5c4113dSnw141292   int seenReplace = 0;
642*c5c4113dSnw141292   int jumpInst1, jumpInst2;
643*c5c4113dSnw141292   int contAddr;
644*c5c4113dSnw141292   int hasTwoRecnos = (isUpdate && recnoChng);
645*c5c4113dSnw141292 
646*c5c4113dSnw141292   v = sqliteGetVdbe(pParse);
647*c5c4113dSnw141292   assert( v!=0 );
648*c5c4113dSnw141292   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
649*c5c4113dSnw141292   nCol = pTab->nCol;
650*c5c4113dSnw141292 
651*c5c4113dSnw141292   /* Test all NOT NULL constraints.
652*c5c4113dSnw141292   */
653*c5c4113dSnw141292   for(i=0; i<nCol; i++){
654*c5c4113dSnw141292     if( i==pTab->iPKey ){
655*c5c4113dSnw141292       continue;
656*c5c4113dSnw141292     }
657*c5c4113dSnw141292     onError = pTab->aCol[i].notNull;
658*c5c4113dSnw141292     if( onError==OE_None ) continue;
659*c5c4113dSnw141292     if( overrideError!=OE_Default ){
660*c5c4113dSnw141292       onError = overrideError;
661*c5c4113dSnw141292     }else if( pParse->db->onError!=OE_Default ){
662*c5c4113dSnw141292       onError = pParse->db->onError;
663*c5c4113dSnw141292     }else if( onError==OE_Default ){
664*c5c4113dSnw141292       onError = OE_Abort;
665*c5c4113dSnw141292     }
666*c5c4113dSnw141292     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
667*c5c4113dSnw141292       onError = OE_Abort;
668*c5c4113dSnw141292     }
669*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
670*c5c4113dSnw141292     addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
671*c5c4113dSnw141292     switch( onError ){
672*c5c4113dSnw141292       case OE_Rollback:
673*c5c4113dSnw141292       case OE_Abort:
674*c5c4113dSnw141292       case OE_Fail: {
675*c5c4113dSnw141292         char *zMsg = 0;
676*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
677*c5c4113dSnw141292         sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
678*c5c4113dSnw141292                         " may not be NULL", (char*)0);
679*c5c4113dSnw141292         sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
680*c5c4113dSnw141292         break;
681*c5c4113dSnw141292       }
682*c5c4113dSnw141292       case OE_Ignore: {
683*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
684*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
685*c5c4113dSnw141292         break;
686*c5c4113dSnw141292       }
687*c5c4113dSnw141292       case OE_Replace: {
688*c5c4113dSnw141292         sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
689*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
690*c5c4113dSnw141292         break;
691*c5c4113dSnw141292       }
692*c5c4113dSnw141292       default: assert(0);
693*c5c4113dSnw141292     }
694*c5c4113dSnw141292     sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
695*c5c4113dSnw141292   }
696*c5c4113dSnw141292 
697*c5c4113dSnw141292   /* Test all CHECK constraints
698*c5c4113dSnw141292   */
699*c5c4113dSnw141292   /**** TBD ****/
700*c5c4113dSnw141292 
701*c5c4113dSnw141292   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
702*c5c4113dSnw141292   ** of the new record does not previously exist.  Except, if this
703*c5c4113dSnw141292   ** is an UPDATE and the primary key is not changing, that is OK.
704*c5c4113dSnw141292   */
705*c5c4113dSnw141292   if( recnoChng ){
706*c5c4113dSnw141292     onError = pTab->keyConf;
707*c5c4113dSnw141292     if( overrideError!=OE_Default ){
708*c5c4113dSnw141292       onError = overrideError;
709*c5c4113dSnw141292     }else if( pParse->db->onError!=OE_Default ){
710*c5c4113dSnw141292       onError = pParse->db->onError;
711*c5c4113dSnw141292     }else if( onError==OE_Default ){
712*c5c4113dSnw141292       onError = OE_Abort;
713*c5c4113dSnw141292     }
714*c5c4113dSnw141292 
715*c5c4113dSnw141292     if( isUpdate ){
716*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
717*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
718*c5c4113dSnw141292       jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
719*c5c4113dSnw141292     }
720*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
721*c5c4113dSnw141292     jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
722*c5c4113dSnw141292     switch( onError ){
723*c5c4113dSnw141292       default: {
724*c5c4113dSnw141292         onError = OE_Abort;
725*c5c4113dSnw141292         /* Fall thru into the next case */
726*c5c4113dSnw141292       }
727*c5c4113dSnw141292       case OE_Rollback:
728*c5c4113dSnw141292       case OE_Abort:
729*c5c4113dSnw141292       case OE_Fail: {
730*c5c4113dSnw141292         sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
731*c5c4113dSnw141292                          "PRIMARY KEY must be unique", P3_STATIC);
732*c5c4113dSnw141292         break;
733*c5c4113dSnw141292       }
734*c5c4113dSnw141292       case OE_Replace: {
735*c5c4113dSnw141292         sqliteGenerateRowIndexDelete(pParse->db, v, pTab, base, 0);
736*c5c4113dSnw141292         if( isUpdate ){
737*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_Dup, nCol+hasTwoRecnos, 1);
738*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
739*c5c4113dSnw141292         }
740*c5c4113dSnw141292         seenReplace = 1;
741*c5c4113dSnw141292         break;
742*c5c4113dSnw141292       }
743*c5c4113dSnw141292       case OE_Ignore: {
744*c5c4113dSnw141292         assert( seenReplace==0 );
745*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
746*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
747*c5c4113dSnw141292         break;
748*c5c4113dSnw141292       }
749*c5c4113dSnw141292     }
750*c5c4113dSnw141292     contAddr = sqliteVdbeCurrentAddr(v);
751*c5c4113dSnw141292     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
752*c5c4113dSnw141292     if( isUpdate ){
753*c5c4113dSnw141292       sqliteVdbeChangeP2(v, jumpInst1, contAddr);
754*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
755*c5c4113dSnw141292       sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
756*c5c4113dSnw141292     }
757*c5c4113dSnw141292   }
758*c5c4113dSnw141292 
759*c5c4113dSnw141292   /* Test all UNIQUE constraints by creating entries for each UNIQUE
760*c5c4113dSnw141292   ** index and making sure that duplicate entries do not already exist.
761*c5c4113dSnw141292   ** Add the new records to the indices as we go.
762*c5c4113dSnw141292   */
763*c5c4113dSnw141292   extra = -1;
764*c5c4113dSnw141292   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
765*c5c4113dSnw141292     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
766*c5c4113dSnw141292     extra++;
767*c5c4113dSnw141292 
768*c5c4113dSnw141292     /* Create a key for accessing the index entry */
769*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
770*c5c4113dSnw141292     for(i=0; i<pIdx->nColumn; i++){
771*c5c4113dSnw141292       int idx = pIdx->aiColumn[i];
772*c5c4113dSnw141292       if( idx==pTab->iPKey ){
773*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
774*c5c4113dSnw141292       }else{
775*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
776*c5c4113dSnw141292       }
777*c5c4113dSnw141292     }
778*c5c4113dSnw141292     jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
779*c5c4113dSnw141292     if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
780*c5c4113dSnw141292 
781*c5c4113dSnw141292     /* Find out what action to take in case there is an indexing conflict */
782*c5c4113dSnw141292     onError = pIdx->onError;
783*c5c4113dSnw141292     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
784*c5c4113dSnw141292     if( overrideError!=OE_Default ){
785*c5c4113dSnw141292       onError = overrideError;
786*c5c4113dSnw141292     }else if( pParse->db->onError!=OE_Default ){
787*c5c4113dSnw141292       onError = pParse->db->onError;
788*c5c4113dSnw141292     }else if( onError==OE_Default ){
789*c5c4113dSnw141292       onError = OE_Abort;
790*c5c4113dSnw141292     }
791*c5c4113dSnw141292     if( seenReplace ){
792*c5c4113dSnw141292       if( onError==OE_Ignore ) onError = OE_Replace;
793*c5c4113dSnw141292       else if( onError==OE_Fail ) onError = OE_Abort;
794*c5c4113dSnw141292     }
795*c5c4113dSnw141292 
796*c5c4113dSnw141292 
797*c5c4113dSnw141292     /* Check to see if the new index entry will be unique */
798*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
799*c5c4113dSnw141292     jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
800*c5c4113dSnw141292 
801*c5c4113dSnw141292     /* Generate code that executes if the new index entry is not unique */
802*c5c4113dSnw141292     switch( onError ){
803*c5c4113dSnw141292       case OE_Rollback:
804*c5c4113dSnw141292       case OE_Abort:
805*c5c4113dSnw141292       case OE_Fail: {
806*c5c4113dSnw141292         int j, n1, n2;
807*c5c4113dSnw141292         char zErrMsg[200];
808*c5c4113dSnw141292         strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
809*c5c4113dSnw141292         n1 = strlen(zErrMsg);
810*c5c4113dSnw141292         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
811*c5c4113dSnw141292           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
812*c5c4113dSnw141292           n2 = strlen(zCol);
813*c5c4113dSnw141292           if( j>0 ){
814*c5c4113dSnw141292             strcpy(&zErrMsg[n1], ", ");
815*c5c4113dSnw141292             n1 += 2;
816*c5c4113dSnw141292           }
817*c5c4113dSnw141292           if( n1+n2>sizeof(zErrMsg)-30 ){
818*c5c4113dSnw141292             strcpy(&zErrMsg[n1], "...");
819*c5c4113dSnw141292             n1 += 3;
820*c5c4113dSnw141292             break;
821*c5c4113dSnw141292           }else{
822*c5c4113dSnw141292             strcpy(&zErrMsg[n1], zCol);
823*c5c4113dSnw141292             n1 += n2;
824*c5c4113dSnw141292           }
825*c5c4113dSnw141292         }
826*c5c4113dSnw141292         strcpy(&zErrMsg[n1],
827*c5c4113dSnw141292             pIdx->nColumn>1 ? " are not unique" : " is not unique");
828*c5c4113dSnw141292         sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
829*c5c4113dSnw141292         break;
830*c5c4113dSnw141292       }
831*c5c4113dSnw141292       case OE_Ignore: {
832*c5c4113dSnw141292         assert( seenReplace==0 );
833*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
834*c5c4113dSnw141292         sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
835*c5c4113dSnw141292         break;
836*c5c4113dSnw141292       }
837*c5c4113dSnw141292       case OE_Replace: {
838*c5c4113dSnw141292         sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
839*c5c4113dSnw141292         if( isUpdate ){
840*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
841*c5c4113dSnw141292           sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
842*c5c4113dSnw141292         }
843*c5c4113dSnw141292         seenReplace = 1;
844*c5c4113dSnw141292         break;
845*c5c4113dSnw141292       }
846*c5c4113dSnw141292       default: assert(0);
847*c5c4113dSnw141292     }
848*c5c4113dSnw141292     contAddr = sqliteVdbeCurrentAddr(v);
849*c5c4113dSnw141292 #if NULL_DISTINCT_FOR_UNIQUE
850*c5c4113dSnw141292     sqliteVdbeChangeP2(v, jumpInst1, contAddr);
851*c5c4113dSnw141292 #endif
852*c5c4113dSnw141292     sqliteVdbeChangeP2(v, jumpInst2, contAddr);
853*c5c4113dSnw141292   }
854*c5c4113dSnw141292 }
855*c5c4113dSnw141292 
856*c5c4113dSnw141292 /*
857*c5c4113dSnw141292 ** This routine generates code to finish the INSERT or UPDATE operation
858*c5c4113dSnw141292 ** that was started by a prior call to sqliteGenerateConstraintChecks.
859*c5c4113dSnw141292 ** The stack must contain keys for all active indices followed by data
860*c5c4113dSnw141292 ** and the recno for the new entry.  This routine creates the new
861*c5c4113dSnw141292 ** entries in all indices and in the main table.
862*c5c4113dSnw141292 **
863*c5c4113dSnw141292 ** The arguments to this routine should be the same as the first six
864*c5c4113dSnw141292 ** arguments to sqliteGenerateConstraintChecks.
865*c5c4113dSnw141292 */
sqliteCompleteInsertion(Parse * pParse,Table * pTab,int base,char * aIdxUsed,int recnoChng,int isUpdate,int newIdx)866*c5c4113dSnw141292 void sqliteCompleteInsertion(
867*c5c4113dSnw141292   Parse *pParse,      /* The parser context */
868*c5c4113dSnw141292   Table *pTab,        /* the table into which we are inserting */
869*c5c4113dSnw141292   int base,           /* Index of a read/write cursor pointing at pTab */
870*c5c4113dSnw141292   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
871*c5c4113dSnw141292   int recnoChng,      /* True if the record number will change */
872*c5c4113dSnw141292   int isUpdate,       /* True for UPDATE, False for INSERT */
873*c5c4113dSnw141292   int newIdx          /* Index of NEW table for triggers.  -1 if none */
874*c5c4113dSnw141292 ){
875*c5c4113dSnw141292   int i;
876*c5c4113dSnw141292   Vdbe *v;
877*c5c4113dSnw141292   int nIdx;
878*c5c4113dSnw141292   Index *pIdx;
879*c5c4113dSnw141292 
880*c5c4113dSnw141292   v = sqliteGetVdbe(pParse);
881*c5c4113dSnw141292   assert( v!=0 );
882*c5c4113dSnw141292   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
883*c5c4113dSnw141292   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
884*c5c4113dSnw141292   for(i=nIdx-1; i>=0; i--){
885*c5c4113dSnw141292     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
886*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
887*c5c4113dSnw141292   }
888*c5c4113dSnw141292   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
889*c5c4113dSnw141292   if( newIdx>=0 ){
890*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Dup, 1, 0);
891*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Dup, 1, 0);
892*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
893*c5c4113dSnw141292   }
894*c5c4113dSnw141292   sqliteVdbeAddOp(v, OP_PutIntKey, base,
895*c5c4113dSnw141292     (pParse->trigStack?0:OPFLAG_NCHANGE) |
896*c5c4113dSnw141292     (isUpdate?0:OPFLAG_LASTROWID) | OPFLAG_CSCHANGE);
897*c5c4113dSnw141292   if( isUpdate && recnoChng ){
898*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Pop, 1, 0);
899*c5c4113dSnw141292   }
900*c5c4113dSnw141292 }
901*c5c4113dSnw141292 
902*c5c4113dSnw141292 /*
903*c5c4113dSnw141292 ** Generate code that will open write cursors for a table and for all
904*c5c4113dSnw141292 ** indices of that table.  The "base" parameter is the cursor number used
905*c5c4113dSnw141292 ** for the table.  Indices are opened on subsequent cursors.
906*c5c4113dSnw141292 **
907*c5c4113dSnw141292 ** Return the total number of cursors opened.  This is always at least
908*c5c4113dSnw141292 ** 1 (for the main table) plus more for each cursor.
909*c5c4113dSnw141292 */
sqliteOpenTableAndIndices(Parse * pParse,Table * pTab,int base)910*c5c4113dSnw141292 int sqliteOpenTableAndIndices(Parse *pParse, Table *pTab, int base){
911*c5c4113dSnw141292   int i;
912*c5c4113dSnw141292   Index *pIdx;
913*c5c4113dSnw141292   Vdbe *v = sqliteGetVdbe(pParse);
914*c5c4113dSnw141292   assert( v!=0 );
915*c5c4113dSnw141292   sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
916*c5c4113dSnw141292   sqliteVdbeOp3(v, OP_OpenWrite, base, pTab->tnum, pTab->zName, P3_STATIC);
917*c5c4113dSnw141292   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
918*c5c4113dSnw141292     sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
919*c5c4113dSnw141292     sqliteVdbeOp3(v, OP_OpenWrite, i+base, pIdx->tnum, pIdx->zName, P3_STATIC);
920*c5c4113dSnw141292   }
921*c5c4113dSnw141292   return i;
922*c5c4113dSnw141292 }
923