xref: /sqlite-3.40.0/src/insert.c (revision 7cf6e4de)
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*7cf6e4deSdrh ** $Id: insert.c,v 1.103 2004/05/19 14:56:56 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
203d1bfeaaSdanielk1977 ** Set P3 of the most recently inserted opcode to a column affinity
21a37cdde0Sdanielk1977 ** string for index pIdx. A column affinity string has one character
223d1bfeaaSdanielk1977 ** for each column in the table, according to the affinity of the column:
233d1bfeaaSdanielk1977 **
243d1bfeaaSdanielk1977 **  Character      Column affinity
253d1bfeaaSdanielk1977 **  ------------------------------
263d1bfeaaSdanielk1977 **  'n'            NUMERIC
273d1bfeaaSdanielk1977 **  'i'            INTEGER
283d1bfeaaSdanielk1977 **  't'            TEXT
293d1bfeaaSdanielk1977 **  'o'            NONE
303d1bfeaaSdanielk1977 */
31a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
32a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
33e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
34a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
35e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
36a37cdde0Sdanielk1977     **
37a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
38e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
39a37cdde0Sdanielk1977     ** up.
40a37cdde0Sdanielk1977     */
41a37cdde0Sdanielk1977     int n;
42a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
43a37cdde0Sdanielk1977     pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
44a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
45a37cdde0Sdanielk1977       return;
46a37cdde0Sdanielk1977     }
47a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
48a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
49a37cdde0Sdanielk1977     }
50a37cdde0Sdanielk1977     pIdx->zColAff[pIdx->nColumn] = '\0';
51a37cdde0Sdanielk1977   }
523d1bfeaaSdanielk1977 
53a37cdde0Sdanielk1977   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, P3_STATIC);
54a37cdde0Sdanielk1977 }
55a37cdde0Sdanielk1977 
56a37cdde0Sdanielk1977 /*
57a37cdde0Sdanielk1977 ** Set P3 of the most recently inserted opcode to a column affinity
58a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
59a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
60a37cdde0Sdanielk1977 ** column:
61a37cdde0Sdanielk1977 **
62a37cdde0Sdanielk1977 **  Character      Column affinity
63a37cdde0Sdanielk1977 **  ------------------------------
64a37cdde0Sdanielk1977 **  'n'            NUMERIC
65a37cdde0Sdanielk1977 **  'i'            INTEGER
66a37cdde0Sdanielk1977 **  't'            TEXT
67a37cdde0Sdanielk1977 **  'o'            NONE
68a37cdde0Sdanielk1977 */
69a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
703d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
713d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
723d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
733d1bfeaaSdanielk1977   **
743d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
753d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
763d1bfeaaSdanielk1977   */
773d1bfeaaSdanielk1977   if( !pTab->zColAff ){
783d1bfeaaSdanielk1977     char *zColAff;
793d1bfeaaSdanielk1977     int i;
803d1bfeaaSdanielk1977 
81a37cdde0Sdanielk1977     zColAff = (char *)sqliteMalloc(pTab->nCol+1);
823d1bfeaaSdanielk1977     if( !zColAff ){
83a37cdde0Sdanielk1977       return;
843d1bfeaaSdanielk1977     }
853d1bfeaaSdanielk1977 
863d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
87a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
883d1bfeaaSdanielk1977     }
893d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
903d1bfeaaSdanielk1977 
913d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
923d1bfeaaSdanielk1977   }
933d1bfeaaSdanielk1977 
943d1bfeaaSdanielk1977   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, P3_STATIC);
953d1bfeaaSdanielk1977 }
963d1bfeaaSdanielk1977 
973d1bfeaaSdanielk1977 
983d1bfeaaSdanielk1977 /*
991ccde15dSdrh ** This routine is call to handle SQL of the following forms:
100cce7d176Sdrh **
101cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
1021ccde15dSdrh **    insert into TABLE (IDLIST) select
103cce7d176Sdrh **
1041ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
1051ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
106967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
1071ccde15dSdrh **
1081ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
1091ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
1101ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
1111ccde15dSdrh ** data for the insert.
112142e30dfSdrh **
113142e30dfSdrh ** The code generated follows one of three templates.  For a simple
114142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
115142e30dfSdrh ** once straight down through.  The template looks like this:
116142e30dfSdrh **
117142e30dfSdrh **         open write cursor to <table> and its indices
118142e30dfSdrh **         puts VALUES clause expressions onto the stack
119142e30dfSdrh **         write the resulting record into <table>
120142e30dfSdrh **         cleanup
121142e30dfSdrh **
122142e30dfSdrh ** If the statement is of the form
123142e30dfSdrh **
124142e30dfSdrh **   INSERT INTO <table> SELECT ...
125142e30dfSdrh **
126142e30dfSdrh ** And the SELECT clause does not read from <table> at any time, then
127142e30dfSdrh ** the generated code follows this template:
128142e30dfSdrh **
129142e30dfSdrh **         goto B
130142e30dfSdrh **      A: setup for the SELECT
131142e30dfSdrh **         loop over the tables in the SELECT
132142e30dfSdrh **           gosub C
133142e30dfSdrh **         end loop
134142e30dfSdrh **         cleanup after the SELECT
135142e30dfSdrh **         goto D
136142e30dfSdrh **      B: open write cursor to <table> and its indices
137142e30dfSdrh **         goto A
138142e30dfSdrh **      C: insert the select result into <table>
139142e30dfSdrh **         return
140142e30dfSdrh **      D: cleanup
141142e30dfSdrh **
142142e30dfSdrh ** The third template is used if the insert statement takes its
143142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
144142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
145142e30dfSdrh ** we have to use a intermediate table to store the results of
146142e30dfSdrh ** the select.  The template is like this:
147142e30dfSdrh **
148142e30dfSdrh **         goto B
149142e30dfSdrh **      A: setup for the SELECT
150142e30dfSdrh **         loop over the tables in the SELECT
151142e30dfSdrh **           gosub C
152142e30dfSdrh **         end loop
153142e30dfSdrh **         cleanup after the SELECT
154142e30dfSdrh **         goto D
155142e30dfSdrh **      C: insert the select result into the intermediate table
156142e30dfSdrh **         return
157142e30dfSdrh **      B: open a cursor to an intermediate table
158142e30dfSdrh **         goto A
159142e30dfSdrh **      D: open write cursor to <table> and its indices
160142e30dfSdrh **         loop over the intermediate table
161142e30dfSdrh **           transfer values form intermediate table into <table>
162142e30dfSdrh **         end the loop
163142e30dfSdrh **         cleanup
164cce7d176Sdrh */
1654adee20fSdanielk1977 void sqlite3Insert(
166cce7d176Sdrh   Parse *pParse,        /* Parser context */
167113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
168cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
1695974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
1709cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
1719cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
172cce7d176Sdrh ){
1735974a30fSdrh   Table *pTab;          /* The table to insert into */
174113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
175e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
1765974a30fSdrh   int i, j, idx;        /* Loop counters */
1775974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
1785974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
179967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
1806a3ea0e6Sdrh   int base;             /* VDBE Cursor number for pTab */
1815974a30fSdrh   int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
182ecdc7530Sdrh   sqlite *db;           /* The main database structure */
1834a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
1840ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
185142e30dfSdrh   int useTempTable;     /* Store SELECT results in intermediate table */
186142e30dfSdrh   int srcTab;           /* Data comes from this temporary cursor if >=0 */
187142e30dfSdrh   int iSelectLoop;      /* Address of code that implements the SELECT */
188142e30dfSdrh   int iCleanup;         /* Address of the cleanup code */
189142e30dfSdrh   int iInsertBlock;     /* Address of the subroutine used to insert data */
190142e30dfSdrh   int iCntMem;          /* Memory cell used for the row counter */
1915cf590c1Sdrh   int isView;           /* True if attempting to insert into a view */
192cce7d176Sdrh 
193c3f9bad2Sdanielk1977   int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
19470ce3f0cSdrh   int before_triggers;        /* True if there are BEFORE triggers */
19570ce3f0cSdrh   int after_triggers;         /* True if there are AFTER triggers */
19670ce3f0cSdrh   int newIdx = -1;            /* Cursor for the NEW table */
197c3f9bad2Sdanielk1977 
19824b03fd0Sdanielk1977   if( pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
199ecdc7530Sdrh   db = pParse->db;
200daffd0e5Sdrh 
2011ccde15dSdrh   /* Locate the table into which we will be inserting new information.
2021ccde15dSdrh   */
203113088ecSdrh   assert( pTabList->nSrc==1 );
204113088ecSdrh   zTab = pTabList->a[0].zName;
205daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
2064adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
207c3f9bad2Sdanielk1977   if( pTab==0 ){
208c3f9bad2Sdanielk1977     goto insert_cleanup;
209c3f9bad2Sdanielk1977   }
210e22a334bSdrh   assert( pTab->iDb<db->nDb );
211e22a334bSdrh   zDb = db->aDb[pTab->iDb].zName;
2124adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
2131962bda7Sdrh     goto insert_cleanup;
2141962bda7Sdrh   }
215c3f9bad2Sdanielk1977 
216c3f9bad2Sdanielk1977   /* Ensure that:
217c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
218c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
219c3f9bad2Sdanielk1977   */
2204adee20fSdanielk1977   before_triggers = sqlite3TriggersExist(pParse, pTab->pTrigger, TK_INSERT,
22170ce3f0cSdrh                                        TK_BEFORE, TK_ROW, 0);
2224adee20fSdanielk1977   after_triggers = sqlite3TriggersExist(pParse, pTab->pTrigger, TK_INSERT,
22370ce3f0cSdrh                                        TK_AFTER, TK_ROW, 0);
22470ce3f0cSdrh   row_triggers_exist = before_triggers || after_triggers;
2255cf590c1Sdrh   isView = pTab->pSelect!=0;
2264adee20fSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, before_triggers) ){
227c3f9bad2Sdanielk1977     goto insert_cleanup;
228c3f9bad2Sdanielk1977   }
229a76b5dfcSdrh   if( pTab==0 ) goto insert_cleanup;
2301ccde15dSdrh 
231f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
232f573c99bSdrh   */
2334adee20fSdanielk1977   if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){
234f573c99bSdrh     goto insert_cleanup;
235f573c99bSdrh   }
236f573c99bSdrh 
2371ccde15dSdrh   /* Allocate a VDBE
2381ccde15dSdrh   */
2394adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2405974a30fSdrh   if( v==0 ) goto insert_cleanup;
2414adee20fSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || row_triggers_exist, pTab->iDb);
2421ccde15dSdrh 
243c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
244f29ce559Sdanielk1977   if( row_triggers_exist ){
245c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
246f29ce559Sdanielk1977   }
247c3f9bad2Sdanielk1977 
2481ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
249142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
250142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
251142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
252142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
253142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
254142e30dfSdrh   ** results in a temporary table. (Template 3.)
2551ccde15dSdrh   */
2565974a30fSdrh   if( pSelect ){
257142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
258142e30dfSdrh     */
259142e30dfSdrh     int rc, iInitCode;
2604adee20fSdanielk1977     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
2614adee20fSdanielk1977     iSelectLoop = sqlite3VdbeCurrentAddr(v);
2624adee20fSdanielk1977     iInsertBlock = sqlite3VdbeMakeLabel(v);
26384ac9d02Sdanielk1977     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0,0);
26424b03fd0Sdanielk1977     if( rc || pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
2654adee20fSdanielk1977     iCleanup = sqlite3VdbeMakeLabel(v);
2664adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
2675974a30fSdrh     assert( pSelect->pEList );
268967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
269142e30dfSdrh 
270142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
271142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
272142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
273048c530cSdrh     **
274048c530cSdrh     ** A temp table must be used if the table being updated is also one
275048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
276048c530cSdrh     ** temp table in the case of row triggers.
277142e30dfSdrh     */
278048c530cSdrh     if( row_triggers_exist ){
279048c530cSdrh       useTempTable = 1;
280048c530cSdrh     }else{
28184ac9d02Sdanielk1977       int addr = sqlite3VdbeFindOp(v, 0, OP_OpenRead, pTab->tnum);
282048c530cSdrh       useTempTable = 0;
283048c530cSdrh       if( addr>0 ){
2844adee20fSdanielk1977         VdbeOp *pOp = sqlite3VdbeGetOp(v, addr-2);
285048c530cSdrh         if( pOp->opcode==OP_Integer && pOp->p1==pTab->iDb ){
286048c530cSdrh           useTempTable = 1;
287048c530cSdrh         }
288048c530cSdrh       }
289048c530cSdrh     }
290142e30dfSdrh 
291142e30dfSdrh     if( useTempTable ){
292142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
293142e30dfSdrh       ** the result.  Store the result in a temporary table
294142e30dfSdrh       */
295142e30dfSdrh       srcTab = pParse->nTab++;
2964adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iInsertBlock);
2974adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
298a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
2994adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, srcTab, 0);
3004adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
3014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutIntKey, srcTab, 0);
3024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
303142e30dfSdrh 
304142e30dfSdrh       /* The following code runs first because the GOTO at the very top
305142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
306142e30dfSdrh       ** back up and execute the SELECT code above.
307142e30dfSdrh       */
3084adee20fSdanielk1977       sqlite3VdbeChangeP2(v, iInitCode, sqlite3VdbeCurrentAddr(v));
3094adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_OpenTemp, srcTab, 0);
310b4964b72Sdanielk1977       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, pTab->nCol);
3114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
3124adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCleanup);
3135974a30fSdrh     }else{
3144adee20fSdanielk1977       sqlite3VdbeChangeP2(v, iInitCode, sqlite3VdbeCurrentAddr(v));
315142e30dfSdrh     }
316142e30dfSdrh   }else{
317142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
318142e30dfSdrh     ** clause
319142e30dfSdrh     */
320ad3cab52Sdrh     SrcList dummy;
321daffd0e5Sdrh     assert( pList!=0 );
3225974a30fSdrh     srcTab = -1;
323142e30dfSdrh     useTempTable = 0;
3245974a30fSdrh     assert( pList );
325967e8b73Sdrh     nColumn = pList->nExpr;
326ad3cab52Sdrh     dummy.nSrc = 0;
327e64e7b20Sdrh     for(i=0; i<nColumn; i++){
3284adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, &dummy, 0, pList->a[i].pExpr) ){
329e64e7b20Sdrh         goto insert_cleanup;
330e64e7b20Sdrh       }
3314adee20fSdanielk1977       if( sqlite3ExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
332b04a5d87Sdrh         goto insert_cleanup;
333b04a5d87Sdrh       }
334e64e7b20Sdrh     }
3355974a30fSdrh   }
3361ccde15dSdrh 
3371ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
3381ccde15dSdrh   ** of columns to be inserted into the table.
3391ccde15dSdrh   */
340967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
3414adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
342da93d238Sdrh        "table %S has %d columns but %d values were supplied",
343da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
344cce7d176Sdrh     goto insert_cleanup;
345cce7d176Sdrh   }
346967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
3474adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
348cce7d176Sdrh     goto insert_cleanup;
349cce7d176Sdrh   }
3501ccde15dSdrh 
3511ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
3521ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
3531ccde15dSdrh   ** remember the column indices.
354c8392586Sdrh   **
355c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
356c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
357c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
358c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
359c8392586Sdrh   ** is appears in the original table.  (The index of the primary
360c8392586Sdrh   ** key in the original table is pTab->iPKey.)
3611ccde15dSdrh   */
362967e8b73Sdrh   if( pColumn ){
363967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
364967e8b73Sdrh       pColumn->a[i].idx = -1;
365cce7d176Sdrh     }
366967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
367cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
3684adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
369967e8b73Sdrh           pColumn->a[i].idx = j;
3704a32431cSdrh           if( j==pTab->iPKey ){
3719aa028daSdrh             keyColumn = i;
3724a32431cSdrh           }
373cce7d176Sdrh           break;
374cce7d176Sdrh         }
375cce7d176Sdrh       }
376cce7d176Sdrh       if( j>=pTab->nCol ){
3774adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
378a0217ba7Sdrh           keyColumn = i;
379a0217ba7Sdrh         }else{
3804adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
381da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
382cce7d176Sdrh           pParse->nErr++;
383cce7d176Sdrh           goto insert_cleanup;
384cce7d176Sdrh         }
385cce7d176Sdrh       }
386cce7d176Sdrh     }
387a0217ba7Sdrh   }
3881ccde15dSdrh 
389aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
390c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
391c8392586Sdrh   ** in the original table definition.
3924a32431cSdrh   */
3934a32431cSdrh   if( pColumn==0 ){
3944a32431cSdrh     keyColumn = pTab->iPKey;
3954a32431cSdrh   }
3964a32431cSdrh 
397142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
398142e30dfSdrh   */
399f29ce559Sdanielk1977   if( row_triggers_exist ){
4004adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
40184ac9d02Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
402f29ce559Sdanielk1977   }
403c3f9bad2Sdanielk1977 
404c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
4051ccde15dSdrh   */
406142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
407142e30dfSdrh     iCntMem = pParse->nMem++;
4084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
4094adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iCntMem, 1);
410c3f9bad2Sdanielk1977   }
411c3f9bad2Sdanielk1977 
412c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
413c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
4145974a30fSdrh     base = pParse->nTab;
4154adee20fSdanielk1977     idx = sqlite3OpenTableAndIndices(pParse, pTab, base);
416832508b7Sdrh     pParse->nTab += idx;
417feeb1394Sdrh   }
418feeb1394Sdrh 
419142e30dfSdrh   /* If the data source is a temporary table, then we have to create
4201ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
421142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
422142e30dfSdrh   ** to launch the SELECT statement processing.
4231ccde15dSdrh   */
424142e30dfSdrh   if( useTempTable ){
4254adee20fSdanielk1977     iBreak = sqlite3VdbeMakeLabel(v);
4264adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
4274adee20fSdanielk1977     iCont = sqlite3VdbeCurrentAddr(v);
428142e30dfSdrh   }else if( pSelect ){
4294adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
4304adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iInsertBlock);
431bed8690fSdrh   }
4321ccde15dSdrh 
4335cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
43470ce3f0cSdrh   */
4354adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
43670ce3f0cSdrh   if( before_triggers ){
437c3f9bad2Sdanielk1977 
43870ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
43970ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
44070ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
44170ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
44270ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
44370ce3f0cSdrh     */
44470ce3f0cSdrh     if( keyColumn<0 ){
4454adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
44670ce3f0cSdrh     }else if( useTempTable ){
4474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
44870ce3f0cSdrh     }else if( pSelect ){
4494adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
45070ce3f0cSdrh     }else{
4514adee20fSdanielk1977       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
4524adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
4534adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
4544adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
4554adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
45670ce3f0cSdrh     }
45770ce3f0cSdrh 
45870ce3f0cSdrh     /* Create the new column data
45970ce3f0cSdrh     */
460c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
461c3f9bad2Sdanielk1977       if( pColumn==0 ){
462c3f9bad2Sdanielk1977         j = i;
463c3f9bad2Sdanielk1977       }else{
464c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
465c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
466c3f9bad2Sdanielk1977         }
467c3f9bad2Sdanielk1977       }
468c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
4694adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
470142e30dfSdrh       }else if( useTempTable ){
4714adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
472142e30dfSdrh       }else if( pSelect ){
4734adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
474c3f9bad2Sdanielk1977       }else{
4754adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr);
476c3f9bad2Sdanielk1977       }
477c3f9bad2Sdanielk1977     }
4784adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
479a37cdde0Sdanielk1977 
480a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
481a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
482a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
483a37cdde0Sdanielk1977     ** table column affinities.
484a37cdde0Sdanielk1977     */
485a37cdde0Sdanielk1977     if( !isView ){
486a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
487a37cdde0Sdanielk1977     }
4884adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutIntKey, newIdx, 0);
489c3f9bad2Sdanielk1977 
4905cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
4914adee20fSdanielk1977     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab,
492b2fe7d8cSdrh         newIdx, -1, onError, endOfLoop) ){
493f29ce559Sdanielk1977       goto insert_cleanup;
494f29ce559Sdanielk1977     }
49570ce3f0cSdrh   }
496c3f9bad2Sdanielk1977 
49770ce3f0cSdrh   /* If any triggers exists, the opening of tables and indices is deferred
49870ce3f0cSdrh   ** until now.
49970ce3f0cSdrh   */
5005cf590c1Sdrh   if( row_triggers_exist && !isView ){
501c3f9bad2Sdanielk1977     base = pParse->nTab;
5024adee20fSdanielk1977     idx = sqlite3OpenTableAndIndices(pParse, pTab, base);
503c3f9bad2Sdanielk1977     pParse->nTab += idx;
504c3f9bad2Sdanielk1977   }
505c3f9bad2Sdanielk1977 
5064a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
5074a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
5084a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
509b419a926Sdrh   ** case the record number is the same as that column.
5101ccde15dSdrh   */
5115cf590c1Sdrh   if( !isView ){
5124a32431cSdrh     if( keyColumn>=0 ){
513142e30dfSdrh       if( useTempTable ){
5144adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
515142e30dfSdrh       }else if( pSelect ){
5164adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
5174a32431cSdrh       }else{
5184adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
51927a32783Sdrh       }
520e1e68f49Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
521e1e68f49Sdrh       ** to generate a unique primary key value.
522e1e68f49Sdrh       */
5234adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
5244adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5254adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, base, 0);
5264adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
5274a32431cSdrh     }else{
5284adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, base, 0);
5294a32431cSdrh     }
5304a32431cSdrh 
531aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
5324a32431cSdrh     ** with the first column.
5334a32431cSdrh     */
534cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
5354a32431cSdrh       if( i==pTab->iPKey ){
5364a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
537aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
538aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
539aacc543eSdrh         ** taking up data space with information that will never be used. */
5404adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_String, 0, 0);
5414a32431cSdrh         continue;
5424a32431cSdrh       }
543967e8b73Sdrh       if( pColumn==0 ){
544cce7d176Sdrh         j = i;
545cce7d176Sdrh       }else{
546967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
547967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
548cce7d176Sdrh         }
549cce7d176Sdrh       }
550967e8b73Sdrh       if( pColumn && j>=pColumn->nId ){
5514adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
552142e30dfSdrh       }else if( useTempTable ){
5534adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
554142e30dfSdrh       }else if( pSelect ){
5554adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
556cce7d176Sdrh       }else{
5574adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr);
558cce7d176Sdrh       }
559cce7d176Sdrh     }
5601ccde15dSdrh 
5610ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
5620ca3e24bSdrh     ** do the insertion.
5634a32431cSdrh     */
5644adee20fSdanielk1977     sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
565a0217ba7Sdrh                                    0, onError, endOfLoop);
5664adee20fSdanielk1977     sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
56770ce3f0cSdrh                             after_triggers ? newIdx : -1);
5685cf590c1Sdrh   }
5691bee3d7bSdrh 
570feeb1394Sdrh   /* Update the count of rows that are inserted
5711bee3d7bSdrh   */
572142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
5734adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, iCntMem, 0);
5741bee3d7bSdrh   }
575c3f9bad2Sdanielk1977 
576c3f9bad2Sdanielk1977   if( row_triggers_exist ){
577c3f9bad2Sdanielk1977     /* Close all tables opened */
5785cf590c1Sdrh     if( !isView ){
5794adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, base, 0);
580c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
5814adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
582c3f9bad2Sdanielk1977       }
583c3f9bad2Sdanielk1977     }
584c3f9bad2Sdanielk1977 
585c3f9bad2Sdanielk1977     /* Code AFTER triggers */
5864adee20fSdanielk1977     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
5876f34903eSdanielk1977           onError, endOfLoop) ){
588f29ce559Sdanielk1977       goto insert_cleanup;
589f29ce559Sdanielk1977     }
590c3f9bad2Sdanielk1977   }
5911bee3d7bSdrh 
5921ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
5931ccde15dSdrh   */
5944adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
595142e30dfSdrh   if( useTempTable ){
5964adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
5974adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iBreak);
5984adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
599142e30dfSdrh   }else if( pSelect ){
6004adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
6014adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
6024adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iCleanup);
6036b56344dSdrh   }
604c3f9bad2Sdanielk1977 
605c3f9bad2Sdanielk1977   if( !row_triggers_exist ){
606c3f9bad2Sdanielk1977     /* Close all tables opened */
6074adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base, 0);
6086b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
6094adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
610cce7d176Sdrh     }
611c3f9bad2Sdanielk1977   }
612c3f9bad2Sdanielk1977 
6134adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SetCounts, 0, 0);
6144adee20fSdanielk1977   sqlite3EndWriteOperation(pParse);
6155e00f6c7Sdrh 
6161bee3d7bSdrh   /*
6171bee3d7bSdrh   ** Return the number of rows inserted.
6181bee3d7bSdrh   */
619142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
6204adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_ColumnName, 0, 1, "rows inserted", P3_STATIC);
6214adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
6224adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
6231bee3d7bSdrh   }
624cce7d176Sdrh 
625cce7d176Sdrh insert_cleanup:
6264adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
6274adee20fSdanielk1977   if( pList ) sqlite3ExprListDelete(pList);
6284adee20fSdanielk1977   if( pSelect ) sqlite3SelectDelete(pSelect);
6294adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
630cce7d176Sdrh }
6319cfcf5d4Sdrh 
6329cfcf5d4Sdrh /*
6339cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
6349cfcf5d4Sdrh **
6359cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
6360ca3e24bSdrh ** the following values:
6370ca3e24bSdrh **
638b2fe7d8cSdrh **    1.  The recno of the row to be updated before the update.  This
639b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
640b419a926Sdrh **        change to the record number.
6410ca3e24bSdrh **
642b419a926Sdrh **    2.  The recno of the row after the update.
6430ca3e24bSdrh **
6440ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
6450ca3e24bSdrh **
6460ca3e24bSdrh **    i.  Data from middle columns...
6470ca3e24bSdrh **
6480ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
6490ca3e24bSdrh **
650b419a926Sdrh ** The old recno shown as entry (1) above is omitted unless both isUpdate
6511c92853dSdrh ** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
6521c92853dSdrh ** INSERTs and recnoChng is true if the record number is being changed.
6530ca3e24bSdrh **
6540ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
6550ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
6560ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
6570ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
6580ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
6599cfcf5d4Sdrh **
6609cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
6619cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
6621c92853dSdrh ** then the appropriate action is performed.  There are five possible
6631c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
6649cfcf5d4Sdrh **
6659cfcf5d4Sdrh **  Constraint type  Action       What Happens
6669cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
6671c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
66824b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
6699cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
6709cfcf5d4Sdrh **
6711c92853dSdrh **  any              ABORT        Back out changes from the current command
6721c92853dSdrh **                                only (do not do a complete rollback) then
67324b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
6741c92853dSdrh **                                with SQLITE_CONSTRAINT.
6751c92853dSdrh **
6761c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
6771c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
6781c92853dSdrh **                                transaction is not rolled back and any
6791c92853dSdrh **                                prior changes are retained.
6801c92853dSdrh **
6819cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
6829cfcf5d4Sdrh **                                the stack and there is an immediate jump
6839cfcf5d4Sdrh **                                to label ignoreDest.
6849cfcf5d4Sdrh **
6859cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
6869cfcf5d4Sdrh **                                value for that column.  If the default value
6879cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
6889cfcf5d4Sdrh **
6899cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
6909cfcf5d4Sdrh **                                being inserted is removed.
6919cfcf5d4Sdrh **
6929cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
6939cfcf5d4Sdrh **
6941c92853dSdrh ** Which action to take is determined by the overrideError parameter.
6951c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
6961c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
6971c92853dSdrh ** for the constraint is used.
6989cfcf5d4Sdrh **
699aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
7009cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
7019cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
7029cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
7039cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
7049cfcf5d4Sdrh **
7059cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
7069cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
7079cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
7089cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
7099cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
7109cfcf5d4Sdrh */
7114adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
7129cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
7139cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
7149cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
7159cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
7160ca3e24bSdrh   int recnoChng,      /* True if the record number will change */
717b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
7189cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
719b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
7209cfcf5d4Sdrh ){
7219cfcf5d4Sdrh   int i;
7229cfcf5d4Sdrh   Vdbe *v;
7239cfcf5d4Sdrh   int nCol;
7249cfcf5d4Sdrh   int onError;
7259cfcf5d4Sdrh   int addr;
7269cfcf5d4Sdrh   int extra;
7270ca3e24bSdrh   int iCur;
7280ca3e24bSdrh   Index *pIdx;
7290ca3e24bSdrh   int seenReplace = 0;
730f5905aa7Sdrh   int jumpInst1, jumpInst2;
7310ca3e24bSdrh   int contAddr;
732b419a926Sdrh   int hasTwoRecnos = (isUpdate && recnoChng);
7339cfcf5d4Sdrh 
7344adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
7359cfcf5d4Sdrh   assert( v!=0 );
736417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
7379cfcf5d4Sdrh   nCol = pTab->nCol;
7389cfcf5d4Sdrh 
7399cfcf5d4Sdrh   /* Test all NOT NULL constraints.
7409cfcf5d4Sdrh   */
7419cfcf5d4Sdrh   for(i=0; i<nCol; i++){
7420ca3e24bSdrh     if( i==pTab->iPKey ){
7430ca3e24bSdrh       continue;
7440ca3e24bSdrh     }
7459cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
7460ca3e24bSdrh     if( onError==OE_None ) continue;
7479cfcf5d4Sdrh     if( overrideError!=OE_Default ){
7489cfcf5d4Sdrh       onError = overrideError;
749a996e477Sdrh     }else if( pParse->db->onError!=OE_Default ){
7500d65dc0eSdrh       onError = pParse->db->onError;
751a996e477Sdrh     }else if( onError==OE_Default ){
752a996e477Sdrh       onError = OE_Abort;
7539cfcf5d4Sdrh     }
7549cfcf5d4Sdrh     if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
7559cfcf5d4Sdrh       onError = OE_Abort;
7569cfcf5d4Sdrh     }
7574adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
7584adee20fSdanielk1977     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
7599cfcf5d4Sdrh     switch( onError ){
7601c92853dSdrh       case OE_Rollback:
7611c92853dSdrh       case OE_Abort:
7621c92853dSdrh       case OE_Fail: {
763483750baSdrh         char *zMsg = 0;
7644adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
7654adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
76641743984Sdrh                         " may not be NULL", (char*)0);
7674adee20fSdanielk1977         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
7689cfcf5d4Sdrh         break;
7699cfcf5d4Sdrh       }
7709cfcf5d4Sdrh       case OE_Ignore: {
7714adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
7724adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
7739cfcf5d4Sdrh         break;
7749cfcf5d4Sdrh       }
7759cfcf5d4Sdrh       case OE_Replace: {
7764adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
7774adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
7789cfcf5d4Sdrh         break;
7799cfcf5d4Sdrh       }
7800ca3e24bSdrh       default: assert(0);
7819cfcf5d4Sdrh     }
7824adee20fSdanielk1977     sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
7839cfcf5d4Sdrh   }
7849cfcf5d4Sdrh 
7859cfcf5d4Sdrh   /* Test all CHECK constraints
7869cfcf5d4Sdrh   */
7870bd1f4eaSdrh   /**** TBD ****/
7889cfcf5d4Sdrh 
7890bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
7900bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
7910bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
7929cfcf5d4Sdrh   */
7935383ae5cSdrh   if( recnoChng ){
7940ca3e24bSdrh     onError = pTab->keyConf;
7950ca3e24bSdrh     if( overrideError!=OE_Default ){
7960ca3e24bSdrh       onError = overrideError;
797a996e477Sdrh     }else if( pParse->db->onError!=OE_Default ){
7980d65dc0eSdrh       onError = pParse->db->onError;
799a996e477Sdrh     }else if( onError==OE_Default ){
800a996e477Sdrh       onError = OE_Abort;
8010ca3e24bSdrh     }
802a0217ba7Sdrh 
80379b0c956Sdrh     if( isUpdate ){
8044adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
8054adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
8064adee20fSdanielk1977       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
80779b0c956Sdrh     }
8084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
8094adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
8100ca3e24bSdrh     switch( onError ){
811a0217ba7Sdrh       default: {
812a0217ba7Sdrh         onError = OE_Abort;
813a0217ba7Sdrh         /* Fall thru into the next case */
814a0217ba7Sdrh       }
8151c92853dSdrh       case OE_Rollback:
8161c92853dSdrh       case OE_Abort:
8171c92853dSdrh       case OE_Fail: {
8184adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
819701a0aebSdrh                          "PRIMARY KEY must be unique", P3_STATIC);
8200ca3e24bSdrh         break;
8210ca3e24bSdrh       }
8225383ae5cSdrh       case OE_Replace: {
8234adee20fSdanielk1977         sqlite3GenerateRowIndexDelete(pParse->db, v, pTab, base, 0);
8245383ae5cSdrh         if( isUpdate ){
8254adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRecnos, 1);
826*7cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
8275383ae5cSdrh         }
8285383ae5cSdrh         seenReplace = 1;
8295383ae5cSdrh         break;
8305383ae5cSdrh       }
8310ca3e24bSdrh       case OE_Ignore: {
8325383ae5cSdrh         assert( seenReplace==0 );
8334adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
8344adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
8350ca3e24bSdrh         break;
8360ca3e24bSdrh       }
8370ca3e24bSdrh     }
8384adee20fSdanielk1977     contAddr = sqlite3VdbeCurrentAddr(v);
8394adee20fSdanielk1977     sqlite3VdbeChangeP2(v, jumpInst2, contAddr);
840f5905aa7Sdrh     if( isUpdate ){
8414adee20fSdanielk1977       sqlite3VdbeChangeP2(v, jumpInst1, contAddr);
8424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
843*7cf6e4deSdrh       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
8440ca3e24bSdrh     }
8450ca3e24bSdrh   }
8460bd1f4eaSdrh 
8470bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
8480bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
8490bd1f4eaSdrh   ** Add the new records to the indices as we go.
8500bd1f4eaSdrh   */
851b2fe7d8cSdrh   extra = -1;
852b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
853b2fe7d8cSdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
8549cfcf5d4Sdrh     extra++;
855b2fe7d8cSdrh 
856b2fe7d8cSdrh     /* Create a key for accessing the index entry */
8574adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
8589cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
8599cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
8609cfcf5d4Sdrh       if( idx==pTab->iPKey ){
8614adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
8629cfcf5d4Sdrh       }else{
8634adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
8649cfcf5d4Sdrh       }
8659cfcf5d4Sdrh     }
8664adee20fSdanielk1977     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
867a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
868b2fe7d8cSdrh 
869b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
8709cfcf5d4Sdrh     onError = pIdx->onError;
871b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
8729cfcf5d4Sdrh     if( overrideError!=OE_Default ){
8739cfcf5d4Sdrh       onError = overrideError;
874a996e477Sdrh     }else if( pParse->db->onError!=OE_Default ){
8750d65dc0eSdrh       onError = pParse->db->onError;
876a996e477Sdrh     }else if( onError==OE_Default ){
877a996e477Sdrh       onError = OE_Abort;
8789cfcf5d4Sdrh     }
8795383ae5cSdrh     if( seenReplace ){
8805383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
8815383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
8825383ae5cSdrh     }
8835383ae5cSdrh 
884b2fe7d8cSdrh 
885b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
8864adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
8874adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
888b2fe7d8cSdrh 
889b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
8909cfcf5d4Sdrh     switch( onError ){
8911c92853dSdrh       case OE_Rollback:
8921c92853dSdrh       case OE_Abort:
8931c92853dSdrh       case OE_Fail: {
89437ed48edSdrh         int j, n1, n2;
89537ed48edSdrh         char zErrMsg[200];
89637ed48edSdrh         strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
89737ed48edSdrh         n1 = strlen(zErrMsg);
89837ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
89937ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90037ed48edSdrh           n2 = strlen(zCol);
90137ed48edSdrh           if( j>0 ){
90237ed48edSdrh             strcpy(&zErrMsg[n1], ", ");
90337ed48edSdrh             n1 += 2;
90437ed48edSdrh           }
90537ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
90637ed48edSdrh             strcpy(&zErrMsg[n1], "...");
90737ed48edSdrh             n1 += 3;
90837ed48edSdrh             break;
90937ed48edSdrh           }else{
91037ed48edSdrh             strcpy(&zErrMsg[n1], zCol);
91137ed48edSdrh             n1 += n2;
91237ed48edSdrh           }
91337ed48edSdrh         }
91437ed48edSdrh         strcpy(&zErrMsg[n1],
91537ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
9164adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
9179cfcf5d4Sdrh         break;
9189cfcf5d4Sdrh       }
9199cfcf5d4Sdrh       case OE_Ignore: {
9200ca3e24bSdrh         assert( seenReplace==0 );
9214adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
9224adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
9239cfcf5d4Sdrh         break;
9249cfcf5d4Sdrh       }
9259cfcf5d4Sdrh       case OE_Replace: {
9264adee20fSdanielk1977         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
9279cfcf5d4Sdrh         if( isUpdate ){
9284adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
929*7cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
9309cfcf5d4Sdrh         }
9310ca3e24bSdrh         seenReplace = 1;
9329cfcf5d4Sdrh         break;
9339cfcf5d4Sdrh       }
9340ca3e24bSdrh       default: assert(0);
9359cfcf5d4Sdrh     }
9364adee20fSdanielk1977     contAddr = sqlite3VdbeCurrentAddr(v);
9370bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
9384adee20fSdanielk1977     sqlite3VdbeChangeP2(v, jumpInst1, contAddr);
9390bd1f4eaSdrh #endif
9404adee20fSdanielk1977     sqlite3VdbeChangeP2(v, jumpInst2, contAddr);
9419cfcf5d4Sdrh   }
9429cfcf5d4Sdrh }
9430ca3e24bSdrh 
9440ca3e24bSdrh /*
9450ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
9464adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
9470ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
9480ca3e24bSdrh ** and the recno for the new entry.  This routine creates the new
9490ca3e24bSdrh ** entries in all indices and in the main table.
9500ca3e24bSdrh **
951b419a926Sdrh ** The arguments to this routine should be the same as the first six
9524adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
9530ca3e24bSdrh */
9544adee20fSdanielk1977 void sqlite3CompleteInsertion(
9550ca3e24bSdrh   Parse *pParse,      /* The parser context */
9560ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
9570ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
9580ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
959b419a926Sdrh   int recnoChng,      /* True if the record number will change */
96070ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
96170ce3f0cSdrh   int newIdx          /* Index of NEW table for triggers.  -1 if none */
9620ca3e24bSdrh ){
9630ca3e24bSdrh   int i;
9640ca3e24bSdrh   Vdbe *v;
9650ca3e24bSdrh   int nIdx;
9660ca3e24bSdrh   Index *pIdx;
9670ca3e24bSdrh 
9684adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
9690ca3e24bSdrh   assert( v!=0 );
970417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
9710ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
9720ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
9730ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
9744adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IdxPut, base+i+1, 0);
9750ca3e24bSdrh   }
9764adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
977a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
97870ce3f0cSdrh   if( newIdx>=0 ){
9794adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
9804adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
9814adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutIntKey, newIdx, 0);
98270ce3f0cSdrh   }
9834adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_PutIntKey, base,
984b0c374ffSrdc     (pParse->trigStack?0:OPFLAG_NCHANGE) |
985b0c374ffSrdc     (isUpdate?0:OPFLAG_LASTROWID) | OPFLAG_CSCHANGE);
986b419a926Sdrh   if( isUpdate && recnoChng ){
9874adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
9880ca3e24bSdrh   }
9890ca3e24bSdrh }
990cd44690aSdrh 
991cd44690aSdrh /*
992cd44690aSdrh ** Generate code that will open write cursors for a table and for all
993cd44690aSdrh ** indices of that table.  The "base" parameter is the cursor number used
994cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
995cd44690aSdrh **
996cd44690aSdrh ** Return the total number of cursors opened.  This is always at least
997cd44690aSdrh ** 1 (for the main table) plus more for each cursor.
998cd44690aSdrh */
9994adee20fSdanielk1977 int sqlite3OpenTableAndIndices(Parse *pParse, Table *pTab, int base){
1000cd44690aSdrh   int i;
1001cd44690aSdrh   Index *pIdx;
10024adee20fSdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1003cd44690aSdrh   assert( v!=0 );
10044adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
10054adee20fSdanielk1977   sqlite3VdbeOp3(v, OP_OpenWrite, base, pTab->tnum, pTab->zName, P3_STATIC);
1006b4964b72Sdanielk1977   sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
1007cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
10084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
10094adee20fSdanielk1977     sqlite3VdbeOp3(v, OP_OpenWrite, i+base, pIdx->tnum, pIdx->zName, P3_STATIC);
1010cd44690aSdrh   }
1011cd44690aSdrh   return i;
1012cd44690aSdrh }
1013