xref: /sqlite-3.40.0/src/insert.c (revision 287fb61c)
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*287fb61cSdanielk1977 ** $Id: insert.c,v 1.210 2008/01/04 19:10:29 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
2066a5167bSdrh ** Set P4 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;
44abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
4517435752Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
46a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
47a37cdde0Sdanielk1977       return;
48a37cdde0Sdanielk1977     }
49a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
50a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
51a37cdde0Sdanielk1977     }
52a37cdde0Sdanielk1977     pIdx->zColAff[pIdx->nColumn] = '\0';
53a37cdde0Sdanielk1977   }
543d1bfeaaSdanielk1977 
5566a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
56a37cdde0Sdanielk1977 }
57a37cdde0Sdanielk1977 
58a37cdde0Sdanielk1977 /*
5966a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
60a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
61a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
62a37cdde0Sdanielk1977 ** column:
63a37cdde0Sdanielk1977 **
64a37cdde0Sdanielk1977 **  Character      Column affinity
65a37cdde0Sdanielk1977 **  ------------------------------
663eda040bSdrh **  'a'            TEXT
673eda040bSdrh **  'b'            NONE
683eda040bSdrh **  'c'            NUMERIC
693eda040bSdrh **  'd'            INTEGER
703eda040bSdrh **  'e'            REAL
71a37cdde0Sdanielk1977 */
72a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
733d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
743d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
753d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
763d1bfeaaSdanielk1977   **
773d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
783d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
793d1bfeaaSdanielk1977   */
803d1bfeaaSdanielk1977   if( !pTab->zColAff ){
813d1bfeaaSdanielk1977     char *zColAff;
823d1bfeaaSdanielk1977     int i;
83abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
843d1bfeaaSdanielk1977 
8517435752Sdrh     zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
863d1bfeaaSdanielk1977     if( !zColAff ){
87a37cdde0Sdanielk1977       return;
883d1bfeaaSdanielk1977     }
893d1bfeaaSdanielk1977 
903d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
91a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
923d1bfeaaSdanielk1977     }
933d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
943d1bfeaaSdanielk1977 
953d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
963d1bfeaaSdanielk1977   }
973d1bfeaaSdanielk1977 
9866a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
993d1bfeaaSdanielk1977 }
1003d1bfeaaSdanielk1977 
1014d88778bSdanielk1977 /*
10248d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
10348d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
10448d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
10548d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
10648d1178aSdrh ** run without using temporary table for the results of the SELECT.
1074d88778bSdanielk1977 */
10848d1178aSdrh static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
1094d88778bSdanielk1977   int i;
11048d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
11148d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
11248d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
113ef0bea92Sdrh     assert( pOp!=0 );
114207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
11548d1178aSdrh       Index *pIndex;
116207872a4Sdanielk1977       int tnum = pOp->p2;
11748d1178aSdrh       if( tnum==pTab->tnum ){
11848d1178aSdrh         return 1;
11948d1178aSdrh       }
12048d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
12148d1178aSdrh         if( tnum==pIndex->tnum ){
12248d1178aSdrh           return 1;
12348d1178aSdrh         }
12448d1178aSdrh       }
12548d1178aSdrh     }
126543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1272dca4ac1Sdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
1282dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
12966a5167bSdrh       assert( pOp->p4type==P4_VTAB );
13048d1178aSdrh       return 1;
1314d88778bSdanielk1977     }
132543165efSdrh #endif
1334d88778bSdanielk1977   }
1344d88778bSdanielk1977   return 0;
1354d88778bSdanielk1977 }
1363d1bfeaaSdanielk1977 
1379d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1389d9cf229Sdrh /*
1399d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1409d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1419d9cf229Sdrh ** table and stores that value in a memory cell.  Code generated by
1429d9cf229Sdrh ** autoIncStep() will keep that memory cell holding the largest
1439d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1449d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1459d9cf229Sdrh **
1469d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1479d9cf229Sdrh ** the maximum rowid counter.
1489d9cf229Sdrh **
1490a07c107Sdrh ** Two memory cells are allocated.  The next memory cell befor the
1509d9cf229Sdrh ** one returned holds the rowid in sqlite_sequence where we will
1519d9cf229Sdrh ** write back the revised maximum rowid.
1529d9cf229Sdrh */
1539d9cf229Sdrh static int autoIncBegin(
1549d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1559d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1569d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1579d9cf229Sdrh ){
1589d9cf229Sdrh   int memId = 0;
1599d9cf229Sdrh   if( pTab->autoInc ){
1609d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1619d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1629d9cf229Sdrh     int iCur = pParse->nTab;
1639d9cf229Sdrh     int addr;
1649d9cf229Sdrh     assert( v );
1659d9cf229Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1669d9cf229Sdrh     pParse->nMem += 2;
1670a07c107Sdrh     memId = pParse->nMem;
1689d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
169207872a4Sdanielk1977     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+12);
17066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Column, iCur, 0);
17166a5167bSdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
172207872a4Sdanielk1977     sqlite3VdbeAddOp2(v, OP_Ne, 0x100, addr+11);
17366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, 0);
17466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemStore, memId-1, 1);
17566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Column, iCur, 1);
17666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemStore, memId, 1);
177207872a4Sdanielk1977     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+12);
178207872a4Sdanielk1977     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+3);
17966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
1809d9cf229Sdrh   }
1819d9cf229Sdrh   return memId;
1829d9cf229Sdrh }
1839d9cf229Sdrh 
1849d9cf229Sdrh /*
1859d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
1869d9cf229Sdrh **
1879d9cf229Sdrh ** This routine should be called when the top of the stack holds a
1889d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
1899d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
1909d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
1919d9cf229Sdrh */
192*287fb61cSdanielk1977 static void autoIncStep(Parse *pParse, int memId, int iRowid){
1939d9cf229Sdrh   if( memId>0 ){
194*287fb61cSdanielk1977     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, iRowid);
1959d9cf229Sdrh   }
1969d9cf229Sdrh }
1979d9cf229Sdrh 
1989d9cf229Sdrh /*
1999d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
2009d9cf229Sdrh ** in mem[memId].  Generate code to write this value back into the
2019d9cf229Sdrh ** the sqlite_sequence table.
2029d9cf229Sdrh */
2039d9cf229Sdrh static void autoIncEnd(
2049d9cf229Sdrh   Parse *pParse,     /* The parsing context */
2059d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
2069d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
2079d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
2089d9cf229Sdrh ){
2099d9cf229Sdrh   if( pTab->autoInc ){
2109d9cf229Sdrh     int iCur = pParse->nTab;
2119d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
2129d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
2139d9cf229Sdrh     int addr;
2149d9cf229Sdrh     assert( v );
2159d9cf229Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2169d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
21766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemLoad, memId-1, 0);
218207872a4Sdanielk1977     sqlite3VdbeAddOp2(v, OP_NotNull, -1, addr+6);
21966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
22066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, 0);
22166a5167bSdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, 0, 0, pTab->zName, 0);
22266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemLoad, memId, 0);
22366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MakeRecord, 2, 0);
2241f4aa337Sdanielk1977     sqlite3CodeInsert(pParse, iCur, OPFLAG_APPEND);
22566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
2269d9cf229Sdrh   }
2279d9cf229Sdrh }
2289d9cf229Sdrh #else
2299d9cf229Sdrh /*
2309d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2319d9cf229Sdrh ** above are all no-ops
2329d9cf229Sdrh */
2339d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
234*287fb61cSdanielk1977 # define autoIncStep(A,B,C)
2359d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2369d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2379d9cf229Sdrh 
2389d9cf229Sdrh 
2399d9cf229Sdrh /* Forward declaration */
2409d9cf229Sdrh static int xferOptimization(
2419d9cf229Sdrh   Parse *pParse,        /* Parser context */
2429d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2439d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2449d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2459d9cf229Sdrh   int iDbDest           /* The database of pDest */
2469d9cf229Sdrh );
2479d9cf229Sdrh 
2483d1bfeaaSdanielk1977 /*
2491ccde15dSdrh ** This routine is call to handle SQL of the following forms:
250cce7d176Sdrh **
251cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2521ccde15dSdrh **    insert into TABLE (IDLIST) select
253cce7d176Sdrh **
2541ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2551ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
256967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2571ccde15dSdrh **
2581ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2591ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2601ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2611ccde15dSdrh ** data for the insert.
262142e30dfSdrh **
2639d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
264142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
265142e30dfSdrh ** once straight down through.  The template looks like this:
266142e30dfSdrh **
267142e30dfSdrh **         open write cursor to <table> and its indices
268142e30dfSdrh **         puts VALUES clause expressions onto the stack
269142e30dfSdrh **         write the resulting record into <table>
270142e30dfSdrh **         cleanup
271142e30dfSdrh **
2729d9cf229Sdrh ** The three remaining templates assume the statement is of the form
273142e30dfSdrh **
274142e30dfSdrh **   INSERT INTO <table> SELECT ...
275142e30dfSdrh **
2769d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
2779d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
2789d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
2799d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
2809d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
2819d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
2829d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
2839d9cf229Sdrh ** template.  This is the second template.
2849d9cf229Sdrh **
2859d9cf229Sdrh **         open a write cursor to <table>
2869d9cf229Sdrh **         open read cursor on <table2>
2879d9cf229Sdrh **         transfer all records in <table2> over to <table>
2889d9cf229Sdrh **         close cursors
2899d9cf229Sdrh **         foreach index on <table>
2909d9cf229Sdrh **           open a write cursor on the <table> index
2919d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
2929d9cf229Sdrh **           transfer all records from the read to the write cursors
2939d9cf229Sdrh **           close cursors
2949d9cf229Sdrh **         end foreach
2959d9cf229Sdrh **
2969d9cf229Sdrh ** The third template is for when the second template does not apply
2979d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
2989d9cf229Sdrh ** The generated code follows this template:
299142e30dfSdrh **
300142e30dfSdrh **         goto B
301142e30dfSdrh **      A: setup for the SELECT
3029d9cf229Sdrh **         loop over the rows in the SELECT
303142e30dfSdrh **           gosub C
304142e30dfSdrh **         end loop
305142e30dfSdrh **         cleanup after the SELECT
306142e30dfSdrh **         goto D
307142e30dfSdrh **      B: open write cursor to <table> and its indices
308142e30dfSdrh **         goto A
309142e30dfSdrh **      C: insert the select result into <table>
310142e30dfSdrh **         return
311142e30dfSdrh **      D: cleanup
312142e30dfSdrh **
3139d9cf229Sdrh ** The fourth template is used if the insert statement takes its
314142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
315142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
316142e30dfSdrh ** we have to use a intermediate table to store the results of
317142e30dfSdrh ** the select.  The template is like this:
318142e30dfSdrh **
319142e30dfSdrh **         goto B
320142e30dfSdrh **      A: setup for the SELECT
321142e30dfSdrh **         loop over the tables in the SELECT
322142e30dfSdrh **           gosub C
323142e30dfSdrh **         end loop
324142e30dfSdrh **         cleanup after the SELECT
325142e30dfSdrh **         goto D
326142e30dfSdrh **      C: insert the select result into the intermediate table
327142e30dfSdrh **         return
328142e30dfSdrh **      B: open a cursor to an intermediate table
329142e30dfSdrh **         goto A
330142e30dfSdrh **      D: open write cursor to <table> and its indices
331142e30dfSdrh **         loop over the intermediate table
332142e30dfSdrh **           transfer values form intermediate table into <table>
333142e30dfSdrh **         end the loop
334142e30dfSdrh **         cleanup
335cce7d176Sdrh */
3364adee20fSdanielk1977 void sqlite3Insert(
337cce7d176Sdrh   Parse *pParse,        /* Parser context */
338113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
339cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3405974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3419cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3429cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
343cce7d176Sdrh ){
3445974a30fSdrh   Table *pTab;          /* The table to insert into */
345113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
346e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3475974a30fSdrh   int i, j, idx;        /* Loop counters */
3485974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3495974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
350967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
351cfe9a69fSdanielk1977   int base = 0;         /* VDBE Cursor number for pTab */
352cfe9a69fSdanielk1977   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
3539bb575fdSdrh   sqlite3 *db;          /* The main database structure */
3544a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3550ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3564d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
357cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
358cfe9a69fSdanielk1977   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
359cfe9a69fSdanielk1977   int iCleanup = 0;     /* Address of the cleanup code */
360cfe9a69fSdanielk1977   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
361cfe9a69fSdanielk1977   int iCntMem = 0;      /* Memory cell used for the row counter */
362798da52cSdrh   int newIdx = -1;      /* Cursor for the NEW table */
3632958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
3642958a4e6Sdrh   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
365e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
366da184236Sdanielk1977   int iDb;
367cce7d176Sdrh 
368034ca14fSdanielk1977   int nHidden = 0;
369034ca14fSdanielk1977 
370798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
371798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
372dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
373798da52cSdrh #endif
374c3f9bad2Sdanielk1977 
37517435752Sdrh   db = pParse->db;
37617435752Sdrh   if( pParse->nErr || db->mallocFailed ){
3776f7adc8aSdrh     goto insert_cleanup;
3786f7adc8aSdrh   }
379daffd0e5Sdrh 
3801ccde15dSdrh   /* Locate the table into which we will be inserting new information.
3811ccde15dSdrh   */
382113088ecSdrh   assert( pTabList->nSrc==1 );
383113088ecSdrh   zTab = pTabList->a[0].zName;
384daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
3854adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
386c3f9bad2Sdanielk1977   if( pTab==0 ){
387c3f9bad2Sdanielk1977     goto insert_cleanup;
388c3f9bad2Sdanielk1977   }
389da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
390da184236Sdanielk1977   assert( iDb<db->nDb );
391da184236Sdanielk1977   pDb = &db->aDb[iDb];
3922958a4e6Sdrh   zDb = pDb->zName;
3934adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
3941962bda7Sdrh     goto insert_cleanup;
3951962bda7Sdrh   }
396c3f9bad2Sdanielk1977 
397b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
398b7f9164eSdrh   ** inserted into is a view
399b7f9164eSdrh   */
400b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
401dca76841Sdrh   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
402b7f9164eSdrh   isView = pTab->pSelect!=0;
403b7f9164eSdrh #else
404dca76841Sdrh # define triggers_exist 0
405b7f9164eSdrh # define isView 0
406b7f9164eSdrh #endif
407b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
408b7f9164eSdrh # undef isView
409b7f9164eSdrh # define isView 0
410b7f9164eSdrh #endif
411b7f9164eSdrh 
412c3f9bad2Sdanielk1977   /* Ensure that:
413c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
414c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
415c3f9bad2Sdanielk1977   */
416dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
417c3f9bad2Sdanielk1977     goto insert_cleanup;
418c3f9bad2Sdanielk1977   }
41943617e9aSdrh   assert( pTab!=0 );
4201ccde15dSdrh 
421f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
422b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
423b3d24bf8Sdanielk1977   ** module table).
424f573c99bSdrh   */
425b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
426f573c99bSdrh     goto insert_cleanup;
427f573c99bSdrh   }
428f573c99bSdrh 
4291ccde15dSdrh   /* Allocate a VDBE
4301ccde15dSdrh   */
4314adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4325974a30fSdrh   if( v==0 ) goto insert_cleanup;
4334794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
434da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4351ccde15dSdrh 
436c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
437dca76841Sdrh   if( triggers_exist ){
438c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
439f29ce559Sdanielk1977   }
440c3f9bad2Sdanielk1977 
4419d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4429d9cf229Sdrh   /* If the statement is of the form
4439d9cf229Sdrh   **
4449d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4459d9cf229Sdrh   **
4469d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4479d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
4489d9cf229Sdrh   */
4499d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4509d9cf229Sdrh     assert( !triggers_exist );
4519d9cf229Sdrh     assert( pList==0 );
4529d9cf229Sdrh     goto insert_cleanup;
4539d9cf229Sdrh   }
4549d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4559d9cf229Sdrh 
4562958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
457f3388144Sdrh   ** sqlite_sequence table and store it in memory cell counterMem.  Also
458f3388144Sdrh   ** remember the rowid of the sqlite_sequence table entry in memory cell
459f3388144Sdrh   ** counterRowid.
4602958a4e6Sdrh   */
4619d9cf229Sdrh   counterMem = autoIncBegin(pParse, iDb, pTab);
4622958a4e6Sdrh 
4631ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
464142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
465142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
466142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
467142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
468142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
469142e30dfSdrh   ** results in a temporary table. (Template 3.)
4701ccde15dSdrh   */
4715974a30fSdrh   if( pSelect ){
472142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
473142e30dfSdrh     */
4746c8c8ce0Sdanielk1977     SelectDest dest = {SRT_Subroutine, 0, 0};
475142e30dfSdrh     int rc, iInitCode;
47666a5167bSdrh     iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4774adee20fSdanielk1977     iSelectLoop = sqlite3VdbeCurrentAddr(v);
4784adee20fSdanielk1977     iInsertBlock = sqlite3VdbeMakeLabel(v);
4796c8c8ce0Sdanielk1977     dest.iParm = iInsertBlock;
480b3bce662Sdanielk1977 
481b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
4826c8c8ce0Sdanielk1977     rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
48317435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
4846f7adc8aSdrh       goto insert_cleanup;
4856f7adc8aSdrh     }
486b3bce662Sdanielk1977 
4874adee20fSdanielk1977     iCleanup = sqlite3VdbeMakeLabel(v);
48866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
4895974a30fSdrh     assert( pSelect->pEList );
490967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
491142e30dfSdrh 
492142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
493142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
494142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
495048c530cSdrh     **
496048c530cSdrh     ** A temp table must be used if the table being updated is also one
497048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
498048c530cSdrh     ** temp table in the case of row triggers.
499142e30dfSdrh     */
50048d1178aSdrh     if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
501048c530cSdrh       useTempTable = 1;
502048c530cSdrh     }
503142e30dfSdrh 
504142e30dfSdrh     if( useTempTable ){
505142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
506142e30dfSdrh       ** the result.  Store the result in a temporary table
507142e30dfSdrh       */
508142e30dfSdrh       srcTab = pParse->nTab++;
5094adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iInsertBlock);
51066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
51166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_MakeRecord, nColumn, 0);
51266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, 0);
51366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Pull, 1, 0);
5141f4aa337Sdanielk1977       sqlite3CodeInsert(pParse, srcTab, OPFLAG_APPEND);
51566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
516142e30dfSdrh 
517142e30dfSdrh       /* The following code runs first because the GOTO at the very top
518142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
519142e30dfSdrh       ** back up and execute the SELECT code above.
520142e30dfSdrh       */
521d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
52266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
52366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
52466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
5254adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCleanup);
5265974a30fSdrh     }else{
527d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
528142e30dfSdrh     }
529142e30dfSdrh   }else{
530142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
531142e30dfSdrh     ** clause
532142e30dfSdrh     */
533b3bce662Sdanielk1977     NameContext sNC;
534b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
535b3bce662Sdanielk1977     sNC.pParse = pParse;
5365974a30fSdrh     srcTab = -1;
53748d1178aSdrh     assert( useTempTable==0 );
538147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
539e64e7b20Sdrh     for(i=0; i<nColumn; i++){
540b3bce662Sdanielk1977       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
541b04a5d87Sdrh         goto insert_cleanup;
542b04a5d87Sdrh       }
543e64e7b20Sdrh     }
5445974a30fSdrh   }
5451ccde15dSdrh 
5461ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
5471ccde15dSdrh   ** of columns to be inserted into the table.
5481ccde15dSdrh   */
549034ca14fSdanielk1977   if( IsVirtual(pTab) ){
550034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
551034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
552034ca14fSdanielk1977     }
553034ca14fSdanielk1977   }
554034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
5554adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
556da93d238Sdrh        "table %S has %d columns but %d values were supplied",
557da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
558cce7d176Sdrh     goto insert_cleanup;
559cce7d176Sdrh   }
560967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
5614adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
562cce7d176Sdrh     goto insert_cleanup;
563cce7d176Sdrh   }
5641ccde15dSdrh 
5651ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
5661ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
5671ccde15dSdrh   ** remember the column indices.
568c8392586Sdrh   **
569c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
570c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
571c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
572c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
573c8392586Sdrh   ** is appears in the original table.  (The index of the primary
574c8392586Sdrh   ** key in the original table is pTab->iPKey.)
5751ccde15dSdrh   */
576967e8b73Sdrh   if( pColumn ){
577967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
578967e8b73Sdrh       pColumn->a[i].idx = -1;
579cce7d176Sdrh     }
580967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
581cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
5824adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
583967e8b73Sdrh           pColumn->a[i].idx = j;
5844a32431cSdrh           if( j==pTab->iPKey ){
5859aa028daSdrh             keyColumn = i;
5864a32431cSdrh           }
587cce7d176Sdrh           break;
588cce7d176Sdrh         }
589cce7d176Sdrh       }
590cce7d176Sdrh       if( j>=pTab->nCol ){
5914adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
592a0217ba7Sdrh           keyColumn = i;
593a0217ba7Sdrh         }else{
5944adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
595da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
596cce7d176Sdrh           pParse->nErr++;
597cce7d176Sdrh           goto insert_cleanup;
598cce7d176Sdrh         }
599cce7d176Sdrh       }
600cce7d176Sdrh     }
601a0217ba7Sdrh   }
6021ccde15dSdrh 
603aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
604c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
605c8392586Sdrh   ** in the original table definition.
6064a32431cSdrh   */
607147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
6084a32431cSdrh     keyColumn = pTab->iPKey;
6094a32431cSdrh   }
6104a32431cSdrh 
611142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
612142e30dfSdrh   */
613dca76841Sdrh   if( triggers_exist ){
61466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
61566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
616f29ce559Sdanielk1977   }
617c3f9bad2Sdanielk1977 
618c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
6191ccde15dSdrh   */
620142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
6210a07c107Sdrh     iCntMem = ++pParse->nMem;
62266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemInt, 0, iCntMem);
623c3f9bad2Sdanielk1977   }
624c3f9bad2Sdanielk1977 
625e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
626e448dc4aSdanielk1977   if( !isView ){
6275974a30fSdrh     base = pParse->nTab;
628290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
629feeb1394Sdrh   }
630feeb1394Sdrh 
631142e30dfSdrh   /* If the data source is a temporary table, then we have to create
6321ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
633142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
634142e30dfSdrh   ** to launch the SELECT statement processing.
6351ccde15dSdrh   */
636142e30dfSdrh   if( useTempTable ){
6374adee20fSdanielk1977     iBreak = sqlite3VdbeMakeLabel(v);
63866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
6394adee20fSdanielk1977     iCont = sqlite3VdbeCurrentAddr(v);
640142e30dfSdrh   }else if( pSelect ){
64166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
6424adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iInsertBlock);
64366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_StackDepth, -1, 0);
644bed8690fSdrh   }
6451ccde15dSdrh 
6465cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
64770ce3f0cSdrh   */
6484adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
649dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
650c3f9bad2Sdanielk1977 
65170ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
65270ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
65370ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
65470ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
65570ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
65670ce3f0cSdrh     */
65770ce3f0cSdrh     if( keyColumn<0 ){
65866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
65970ce3f0cSdrh     }else if( useTempTable ){
66066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Column, srcTab, keyColumn);
66170ce3f0cSdrh     }else{
662d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
663389a1adbSdrh       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
66466a5167bSdrh       sqlite3VdbeAddOp2(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
66566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
66666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, 0);
66766a5167bSdrh       sqlite3VdbeAddOp2(v, OP_MustBeInt, 0, 0);
66870ce3f0cSdrh     }
66970ce3f0cSdrh 
670034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
671034ca14fSdanielk1977     ** this block would have to account for hidden column.
672034ca14fSdanielk1977     */
673034ca14fSdanielk1977     assert(!IsVirtual(pTab));
674034ca14fSdanielk1977 
67570ce3f0cSdrh     /* Create the new column data
67670ce3f0cSdrh     */
677c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
678c3f9bad2Sdanielk1977       if( pColumn==0 ){
679c3f9bad2Sdanielk1977         j = i;
680c3f9bad2Sdanielk1977       }else{
681c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
682c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
683c3f9bad2Sdanielk1977         }
684c3f9bad2Sdanielk1977       }
685c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
686389a1adbSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
687142e30dfSdrh       }else if( useTempTable ){
68866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Column, srcTab, j);
689c3f9bad2Sdanielk1977       }else{
690d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
69125303780Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
692c3f9bad2Sdanielk1977       }
693c3f9bad2Sdanielk1977     }
69466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
695a37cdde0Sdanielk1977 
696a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
697a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
698a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
699a37cdde0Sdanielk1977     ** table column affinities.
700a37cdde0Sdanielk1977     */
701a37cdde0Sdanielk1977     if( !isView ){
702a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
703a37cdde0Sdanielk1977     }
7041f4aa337Sdanielk1977     sqlite3CodeInsert(pParse, newIdx, OPFLAG_APPEND);
705c3f9bad2Sdanielk1977 
7065cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
707dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
7088f2c54e6Sdanielk1977         newIdx, -1, onError, endOfLoop, 0, 0) ){
709f29ce559Sdanielk1977       goto insert_cleanup;
710f29ce559Sdanielk1977     }
71170ce3f0cSdrh   }
712c3f9bad2Sdanielk1977 
7134a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
714f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
7154a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
716b419a926Sdrh   ** case the record number is the same as that column.
7171ccde15dSdrh   */
7185cf590c1Sdrh   if( !isView ){
719*287fb61cSdanielk1977     int iReg = pParse->nMem+1;
720*287fb61cSdanielk1977     int iRowid = iReg+(IsVirtual(pTab)?1:0);
721*287fb61cSdanielk1977     pParse->nMem += pTab->nCol + (IsVirtual(pTab)?2:1);
722*287fb61cSdanielk1977 
7234cbdda9eSdrh     if( IsVirtual(pTab) ){
7244cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
725*287fb61cSdanielk1977       sqlite3VdbeAddOp2(v, OP_MemNull, 0, iReg);
7264cbdda9eSdrh     }
7274a32431cSdrh     if( keyColumn>=0 ){
728142e30dfSdrh       if( useTempTable ){
729*287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, iRowid);
730142e30dfSdrh       }else if( pSelect ){
731*287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Dup, nColumn - keyColumn - 1, 1, iRowid);
732*287fb61cSdanielk1977         /* TODO: Avoid this use of the stack. */
733*287fb61cSdanielk1977         sqlite3VdbeAddOp2(v, OP_MemStore, iRowid, 1);
7344a32431cSdrh       }else{
735e4d90813Sdrh         VdbeOp *pOp;
736389a1adbSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, 0);
737e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
73801256832Sdanielk1977         if( pOp && pOp->opcode==OP_Null ){
739e4d90813Sdrh           appendFlag = 1;
740e4d90813Sdrh           pOp->opcode = OP_NewRowid;
741e4d90813Sdrh           pOp->p1 = base;
742e4d90813Sdrh           pOp->p2 = counterMem;
743*287fb61cSdanielk1977           pOp->p3 = iRowid;
744*287fb61cSdanielk1977         }else{
745*287fb61cSdanielk1977           /* TODO: Avoid this use of the stack. */
746*287fb61cSdanielk1977           sqlite3VdbeAddOp2(v, OP_MemStore, iRowid, 1);
747e4d90813Sdrh         }
74827a32783Sdrh       }
749f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
750e1e68f49Sdrh       ** to generate a unique primary key value.
751e1e68f49Sdrh       */
752e4d90813Sdrh       if( !appendFlag ){
753*287fb61cSdanielk1977         sqlite3VdbeAddOp2(v, OP_IfMemNull, iRowid, sqlite3VdbeCurrentAddr(v)+2);
754*287fb61cSdanielk1977         sqlite3VdbeAddOp2(v, OP_Goto, -1, sqlite3VdbeCurrentAddr(v)+2);
755*287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_NewRowid, base, counterMem, iRowid);
756*287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_MustBeInt, 0, 0, iRowid);
757e4d90813Sdrh       }
7584cbdda9eSdrh     }else if( IsVirtual(pTab) ){
759*287fb61cSdanielk1977       sqlite3VdbeAddOp2(v, OP_MemNull, 0, iRowid);
7604a32431cSdrh     }else{
76166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, base, counterMem);
762*287fb61cSdanielk1977       sqlite3VdbeAddOp2(v, OP_MemStore, iRowid, 1);
763e4d90813Sdrh       appendFlag = 1;
7644a32431cSdrh     }
765*287fb61cSdanielk1977     autoIncStep(pParse, counterMem, iRowid);
7664a32431cSdrh 
767aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
7684a32431cSdrh     ** with the first column.
7694a32431cSdrh     */
770034ca14fSdanielk1977     nHidden = 0;
771cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
772*287fb61cSdanielk1977       int iRegStore = iRowid+1+i;
7734a32431cSdrh       if( i==pTab->iPKey ){
7744a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
775aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
776aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
777aacc543eSdrh         ** taking up data space with information that will never be used. */
778*287fb61cSdanielk1977         sqlite3VdbeAddOp2(v, OP_MemNull, 0, iRegStore);
7794a32431cSdrh         continue;
7804a32431cSdrh       }
781967e8b73Sdrh       if( pColumn==0 ){
782034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
783034ca14fSdanielk1977           assert( IsVirtual(pTab) );
784034ca14fSdanielk1977           j = -1;
785034ca14fSdanielk1977           nHidden++;
786034ca14fSdanielk1977         }else{
787034ca14fSdanielk1977           j = i - nHidden;
788034ca14fSdanielk1977         }
789cce7d176Sdrh       }else{
790967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
791967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
792cce7d176Sdrh         }
793cce7d176Sdrh       }
794034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
795*287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
796142e30dfSdrh       }else if( useTempTable ){
797*287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
798142e30dfSdrh       }else if( pSelect ){
799*287fb61cSdanielk1977         sqlite3VdbeAddOp2(v, OP_Dup, nColumn-j-1, 1);
800*287fb61cSdanielk1977         /* TODO: Avoid this use of the stack */
801*287fb61cSdanielk1977         sqlite3VdbeAddOp2(v, OP_MemStore, iRegStore, 1);
802cce7d176Sdrh       }else{
803*287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
804cce7d176Sdrh       }
805cce7d176Sdrh     }
8061ccde15dSdrh 
8070ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
8080ca3e24bSdrh     ** do the insertion.
8094a32431cSdrh     */
8104cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
8114cbdda9eSdrh     if( IsVirtual(pTab) ){
812f9e7dda7Sdanielk1977       pParse->pVirtualLock = pTab;
8132a339ff6Sdanielk1977       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, iReg,
81466a5167bSdrh                      (const char*)pTab->pVtab, P4_VTAB);
8154cbdda9eSdrh     }else
8164cbdda9eSdrh #endif
8174cbdda9eSdrh     {
818*287fb61cSdanielk1977       sqlite3RegToStack(pParse, iReg, pTab->nCol+1);
8194adee20fSdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
820a0217ba7Sdrh                                      0, onError, endOfLoop);
8214adee20fSdanielk1977       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
822e4d90813Sdrh                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
823e4d90813Sdrh                             appendFlag);
8245cf590c1Sdrh     }
8254cbdda9eSdrh   }
8261bee3d7bSdrh 
827feeb1394Sdrh   /* Update the count of rows that are inserted
8281bee3d7bSdrh   */
829142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
83066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_MemIncr, 1, iCntMem);
8311bee3d7bSdrh   }
832c3f9bad2Sdanielk1977 
833dca76841Sdrh   if( triggers_exist ){
834c3f9bad2Sdanielk1977     /* Code AFTER triggers */
835dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
8368f2c54e6Sdanielk1977           newIdx, -1, onError, endOfLoop, 0, 0) ){
837f29ce559Sdanielk1977       goto insert_cleanup;
838f29ce559Sdanielk1977     }
839c3f9bad2Sdanielk1977   }
8401bee3d7bSdrh 
8411ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
8421ccde15dSdrh   */
8434adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
844142e30dfSdrh   if( useTempTable ){
84566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
8464adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iBreak);
84766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
848142e30dfSdrh   }else if( pSelect ){
84966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Pop, nColumn, 0);
85066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
8514adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iCleanup);
8526b56344dSdrh   }
853c3f9bad2Sdanielk1977 
854e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
855c3f9bad2Sdanielk1977     /* Close all tables opened */
85666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, base, 0);
8576b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
85866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, idx+base, 0);
859cce7d176Sdrh     }
860c3f9bad2Sdanielk1977   }
861c3f9bad2Sdanielk1977 
862f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
863f3388144Sdrh   ** counter value in memory counterMem back into the sqlite_sequence
864f3388144Sdrh   ** table.
8652958a4e6Sdrh   */
8669d9cf229Sdrh   autoIncEnd(pParse, iDb, pTab, counterMem);
8672958a4e6Sdrh 
8681bee3d7bSdrh   /*
869e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
870e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
871e7de6f25Sdanielk1977   ** invoke the callback function.
8721bee3d7bSdrh   */
873cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
87466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, iCntMem, 1);
87522322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
87666a5167bSdrh     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
8771bee3d7bSdrh   }
878cce7d176Sdrh 
879cce7d176Sdrh insert_cleanup:
8804adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
881d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
882d5d56523Sdanielk1977   sqlite3SelectDelete(pSelect);
8834adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
884cce7d176Sdrh }
8859cfcf5d4Sdrh 
8869cfcf5d4Sdrh /*
8879cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
8889cfcf5d4Sdrh **
8899cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
8900ca3e24bSdrh ** the following values:
8910ca3e24bSdrh **
892f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
893b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
894b419a926Sdrh **        change to the record number.
8950ca3e24bSdrh **
896f0863fe5Sdrh **    2.  The rowid of the row after the update.
8970ca3e24bSdrh **
8980ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
8990ca3e24bSdrh **
9000ca3e24bSdrh **    i.  Data from middle columns...
9010ca3e24bSdrh **
9020ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
9030ca3e24bSdrh **
904f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
905f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
906f0863fe5Sdrh ** INSERTs and rowidChng is true if the record number is being changed.
9070ca3e24bSdrh **
9080ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
9090ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
9100ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
9110ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
9120ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
9139cfcf5d4Sdrh **
9149cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
9159cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
9161c92853dSdrh ** then the appropriate action is performed.  There are five possible
9171c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
9189cfcf5d4Sdrh **
9199cfcf5d4Sdrh **  Constraint type  Action       What Happens
9209cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
9211c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
92224b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
9239cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
9249cfcf5d4Sdrh **
9251c92853dSdrh **  any              ABORT        Back out changes from the current command
9261c92853dSdrh **                                only (do not do a complete rollback) then
92724b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
9281c92853dSdrh **                                with SQLITE_CONSTRAINT.
9291c92853dSdrh **
9301c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
9311c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
9321c92853dSdrh **                                transaction is not rolled back and any
9331c92853dSdrh **                                prior changes are retained.
9341c92853dSdrh **
9359cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
9369cfcf5d4Sdrh **                                the stack and there is an immediate jump
9379cfcf5d4Sdrh **                                to label ignoreDest.
9389cfcf5d4Sdrh **
9399cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
9409cfcf5d4Sdrh **                                value for that column.  If the default value
9419cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
9429cfcf5d4Sdrh **
9439cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
9449cfcf5d4Sdrh **                                being inserted is removed.
9459cfcf5d4Sdrh **
9469cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
9479cfcf5d4Sdrh **
9481c92853dSdrh ** Which action to take is determined by the overrideError parameter.
9491c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
9501c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
9511c92853dSdrh ** for the constraint is used.
9529cfcf5d4Sdrh **
953aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
9549cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
9559cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
9569cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
9579cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
9589cfcf5d4Sdrh **
9599cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
9609cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
9619cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
9629cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
9639cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
9649cfcf5d4Sdrh */
9654adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
9669cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
9679cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
9689cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
9699cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
970f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
971b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
9729cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
973b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
9749cfcf5d4Sdrh ){
9759cfcf5d4Sdrh   int i;
9769cfcf5d4Sdrh   Vdbe *v;
9779cfcf5d4Sdrh   int nCol;
9789cfcf5d4Sdrh   int onError;
9799cfcf5d4Sdrh   int addr;
9809cfcf5d4Sdrh   int extra;
9810ca3e24bSdrh   int iCur;
9820ca3e24bSdrh   Index *pIdx;
9830ca3e24bSdrh   int seenReplace = 0;
984cfe9a69fSdanielk1977   int jumpInst1=0, jumpInst2;
985f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
9869cfcf5d4Sdrh 
9874adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
9889cfcf5d4Sdrh   assert( v!=0 );
989417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
9909cfcf5d4Sdrh   nCol = pTab->nCol;
9919cfcf5d4Sdrh 
9929cfcf5d4Sdrh   /* Test all NOT NULL constraints.
9939cfcf5d4Sdrh   */
9949cfcf5d4Sdrh   for(i=0; i<nCol; i++){
9950ca3e24bSdrh     if( i==pTab->iPKey ){
9960ca3e24bSdrh       continue;
9970ca3e24bSdrh     }
9989cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
9990ca3e24bSdrh     if( onError==OE_None ) continue;
10009cfcf5d4Sdrh     if( overrideError!=OE_Default ){
10019cfcf5d4Sdrh       onError = overrideError;
1002a996e477Sdrh     }else if( onError==OE_Default ){
1003a996e477Sdrh       onError = OE_Abort;
10049cfcf5d4Sdrh     }
10057977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
10069cfcf5d4Sdrh       onError = OE_Abort;
10079cfcf5d4Sdrh     }
100866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, nCol-1-i, 1);
100966a5167bSdrh     addr = sqlite3VdbeAddOp2(v, OP_NotNull, 1, 0);
1010b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1011b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
10129cfcf5d4Sdrh     switch( onError ){
10131c92853dSdrh       case OE_Rollback:
10141c92853dSdrh       case OE_Abort:
10151c92853dSdrh       case OE_Fail: {
1016483750baSdrh         char *zMsg = 0;
101766a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
10184adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
101941743984Sdrh                         " may not be NULL", (char*)0);
102066a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
10219cfcf5d4Sdrh         break;
10229cfcf5d4Sdrh       }
10239cfcf5d4Sdrh       case OE_Ignore: {
102466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
102566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
10269cfcf5d4Sdrh         break;
10279cfcf5d4Sdrh       }
10289cfcf5d4Sdrh       case OE_Replace: {
1029389a1adbSdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, 0);
103066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Push, nCol-i, 0);
10319cfcf5d4Sdrh         break;
10329cfcf5d4Sdrh       }
10339cfcf5d4Sdrh     }
1034d654be80Sdrh     sqlite3VdbeJumpHere(v, addr);
10359cfcf5d4Sdrh   }
10369cfcf5d4Sdrh 
10379cfcf5d4Sdrh   /* Test all CHECK constraints
10389cfcf5d4Sdrh   */
1039ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
10400cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1041ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
1042ffe07b2dSdrh     assert( pParse->ckOffset==0 );
1043ffe07b2dSdrh     pParse->ckOffset = nCol;
10446275b88bSdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
1045ffe07b2dSdrh     assert( pParse->ckOffset==nCol );
1046ffe07b2dSdrh     pParse->ckOffset = 0;
1047aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
10482e06c67cSdrh     if( onError==OE_Ignore ){
104966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
105066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1051aa01c7e2Sdrh     }else{
105266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1053aa01c7e2Sdrh     }
1054ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1055ffe07b2dSdrh   }
1056ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
10579cfcf5d4Sdrh 
10580bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
10590bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
10600bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
10619cfcf5d4Sdrh   */
1062f0863fe5Sdrh   if( rowidChng ){
10630ca3e24bSdrh     onError = pTab->keyConf;
10640ca3e24bSdrh     if( overrideError!=OE_Default ){
10650ca3e24bSdrh       onError = overrideError;
1066a996e477Sdrh     }else if( onError==OE_Default ){
1067a996e477Sdrh       onError = OE_Abort;
10680ca3e24bSdrh     }
1069a0217ba7Sdrh 
107079b0c956Sdrh     if( isUpdate ){
107166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Dup, nCol+1, 1);
107266a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Dup, nCol+1, 1);
107366a5167bSdrh       jumpInst1 = sqlite3VdbeAddOp2(v, OP_Eq, 0, 0);
107479b0c956Sdrh     }
107566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, nCol, 1);
107666a5167bSdrh     jumpInst2 = sqlite3VdbeAddOp2(v, OP_NotExists, base, 0);
10770ca3e24bSdrh     switch( onError ){
1078a0217ba7Sdrh       default: {
1079a0217ba7Sdrh         onError = OE_Abort;
1080a0217ba7Sdrh         /* Fall thru into the next case */
1081a0217ba7Sdrh       }
10821c92853dSdrh       case OE_Rollback:
10831c92853dSdrh       case OE_Abort:
10841c92853dSdrh       case OE_Fail: {
108566a5167bSdrh         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
108666a5167bSdrh                          "PRIMARY KEY must be unique", P4_STATIC);
10870ca3e24bSdrh         break;
10880ca3e24bSdrh       }
10895383ae5cSdrh       case OE_Replace: {
109074161705Sdrh         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
10915383ae5cSdrh         if( isUpdate ){
109266a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Dup, nCol+hasTwoRowids, 1);
109366a5167bSdrh           sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
10945383ae5cSdrh         }
10955383ae5cSdrh         seenReplace = 1;
10965383ae5cSdrh         break;
10975383ae5cSdrh       }
10980ca3e24bSdrh       case OE_Ignore: {
10995383ae5cSdrh         assert( seenReplace==0 );
110066a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Pop, nCol+1+hasTwoRowids, 0);
110166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
11020ca3e24bSdrh         break;
11030ca3e24bSdrh       }
11040ca3e24bSdrh     }
1105d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
1106f5905aa7Sdrh     if( isUpdate ){
1107d654be80Sdrh       sqlite3VdbeJumpHere(v, jumpInst1);
110866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Dup, nCol+1, 1);
110966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
11100ca3e24bSdrh     }
11110ca3e24bSdrh   }
11120bd1f4eaSdrh 
11130bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
11140bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
11150bd1f4eaSdrh   ** Add the new records to the indices as we go.
11160bd1f4eaSdrh   */
1117b2fe7d8cSdrh   extra = -1;
1118b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1119b2fe7d8cSdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
11209cfcf5d4Sdrh     extra++;
1121b2fe7d8cSdrh 
1122b2fe7d8cSdrh     /* Create a key for accessing the index entry */
112366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, nCol+extra, 1);
11249cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
11259cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
11269cfcf5d4Sdrh       if( idx==pTab->iPKey ){
112766a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Dup, i+extra+nCol+1, 1);
11289cfcf5d4Sdrh       }else{
112966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Dup, i+extra+nCol-idx, 1);
11309cfcf5d4Sdrh       }
11319cfcf5d4Sdrh     }
113266a5167bSdrh     jumpInst1 = sqlite3VdbeAddOp2(v, OP_MakeIdxRec, pIdx->nColumn, 0);
1133a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
1134b2fe7d8cSdrh 
1135b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
11369cfcf5d4Sdrh     onError = pIdx->onError;
1137b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
11389cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11399cfcf5d4Sdrh       onError = overrideError;
1140a996e477Sdrh     }else if( onError==OE_Default ){
1141a996e477Sdrh       onError = OE_Abort;
11429cfcf5d4Sdrh     }
11435383ae5cSdrh     if( seenReplace ){
11445383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
11455383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
11465383ae5cSdrh     }
11475383ae5cSdrh 
1148b2fe7d8cSdrh 
1149b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
115066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
115166a5167bSdrh     jumpInst2 = sqlite3VdbeAddOp2(v, OP_IsUnique, base+iCur+1, 0);
1152b2fe7d8cSdrh 
1153b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1154b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1155b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11569cfcf5d4Sdrh     switch( onError ){
11571c92853dSdrh       case OE_Rollback:
11581c92853dSdrh       case OE_Abort:
11591c92853dSdrh       case OE_Fail: {
116037ed48edSdrh         int j, n1, n2;
116137ed48edSdrh         char zErrMsg[200];
11625bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
11635bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
116437ed48edSdrh         n1 = strlen(zErrMsg);
116537ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
116637ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
116737ed48edSdrh           n2 = strlen(zCol);
116837ed48edSdrh           if( j>0 ){
11695bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
117037ed48edSdrh             n1 += 2;
117137ed48edSdrh           }
117237ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
11735bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
117437ed48edSdrh             n1 += 3;
117537ed48edSdrh             break;
117637ed48edSdrh           }else{
11775bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
117837ed48edSdrh             n1 += n2;
117937ed48edSdrh           }
118037ed48edSdrh         }
11815bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
118237ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
118366a5167bSdrh         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
11849cfcf5d4Sdrh         break;
11859cfcf5d4Sdrh       }
11869cfcf5d4Sdrh       case OE_Ignore: {
11870ca3e24bSdrh         assert( seenReplace==0 );
118866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
118966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
11909cfcf5d4Sdrh         break;
11919cfcf5d4Sdrh       }
11929cfcf5d4Sdrh       case OE_Replace: {
119396cb76fcSdanielk1977         int iRowid = sqlite3StackToReg(pParse, 1);
119496cb76fcSdanielk1977         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, iRowid, 0);
11959cfcf5d4Sdrh         if( isUpdate ){
119666a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
119766a5167bSdrh           sqlite3VdbeAddOp2(v, OP_MoveGe, base, 0);
11989cfcf5d4Sdrh         }
11990ca3e24bSdrh         seenReplace = 1;
12009cfcf5d4Sdrh         break;
12019cfcf5d4Sdrh       }
12029cfcf5d4Sdrh     }
12030bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
1204d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst1);
12050bd1f4eaSdrh #endif
1206d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
12079cfcf5d4Sdrh   }
12089cfcf5d4Sdrh }
12090ca3e24bSdrh 
12100ca3e24bSdrh /*
12110ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
12124adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
12130ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
1214f0863fe5Sdrh ** and the rowid for the new entry.  This routine creates the new
12150ca3e24bSdrh ** entries in all indices and in the main table.
12160ca3e24bSdrh **
1217b419a926Sdrh ** The arguments to this routine should be the same as the first six
12184adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
12190ca3e24bSdrh */
12204adee20fSdanielk1977 void sqlite3CompleteInsertion(
12210ca3e24bSdrh   Parse *pParse,      /* The parser context */
12220ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
12230ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
12240ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
1225f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
122670ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1227e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1228e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
12290ca3e24bSdrh ){
12300ca3e24bSdrh   int i;
12310ca3e24bSdrh   Vdbe *v;
12320ca3e24bSdrh   int nIdx;
12330ca3e24bSdrh   Index *pIdx;
1234b28af71aSdanielk1977   int pik_flags;
12350ca3e24bSdrh 
12364adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12370ca3e24bSdrh   assert( v!=0 );
1238417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12390ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
12400ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
12410ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
124266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, base+i+1, 0);
12430ca3e24bSdrh   }
124466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_MakeRecord, pTab->nCol, 0);
1245a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1246b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
124770ce3f0cSdrh   if( newIdx>=0 ){
124866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, 1, 0);
124966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, 1, 0);
12501f4aa337Sdanielk1977     sqlite3CodeInsert(pParse, newIdx, 0);
125170ce3f0cSdrh   }
1252b84f96f8Sdanielk1977 #endif
12534794f735Sdrh   if( pParse->nested ){
12544794f735Sdrh     pik_flags = 0;
12554794f735Sdrh   }else{
125694eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
125794eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
12584794f735Sdrh   }
1259e4d90813Sdrh   if( appendBias ){
1260e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1261e4d90813Sdrh   }
12621f4aa337Sdanielk1977   sqlite3CodeInsert(pParse, base, pik_flags);
126394eb6a14Sdanielk1977   if( !pParse->nested ){
126466a5167bSdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
126594eb6a14Sdanielk1977   }
1266b28af71aSdanielk1977 
1267f0863fe5Sdrh   if( isUpdate && rowidChng ){
126866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Pop, 1, 0);
12690ca3e24bSdrh   }
12700ca3e24bSdrh }
1271cd44690aSdrh 
1272cd44690aSdrh /*
1273290c1948Sdrh ** Generate code that will open cursors for a table and for all
1274cd44690aSdrh ** indices of that table.  The "base" parameter is the cursor number used
1275cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1276cd44690aSdrh */
1277290c1948Sdrh void sqlite3OpenTableAndIndices(
1278290c1948Sdrh   Parse *pParse,   /* Parsing context */
1279290c1948Sdrh   Table *pTab,     /* Table to be opened */
1280290c1948Sdrh   int base,        /* Cursor number assigned to the table */
1281290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1282290c1948Sdrh ){
1283cd44690aSdrh   int i;
12844cbdda9eSdrh   int iDb;
1285cd44690aSdrh   Index *pIdx;
12864cbdda9eSdrh   Vdbe *v;
12874cbdda9eSdrh 
12884cbdda9eSdrh   if( IsVirtual(pTab) ) return;
12894cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
12904cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1291cd44690aSdrh   assert( v!=0 );
1292c00da105Sdanielk1977   sqlite3OpenTable(pParse, base, iDb, pTab, op);
1293cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1294b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1295da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
1296207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, op, i+base, pIdx->tnum, iDb,
129766a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1298207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1299cd44690aSdrh   }
1300290c1948Sdrh   if( pParse->nTab<=base+i ){
1301290c1948Sdrh     pParse->nTab = base+i;
1302290c1948Sdrh   }
1303cd44690aSdrh }
13049d9cf229Sdrh 
130591c58e23Sdrh 
130691c58e23Sdrh #ifdef SQLITE_TEST
130791c58e23Sdrh /*
130891c58e23Sdrh ** The following global variable is incremented whenever the
130991c58e23Sdrh ** transfer optimization is used.  This is used for testing
131091c58e23Sdrh ** purposes only - to make sure the transfer optimization really
131191c58e23Sdrh ** is happening when it is suppose to.
131291c58e23Sdrh */
131391c58e23Sdrh int sqlite3_xferopt_count;
131491c58e23Sdrh #endif /* SQLITE_TEST */
131591c58e23Sdrh 
131691c58e23Sdrh 
13179d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
13189d9cf229Sdrh /*
13199d9cf229Sdrh ** Check to collation names to see if they are compatible.
13209d9cf229Sdrh */
13219d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
13229d9cf229Sdrh   if( z1==0 ){
13239d9cf229Sdrh     return z2==0;
13249d9cf229Sdrh   }
13259d9cf229Sdrh   if( z2==0 ){
13269d9cf229Sdrh     return 0;
13279d9cf229Sdrh   }
13289d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
13299d9cf229Sdrh }
13309d9cf229Sdrh 
13319d9cf229Sdrh 
13329d9cf229Sdrh /*
13339d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
13349d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
13359d9cf229Sdrh ** for a compatible index:
13369d9cf229Sdrh **
13379d9cf229Sdrh **    *   The index is over the same set of columns
13389d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
13399d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
13409d9cf229Sdrh **    *   The same collating sequence on each column
13419d9cf229Sdrh */
13429d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
13439d9cf229Sdrh   int i;
13449d9cf229Sdrh   assert( pDest && pSrc );
13459d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
13469d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
13479d9cf229Sdrh     return 0;   /* Different number of columns */
13489d9cf229Sdrh   }
13499d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
13509d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
13519d9cf229Sdrh   }
13529d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
13539d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
13549d9cf229Sdrh       return 0;   /* Different columns indexed */
13559d9cf229Sdrh     }
13569d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
13579d9cf229Sdrh       return 0;   /* Different sort orders */
13589d9cf229Sdrh     }
13599d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
13609d9cf229Sdrh       return 0;   /* Different sort orders */
13619d9cf229Sdrh     }
13629d9cf229Sdrh   }
13639d9cf229Sdrh 
13649d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
13659d9cf229Sdrh   return 1;
13669d9cf229Sdrh }
13679d9cf229Sdrh 
13689d9cf229Sdrh /*
13699d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
13709d9cf229Sdrh **
13719d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
13729d9cf229Sdrh **
13739d9cf229Sdrh ** This optimization is only attempted if
13749d9cf229Sdrh **
13759d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
13768103b7d2Sdrh **         same indices and constraints
13779d9cf229Sdrh **
13789d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
13799d9cf229Sdrh **
13809d9cf229Sdrh **    (3)  There must be no triggers on tab1
13819d9cf229Sdrh **
13829d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
13839d9cf229Sdrh **
13849d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
13859d9cf229Sdrh **         or LIMIT clause.
13869d9cf229Sdrh **
13879d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
13889d9cf229Sdrh **         contains only tab2 in its FROM clause
13899d9cf229Sdrh **
13909d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
13919d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
13929d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
13939d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
13949d9cf229Sdrh **
13959d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
13969d9cf229Sdrh ** of the conditions above fail so that the optimization should not
13979d9cf229Sdrh ** be attempted, then this routine returns FALSE.
13989d9cf229Sdrh */
13999d9cf229Sdrh static int xferOptimization(
14009d9cf229Sdrh   Parse *pParse,        /* Parser context */
14019d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
14029d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
14039d9cf229Sdrh   int onError,          /* How to handle constraint errors */
14049d9cf229Sdrh   int iDbDest           /* The database of pDest */
14059d9cf229Sdrh ){
14069d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
14079d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
14089d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
14099d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
14109d9cf229Sdrh   int i;                           /* Loop counter */
14119d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
14129d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
14139d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
14149d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
14159d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
14169d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
14179d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
14189d9cf229Sdrh   int counterMem;                  /* Memory register used by AUTOINC */
1419f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
14209d9cf229Sdrh 
14219d9cf229Sdrh   if( pSelect==0 ){
14229d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
14239d9cf229Sdrh   }
14249d9cf229Sdrh   if( pDest->pTrigger ){
14259d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
14269d9cf229Sdrh   }
14279d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14289d9cf229Sdrh   if( pDest->isVirtual ){
14299d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
14309d9cf229Sdrh   }
14319d9cf229Sdrh #endif
14329d9cf229Sdrh   if( onError==OE_Default ){
14339d9cf229Sdrh     onError = OE_Abort;
14349d9cf229Sdrh   }
14359d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
14369d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
14379d9cf229Sdrh   }
14385ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
14399d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
14409d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
14419d9cf229Sdrh   }
14429d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
14439d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
14449d9cf229Sdrh   }
14459d9cf229Sdrh   if( pSelect->pWhere ){
14469d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
14479d9cf229Sdrh   }
14489d9cf229Sdrh   if( pSelect->pOrderBy ){
14499d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
14509d9cf229Sdrh   }
14518103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
14528103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
14539d9cf229Sdrh   if( pSelect->pGroupBy ){
14549d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
14559d9cf229Sdrh   }
14569d9cf229Sdrh   if( pSelect->pLimit ){
14579d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
14589d9cf229Sdrh   }
14598103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
14609d9cf229Sdrh   if( pSelect->pPrior ){
14619d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
14629d9cf229Sdrh   }
14639d9cf229Sdrh   if( pSelect->isDistinct ){
14649d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
14659d9cf229Sdrh   }
14669d9cf229Sdrh   pEList = pSelect->pEList;
14679d9cf229Sdrh   assert( pEList!=0 );
14689d9cf229Sdrh   if( pEList->nExpr!=1 ){
14699d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
14709d9cf229Sdrh   }
14719d9cf229Sdrh   assert( pEList->a[0].pExpr );
14729d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
14739d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
14749d9cf229Sdrh   }
14759d9cf229Sdrh 
14769d9cf229Sdrh   /* At this point we have established that the statement is of the
14779d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
14789d9cf229Sdrh   ** we have to check the semantics.
14799d9cf229Sdrh   */
14809d9cf229Sdrh   pItem = pSelect->pSrc->a;
14819d9cf229Sdrh   pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
14829d9cf229Sdrh   if( pSrc==0 ){
14839d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
14849d9cf229Sdrh   }
14859d9cf229Sdrh   if( pSrc==pDest ){
14869d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
14879d9cf229Sdrh   }
14889d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14899d9cf229Sdrh   if( pSrc->isVirtual ){
14909d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
14919d9cf229Sdrh   }
14929d9cf229Sdrh #endif
14939d9cf229Sdrh   if( pSrc->pSelect ){
14949d9cf229Sdrh     return 0;   /* tab2 may not be a view */
14959d9cf229Sdrh   }
14969d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
14979d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
14989d9cf229Sdrh   }
14999d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
15009d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
15019d9cf229Sdrh   }
15029d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
15039d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
15049d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
15059d9cf229Sdrh     }
15069d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
15079d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
15089d9cf229Sdrh     }
15099d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
15109d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
15119d9cf229Sdrh     }
15129d9cf229Sdrh   }
15139d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1514f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1515f33c9fadSdrh       destHasUniqueIdx = 1;
1516f33c9fadSdrh     }
15179d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
15189d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
15199d9cf229Sdrh     }
15209d9cf229Sdrh     if( pSrcIdx==0 ){
15219d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
15229d9cf229Sdrh     }
15239d9cf229Sdrh   }
15247fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1525fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
15268103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
15278103b7d2Sdrh   }
15287fc2f41bSdrh #endif
15299d9cf229Sdrh 
15309d9cf229Sdrh   /* If we get this far, it means either:
15319d9cf229Sdrh   **
15329d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
15339d9cf229Sdrh   **        an integer primary key
15349d9cf229Sdrh   **
15359d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
15369d9cf229Sdrh   **        table is empty.
15379d9cf229Sdrh   */
1538dd73521bSdrh #ifdef SQLITE_TEST
1539dd73521bSdrh   sqlite3_xferopt_count++;
1540dd73521bSdrh #endif
15419d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
15429d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1543f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
15449d9cf229Sdrh   iSrc = pParse->nTab++;
15459d9cf229Sdrh   iDest = pParse->nTab++;
15469d9cf229Sdrh   counterMem = autoIncBegin(pParse, iDbDest, pDest);
15479d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1548f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1549bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1550bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1551bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1552bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1553f33c9fadSdrh     **
1554f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1555f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1556f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1557f33c9fadSdrh     ** unique.
15589d9cf229Sdrh     */
155966a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
156066a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
15619d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
15629d9cf229Sdrh   }else{
15639d9cf229Sdrh     emptyDestTest = 0;
15649d9cf229Sdrh   }
15659d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
156666a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
156742242dedSdrh   if( pDest->iPKey>=0 ){
156866a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
156966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Dup, 0, 0);
157066a5167bSdrh     addr2 = sqlite3VdbeAddOp2(v, OP_NotExists, iDest, 0);
157166a5167bSdrh     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
157266a5167bSdrh                       "PRIMARY KEY must be unique", P4_STATIC);
15739d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1574*287fb61cSdanielk1977     autoIncStep(pParse, counterMem, 0);
1575bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
157666a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, 0);
157795bad4c7Sdrh   }else{
157866a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, 0);
157942242dedSdrh     assert( pDest->autoInc==0 );
158095bad4c7Sdrh   }
158166a5167bSdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, 0);
15821f4aa337Sdanielk1977   sqlite3CodeInsert(pParse,iDest,OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
15831f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
158466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
15859d9cf229Sdrh   autoIncEnd(pParse, iDbDest, pDest, counterMem);
15869d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
15879d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
15889d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
15899d9cf229Sdrh     }
15909d9cf229Sdrh     assert( pSrcIdx );
159166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
159266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
15939d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1594207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1595207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1596d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
15979d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1598207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
159966a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1600207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
160166a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
160266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, 0);
160366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, 1);
160466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
16059d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16069d9cf229Sdrh   }
16079d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
160866a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
160966a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
16109d9cf229Sdrh   if( emptyDestTest ){
161166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
16129d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
161366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
16149d9cf229Sdrh     return 0;
16159d9cf229Sdrh   }else{
16169d9cf229Sdrh     return 1;
16179d9cf229Sdrh   }
16189d9cf229Sdrh }
16199d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1620