xref: /sqlite-3.40.0/src/insert.c (revision 16ed8a64)
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*16ed8a64Sdrh ** $Id: insert.c,v 1.172 2006/08/29 18:46:14 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 **  ------------------------------
263eda040bSdrh **  'a'            TEXT
273eda040bSdrh **  'b'            NONE
283eda040bSdrh **  'c'            NUMERIC
293eda040bSdrh **  'd'            INTEGER
303eda040bSdrh **  'e'            REAL
313d1bfeaaSdanielk1977 */
32a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
33a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
34e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
35a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
36e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
37a37cdde0Sdanielk1977     **
38a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
39e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
40a37cdde0Sdanielk1977     ** up.
41a37cdde0Sdanielk1977     */
42a37cdde0Sdanielk1977     int n;
43a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
44a37cdde0Sdanielk1977     pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
45a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
46a37cdde0Sdanielk1977       return;
47a37cdde0Sdanielk1977     }
48a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
49a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
50a37cdde0Sdanielk1977     }
51a37cdde0Sdanielk1977     pIdx->zColAff[pIdx->nColumn] = '\0';
52a37cdde0Sdanielk1977   }
533d1bfeaaSdanielk1977 
54956bc92cSdrh   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
55a37cdde0Sdanielk1977 }
56a37cdde0Sdanielk1977 
57a37cdde0Sdanielk1977 /*
58a37cdde0Sdanielk1977 ** Set P3 of the most recently inserted opcode to a column affinity
59a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
60a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
61a37cdde0Sdanielk1977 ** column:
62a37cdde0Sdanielk1977 **
63a37cdde0Sdanielk1977 **  Character      Column affinity
64a37cdde0Sdanielk1977 **  ------------------------------
653eda040bSdrh **  'a'            TEXT
663eda040bSdrh **  'b'            NONE
673eda040bSdrh **  'c'            NUMERIC
683eda040bSdrh **  'd'            INTEGER
693eda040bSdrh **  'e'            REAL
70a37cdde0Sdanielk1977 */
71a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
723d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
733d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
743d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
753d1bfeaaSdanielk1977   **
763d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
773d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
783d1bfeaaSdanielk1977   */
793d1bfeaaSdanielk1977   if( !pTab->zColAff ){
803d1bfeaaSdanielk1977     char *zColAff;
813d1bfeaaSdanielk1977     int i;
823d1bfeaaSdanielk1977 
83a37cdde0Sdanielk1977     zColAff = (char *)sqliteMalloc(pTab->nCol+1);
843d1bfeaaSdanielk1977     if( !zColAff ){
85a37cdde0Sdanielk1977       return;
863d1bfeaaSdanielk1977     }
873d1bfeaaSdanielk1977 
883d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
89a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
903d1bfeaaSdanielk1977     }
913d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
923d1bfeaaSdanielk1977 
933d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
943d1bfeaaSdanielk1977   }
953d1bfeaaSdanielk1977 
96956bc92cSdrh   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
973d1bfeaaSdanielk1977 }
983d1bfeaaSdanielk1977 
994d88778bSdanielk1977 /*
1004d88778bSdanielk1977 ** Return non-zero if SELECT statement p opens the table with rootpage
1014d88778bSdanielk1977 ** iTab in database iDb.  This is used to see if a statement of the form
1024d88778bSdanielk1977 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
1034d88778bSdanielk1977 ** table for the results of the SELECT.
1044d88778bSdanielk1977 **
1054d88778bSdanielk1977 ** No checking is done for sub-selects that are part of expressions.
1064d88778bSdanielk1977 */
107e501b89aSdanielk1977 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
1084d88778bSdanielk1977   int i;
1094d88778bSdanielk1977   struct SrcList_item *pItem;
1104d88778bSdanielk1977   if( p->pSrc==0 ) return 0;
1114d88778bSdanielk1977   for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
1124d88778bSdanielk1977     if( pItem->pSelect ){
113da184236Sdanielk1977       if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
1144d88778bSdanielk1977     }else{
115da184236Sdanielk1977       if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
1164d88778bSdanielk1977     }
1174d88778bSdanielk1977   }
1184d88778bSdanielk1977   return 0;
1194d88778bSdanielk1977 }
1203d1bfeaaSdanielk1977 
1213d1bfeaaSdanielk1977 /*
1221ccde15dSdrh ** This routine is call to handle SQL of the following forms:
123cce7d176Sdrh **
124cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
1251ccde15dSdrh **    insert into TABLE (IDLIST) select
126cce7d176Sdrh **
1271ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
1281ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
129967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
1301ccde15dSdrh **
1311ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
1321ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
1331ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
1341ccde15dSdrh ** data for the insert.
135142e30dfSdrh **
136142e30dfSdrh ** The code generated follows one of three templates.  For a simple
137142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
138142e30dfSdrh ** once straight down through.  The template looks like this:
139142e30dfSdrh **
140142e30dfSdrh **         open write cursor to <table> and its indices
141142e30dfSdrh **         puts VALUES clause expressions onto the stack
142142e30dfSdrh **         write the resulting record into <table>
143142e30dfSdrh **         cleanup
144142e30dfSdrh **
145142e30dfSdrh ** If the statement is of the form
146142e30dfSdrh **
147142e30dfSdrh **   INSERT INTO <table> SELECT ...
148142e30dfSdrh **
149142e30dfSdrh ** And the SELECT clause does not read from <table> at any time, then
150142e30dfSdrh ** the generated code follows this template:
151142e30dfSdrh **
152142e30dfSdrh **         goto B
153142e30dfSdrh **      A: setup for the SELECT
154142e30dfSdrh **         loop over the tables in the SELECT
155142e30dfSdrh **           gosub C
156142e30dfSdrh **         end loop
157142e30dfSdrh **         cleanup after the SELECT
158142e30dfSdrh **         goto D
159142e30dfSdrh **      B: open write cursor to <table> and its indices
160142e30dfSdrh **         goto A
161142e30dfSdrh **      C: insert the select result into <table>
162142e30dfSdrh **         return
163142e30dfSdrh **      D: cleanup
164142e30dfSdrh **
165142e30dfSdrh ** The third template is used if the insert statement takes its
166142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
167142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
168142e30dfSdrh ** we have to use a intermediate table to store the results of
169142e30dfSdrh ** the select.  The template is like this:
170142e30dfSdrh **
171142e30dfSdrh **         goto B
172142e30dfSdrh **      A: setup for the SELECT
173142e30dfSdrh **         loop over the tables in the SELECT
174142e30dfSdrh **           gosub C
175142e30dfSdrh **         end loop
176142e30dfSdrh **         cleanup after the SELECT
177142e30dfSdrh **         goto D
178142e30dfSdrh **      C: insert the select result into the intermediate table
179142e30dfSdrh **         return
180142e30dfSdrh **      B: open a cursor to an intermediate table
181142e30dfSdrh **         goto A
182142e30dfSdrh **      D: open write cursor to <table> and its indices
183142e30dfSdrh **         loop over the intermediate table
184142e30dfSdrh **           transfer values form intermediate table into <table>
185142e30dfSdrh **         end the loop
186142e30dfSdrh **         cleanup
187cce7d176Sdrh */
1884adee20fSdanielk1977 void sqlite3Insert(
189cce7d176Sdrh   Parse *pParse,        /* Parser context */
190113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
191cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
1925974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
1939cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
1949cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
195cce7d176Sdrh ){
1965974a30fSdrh   Table *pTab;          /* The table to insert into */
197113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
198e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
1995974a30fSdrh   int i, j, idx;        /* Loop counters */
2005974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
2015974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
202967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
203cfe9a69fSdanielk1977   int base = 0;         /* VDBE Cursor number for pTab */
204cfe9a69fSdanielk1977   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
2059bb575fdSdrh   sqlite3 *db;          /* The main database structure */
2064a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
2070ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
2084d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
209cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
210cfe9a69fSdanielk1977   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
211cfe9a69fSdanielk1977   int iCleanup = 0;     /* Address of the cleanup code */
212cfe9a69fSdanielk1977   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
213cfe9a69fSdanielk1977   int iCntMem = 0;      /* Memory cell used for the row counter */
214798da52cSdrh   int newIdx = -1;      /* Cursor for the NEW table */
2152958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
2162958a4e6Sdrh   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
217da184236Sdanielk1977   int iDb;
218cce7d176Sdrh 
219798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
220798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
221dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
222798da52cSdrh #endif
223c3f9bad2Sdanielk1977 
224f3388144Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
22502afc861Sdrh   int counterRowid = 0;  /* Memory cell holding rowid of autoinc counter */
226f3388144Sdrh #endif
227f3388144Sdrh 
2289e12800dSdanielk1977   if( pParse->nErr || sqlite3MallocFailed() ){
2296f7adc8aSdrh     goto insert_cleanup;
2306f7adc8aSdrh   }
231ecdc7530Sdrh   db = pParse->db;
232daffd0e5Sdrh 
2331ccde15dSdrh   /* Locate the table into which we will be inserting new information.
2341ccde15dSdrh   */
235113088ecSdrh   assert( pTabList->nSrc==1 );
236113088ecSdrh   zTab = pTabList->a[0].zName;
237daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
2384adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
239c3f9bad2Sdanielk1977   if( pTab==0 ){
240c3f9bad2Sdanielk1977     goto insert_cleanup;
241c3f9bad2Sdanielk1977   }
242da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
243da184236Sdanielk1977   assert( iDb<db->nDb );
244da184236Sdanielk1977   pDb = &db->aDb[iDb];
2452958a4e6Sdrh   zDb = pDb->zName;
2464adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
2471962bda7Sdrh     goto insert_cleanup;
2481962bda7Sdrh   }
249c3f9bad2Sdanielk1977 
250b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
251b7f9164eSdrh   ** inserted into is a view
252b7f9164eSdrh   */
253b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
254dca76841Sdrh   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
255b7f9164eSdrh   isView = pTab->pSelect!=0;
256b7f9164eSdrh #else
257dca76841Sdrh # define triggers_exist 0
258b7f9164eSdrh # define isView 0
259b7f9164eSdrh #endif
260b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
261b7f9164eSdrh # undef isView
262b7f9164eSdrh # define isView 0
263b7f9164eSdrh #endif
264b7f9164eSdrh 
265c3f9bad2Sdanielk1977   /* Ensure that:
266c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
267c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
268c3f9bad2Sdanielk1977   */
269dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
270c3f9bad2Sdanielk1977     goto insert_cleanup;
271c3f9bad2Sdanielk1977   }
27243617e9aSdrh   assert( pTab!=0 );
2731ccde15dSdrh 
274f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
275b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
276b3d24bf8Sdanielk1977   ** module table).
277f573c99bSdrh   */
278b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
279f573c99bSdrh     goto insert_cleanup;
280f573c99bSdrh   }
281f573c99bSdrh 
2821ccde15dSdrh   /* Allocate a VDBE
2831ccde15dSdrh   */
2844adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2855974a30fSdrh   if( v==0 ) goto insert_cleanup;
2864794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
287da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
2881ccde15dSdrh 
289c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
290dca76841Sdrh   if( triggers_exist ){
291c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
292f29ce559Sdanielk1977   }
293c3f9bad2Sdanielk1977 
2942958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
2952958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
296f3388144Sdrh   ** sqlite_sequence table and store it in memory cell counterMem.  Also
297f3388144Sdrh   ** remember the rowid of the sqlite_sequence table entry in memory cell
298f3388144Sdrh   ** counterRowid.
2992958a4e6Sdrh   */
3002958a4e6Sdrh   if( pTab->autoInc ){
301f3388144Sdrh     int iCur = pParse->nTab;
302f0113000Sdanielk1977     int addr = sqlite3VdbeCurrentAddr(v);
303f3388144Sdrh     counterRowid = pParse->nMem++;
304f3388144Sdrh     counterMem = pParse->nMem++;
305c00da105Sdanielk1977     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
306f0113000Sdanielk1977     sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
307f3388144Sdrh     sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
308f3388144Sdrh     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
309f0113000Sdanielk1977     sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
310f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
311f3388144Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, counterRowid, 1);
312f3388144Sdrh     sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
313f3388144Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, counterMem, 1);
314f0113000Sdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
315f0113000Sdanielk1977     sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
316f3388144Sdrh     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
3172958a4e6Sdrh   }
3182958a4e6Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
3192958a4e6Sdrh 
3201ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
321142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
322142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
323142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
324142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
325142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
326142e30dfSdrh   ** results in a temporary table. (Template 3.)
3271ccde15dSdrh   */
3285974a30fSdrh   if( pSelect ){
329142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
330142e30dfSdrh     */
331142e30dfSdrh     int rc, iInitCode;
3324adee20fSdanielk1977     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
3334adee20fSdanielk1977     iSelectLoop = sqlite3VdbeCurrentAddr(v);
3344adee20fSdanielk1977     iInsertBlock = sqlite3VdbeMakeLabel(v);
335b3bce662Sdanielk1977 
336b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
337b3bce662Sdanielk1977     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
3389e12800dSdanielk1977     if( rc || pParse->nErr || sqlite3MallocFailed() ){
3396f7adc8aSdrh       goto insert_cleanup;
3406f7adc8aSdrh     }
341b3bce662Sdanielk1977 
3424adee20fSdanielk1977     iCleanup = sqlite3VdbeMakeLabel(v);
3434adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
3445974a30fSdrh     assert( pSelect->pEList );
345967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
346142e30dfSdrh 
347142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
348142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
349142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
350048c530cSdrh     **
351048c530cSdrh     ** A temp table must be used if the table being updated is also one
352048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
353048c530cSdrh     ** temp table in the case of row triggers.
354142e30dfSdrh     */
355da184236Sdanielk1977     if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
356048c530cSdrh       useTempTable = 1;
357048c530cSdrh     }
358142e30dfSdrh 
359142e30dfSdrh     if( useTempTable ){
360142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
361142e30dfSdrh       ** the result.  Store the result in a temporary table
362142e30dfSdrh       */
363142e30dfSdrh       srcTab = pParse->nTab++;
3644adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iInsertBlock);
3654adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
366f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
3674adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
368f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Insert, srcTab, 0);
3694adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
370142e30dfSdrh 
371142e30dfSdrh       /* The following code runs first because the GOTO at the very top
372142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
373142e30dfSdrh       ** back up and execute the SELECT code above.
374142e30dfSdrh       */
375d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
376b9bb7c18Sdrh       sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
377b6f5452fSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
3784adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
3794adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCleanup);
3805974a30fSdrh     }else{
381d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
382142e30dfSdrh     }
383142e30dfSdrh   }else{
384142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
385142e30dfSdrh     ** clause
386142e30dfSdrh     */
387b3bce662Sdanielk1977     NameContext sNC;
388b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
389b3bce662Sdanielk1977     sNC.pParse = pParse;
3905974a30fSdrh     srcTab = -1;
391142e30dfSdrh     useTempTable = 0;
392147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
393e64e7b20Sdrh     for(i=0; i<nColumn; i++){
394b3bce662Sdanielk1977       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
395b04a5d87Sdrh         goto insert_cleanup;
396b04a5d87Sdrh       }
397e64e7b20Sdrh     }
3985974a30fSdrh   }
3991ccde15dSdrh 
4001ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
4011ccde15dSdrh   ** of columns to be inserted into the table.
4021ccde15dSdrh   */
403147d0cccSdrh   if( pColumn==0 && nColumn && nColumn!=pTab->nCol ){
4044adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
405da93d238Sdrh        "table %S has %d columns but %d values were supplied",
406da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
407cce7d176Sdrh     goto insert_cleanup;
408cce7d176Sdrh   }
409967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
4104adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
411cce7d176Sdrh     goto insert_cleanup;
412cce7d176Sdrh   }
4131ccde15dSdrh 
4141ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
4151ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
4161ccde15dSdrh   ** remember the column indices.
417c8392586Sdrh   **
418c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
419c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
420c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
421c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
422c8392586Sdrh   ** is appears in the original table.  (The index of the primary
423c8392586Sdrh   ** key in the original table is pTab->iPKey.)
4241ccde15dSdrh   */
425967e8b73Sdrh   if( pColumn ){
426967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
427967e8b73Sdrh       pColumn->a[i].idx = -1;
428cce7d176Sdrh     }
429967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
430cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
4314adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
432967e8b73Sdrh           pColumn->a[i].idx = j;
4334a32431cSdrh           if( j==pTab->iPKey ){
4349aa028daSdrh             keyColumn = i;
4354a32431cSdrh           }
436cce7d176Sdrh           break;
437cce7d176Sdrh         }
438cce7d176Sdrh       }
439cce7d176Sdrh       if( j>=pTab->nCol ){
4404adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
441a0217ba7Sdrh           keyColumn = i;
442a0217ba7Sdrh         }else{
4434adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
444da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
445cce7d176Sdrh           pParse->nErr++;
446cce7d176Sdrh           goto insert_cleanup;
447cce7d176Sdrh         }
448cce7d176Sdrh       }
449cce7d176Sdrh     }
450a0217ba7Sdrh   }
4511ccde15dSdrh 
452aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
453c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
454c8392586Sdrh   ** in the original table definition.
4554a32431cSdrh   */
456147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
4574a32431cSdrh     keyColumn = pTab->iPKey;
4584a32431cSdrh   }
4594a32431cSdrh 
460142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
461142e30dfSdrh   */
462dca76841Sdrh   if( triggers_exist ){
4634adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
46484ac9d02Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
465f29ce559Sdanielk1977   }
466c3f9bad2Sdanielk1977 
467c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
4681ccde15dSdrh   */
469142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
470142e30dfSdrh     iCntMem = pParse->nMem++;
471d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
472c3f9bad2Sdanielk1977   }
473c3f9bad2Sdanielk1977 
474c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
475dca76841Sdrh   if( !triggers_exist ){
4765974a30fSdrh     base = pParse->nTab;
477290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
478feeb1394Sdrh   }
479feeb1394Sdrh 
480142e30dfSdrh   /* If the data source is a temporary table, then we have to create
4811ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
482142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
483142e30dfSdrh   ** to launch the SELECT statement processing.
4841ccde15dSdrh   */
485142e30dfSdrh   if( useTempTable ){
4864adee20fSdanielk1977     iBreak = sqlite3VdbeMakeLabel(v);
4874adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
4884adee20fSdanielk1977     iCont = sqlite3VdbeCurrentAddr(v);
489142e30dfSdrh   }else if( pSelect ){
4904adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
4914adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iInsertBlock);
492bed8690fSdrh   }
4931ccde15dSdrh 
4945cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
49570ce3f0cSdrh   */
4964adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
497dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
498c3f9bad2Sdanielk1977 
49970ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
50070ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
50170ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
50270ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
50370ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
50470ce3f0cSdrh     */
50570ce3f0cSdrh     if( keyColumn<0 ){
5064adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
50770ce3f0cSdrh     }else if( useTempTable ){
5084adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
50970ce3f0cSdrh     }else{
510d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
5114adee20fSdanielk1977       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
5124adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
5134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
5144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
5154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
51670ce3f0cSdrh     }
51770ce3f0cSdrh 
51870ce3f0cSdrh     /* Create the new column data
51970ce3f0cSdrh     */
520c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
521c3f9bad2Sdanielk1977       if( pColumn==0 ){
522c3f9bad2Sdanielk1977         j = i;
523c3f9bad2Sdanielk1977       }else{
524c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
525c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
526c3f9bad2Sdanielk1977         }
527c3f9bad2Sdanielk1977       }
528c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
5297977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
530142e30dfSdrh       }else if( useTempTable ){
5314adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
532c3f9bad2Sdanielk1977       }else{
533d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
53425303780Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
535c3f9bad2Sdanielk1977       }
536c3f9bad2Sdanielk1977     }
5374adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
538a37cdde0Sdanielk1977 
539a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
540a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
541a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
542a37cdde0Sdanielk1977     ** table column affinities.
543a37cdde0Sdanielk1977     */
544a37cdde0Sdanielk1977     if( !isView ){
545a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
546a37cdde0Sdanielk1977     }
547f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
548c3f9bad2Sdanielk1977 
5495cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
550dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
551b2fe7d8cSdrh         newIdx, -1, onError, endOfLoop) ){
552f29ce559Sdanielk1977       goto insert_cleanup;
553f29ce559Sdanielk1977     }
55470ce3f0cSdrh   }
555c3f9bad2Sdanielk1977 
55670ce3f0cSdrh   /* If any triggers exists, the opening of tables and indices is deferred
55770ce3f0cSdrh   ** until now.
55870ce3f0cSdrh   */
559dca76841Sdrh   if( triggers_exist && !isView ){
560c3f9bad2Sdanielk1977     base = pParse->nTab;
561290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
562c3f9bad2Sdanielk1977   }
563c3f9bad2Sdanielk1977 
5644a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
565f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
5664a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
567b419a926Sdrh   ** case the record number is the same as that column.
5681ccde15dSdrh   */
5695cf590c1Sdrh   if( !isView ){
5704cbdda9eSdrh     if( IsVirtual(pTab) ){
5714cbdda9eSdrh       /* The row that the VUpdate opcode will delete:  none */
5724cbdda9eSdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
5734cbdda9eSdrh     }
5744a32431cSdrh     if( keyColumn>=0 ){
575142e30dfSdrh       if( useTempTable ){
5764adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
577142e30dfSdrh       }else if( pSelect ){
5784adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
5794a32431cSdrh       }else{
5804adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
58127a32783Sdrh       }
582f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
583e1e68f49Sdrh       ** to generate a unique primary key value.
584e1e68f49Sdrh       */
5854adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
5864adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
587f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
5884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
5894cbdda9eSdrh     }else if( IsVirtual(pTab) ){
5904cbdda9eSdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
5914a32431cSdrh     }else{
592f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
5934a32431cSdrh     }
5942958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
5952958a4e6Sdrh     if( pTab->autoInc ){
5962958a4e6Sdrh       sqlite3VdbeAddOp(v, OP_MemMax, counterMem, 0);
5972958a4e6Sdrh     }
5982958a4e6Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
5994a32431cSdrh 
600aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
6014a32431cSdrh     ** with the first column.
6024a32431cSdrh     */
603cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
6044a32431cSdrh       if( i==pTab->iPKey ){
6054a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
606aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
607aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
608aacc543eSdrh         ** taking up data space with information that will never be used. */
609f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
6104a32431cSdrh         continue;
6114a32431cSdrh       }
612967e8b73Sdrh       if( pColumn==0 ){
613cce7d176Sdrh         j = i;
614cce7d176Sdrh       }else{
615967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
616967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
617cce7d176Sdrh         }
618cce7d176Sdrh       }
619147d0cccSdrh       if( nColumn==0 || (pColumn && j>=pColumn->nId) ){
6207977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
621142e30dfSdrh       }else if( useTempTable ){
6224adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
623142e30dfSdrh       }else if( pSelect ){
624*16ed8a64Sdrh         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
625cce7d176Sdrh       }else{
6264adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr);
627cce7d176Sdrh       }
628cce7d176Sdrh     }
6291ccde15dSdrh 
6300ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
6310ca3e24bSdrh     ** do the insertion.
6324a32431cSdrh     */
6334cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
6344cbdda9eSdrh     if( IsVirtual(pTab) ){
635f9e7dda7Sdanielk1977       pParse->pVirtualLock = pTab;
6361f6eec54Sdanielk1977       sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
6374cbdda9eSdrh                      (const char*)pTab->pVtab, P3_VTAB);
6384cbdda9eSdrh     }else
6394cbdda9eSdrh #endif
6404cbdda9eSdrh     {
6414adee20fSdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
642a0217ba7Sdrh                                      0, onError, endOfLoop);
6434adee20fSdanielk1977       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
644dca76841Sdrh                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1);
6455cf590c1Sdrh     }
6464cbdda9eSdrh   }
6471bee3d7bSdrh 
648feeb1394Sdrh   /* Update the count of rows that are inserted
6491bee3d7bSdrh   */
650142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
65115007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
6521bee3d7bSdrh   }
653c3f9bad2Sdanielk1977 
654dca76841Sdrh   if( triggers_exist ){
655c3f9bad2Sdanielk1977     /* Close all tables opened */
6565cf590c1Sdrh     if( !isView ){
6574adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, base, 0);
658c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
6594adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
660c3f9bad2Sdanielk1977       }
661c3f9bad2Sdanielk1977     }
662c3f9bad2Sdanielk1977 
663c3f9bad2Sdanielk1977     /* Code AFTER triggers */
664dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
665dca76841Sdrh           newIdx, -1, onError, endOfLoop) ){
666f29ce559Sdanielk1977       goto insert_cleanup;
667f29ce559Sdanielk1977     }
668c3f9bad2Sdanielk1977   }
6691bee3d7bSdrh 
6701ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
6711ccde15dSdrh   */
6724adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
673142e30dfSdrh   if( useTempTable ){
6744adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
6754adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iBreak);
6764adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
677142e30dfSdrh   }else if( pSelect ){
6784adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
6794adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
6804adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iCleanup);
6816b56344dSdrh   }
682c3f9bad2Sdanielk1977 
6834cbdda9eSdrh   if( !triggers_exist && !IsVirtual(pTab) ){
684c3f9bad2Sdanielk1977     /* Close all tables opened */
6854adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base, 0);
6866b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
6874adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
688cce7d176Sdrh     }
689c3f9bad2Sdanielk1977   }
690c3f9bad2Sdanielk1977 
6912958a4e6Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
692f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
693f3388144Sdrh   ** counter value in memory counterMem back into the sqlite_sequence
694f3388144Sdrh   ** table.
6952958a4e6Sdrh   */
6962958a4e6Sdrh   if( pTab->autoInc ){
697f3388144Sdrh     int iCur = pParse->nTab;
698f0113000Sdanielk1977     int addr = sqlite3VdbeCurrentAddr(v);
699c00da105Sdanielk1977     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
700f3388144Sdrh     sqlite3VdbeAddOp(v, OP_MemLoad, counterRowid, 0);
701f0113000Sdanielk1977     sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
702f3388144Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
703f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
704f3388144Sdrh     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
705f3388144Sdrh     sqlite3VdbeAddOp(v, OP_MemLoad, counterMem, 0);
706f3388144Sdrh     sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
707f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, iCur, 0);
708f3388144Sdrh     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
7092958a4e6Sdrh   }
7102958a4e6Sdrh #endif
7112958a4e6Sdrh 
7121bee3d7bSdrh   /*
713e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
714e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
715e7de6f25Sdanielk1977   ** invoke the callback function.
7161bee3d7bSdrh   */
717cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
7184adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
7194adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
72022322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
721955de52cSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
7221bee3d7bSdrh   }
723cce7d176Sdrh 
724cce7d176Sdrh insert_cleanup:
7254adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
726d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
727d5d56523Sdanielk1977   sqlite3SelectDelete(pSelect);
7284adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
729cce7d176Sdrh }
7309cfcf5d4Sdrh 
7319cfcf5d4Sdrh /*
7329cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
7339cfcf5d4Sdrh **
7349cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
7350ca3e24bSdrh ** the following values:
7360ca3e24bSdrh **
737f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
738b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
739b419a926Sdrh **        change to the record number.
7400ca3e24bSdrh **
741f0863fe5Sdrh **    2.  The rowid of the row after the update.
7420ca3e24bSdrh **
7430ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
7440ca3e24bSdrh **
7450ca3e24bSdrh **    i.  Data from middle columns...
7460ca3e24bSdrh **
7470ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
7480ca3e24bSdrh **
749f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
750f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
751f0863fe5Sdrh ** INSERTs and rowidChng is true if the record number is being changed.
7520ca3e24bSdrh **
7530ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
7540ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
7550ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
7560ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
7570ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
7589cfcf5d4Sdrh **
7599cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
7609cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
7611c92853dSdrh ** then the appropriate action is performed.  There are five possible
7621c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
7639cfcf5d4Sdrh **
7649cfcf5d4Sdrh **  Constraint type  Action       What Happens
7659cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
7661c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
76724b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
7689cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
7699cfcf5d4Sdrh **
7701c92853dSdrh **  any              ABORT        Back out changes from the current command
7711c92853dSdrh **                                only (do not do a complete rollback) then
77224b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
7731c92853dSdrh **                                with SQLITE_CONSTRAINT.
7741c92853dSdrh **
7751c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
7761c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
7771c92853dSdrh **                                transaction is not rolled back and any
7781c92853dSdrh **                                prior changes are retained.
7791c92853dSdrh **
7809cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
7819cfcf5d4Sdrh **                                the stack and there is an immediate jump
7829cfcf5d4Sdrh **                                to label ignoreDest.
7839cfcf5d4Sdrh **
7849cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
7859cfcf5d4Sdrh **                                value for that column.  If the default value
7869cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
7879cfcf5d4Sdrh **
7889cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
7899cfcf5d4Sdrh **                                being inserted is removed.
7909cfcf5d4Sdrh **
7919cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
7929cfcf5d4Sdrh **
7931c92853dSdrh ** Which action to take is determined by the overrideError parameter.
7941c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
7951c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
7961c92853dSdrh ** for the constraint is used.
7979cfcf5d4Sdrh **
798aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
7999cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
8009cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
8019cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
8029cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
8039cfcf5d4Sdrh **
8049cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
8059cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
8069cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
8079cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
8089cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
8099cfcf5d4Sdrh */
8104adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
8119cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
8129cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
8139cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
8149cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
815f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
816b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
8179cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
818b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
8199cfcf5d4Sdrh ){
8209cfcf5d4Sdrh   int i;
8219cfcf5d4Sdrh   Vdbe *v;
8229cfcf5d4Sdrh   int nCol;
8239cfcf5d4Sdrh   int onError;
8249cfcf5d4Sdrh   int addr;
8259cfcf5d4Sdrh   int extra;
8260ca3e24bSdrh   int iCur;
8270ca3e24bSdrh   Index *pIdx;
8280ca3e24bSdrh   int seenReplace = 0;
829cfe9a69fSdanielk1977   int jumpInst1=0, jumpInst2;
830f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
8319cfcf5d4Sdrh 
8324adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
8339cfcf5d4Sdrh   assert( v!=0 );
834417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
8359cfcf5d4Sdrh   nCol = pTab->nCol;
8369cfcf5d4Sdrh 
8379cfcf5d4Sdrh   /* Test all NOT NULL constraints.
8389cfcf5d4Sdrh   */
8399cfcf5d4Sdrh   for(i=0; i<nCol; i++){
8400ca3e24bSdrh     if( i==pTab->iPKey ){
8410ca3e24bSdrh       continue;
8420ca3e24bSdrh     }
8439cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
8440ca3e24bSdrh     if( onError==OE_None ) continue;
8459cfcf5d4Sdrh     if( overrideError!=OE_Default ){
8469cfcf5d4Sdrh       onError = overrideError;
847a996e477Sdrh     }else if( onError==OE_Default ){
848a996e477Sdrh       onError = OE_Abort;
8499cfcf5d4Sdrh     }
8507977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
8519cfcf5d4Sdrh       onError = OE_Abort;
8529cfcf5d4Sdrh     }
8534adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
8544adee20fSdanielk1977     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
855b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
856b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
8579cfcf5d4Sdrh     switch( onError ){
8581c92853dSdrh       case OE_Rollback:
8591c92853dSdrh       case OE_Abort:
8601c92853dSdrh       case OE_Fail: {
861483750baSdrh         char *zMsg = 0;
8624adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
8634adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
86441743984Sdrh                         " may not be NULL", (char*)0);
8654adee20fSdanielk1977         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
8669cfcf5d4Sdrh         break;
8679cfcf5d4Sdrh       }
8689cfcf5d4Sdrh       case OE_Ignore: {
869f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
8704adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
8719cfcf5d4Sdrh         break;
8729cfcf5d4Sdrh       }
8739cfcf5d4Sdrh       case OE_Replace: {
8747977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
8754adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
8769cfcf5d4Sdrh         break;
8779cfcf5d4Sdrh       }
8789cfcf5d4Sdrh     }
879d654be80Sdrh     sqlite3VdbeJumpHere(v, addr);
8809cfcf5d4Sdrh   }
8819cfcf5d4Sdrh 
8829cfcf5d4Sdrh   /* Test all CHECK constraints
8839cfcf5d4Sdrh   */
884ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
8850cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
886ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
887ffe07b2dSdrh     assert( pParse->ckOffset==0 );
888ffe07b2dSdrh     pParse->ckOffset = nCol;
8896275b88bSdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
890ffe07b2dSdrh     assert( pParse->ckOffset==nCol );
891ffe07b2dSdrh     pParse->ckOffset = 0;
892aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
893aa01c7e2Sdrh     if( onError==OE_Ignore || onError==OE_Replace ){
894aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
895aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
896aa01c7e2Sdrh     }else{
897aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
898aa01c7e2Sdrh     }
899ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
900ffe07b2dSdrh   }
901ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
9029cfcf5d4Sdrh 
9030bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
9040bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
9050bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
9069cfcf5d4Sdrh   */
907f0863fe5Sdrh   if( rowidChng ){
9080ca3e24bSdrh     onError = pTab->keyConf;
9090ca3e24bSdrh     if( overrideError!=OE_Default ){
9100ca3e24bSdrh       onError = overrideError;
911a996e477Sdrh     }else if( onError==OE_Default ){
912a996e477Sdrh       onError = OE_Abort;
9130ca3e24bSdrh     }
914a0217ba7Sdrh 
91579b0c956Sdrh     if( isUpdate ){
9164adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
9174adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
9184adee20fSdanielk1977       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
91979b0c956Sdrh     }
9204adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
9214adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
9220ca3e24bSdrh     switch( onError ){
923a0217ba7Sdrh       default: {
924a0217ba7Sdrh         onError = OE_Abort;
925a0217ba7Sdrh         /* Fall thru into the next case */
926a0217ba7Sdrh       }
9271c92853dSdrh       case OE_Rollback:
9281c92853dSdrh       case OE_Abort:
9291c92853dSdrh       case OE_Fail: {
9304adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
931701a0aebSdrh                          "PRIMARY KEY must be unique", P3_STATIC);
9320ca3e24bSdrh         break;
9330ca3e24bSdrh       }
9345383ae5cSdrh       case OE_Replace: {
93574161705Sdrh         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
9365383ae5cSdrh         if( isUpdate ){
937f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
9387cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
9395383ae5cSdrh         }
9405383ae5cSdrh         seenReplace = 1;
9415383ae5cSdrh         break;
9425383ae5cSdrh       }
9430ca3e24bSdrh       case OE_Ignore: {
9445383ae5cSdrh         assert( seenReplace==0 );
945f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
9464adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
9470ca3e24bSdrh         break;
9480ca3e24bSdrh       }
9490ca3e24bSdrh     }
950d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
951f5905aa7Sdrh     if( isUpdate ){
952d654be80Sdrh       sqlite3VdbeJumpHere(v, jumpInst1);
9534adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
9547cf6e4deSdrh       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
9550ca3e24bSdrh     }
9560ca3e24bSdrh   }
9570bd1f4eaSdrh 
9580bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
9590bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
9600bd1f4eaSdrh   ** Add the new records to the indices as we go.
9610bd1f4eaSdrh   */
962b2fe7d8cSdrh   extra = -1;
963b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
964b2fe7d8cSdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
9659cfcf5d4Sdrh     extra++;
966b2fe7d8cSdrh 
967b2fe7d8cSdrh     /* Create a key for accessing the index entry */
9684adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
9699cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
9709cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
9719cfcf5d4Sdrh       if( idx==pTab->iPKey ){
9724adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
9739cfcf5d4Sdrh       }else{
9744adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
9759cfcf5d4Sdrh       }
9769cfcf5d4Sdrh     }
9777f057c91Sdrh     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
978a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
979b2fe7d8cSdrh 
980b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
9819cfcf5d4Sdrh     onError = pIdx->onError;
982b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
9839cfcf5d4Sdrh     if( overrideError!=OE_Default ){
9849cfcf5d4Sdrh       onError = overrideError;
985a996e477Sdrh     }else if( onError==OE_Default ){
986a996e477Sdrh       onError = OE_Abort;
9879cfcf5d4Sdrh     }
9885383ae5cSdrh     if( seenReplace ){
9895383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
9905383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
9915383ae5cSdrh     }
9925383ae5cSdrh 
993b2fe7d8cSdrh 
994b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
995f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
9964adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
997b2fe7d8cSdrh 
998b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
999b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1000b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
10019cfcf5d4Sdrh     switch( onError ){
10021c92853dSdrh       case OE_Rollback:
10031c92853dSdrh       case OE_Abort:
10041c92853dSdrh       case OE_Fail: {
100537ed48edSdrh         int j, n1, n2;
100637ed48edSdrh         char zErrMsg[200];
100737ed48edSdrh         strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
100837ed48edSdrh         n1 = strlen(zErrMsg);
100937ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
101037ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
101137ed48edSdrh           n2 = strlen(zCol);
101237ed48edSdrh           if( j>0 ){
101337ed48edSdrh             strcpy(&zErrMsg[n1], ", ");
101437ed48edSdrh             n1 += 2;
101537ed48edSdrh           }
101637ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
101737ed48edSdrh             strcpy(&zErrMsg[n1], "...");
101837ed48edSdrh             n1 += 3;
101937ed48edSdrh             break;
102037ed48edSdrh           }else{
102137ed48edSdrh             strcpy(&zErrMsg[n1], zCol);
102237ed48edSdrh             n1 += n2;
102337ed48edSdrh           }
102437ed48edSdrh         }
102537ed48edSdrh         strcpy(&zErrMsg[n1],
102637ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
10274adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
10289cfcf5d4Sdrh         break;
10299cfcf5d4Sdrh       }
10309cfcf5d4Sdrh       case OE_Ignore: {
10310ca3e24bSdrh         assert( seenReplace==0 );
1032f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
10334adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
10349cfcf5d4Sdrh         break;
10359cfcf5d4Sdrh       }
10369cfcf5d4Sdrh       case OE_Replace: {
10374adee20fSdanielk1977         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
10389cfcf5d4Sdrh         if( isUpdate ){
1039f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
10407cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
10419cfcf5d4Sdrh         }
10420ca3e24bSdrh         seenReplace = 1;
10439cfcf5d4Sdrh         break;
10449cfcf5d4Sdrh       }
10459cfcf5d4Sdrh     }
10460bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
1047d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst1);
10480bd1f4eaSdrh #endif
1049d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
10509cfcf5d4Sdrh   }
10519cfcf5d4Sdrh }
10520ca3e24bSdrh 
10530ca3e24bSdrh /*
10540ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
10554adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
10560ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
1057f0863fe5Sdrh ** and the rowid for the new entry.  This routine creates the new
10580ca3e24bSdrh ** entries in all indices and in the main table.
10590ca3e24bSdrh **
1060b419a926Sdrh ** The arguments to this routine should be the same as the first six
10614adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
10620ca3e24bSdrh */
10634adee20fSdanielk1977 void sqlite3CompleteInsertion(
10640ca3e24bSdrh   Parse *pParse,      /* The parser context */
10650ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
10660ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
10670ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
1068f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
106970ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
107070ce3f0cSdrh   int newIdx          /* Index of NEW table for triggers.  -1 if none */
10710ca3e24bSdrh ){
10720ca3e24bSdrh   int i;
10730ca3e24bSdrh   Vdbe *v;
10740ca3e24bSdrh   int nIdx;
10750ca3e24bSdrh   Index *pIdx;
1076b28af71aSdanielk1977   int pik_flags;
10770ca3e24bSdrh 
10784adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
10790ca3e24bSdrh   assert( v!=0 );
1080417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
10810ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
10820ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
10830ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
1084f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
10850ca3e24bSdrh   }
10864adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1087a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1088b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
108970ce3f0cSdrh   if( newIdx>=0 ){
10904adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
10914adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1092f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
109370ce3f0cSdrh   }
1094b84f96f8Sdanielk1977 #endif
10954794f735Sdrh   if( pParse->nested ){
10964794f735Sdrh     pik_flags = 0;
10974794f735Sdrh   }else{
109894eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
109994eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
11004794f735Sdrh   }
1101f0863fe5Sdrh   sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
110294eb6a14Sdanielk1977   if( !pParse->nested ){
110394eb6a14Sdanielk1977     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
110494eb6a14Sdanielk1977   }
1105b28af71aSdanielk1977 
1106f0863fe5Sdrh   if( isUpdate && rowidChng ){
11074adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
11080ca3e24bSdrh   }
11090ca3e24bSdrh }
1110cd44690aSdrh 
1111cd44690aSdrh /*
1112290c1948Sdrh ** Generate code that will open cursors for a table and for all
1113cd44690aSdrh ** indices of that table.  The "base" parameter is the cursor number used
1114cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1115cd44690aSdrh */
1116290c1948Sdrh void sqlite3OpenTableAndIndices(
1117290c1948Sdrh   Parse *pParse,   /* Parsing context */
1118290c1948Sdrh   Table *pTab,     /* Table to be opened */
1119290c1948Sdrh   int base,        /* Cursor number assigned to the table */
1120290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1121290c1948Sdrh ){
1122cd44690aSdrh   int i;
11234cbdda9eSdrh   int iDb;
1124cd44690aSdrh   Index *pIdx;
11254cbdda9eSdrh   Vdbe *v;
11264cbdda9eSdrh 
11274cbdda9eSdrh   if( IsVirtual(pTab) ) return;
11284cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
11294cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1130cd44690aSdrh   assert( v!=0 );
1131c00da105Sdanielk1977   sqlite3OpenTable(pParse, base, iDb, pTab, op);
1132cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1133b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1134da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
1135da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
113629dda4aeSdrh     VdbeComment((v, "# %s", pIdx->zName));
1137b3bf556eSdanielk1977     sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
1138cd44690aSdrh   }
1139290c1948Sdrh   if( pParse->nTab<=base+i ){
1140290c1948Sdrh     pParse->nTab = base+i;
1141290c1948Sdrh   }
1142cd44690aSdrh }
1143